Advertisement
Guest User

Script de comunicação GT06

a guest
Aug 18th, 2016
383
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 59.41 KB | None | 0 0
  1. #!/usr/bin/php -q
  2. <?php
  3.  
  4. $tipoLog = "arquivo"; // tela //debug log, escreve na tela ou no arquivo de log.
  5.  
  6. $fh = null;
  7. $remip = null;
  8. $remport = null;
  9. $imei = '';
  10.  
  11. function abrirArquivoLog($imeiLog) {
  12. GLOBAL $fh;
  13.  
  14. $fn = "./var/www/sites/1/logs/Log_". trim($imeiLog) .".log";
  15. $fn = trim($fn);
  16. $fh = fopen($fn, 'a') or die ("Can not create file");
  17. $tempstr = "Log Inicio".chr(13).chr(10);
  18. fwrite($fh, $tempstr);
  19. }
  20.  
  21. function fecharArquivoLog() {
  22. GLOBAL $fh;
  23. if ($fh != null)
  24. fclose($fh);
  25. }
  26.  
  27. function printLog( $fh, $mensagem ) {
  28. GLOBAL $tipoLog;
  29. GLOBAL $fh;
  30.  
  31. if ($tipoLog == "arquivo") {
  32. //escreve no arquivo
  33. if ($fh != null)
  34. fwrite($fh, $mensagem.chr(13).chr(10));
  35. } else {
  36. //escreve na tela
  37. echo $mensagem."<br />";
  38. }
  39. }
  40.  
  41. // IP Local
  42. $ip = '181.215.114.191';
  43. // Port
  44. $port = 7091;
  45. // Path to look for files with commands to send
  46. $command_path = "./var/www/sites/1/";
  47. //$from_email = $dataEmail['valor'];
  48. $from_email = 'teste@provedor.com.br';
  49.  
  50. //mysql_close($cnx);
  51.  
  52. $__server_listening = true;
  53.  
  54. error_reporting(E_ALL);
  55. set_time_limit(0);
  56. ob_implicit_flush();
  57. declare(ticks = 1);
  58. ini_set('sendmail_from', $from_email);
  59.  
  60. //printLog($fh, "become_daemon() in");
  61. become_daemon();
  62. //printLog($fh, "become_daemon() out");
  63.  
  64. /* handle signals */
  65. pcntl_signal(SIGTERM, 'sig_handler');
  66. pcntl_signal(SIGINT, 'sig_handler');
  67. pcntl_signal(SIGCHLD, 'sig_handler');
  68.  
  69. /* change this to your own host / port */
  70. server_loop($ip, $port);
  71.  
  72. /**
  73. * Change the identity to a non-priv user
  74. */
  75. function change_identity( $uid, $gid ) {
  76. if( !posix_setgid( $gid ) ) {
  77. print "Unable to setgid to " . $gid . "!\n";
  78. exit;
  79. }
  80.  
  81. if( !posix_setuid( $uid ) ) {
  82. print "Unable to setuid to " . $uid . "!\n";
  83. exit;
  84. }
  85. }
  86.  
  87. /**
  88. * Creates a server socket and listens for incoming client connections
  89. * @param string $address The address to listen on
  90. * @param int $port The port to listen on
  91. */
  92. function server_loop($address, $port) {
  93. GLOBAL $fh;
  94. GLOBAL $__server_listening;
  95.  
  96. printLog($fh, "server_looping...");
  97.  
  98. if(($sock = socket_create(AF_INET, SOCK_STREAM, 0)) < 0) {
  99. printLog($fh, "failed to create socket: ".socket_strerror($sock));
  100. exit();
  101. }
  102.  
  103. if(($ret = socket_bind($sock, $address, $port)) < 0) {
  104. printLog($fh, "failed to bind socket: ".socket_strerror($ret));
  105. exit();
  106. }
  107.  
  108. if( ( $ret = socket_listen( $sock, 0 ) ) < 0 ) {
  109. printLog($fh, "failed to listen to socket: ".socket_strerror($ret));
  110. exit();
  111. }
  112.  
  113. socket_set_nonblock($sock);
  114.  
  115. printLog($fh, "waiting for clients to connect...");
  116.  
  117. while ($__server_listening) {
  118. $connection = @socket_accept($sock);
  119. if ($connection === false) {
  120. usleep(100);
  121. } elseif ($connection > 0) {
  122. handle_client($sock, $connection);
  123. } else {
  124. printLog($fh, "error: ".socket_strerror($connection));
  125. die;
  126. }
  127. }
  128. }
  129.  
  130. /**
  131. * Signal handler
  132. */
  133. function sig_handler($sig) {
  134. switch($sig) {
  135. case SIGTERM:
  136. case SIGINT:
  137. //exit();
  138. break;
  139.  
  140. case SIGCHLD:
  141. pcntl_waitpid(-1, $status);
  142. break;
  143. }
  144. }
  145.  
  146. $firstInteraction = false;
  147.  
  148. /**
  149. * Handle a new client connection
  150. */
  151. function handle_client($ssock, $csock) {
  152. GLOBAL $__server_listening;
  153. GLOBAL $fh;
  154. GLOBAL $firstInteraction;
  155. GLOBAL $remip;
  156. GLOBAL $remport;
  157.  
  158. $pid = pcntl_fork();
  159.  
  160. if ($pid == -1) {
  161. /* fork failed */
  162. //printLog($fh, "fork failure!");
  163. die;
  164. } elseif ($pid == 0) {
  165. /* child process */
  166. $__server_listening = false;
  167. socket_getpeername($csock, $remip, $remport);
  168.  
  169. $firstInteraction = true;
  170.  
  171. socket_close($ssock);
  172. interact($csock);
  173. socket_close($csock);
  174.  
  175. printLog($fh, date("d-m-y h:i:sa") . " Connection to $remip:$remport closed");
  176.  
  177. fecharArquivoLog();
  178.  
  179. } else {
  180. socket_close($csock);
  181. }
  182. }
  183.  
  184. function interact($socket) {
  185. GLOBAL $fh;
  186. GLOBAL $command_path;
  187. GLOBAL $firstInteraction;
  188. GLOBAL $remip;
  189. GLOBAL $remport;
  190. GLOBAL $imei;
  191.  
  192. $loopcount = 0;
  193. $conn_imei = "";
  194. /* TALK TO YOUR CLIENT */
  195. $rec = "";
  196. // Variavel que indica se comando est� em banco ou arquivo.
  197. $tipoComando = "banco"; //"arquivo";
  198.  
  199. //Checando o protocolo
  200. $isGIMEI = false;
  201. $isGPRMC = false;
  202.  
  203. $send_cmd = "";
  204.  
  205. $last_status = "";
  206.  
  207. # Read the socket but don't wait for data..
  208. while (@socket_recv($socket, $rec, 2048, 0x40) !== 0) {
  209.  
  210. # If we know the imei of the phone and there is a pending command send it.
  211.  
  212. if ($conn_imei != "") {
  213. if ($tipoComando == "arquivo" and file_exists("$command_path/$conn_imei")) {
  214. $send_cmd = file_get_contents("$command_path/$conn_imei");
  215.  
  216. /**/
  217. $sendcmd = trataCommand($send_cmd, $conn_imei);
  218. socket_send($socket, $sendcmd, strlen($sendcmd), 0);
  219.  
  220. unlink("$command_path/$conn_imei");
  221. printLog($fh, "Arquivo de comandos apagado: " . $sendcmd . " imei: " . $conn_imei);
  222. } else {
  223. if ($tipoComando == "banco" and file_exists("$command_path/$conn_imei")) {
  224. //Conecta e pega o comando pendente
  225. $cnx = mysql_connect("localhost", "user_database", "pass_database")
  226. or die("Could not connect: " . mysql_error());
  227. mysql_select_db('tracker', $cnx);
  228. $res = mysql_query("SELECT c.command FROM command c WHERE c.imei = '$conn_imei' ORDER BY date DESC LIMIT 1", $cnx);
  229. $sendcmd = '';
  230. while($data = mysql_fetch_assoc($res)) {
  231. $sendcmd = trataCommand($data['command'], $conn_imei);
  232. }
  233. // Deletando comando
  234.  
  235. socket_send($socket, $sendcmd, strlen($sendcmd), 0);
  236.  
  237. mysql_close($cnx);
  238.  
  239. unlink("$command_path/$conn_imei");
  240.  
  241. printLog($fh, "Comandos do arquivo apagado: " . $sendcmd . " imei: " . $conn_imei);
  242. } else {
  243. //Se nao tiver comando na fila e for a primeira iteracao, obtem o ultimo comando v�lido enviado
  244. if ($firstInteraction == true) {
  245. sleep (1);
  246. $firstInteraction = false;
  247. }
  248. }
  249. }
  250. }
  251.  
  252. if(file_exists("$command_path/$conn_imei")){
  253. $send_cmd = file_get_contents("$command_path/$conn_imei");
  254. if($send_cmd == 'shutdown'){
  255. unlink("$command_path/$conn_imei");
  256. socket_shutdown($socket, 2);
  257. }
  258. }
  259. # Some pacing to ensure we don't split any incoming data.
  260. sleep (1);
  261.  
  262. # Timeout the socket if it's not talking...
  263. # Prevents duplicate connections, confusing the send commands
  264. $loopcount++;
  265. if ($loopcount > 120) return;
  266.  
  267. #remove any whitespace from ends of string.
  268.  
  269. if ($rec != "") {
  270.  
  271. $isGt06 = false;
  272. $tempString = $rec."";
  273. //verifica se é gt06
  274. $retTracker = hex_dump($rec."");
  275. $arCommands = explode(' ',trim($retTracker));
  276. if(count($arCommands) > 0){
  277. if($arCommands[0].$arCommands[1] == '7878'){
  278. $isGt06 = true;
  279. }
  280. }
  281.  
  282. if($isGt06){
  283. $arCommands = explode(' ',$retTracker);
  284. $tmpArray = array_count_values($arCommands);
  285.  
  286. $count = $tmpArray[78];
  287. $count = $count / 2;
  288.  
  289. $tmpArCommand = array();
  290. if($count >= 1){
  291. $ar = array();
  292. for($i=0;$i<count($arCommands);$i++){
  293. if(strtoupper(trim($arCommands[$i]))=="78" && isset($arCommands[$i+1]) && strtoupper(trim($arCommands[$i+1])) == "78"){
  294. $ar = array();
  295. if(strlen($arCommands[$i]) == 4){
  296. $ar[] = substr($arCommands[$i],0,2);
  297. $ar[] = substr($arCommands[$i],2,2);
  298. } else {
  299. $ar[] = $arCommands[$i];
  300. }
  301. } elseif(isset($arCommands[$i+1]) && strtoupper(trim($arCommands[$i+1]))=="78" && strtoupper(trim($arCommands[$i]))!="78" && isset($arCommands[$i+2]) && strtoupper(trim($arCommands[$i+2]))=="78"){
  302. if(strlen($arCommands[$i]) == 4){
  303. $ar[] = substr($arCommands[$i],0,2);
  304. $ar[] = substr($arCommands[$i],2,2);
  305. } else {
  306. $ar[] = $arCommands[$i];
  307. }
  308. $tmpArCommand[] = $ar;
  309. } elseif($i == count($arCommands)-1){
  310. if(strlen($arCommands[$i]) == 4){
  311. $ar[] = substr($arCommands[$i],0,2);
  312. $ar[] = substr($arCommands[$i],2,2);
  313. } else {
  314. $ar[] = $arCommands[$i];
  315. }
  316. $tmpArCommand[] = $ar;
  317. } else {
  318. if(strlen($arCommands[$i]) == 4){
  319. $ar[] = substr($arCommands[$i],0,2);
  320. $ar[] = substr($arCommands[$i],2,2);
  321. } else {
  322. $ar[] = $arCommands[$i];
  323. }
  324. }
  325. }
  326. }
  327. for($i=0;$i<count($tmpArCommand);$i++) {
  328. $arCommands = $tmpArCommand[$i];
  329. $sizeData = $arCommands[2];
  330.  
  331. $protocolNumber = strtoupper(trim($arCommands[3]));
  332.  
  333. if($protocolNumber == '01'){
  334. $imei = '';
  335.  
  336. for($i=4; $i<12; $i++){
  337. $imei = $imei.$arCommands[$i];
  338. }
  339. $imei = substr($imei,1,15);
  340. $conn_imei = $imei;
  341.  
  342. abrirArquivoLog($imei);
  343.  
  344. $sendCommands = array();
  345.  
  346. $send_cmd = '78 78 05 01 '.strtoupper($arCommands[12]).' '.strtoupper($arCommands[13]);
  347.  
  348. atualizarBemSerial($conn_imei, strtoupper($arCommands[12]).' '.strtoupper($arCommands[13]));
  349.  
  350. $newString = '';
  351. $newString = chr(0x05).chr(0x01).$rec[12].$rec[13];
  352. $crc16 = GetCrc16($newString,strlen($newString));
  353. $crc16h = floor($crc16/256);
  354. $crc16l = $crc16 - $crc16h*256;
  355.  
  356. $crc = dechex($crc16h).' '.dechex($crc16l);
  357.  
  358. $send_cmd = $send_cmd. ' ' . $crc . ' 0D 0A';
  359.  
  360. $sendCommands = explode(' ', $send_cmd);
  361.  
  362. printLog($fh, date("d-m-y h:i:sa") . " Imei: $imei Got: ".implode(" ",$arCommands));
  363. printLog($fh, date("d-m-y h:i:sa") . " Imei: $imei Sent: $send_cmd Length: ".strlen($send_cmd));
  364.  
  365. $send_cmd = '';
  366. for($i=0; $i<count($sendCommands); $i++){
  367. $send_cmd .= chr(hexdec(trim($sendCommands[$i])));
  368. }
  369. socket_send($socket, $send_cmd, strlen($send_cmd), 0);
  370. } else if ($protocolNumber == '12') {
  371. printLog($fh, date("d-m-y h:i:sa") . " Imei: $imei Got: ".implode(" ",$arCommands));
  372. $dataPosition = hexdec($arCommands[4]).'-'.hexdec($arCommands[5]).'-'.hexdec($arCommands[6]).' '.hexdec($arCommands[7]).':'.hexdec($arCommands[8]).':'.hexdec($arCommands[9]);
  373. $gpsQuantity = $arCommands[10];
  374. $lengthGps = hexdec(substr($gpsQuantity,0,1));
  375. $satellitesGps = hexdec(substr($gpsQuantity,1,1));
  376. $latitudeHemisphere = '';
  377. $longitudeHemisphere = '';
  378. $speed = hexdec($arCommands[19]);
  379.  
  380. if(isset($arCommands[20]) && isset($arCommands[21])){
  381. $course = decbin(hexdec($arCommands[20]));
  382. while(strlen($course) < 8) $course = '0'.$course;
  383.  
  384. $status = decbin(hexdec($arCommands[21]));
  385. while(strlen($status) < 8) $status = '0'.$status;
  386. $courseStatus = $course.$status;
  387.  
  388. $gpsRealTime = substr($courseStatus, 2,1) == '0' ? 'F':'D';
  389. $gpsPosition = substr($courseStatus, 3,1) == '0' ? 'F':'L';
  390. //$gpsPosition = 'S';
  391. $gpsPosition == 'F' ? 'S' : 'N';
  392. $latitudeHemisphere = substr($courseStatus, 5,1) == '0' ? 'S' : 'N';
  393. $longitudeHemisphere = substr($courseStatus, 4,1) == '0' ? 'E' : 'W';
  394. }
  395. $latHex = hexdec($arCommands[11].$arCommands[12].$arCommands[13].$arCommands[14]);
  396. $lonHex = hexdec($arCommands[15].$arCommands[16].$arCommands[17].$arCommands[18]);
  397.  
  398. $latitudeDecimalDegrees = ($latHex*90)/162000000;
  399. $longitudeDecimalDegrees = ($lonHex*180)/324000000;
  400.  
  401. $latitudeHemisphere == 'S' && $latitudeDecimalDegrees = $latitudeDecimalDegrees*-1;
  402. $longitudeHemisphere == 'W' && $longitudeDecimalDegrees = $longitudeDecimalDegrees*-1;
  403. if(isset($arCommands[30]) && isset($arCommands[30])){
  404. atualizarBemSerial($conn_imei, strtoupper($arCommands[30]).' '.strtoupper($arCommands[31]));
  405. } else {
  406. echo 'Imei: '.$imei.' Got:'.$retTracker;
  407. }
  408. $dados = array($gpsPosition,
  409. $latitudeDecimalDegrees,
  410. $longitudeDecimalDegrees,
  411. $latitudeHemisphere,
  412. $longitudeHemisphere,
  413. $speed,
  414. $imei,
  415. $dataPosition,
  416. 'tracker',
  417. '',
  418. 'S',
  419. $gpsRealTime);
  420.  
  421. tratarDados($dados);
  422. // echo "[PROTOCOLO 12] Lat/Long: ".$latitudeDecimalDegrees.", ".$longitudeDecimalDegrees."****************";
  423. } else if ($protocolNumber == '13') { //heatbeat
  424. $terminalInformation = decbin(hexdec($arCommands[4]));
  425. while(strlen($terminalInformation) < 8) $terminalInformation = '0'.$terminalInformation; //00101110
  426. $gasOil = substr($terminalInformation,0,1) == '0' ? 'S' : 'N';
  427. $gpsTrack = substr($terminalInformation,1,1) == '1' ? 'S' : 'N';
  428. $alarm = '';
  429. //78 78 0a 13 05 06 04 00 02 00 18 68 47 0d 0a
  430. //76543210
  431. //00000101
  432. //01234567
  433. switch(substr($terminalInformation,2,3)){
  434. case '100': $alarm = 'help me'; break;
  435. case '011': $alarm = 'low battery'; break;
  436. case '010': $alarm = 'dt'; break;
  437. case '001': $alarm = 'move'; break;
  438. case '000': $alarm = 'tracker'; break;
  439. }
  440.  
  441. $ativo = substr($terminalInformation,7,1) == '1' ? 'S' : 'S';
  442. $charge = substr($terminalInformation,5,1) == '1' ? 'S' : 'N';
  443. $acc = substr($terminalInformation,6,1) == '1' ? 'S' : 'N';
  444. //$defense = substr($terminalInformation,7,1) == '1' ? 'S' : 'N';
  445. $voltageLevel = hexdec($arCommands[5]);
  446. $gsmSignal = hexdec($arCommands[6]);
  447.  
  448. $alarmLanguage = hexdec($arCommands[7]);
  449.  
  450. switch($alarmLanguage){
  451. case 0: $alarm = 'tracker'; break;
  452. case 1: $alarm = 'help me'; break;
  453. case 2: $alarm = 'dt'; break;
  454. case 3: $alarm = 'move'; break;
  455. case 4: $alarm = 'stockade'; break;
  456. case 5: $alarm = 'stockade'; break;
  457. }
  458.  
  459. $sendCommands = array();
  460. if(strlen($arCommands[9]) == 4 && count($arCommands) == 10){
  461. $arCommands[9] = substr($terminalInformation,0,2);
  462. $arCommands[] = substr($terminalInformation,2,2);
  463. }
  464.  
  465. $send_cmd = '78 78 05 13 '.strtoupper($arCommands[9]).' '.strtoupper($arCommands[10]);
  466.  
  467. $newString = '';
  468. $newString = chr(0x05).chr(0x13).$rec[9].$rec[10];
  469. $crc16 = GetCrc16($newString,strlen($newString));
  470. $crc16h = floor($crc16/256);
  471. $crc16l = $crc16 - $crc16h*256;
  472.  
  473. $crc = dechex($crc16h).' '.dechex($crc16l);
  474.  
  475. $send_cmd = $send_cmd. ' ' . $crc . ' 0D 0A';
  476.  
  477. $sendCommands = explode(' ', $send_cmd);
  478.  
  479. atualizarBemSerial($conn_imei, strtoupper($arCommands[9]).' '.strtoupper($arCommands[10]));
  480.  
  481. printLog($fh, date("d-m-y h:i:sa") . " Imei: $imei Got: ".implode(" ",$arCommands));
  482. printLog($fh, date("d-m-y h:i:sa") . " Imei: $imei Sent: $send_cmd Length: ".strlen($send_cmd));
  483. $send_cmd = '';
  484. for($i=0; $i<count($sendCommands); $i++){
  485. $send_cmd .= chr(hexdec(trim($sendCommands[$i])));
  486. }
  487. socket_send($socket, $send_cmd, strlen($send_cmd), 0);
  488.  
  489. $con = mysql_connect("localhost", "user_database", "pass_database");
  490. if($con !== false){
  491. mysql_select_db('tracker', $con);
  492. $res = mysql_query("SELECT * FROM loc_atual WHERE imei = '$imei'", $con);
  493. if($res !== false){
  494. $data = mysql_fetch_assoc($res);
  495. mysql_close($con);
  496. $dados = array($gpsTrack,
  497. $data['latitudeDecimalDegrees'],
  498. $data['longitudeDecimalDegrees'],
  499. $data['latitudeHemisphere'],
  500. $data['longitudeHemisphere'],
  501. 0,
  502. $imei,
  503. date('Y-m-d'),
  504. $alarm,
  505. $acc,
  506. $ativo);
  507.  
  508. tratarDados($dados);
  509. // echo "[PROTOCOLO 13] Lat/Long: ".$data['latitudeDecimalDegrees'].", ".$data['longitudeDecimalDegrees']."****************";
  510. }
  511. }
  512. } else if ($protocolNumber == '15') {
  513. printLog($fh, date("d-m-y h:i:sa") . " Got: $retTracker");
  514. $msg = '';
  515. for($i=9; $i<count($arCommands)-8; $i++){
  516. $msg .= chr(hexdec($arCommands[$i]));
  517. }
  518. $con = mysql_connect("localhost", "user_database", "pass_database");
  519. if($con !== false){
  520. mysql_select_db('tracker', $con);
  521.  
  522. $alerta = '';
  523. if(strpos($msg, 'Already') > -1){
  524. $alerta = 'Bloqueio já efetuado!';
  525. }
  526.  
  527. if(strpos($msg, 'DYD=Suc') > -1){
  528. $alerta = 'Bloqueio efetuado!';
  529. }
  530.  
  531. if(strpos($msg, 'HFYD=Su') > -1){
  532. $alerta = 'Desbloqueio efetuado!';
  533. }
  534.  
  535.  
  536. mysql_query("INSERT INTO message (imei, message) VALUES ('$conn_imei', '$alerta')", $con);
  537. mysql_close($con);
  538. }
  539. } else if ($protocolNumber == '16') {
  540. printLog($fh, date("d-m-y h:i:sa") . " Got: ".implode(" ",$arCommands));
  541. $dataPosition = hexdec($arCommands[4]).'-'.hexdec($arCommands[5]).'-'.hexdec($arCommands[6]).' '.hexdec($arCommands[7]).':'.hexdec($arCommands[8]).':'.hexdec($arCommands[9]);
  542. $gpsQuantity = $arCommands[10];
  543. $lengthGps = hexdec(substr($gpsQuantity,0,1));
  544. $satellitesGps = hexdec(substr($gpsQuantity,1,1));
  545. $latitudeHemisphere = '';
  546. $longitudeHemisphere = '';
  547. $speed = hexdec($arCommands[19]);
  548. $course = decbin(hexdec($arCommands[20]));
  549.  
  550. while(strlen($course) < 8) $course = '0'.$course;
  551. $status = decbin(hexdec($arCommands[21]));
  552. while(strlen($status) < 8) $status = '0'.$status;
  553. $courseStatus = $course.$status;
  554.  
  555. $gpsRealTime = substr($courseStatus, 2,1);
  556. $gpsPosition = substr($courseStatus, 3,1) == '0' ? 'F':'L';
  557. $gpsPosition = 'S';
  558. $latitudeHemisphere = substr($courseStatus, 5,1) == '0' ? 'S' : 'N';
  559. $longitudeHemisphere = substr($courseStatus, 4,1) == '0' ? 'E' : 'W';
  560.  
  561. $latHex = hexdec($arCommands[11].$arCommands[12].$arCommands[13].$arCommands[14]);
  562. $lonHex = hexdec($arCommands[15].$arCommands[16].$arCommands[17].$arCommands[18]);
  563.  
  564. $latitudeDecimalDegrees = ($latHex*90)/162000000;
  565. $longitudeDecimalDegrees = ($lonHex*180)/324000000;
  566.  
  567. $latitudeHemisphere == 'S' && $latitudeDecimalDegrees = $latitudeDecimalDegrees*-1;
  568. $longitudeHemisphere == 'W' && $longitudeDecimalDegrees = $longitudeDecimalDegrees*-1;
  569.  
  570. //78 78 25 16 0e 02 1b 11 11 26 c3 02 73 a8 0c 04 a6 5c 77 02 18 11 09 02 d4 0b 15 91 00 1e 0b 66 01 04 01 02 00 10 fe 67 0d 0a
  571. //66 01100110
  572. $terminalInformation = decbin(hexdec($arCommands[31]));
  573. while(strlen($terminalInformation) < 8) $terminalInformation = '0'.$terminalInformation;
  574. $gasOil = substr($terminalInformation,0,1) == '0' ? 'S' : 'N';
  575. $gpsTrack = substr($terminalInformation,1,1) == '1' ? 'S' : 'N';
  576. $alarm = '';
  577. switch(substr($terminalInformation,2,3)){
  578. case '100': $alarm = 'help me'; break;
  579. case '011': $alarm = 'low battery'; break;
  580. case '010': $alarm = 'dt'; break;
  581. case '001': $alarm = 'move'; break;
  582. case '000': $alarm = 'tracker'; break;
  583. }
  584.  
  585. $con = mysql_connect("localhost", "user_database", "pass_database");
  586. if($con !== false){
  587. mysql_select_db('tracker', $con);
  588. if($alarm == "help me")
  589. mysql_query("INSERT INTO message (imei, message) VALUES ('$conn_imei', 'SOS!')", $con);
  590. mysql_close($con);
  591. }
  592. $charge = substr($terminalInformation,5,1) == '1' ? 'S' : 'N';
  593. $acc = substr($terminalInformation,6,1) == '1' ? 'acc on' : 'acc off';
  594. $defense = substr($terminalInformation,7,1) == '1' ? 'S' : 'N';
  595. $voltageLevel = hexdec($arCommands[32]);
  596. $gsmSignal = hexdec($arCommands[33]);
  597.  
  598. $alarmLanguage = hexdec($arCommands[34]);
  599. /*
  600. switch($alarmLanguage){
  601. case 0: $alarm = 'normal'; break;
  602. case 1: $alarm = 'help me'; break;
  603. case 2: $alarm = 'dt'; break;
  604. case 3: $alarm = 'move'; break;
  605. case 4: $alarm = 'stockade'; break;
  606. case 5: $alarm = 'stockade'; break;
  607. }
  608. */
  609. $dados = array($gpsPosition,
  610. $latitudeDecimalDegrees,
  611. $longitudeDecimalDegrees,
  612. $latitudeHemisphere,
  613. $longitudeHemisphere,
  614. $speed,
  615. $imei,
  616. $dataPosition,
  617. $alarm,
  618. $acc);
  619.  
  620. tratarDados($dados);
  621. // echo "[PROTOCOLO 16] Lat/Long: ".$latitudeDecimalDegrees.", ".$longitudeDecimalDegrees."****************";
  622.  
  623. $send_cmd = '78 78 05 16 '.strtoupper($arCommands[36]).' '.strtoupper($arCommands[37]);
  624.  
  625. //$crc = crcx25('05 16 '.strtoupper($arCommands[36]).' '.strtoupper($arCommands[37]));
  626.  
  627. atualizarBemSerial($conn_imei, strtoupper($arCommands[36]).' '.strtoupper($arCommands[37]));
  628.  
  629. //$crc = str_replace('ffff','',dechex($crc));
  630.  
  631. //$crc = strtoupper(substr($crc,0,2)).' '.strtoupper(substr($crc,2,2));
  632.  
  633. $newString = '';
  634. $newString = chr(0x05).chr(0x16).$rec[36].$rec[37];
  635. $crc16 = GetCrc16($newString,strlen($newString));
  636. $crc16h = floor($crc16/256);
  637. $crc16l = $crc16 - $crc16h*256;
  638.  
  639. $crc = dechex($crc16h).' '.dechex($crc16l);
  640.  
  641. $send_cmd = $send_cmd. ' ' . $crc . ' 0D 0A';
  642.  
  643. $sendCommands = explode(' ', $send_cmd);
  644.  
  645. printLog($fh, date("d-m-y h:i:sa") . " Imei: $imei Sent: $send_cmd Length: ".strlen($send_cmd));
  646. $send_cmd = '';
  647. for($i=0; $i<count($sendCommands); $i++){
  648. $send_cmd .= chr(hexdec(trim($sendCommands[$i])));
  649. }
  650. socket_send($socket, $send_cmd, strlen($send_cmd), 0);
  651. } else if ($protocolNumber == '1A') {
  652. printLog($fh, date("d-m-y h:i:sa") . " Got: ".implode(" ",$arCommands));
  653. } else if ($protocolNumber == '80') {
  654. printLog($fh, date("d-m-y h:i:sa") . " Got: ".implode(" ",$arCommands));
  655. }
  656. }
  657. }
  658. }
  659. $rec = "";
  660. } //while
  661.  
  662. } //fim interact
  663.  
  664. /**
  665. * Become a daemon by forking and closing the parent
  666. */
  667. function become_daemon() {
  668. GLOBAL $fh;
  669.  
  670. //printLog($fh, "pcntl_fork() in");
  671. $pid = pcntl_fork();
  672. //printLog($fh, "pcntl_fork() out");
  673.  
  674. if ($pid == -1) {
  675. /* fork failed */
  676. //printLog($fh, "fork failure!");
  677. exit();
  678. } elseif ($pid) {
  679. //printLog($fh, "pid: " . $pid);
  680. /* close the parent */
  681. exit();
  682. } else {
  683. /* child becomes our daemon */
  684. posix_setsid();
  685. chdir('/');
  686. umask(0);
  687. return posix_getpid();
  688. }
  689.  
  690. //printLog($fh, "become_daemon() fim");
  691. }
  692.  
  693. function gprsToGps($cord, $hemisphere){
  694. $novaCord = 0;
  695. strlen($cord) == 9 && $cord = '0'.$cord;
  696. $g = substr($cord,0,3);
  697. $d = substr($cord,3);
  698. $novaCord = $g + ($d/60);
  699. $novaCord = ($hemisphere == "S" || $hemisphere == "W") ? $novaCord * -1 : $novaCord ;
  700. return $novaCord;
  701. }
  702.  
  703. function sendSMS($contato, $mensagem, $remetente){
  704. $cnx = mysql_connect("localhost", "user_database", "pass_database")
  705. or die("Could not connect: " . mysql_error());
  706. mysql_select_db('tracker', $cnx);
  707. $res = mysql_query("select valor from preferencias where nome = 'url_sms'", $cnx);
  708. $data = mysql_fetch_assoc($res);
  709. $url = $data['valor'];
  710.  
  711. $res = mysql_query("select valor from preferencias where nome = 'usuario_sms'", $cnx);
  712. $data = mysql_fetch_assoc($res);
  713. $usuario = $data['valor'];
  714.  
  715. $res = mysql_query("select valor from preferencias where nome = 'senha_sms'", $cnx);
  716. $data = mysql_fetch_assoc($res);
  717. $senha = $data['valor'];
  718.  
  719. $res = mysql_query("select valor from preferencias where nome = 'de_sms'", $cnx);
  720. $data = mysql_fetch_assoc($res);
  721. $de = $data['valor'];
  722. file_get_contents($url."usr=".$usuario."&pwd=".$senha."&number=55".$contato."&sender=".$de."&msg=$mensagem");
  723. }
  724.  
  725. function enviaEmail($destinatario, $assunto, $msgConteudo){
  726. require_once '/var/www/phpmailer/class.phpmailer.php';
  727. require_once '/var/www/config.php';
  728. // Inicia a classe PHPMailer
  729. $mail = new PHPMailer();
  730.  
  731. // Define os dados do servidor e tipo de conexão
  732. // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  733. $mail->IsSMTP(); // Define que a mensagem será SMTP
  734. $mail->Host = HOST_SMTP; // Endereço do servidor SMTP
  735. $mail->SMTPAuth = AUTENT_SMTP; // Usa autenticação SMTP? (opcional)
  736. $mail->Username = USER_SMTP; // Usuário do servidor SMTP
  737. $mail->Password = SENHA_SMTP; // Senha do servidor SMTP
  738.  
  739. // Define o remetente
  740. // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  741. $mail->From = USER_SMTP; // Seu e-mail
  742. $mail->FromName = "InovarSat"; // Seu nome
  743.  
  744. // Define os destinatário(s)
  745. // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  746. $mail->AddAddress($destinatario);
  747. $mail->AddAddress('teste@provedor.com.br');
  748.  
  749. // Define os dados técnicos da Mensagem
  750. // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  751. $mail->IsHTML(true); // Define que o e-mail será enviado como HTML
  752. $mail->CharSet = 'utf-8'; // Charset da mensagem (opcional)
  753. $mail->setLanguage('br', '/var/www/phpmailer/language/');
  754.  
  755. // Define a mensagem (Texto e Assunto)
  756. // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  757. $mail->Subject = $assunto; // Assunto da mensagem
  758. $mail->Body = $msgConteudo;
  759. $mail->AltBody = strip_tags($msgConteudo);
  760.  
  761. // Define os anexos (opcional)
  762. // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  763.  
  764. // Envia o e-mail
  765. $enviado = $mail->Send();
  766.  
  767. // Limpa os destinatários e os anexos
  768. $mail->ClearAllRecipients();
  769. $mail->ClearAttachments();
  770.  
  771. // Exibe uma mensagem de resultado
  772. if ($enviado) {
  773. echo "E-mail enviado com sucesso! (" . $msgConteudo . ")";
  774. } else {
  775. echo "Não foi possível enviar o e-mail ($assunto). " . $mail->ErrorInfo;
  776. }
  777. }
  778.  
  779. /**
  780. * [checkAlerta Verifica se já foi emitido um alerta do mesmo tipo para aquele dia]
  781. * @param [int] $imei [IMEI do Rastreador]
  782. * @param [string] $mensagem [Título total ou parcial do nome ao qual se deseja buscar]
  783. * @return [boolean] [TRUE - se já houver alertas | FALSE - se não houver alertas]
  784. */
  785. function checkAlerta($imei, $mensagem){
  786. $cnx = mysql_connect("localhost", "user_database", "pass_database") or die("Could not connect: " . mysql_error());
  787. mysql_select_db('tracker', $cnx);
  788. $res = mysql_query("SELECT message, DATE_FORMAT(date, '%d/%m/%Y') AS data FROM message WHERE imei = $imei AND viewed = 'N' ", $cnx);
  789.  
  790. if (mysql_num_rows($res) > 0) {
  791. $data = date("d/m/Y");
  792. while ($alerta = mysql_fetch_array($res)) {
  793. if ( $alerta['data'] == $data && (stripos($mensagem, $alerta['message']) !== false) ) return true;
  794. }
  795. }
  796. else return false;
  797. }
  798.  
  799. /*function distance($lat1, $lon1, $lat2, $lon2, $unit) {
  800.  
  801. $theta = $lon1 - $lon2;
  802. $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
  803. $dist = acos($dist);
  804. $dist = rad2deg($dist);
  805. $miles = $dist * 60 * 1.1515;
  806. $unit = strtoupper($unit);
  807.  
  808. if ($unit == "K") {
  809. return ($miles * 1.609344);
  810. } else if ($unit == "N") {
  811. return ($miles * 0.8684);
  812. } else {
  813. return $miles;
  814. }
  815. }*/
  816.  
  817. function distance($lat1, $lng1, $lat2, $lng2, $miles = false){
  818. $pi80 = M_PI / 180;
  819. $lat1 *= $pi80;
  820. $lng1 *= $pi80;
  821. $lat2 *= $pi80;
  822. $lng2 *= $pi80;
  823.  
  824. $r = 6372.797; // mean radius of Earth in km
  825. $dlat = $lat2 - $lat1;
  826. $dlng = $lng2 - $lng1;
  827. $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlng / 2) * sin($dlng / 2);
  828. $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
  829. $km = $r * $c;
  830.  
  831. return ($miles ? ($km * 0.621371192) : $km);
  832. }
  833.  
  834. function strToHex($string){
  835. $hex = '';
  836. for ($i=0; $i<strlen($string); $i++){
  837. $ord = ord($string[$i]);
  838. $hexCode = dechex($ord);
  839. $hex .= substr('0'.$hexCode, -2);
  840. }
  841. return strToUpper($hex);
  842. }
  843. function hexToStr($hex){
  844. $string='';
  845. for ($i=0; $i < strlen($hex)-1; $i+=2){
  846. $string .= chr(hexdec($hex[$i].$hex[$i+1]));
  847. }
  848. return $string;
  849. }
  850.  
  851. function hex2str($hex) {
  852. for($i=0;$i<strlen($hex);$i+=2) $str .= chr(hexdec(substr($hex,$i,2)));
  853. return $str;
  854. }
  855.  
  856. function bin2string($bin) {
  857. $res = "";
  858. for($p=31; $p >= 0; $p--) {
  859. $res .= ($bin & (1 << $p)) ? "1" : "0";
  860. }
  861. return $res;
  862. }
  863. function teste($input){
  864. $output = '';
  865. foreach( explode( "\n", $input) as $line) {
  866. if( preg_match( '/(?:[a-f0-9]{2}\s){1,16}/i', $line, $matches)) {
  867. $output .= ' ' . $matches[0];
  868. }
  869. }
  870. return $output;
  871. }
  872.  
  873. function ascii2hex($ascii) {
  874. $hex = '';
  875. for ($i = 0; $i < strlen($ascii); $i++) {
  876. $byte = strtoupper(dechex(ord($ascii{$i})));
  877. $byte = str_repeat('0', 2 - strlen($byte)).$byte;
  878. $hex.=$byte." ";
  879. }
  880. return $hex;
  881. }
  882.  
  883.  
  884. function hexStringToString($hex) {
  885. return pack('H*', $hex);
  886. }
  887.  
  888. function hex_dump($data, $newline="\n")
  889. {
  890. static $from = '';
  891. static $to = '';
  892.  
  893. static $width = 50; # number of bytes per line
  894.  
  895. static $pad = '.'; # padding for non-visible characters
  896.  
  897. if ($from==='')
  898. {
  899. for ($i=0; $i<=0xFF; $i++)
  900. {
  901. $from .= chr($i);
  902. $to .= ($i >= 0x20 && $i <= 0x7E) ? chr($i) : $pad;
  903. }
  904. }
  905.  
  906. $hex = str_split(bin2hex($data), $width*2);
  907. $chars = str_split(strtr($data, $from, $to), $width);
  908.  
  909. $offset = 0;
  910. $retorno = '';
  911. foreach ($hex as $i => $line)
  912. {
  913. $retorno .= implode(' ', str_split($line,2));
  914. $offset += $width;
  915. }
  916. return $retorno;
  917. //sprintf($retorno);
  918. }
  919.  
  920. function crcx25($data) {
  921. //i explode() $data and make $content array
  922. $content = explode(' ',$data) ;
  923. //i count() the array to get data length
  924. $len = count($content) ;
  925. $n = 0 ;
  926.  
  927. $crc = 0xFFFF;
  928. while ($len > 0)
  929. {
  930. $crc ^= hexdec($content[$n]);
  931. for ($i=0; $i<8; $i++) {
  932. if ($crc & 1) $crc = ($crc >> 1) ^ 0x8408;
  933. else $crc >>= 1;
  934. }
  935. $n++ ;
  936. $len-- ;
  937. }
  938.  
  939. return(~$crc);
  940. }
  941.  
  942. function tratarDados($dados){
  943. $con = mysql_connect("localhost", "user_database", "pass_database");
  944. if($con !== false){
  945. mysql_select_db('tracker', $con);
  946.  
  947. $gpsSignalIndicator = 'F';
  948. $latitudeDecimalDegrees = $dados[1];
  949. $longitudeDecimalDegrees = $dados[2];
  950. $latitudeHemisphere = $dados[3];
  951. $longitudeHemisphere = $dados[4];
  952. $speed = $dados[5];
  953. $imei = $dados[6];
  954. $satelliteFixStatus = 'A';
  955. $phone = '';
  956. $infotext = $dados[8];
  957. $dataBem = null;
  958. $dataCliente = null;
  959. $ligado = (count($dados) > 9) ? $dados[9] : 'N';
  960. $ativo = (count($dados) > 10) ? $dados[10] : 'N';
  961. $realTime = (count($dados) > 11) ? $dados[11] : '';
  962. //D para diferencial
  963.  
  964. $gpsSignalIndicator = $dados[0] == 'S' ? 'F' : 'L';
  965. /*
  966. if($realTime == 'D')
  967. $gpsSignalIndicator = 'D';
  968. else
  969. $gpsSignalIndicator = 'R';
  970. */
  971. $resBem = mysql_query("SELECT id, cliente, envia_sms, name, hodometro, alerta_hodometro, alerta_hodometro_saldo, limite_velocidade FROM bem WHERE imei = '$imei'", $con);
  972. //echo 'Ligado: '.$ligado;
  973. $dataBem = mysql_fetch_assoc($resBem);
  974.  
  975. if($resBem !== false){
  976.  
  977. $resCliente = mysql_query("SELECT id, celular, dt_ultm_sms, envia_sms, sms_acada, hour(TIMEDIFF(now(), dt_ultm_sms)) horas, minute(TIMEDIFF(now(), dt_ultm_sms)) minutos, nome, email FROM cliente WHERE id = ".$dataBem['cliente'], $con);
  978. if($resCliente !== false){
  979. $dataCliente = mysql_fetch_assoc($resCliente);
  980.  
  981. $texto_sms_localiza = "";
  982. $texto_sms_alerta_hodometro = "";
  983. $texto_sms_alerta = "";
  984.  
  985. $result = mysql_query("SELECT * FROM preferencias", $con);
  986. if(mysql_num_rows($result) > 0){
  987. while ($dataPref = mysql_fetch_assoc($result)){
  988. if($dataPref['nome'] == 'texto_sms_localiza')
  989. $texto_sms_localiza = $dataPref['valor'];
  990.  
  991. if($dataPref['nome'] == 'texto_sms_alerta_hodometro')
  992. $texto_sms_alerta_hodometro = $dataPref['valor'];
  993.  
  994. if($dataPref['nome'] == 'texto_sms_alerta')
  995. $texto_sms_alerta = $dataPref['valor'];
  996. }
  997. }
  998.  
  999. $movimento = '';
  1000. if ($speed > 0){
  1001. $movimento = 'S';
  1002. if ($dataBem['limite_velocidade'] != "0" && $dataBem['limite_velocidade'] != null && $speed > $dataBem['limite_velocidade']) {
  1003. if (!checkAlerta($imei, 'Limite Velocidade')) {
  1004. mysql_query("INSERT INTO message (imei, message) VALUES ('$imei', 'Limite Velocidade')", $con);
  1005. $msgEmail = "<p><b>Alerta de Limite de Velocidade: </b></p><br><p>O veículo ". $dataBem['name'] ." está trafegando com velocidade de ". $speed ." Km/h, ultrapassando o limite de velocidade definido (".$dataBem['limite_velocidade']." Km/h) em ". date("d/m/Y") . " às " . date("H:i:s") .".</p><br><i>Equipe InovarSat</i>";
  1006. enviaEmail($dataCliente['email'], "Alerta de Limite de Velocidade", $msgEmail);
  1007. }
  1008. }
  1009. }
  1010. else $movimento = 'N';
  1011.  
  1012. // CERCA VIRTUAL
  1013. if ( $imei != "" ) {
  1014. $consulta = mysql_query("SELECT * FROM geo_fence WHERE imei = '$imei'", $con);
  1015. while($data = mysql_fetch_assoc($consulta)) {
  1016. $idCerca = $data['id'];
  1017. $imeiCerca = $data['imei'];
  1018. $nomeCerca = $data['nome'];
  1019. $coordenadasCerca = $data['coordenadas'];
  1020. $resultCerca = $data['tipo'];
  1021. $tipoEnvio = $data['tipoEnvio'];
  1022.  
  1023. $lat_point = $latitudeDecimalDegrees;
  1024. $lng_point = $longitudeDecimalDegrees;
  1025.  
  1026. $exp = explode("|", $coordenadasCerca);
  1027.  
  1028. if( count($exp) < 5 ) {
  1029. $strExp = explode(",", $exp[0]);
  1030. $strExp1 = explode(",", $exp[2]);
  1031. } else {
  1032. $int = (count($exp)) / 2;
  1033. $strExp = explode(",", $exp[0]);
  1034. $strExp1 = explode(",", $exp[$int]);
  1035. }
  1036.  
  1037. $lat_vertice_1 = $strExp[0];
  1038. $lng_vertice_1 = $strExp[1];
  1039. $lat_vertice_2 = $strExp1[0];
  1040. $lng_vertice_2 = $strExp1[1];
  1041.  
  1042. if ( $lat_vertice_1 < $lat_point Or $lat_point < $lat_vertice_2 And $lng_point < $lng_vertice_1 Or $lng_vertice_2 < $lng_point ) {
  1043. $result = '0';
  1044. $situacao = 'fora';
  1045. } else {
  1046. $result = '1';
  1047. $situacao = 'dentro';
  1048. }
  1049.  
  1050. if ( $result == 0 And $movimento == 'S' ) {
  1051.  
  1052. if (!checkAlerta($imei, 'Cerca Violada')){
  1053. mysql_query("INSERT INTO message (imei, message) VALUES ('$imei', 'Cerca Violada')", $con);
  1054.  
  1055. if ( $tipoEnvio == 0 ) {
  1056. # Convert the GPS coordinates to a human readable address
  1057. /*$tempstr = "http://maps.google.com/maps/geo?q=$lat_point,$lng_point&oe=utf-8&sensor=true&key=ABQIAAAAFd56B-wCWVpooPPO7LR3ihTz-K-sFZ2BISbybur6B4OYOOGbdRShvXwdlYvbnwC38zgCx2up86CqEg&output=csv"; //output = csv, xml, kml, json
  1058. $rev_geo_str = file_get_contents($tempstr);
  1059. $rev_geo_str = preg_replace("/\"/","", $rev_geo_str);
  1060. $rev_geo = explode(',', $rev_geo_str);
  1061. $logradouro = $rev_geo[2] .",". $rev_geo[3] ;*/
  1062.  
  1063. /*$consulta1 = mysql_query("SELECT a.*, b.* FROM cliente a INNER JOIN bem b ON a.id = b.cliente WHERE b.imei = '$imei'", $con);
  1064.  
  1065. while($data = mysql_fetch_assoc($consulta1)) {
  1066. $emailDestino = $data['email'];
  1067. $nameBem = $data['name'];
  1068. $msgEmail = "<p><b>Alerta de Violação de Perímetro:</b></p><br><p>O veículo ". $nameBem .", está ". $situacao ." do perímetro ". $nomeCerca .", as ". date("H:i:s") ." do dia ". date("d/m/Y") . ".</p><br><i>Equipe InovarSat</i>";
  1069. enviaEmail($emailDestino, "Alerta de Violação de Perímetro", $msgEmail);
  1070. }*/
  1071. $json = json_decode(file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=".$lat_point.",".$lng_point."&sensor=false"));
  1072. if ( isset( $json->status ) && $json->status == 'OK') {
  1073. $address = $json->results[0]->formatted_address;
  1074. $address = utf8_decode($address);
  1075. }
  1076. //else echo $json->status;
  1077.  
  1078. $emailDestino = $dataCliente['email'];
  1079. $nameBem = $dataBem['name'];
  1080. $msgEmail = "<p><b>Alerta de Violação de Perímetro: </b></p><br><p>O veículo ". $nameBem .", está ". $situacao ." do perímetro ". $nomeCerca .", transitando na " . $address . " às ". date("H:i:s") ." do dia ". date("d/m/Y") . ".</p><br><i>Equipe InovarSat</i>";
  1081. enviaEmail($emailDestino, "Alerta de Violação de Perímetro", $msgEmail);
  1082. }
  1083. }
  1084. }
  1085. }
  1086. }//FIM CERCA VIRTUAL
  1087.  
  1088.  
  1089. # Write it to the database...
  1090. if ($gpsSignalIndicator != 'L' && !empty($latitudeDecimalDegrees)) {
  1091.  
  1092. $gpsLat = $latitudeDecimalDegrees;//gprsToGps($latitudeDecimalDegrees, $latitudeHemisphere)
  1093. $gpsLon = $longitudeDecimalDegrees;//gprsToGps($longitudeDecimalDegrees, $longitudeHemisphere)
  1094. $gpsLatAnt = 0;
  1095. $gpsLatHemAnt = '';
  1096. $gpsLonAnt = 0;
  1097. $gpsLonHemAnt = '';
  1098. $alertaACadaSaldo = 0;
  1099.  
  1100. $resLocAtual = mysql_query("SELECT id, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere FROM loc_atual WHERE imei = '$imei' LIMIT 1", $con);
  1101. $numRows = mysql_num_rows($resLocAtual);
  1102.  
  1103. if($numRows == 0){
  1104. mysql_query("INSERT INTO loc_atual (date, imei, phone, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator, converte, ligado) VALUES (now(), '$imei', '$phone', '$satelliteFixStatus', '$latitudeDecimalDegrees', '$latitudeHemisphere', '$longitudeDecimalDegrees', '$longitudeHemisphere', '$speed', '$infotext', '$gpsSignalIndicator', 0, '$ligado')", $con);
  1105. } else {
  1106. mysql_query("UPDATE loc_atual SET date = now(), phone = '$phone', satelliteFixStatus = '$satelliteFixStatus', latitudeDecimalDegrees = '$latitudeDecimalDegrees', latitudeHemisphere = '$latitudeHemisphere', longitudeDecimalDegrees = '$longitudeDecimalDegrees', longitudeHemisphere = '$longitudeHemisphere', speed = '$speed', infotext = '$infotext', gpsSignalIndicator = '$gpsSignalIndicator', converte = 0, ligado = '$ligado' WHERE imei = '$imei'", $con);
  1107. }
  1108.  
  1109. $distance = 0;
  1110. try{
  1111. $bemId = $dataBem['id'];
  1112. $countGeoDistance = mysql_query("SELECT bem FROM geo_distance WHERE bem = $bemId", $con);
  1113. if($countGeoDistance === false || mysql_num_rows($countGeoDistance) == 0) {
  1114. mysql_query("INSERT INTO geo_distance (bem, tipo) VALUES($bemId, 'I')", $con);
  1115. mysql_query("INSERT INTO geo_distance (bem, tipo) VALUES($bemId, 'F')", $con);
  1116. }
  1117.  
  1118. /*envio de sms*/
  1119. if($dataCliente['envia_sms'] == 'S' && $dataBem['envia_sms'] == 'S' && !empty($dataCliente['celular']) && !empty($dataCliente['sms_acada'])){
  1120. if(empty($dataCliente['dt_ultm_sms'])){
  1121. mysql_query("UPDATE cliente SET dt_ultm_sms = now() WHERE id = " . $dataCliente['id'],$con);
  1122. } else {
  1123. $horas = $dataCliente['horas'];
  1124. $minutos = $dataCliente['minutos'];
  1125. if(!empty($horas))
  1126. $horas = $horas * 60;
  1127. $tempoTotal = $horas+$minutos;
  1128. if($tempoTotal > $dataCliente['sms_acada']){
  1129. $json = json_decode(file_get_contents("http://maps.google.com/maps/api/geocode/json?sensor=false&latlng=$gpsLat,$gpsLon&language=es-ES"));
  1130. if ( isset( $json->status ) && $json->status == 'OK' && isset($json->results[0]->formatted_address)) {
  1131. $address = $json->results[0]->formatted_address;
  1132. $address = utf8_decode($address);
  1133. $aDataCliente = split(' ', $dataCliente['nome']);
  1134. $msg = $texto_sms_localiza;
  1135. $msg = str_replace("#CLIENTE", $aDataCliente[0], $msg);
  1136. $msg = str_replace("#VEICULO", $dataBem['name'], $msg);
  1137. $msg = str_replace("#LOCALIZACAO", $address, $msg);
  1138. $msg = str_replace(' ', '+', $msg);
  1139. sendSMS($dataCliente['celular'], $msg, '');
  1140. if($retorno < 0) mysql_query("INSERT INTO controle(texto) VALUES('envio de sms retorno: $retorno')",$con);
  1141. else mysql_query("UPDATE cliente SET dt_ultm_sms = now() WHERE id = " . $dataCliente['id'],$con);
  1142. }
  1143. }
  1144. }
  1145. }
  1146.  
  1147. if($movimento == 'S'){
  1148. $resGeoDistance = mysql_query("SELECT parou FROM geo_distance WHERE bem = $bemId AND tipo = 'I'", $con);
  1149. if($resGeoDistance !== false) {
  1150. $dataGeoDistance = mysql_fetch_assoc($resGeoDistance);
  1151. if($dataGeoDistance['parou'] == 'S' || empty($dataGeoDistance['parou'])){
  1152. mysql_query("UPDATE geo_distance SET latitudeDecimalDegrees = '$latitudeDecimalDegrees', latitudeHemisphere = '$latitudeHemisphere', longitudeDecimalDegrees = '$longitudeDecimalDegrees', longitudeHemisphere = '$longitudeHemisphere', parou = 'N' WHERE bem = $bemId AND tipo = 'I'", $con);
  1153. }
  1154. }
  1155. } else {
  1156. $resGeoDistance = mysql_query("SELECT latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere FROM geo_distance WHERE bem = $bemId AND tipo = 'I'", $con);
  1157. if(mysql_num_rows($resGeoDistance) > 0){
  1158. $update = mysql_query("UPDATE geo_distance SET latitudeDecimalDegrees = '$latitudeDecimalDegrees', latitudeHemisphere = '$latitudeHemisphere', longitudeDecimalDegrees = '$longitudeDecimalDegrees', longitudeHemisphere = '$longitudeHemisphere', parou = 'S' WHERE bem = $bemId AND tipo = 'I'", $con);
  1159. $dataGeoDistance = mysql_fetch_assoc($resGeoDistance);
  1160. $gpsLatAnt = (!strstr($dataGeoDistance['latitudeDecimalDegrees'], "-")) ? gprsToGps($dataGeoDistance['latitudeDecimalDegrees'], $dataGeoDistance['latitudeHemisphere']) : $dataGeoDistance['latitudeDecimalDegrees'] ;
  1161. $gpsLonAnt = (!strstr($dataGeoDistance['longitudeDecimalDegrees'], "-")) ? gprsToGps($dataGeoDistance['longitudeDecimalDegrees'], $dataGeoDistance['longitudeHemisphere']) : $dataGeoDistance['longitudeDecimalDegrees'] ;
  1162.  
  1163. // $gpsLatAnt = gprsToGps($dataGeoDistance['latitudeDecimalDegrees'], $dataGeoDistance['latitudeHemisphere']); //$dataGeoDistance['latitudeDecimalDegrees'];
  1164. // $gpsLonAnt = gprsToGps($dataGeoDistance['longitudeDecimalDegrees'], $dataGeoDistance['longitudeHemisphere']); //$dataGeoDistance['longitudeDecimalDegrees'];
  1165. if($gpsLatAnt != $gpsLat) {
  1166. if($gpsLatAnt != 0 && $gpsLonAnt != 0){
  1167.  
  1168. $geoDistance = distance($gpsLatAnt, $gpsLonAnt, $gpsLat, $gpsLon);
  1169. //$strDistance = $json->rows[0]->elements[0]->distance->value;
  1170. $distance = (int) $geoDistance;//(int)($geoDistance*1000)
  1171. //echo "******************************IMEI: ". $imei ." | Lat/Long Antiga: ". $gpsLatAnt . ", ". $gpsLonAnt ." | Lat/Long Atual: ". $gpsLat .", ". $gpsLon ." | Geodistance : ". $geoDistance ." | Inteiro: ". $distance ."<br>";
  1172.  
  1173. $alertaACada = $dataBem['alerta_hodometro'];
  1174. $alertaACadaSaldo = $dataBem['alerta_hodometro_saldo'];
  1175. $alertaACadaSaldo = $alertaACadaSaldo - $distance;
  1176.  
  1177. if($alertaACadaSaldo <= 0 && $alertaACada > 0){
  1178. $msg = $texto_sms_alerta_hodometro;
  1179. $msg = str_replace("#CLIENTE", $dataCliente['nome'], $msg);
  1180. $msg = str_replace("#VEICULO", $dataBem['name'], $msg);
  1181. $msg = str_replace("#HODOMETRO", $alertaACada, $msg);
  1182. $msg = str_replace(' ', '+', $msg);
  1183. //sendSMS($dataCliente['celular'], $msg, '');
  1184. $msgEmail = "<p><b>Quilometragem atingida: </b></p><br><p>O veículo ". $dataBem['name'] ." atingiu a quilometragem de ". $dataBem['hodometro'] ."Km rodados às ". date("H:i:s") ." do dia ". date("d/m/Y") . ".</p><br><i>Equipe InovarSat</i>";
  1185. //echo $msgEmail;
  1186. // enviaEmail($dataCliente['email'], 'Hodômetro - Quilometragem Atingida', $msgEmail);
  1187. $alertaACadaSaldo = $alertaACada;
  1188. }
  1189. // $alertaACadaSaldo = (int)$alertaACadaSaldo;//(int)$alertaACadaSaldo/1000
  1190. }
  1191. }
  1192. }
  1193. }
  1194. }catch(Exception $e){
  1195. mysql_query("INSERT INTO controle (texto) VALUES ($e->getMessage())", $con);
  1196. }
  1197. if(!empty($latitudeDecimalDegrees)){
  1198. mysql_query("INSERT INTO gprmc (date, imei, phone, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator, km_rodado, converte, ligado) VALUES (now(), '$imei', '$phone', '$satelliteFixStatus', '$latitudeDecimalDegrees', '$latitudeHemisphere', '$longitudeDecimalDegrees', '$longitudeHemisphere', '$speed', '$infotext', '$gpsSignalIndicator', $distance, 0, '$ligado')", $con);
  1199. }
  1200.  
  1201. if($alertaACadaSaldo == 0) {
  1202. mysql_query("UPDATE bem set date = now(), status_sinal = 'R', movimento = '$movimento', hodometro = hodometro+$distance WHERE imei = '$imei'", $con);
  1203. } else {
  1204. mysql_query("UPDATE bem set date = now(), status_sinal = 'R', movimento = '$movimento', hodometro = hodometro+$distance, alerta_hodometro_saldo = $alertaACadaSaldo WHERE imei = '$imei'", $con);
  1205. }
  1206. /*
  1207. if($numRows == 0){
  1208. mysql_query("INSERT INTO loc_atual (date, imei, phone, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator) VALUES (now(), '$imei', '$phone', '$satelliteFixStatus', '$latitudeDecimalDegrees', '$latitudeHemisphere', '$longitudeDecimalDegrees', '$longitudeHemisphere', '$speed', '$infotext', '$gpsSignalIndicator')", $cnx);
  1209. } else {
  1210. mysql_query("UPDATE loc_atual set date = now(), phone = '$phone', satelliteFixStatus = '$satelliteFixStatus', latitudeDecimalDegrees = '$latitudeDecimalDegrees', latitudeHemisphere = '$latitudeHemisphere', longitudeDecimalDegrees = '$longitudeDecimalDegrees', longitudeHemisphere = '$longitudeHemisphere', speed = '$speed', infotext = '$infotext', gpsSignalIndicator = '$gpsSignalIndicator' where imei = '$imei'", $cnx);
  1211. }
  1212. */
  1213. } else {
  1214. $resLocAtual = mysql_query("SELECT id, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere FROM loc_atual WHERE imei = '$imei' LIMIT 1", $con);
  1215. $numRows = mysql_num_rows($resLocAtual);
  1216.  
  1217. if($numRows == 0){
  1218. mysql_query("INSERT INTO loc_atual (date, imei, phone, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator, converte, ligado) VALUES (now(), '$imei', '$phone', '$satelliteFixStatus', '$latitudeDecimalDegrees', '$latitudeHemisphere', '$longitudeDecimalDegrees', '$longitudeHemisphere', '$speed', '$infotext', '$gpsSignalIndicator', 0, '$ligado')", $con);
  1219. } else {
  1220. mysql_query("UPDATE loc_atual SET date = now(), phone = '$phone', satelliteFixStatus = '$satelliteFixStatus', latitudeDecimalDegrees = '$latitudeDecimalDegrees', latitudeHemisphere = '$latitudeHemisphere', longitudeDecimalDegrees = '$longitudeDecimalDegrees', longitudeHemisphere = '$longitudeHemisphere', speed = '$speed', infotext = '$infotext', gpsSignalIndicator = '$gpsSignalIndicator', converte = 0, ligado = '$ligado' WHERE imei = '$imei'", $con);
  1221. }
  1222. if(!empty($latitudeDecimalDegrees)){
  1223. mysql_query("INSERT INTO gprmc (date, imei, phone, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator, km_rodado, converte, ligado) VALUES (now(), '$imei', '$phone', '$satelliteFixStatus', '$latitudeDecimalDegrees', '$latitudeHemisphere', '$longitudeDecimalDegrees', '$longitudeHemisphere', '$speed', '$infotext', '$gpsSignalIndicator', 0, 0, '$ligado')", $con);
  1224. }
  1225. mysql_query("UPDATE bem set date = now(), status_sinal = 'S' WHERE imei = '$imei'", $con);
  1226. }
  1227.  
  1228. if(!empty($ligado)){
  1229. mysql_query("UPDATE bem SET ligado = '$ligado' where imei = '$imei'", $con);
  1230. }
  1231.  
  1232.  
  1233. # Now check to see if we need to send any alerts.
  1234. if ($infotext != "tracker") {
  1235. $msg = $texto_sms_alerta;
  1236. $msg = str_replace("#CLIENTE", $dataCliente['nome'], $msg);
  1237. $msg = str_replace("#VEICULO", $dataBem['name'], $msg);
  1238.  
  1239. $res = mysql_query("SELECT responsible FROM bem WHERE imei='$imei'", $con);
  1240. while($data = mysql_fetch_assoc($res)) {
  1241. switch ($infotext) {
  1242. case "dt":
  1243. if (!checkAlerta($imei, 'Rastreador Desat.')) {
  1244. $body = "Disable Track OK";
  1245. $msg = str_replace("#TIPOALERTA", "Rastreador Desabilitado", $msg);
  1246. mysql_query("INSERT INTO message (imei, message) VALUES ('$imei', 'Rastreador Desat.')", $con);
  1247. }
  1248. break;
  1249.  
  1250. case "et":
  1251. if (!checkAlerta($imei, 'Alarme Parado')) {
  1252. $body = "Stop Alarm OK";
  1253. $msg = str_replace("#TIPOALERTA", "Alarme parado", $msg);
  1254. mysql_query("INSERT INTO message (imei, message) VALUES ('$imei', 'Alarme Parado')", $con);
  1255. }
  1256. break;
  1257.  
  1258. case "gt";
  1259. if (!checkAlerta($imei, 'Alarme Movimento')) {
  1260. $body = "Move Alarm set OK";
  1261. $msg = str_replace("#TIPOALERTA", "Alarme de Movimento ativado", $msg);
  1262. mysql_query("INSERT INTO message (imei, message) VALUES ('$imei', 'Alarme Movimento')", $con);
  1263. }
  1264. break;
  1265.  
  1266. case "help me":
  1267. if (!checkAlerta($imei, 'SOS!')) {
  1268. $body = "Help!";
  1269. mysql_query("INSERT INTO message (imei, message) VALUES ('$imei', 'SOS!')", $con);
  1270. $msg = str_replace("#TIPOALERTA", "SOS", $msg);
  1271. }
  1272.  
  1273. //Envia comando de resposta: alerta recebido
  1274. //$send_cmd = "**,imei:". $conn_imei .",E";
  1275. //socket_send($socket, $send_cmd, strlen($send_cmd), 0);
  1276. //printLog($fh, "Comando de resposta (help me): " . $send_cmd . " imei: " . $conn_imei);
  1277. break;
  1278.  
  1279. case "ht":
  1280. if (!checkAlerta($imei, 'Alarme Velocidade')) {
  1281. $body = "Speed alarm set OK";
  1282. $msg = str_replace("#TIPOALERTA", "Alarme de velocidade ativado", $msg);
  1283. mysql_query("INSERT INTO message (imei, message) VALUES ('$imei', 'Alarme Velocidade')", $con);
  1284. }
  1285. break;
  1286.  
  1287. case "it":
  1288. $body = "Timezone set OK";
  1289. break;
  1290.  
  1291. case "low battery":
  1292. if (!checkAlerta($imei, 'Bateria Fraca')) {
  1293. $body = "Low battery!\nYou have about 2 minutes...";
  1294. $msg = str_replace("#TIPOALERTA", "Bateria fraca, voce tem 2 minutos", $msg);
  1295. mysql_query("INSERT INTO message (imei, message) VALUES ('$imei', 'Bateria Fraca')", $con);
  1296. }
  1297. //Envia comando de resposta: alerta recebido
  1298. $send_cmd = "**,imei:". $conn_imei .",E";
  1299. socket_send($socket, $send_cmd, strlen($send_cmd), 0);
  1300. //printLog($fh, "Comando de resposta (low battery): " . $send_cmd . " imei: " . $conn_imei);
  1301. break;
  1302.  
  1303. case "move":
  1304. if (!checkAlerta($imei, 'Movimento')) {
  1305. $body = "Move Alarm!";
  1306. $msg = str_replace("#TIPOALERTA", "Seu veiculo esta em movimento", $msg);
  1307. mysql_query("INSERT INTO message (imei, message) VALUES ('$imei', 'Movimento')", $con);
  1308. }
  1309. //Envia comando de resposta: alerta recebido
  1310. $send_cmd = "**,imei:". $conn_imei .",E";
  1311. socket_send($socket, $send_cmd, strlen($send_cmd), 0);
  1312. //printLog($fh, "Comando de resposta (move): " . $send_cmd . " imei: " . $conn_imei);
  1313. break;
  1314.  
  1315. case "nt":
  1316. $body = "Returned to SMS mode OK";
  1317. break;
  1318.  
  1319. case "speed":
  1320. if (!checkAlerta($imei, 'Velocidade')) {
  1321. $body = "Speed alarm!";
  1322. $msg = str_replace("#TIPOALERTA", "Seu veiculo ultrapassou o limite de velocidade", $msg);
  1323. mysql_query("INSERT INTO message (imei, message) VALUES ('$imei', 'Velocidade')", $con);
  1324. }
  1325. //Envia comando de resposta: alerta recebido
  1326. $send_cmd = "**,imei:". $conn_imei .",E";
  1327. socket_send($socket, $send_cmd, strlen($send_cmd), 0);
  1328. //printLog($fh, "Comando de resposta (speed): " . $send_cmd . " imei: " . $conn_imei);
  1329. break;
  1330.  
  1331. case "stockade":
  1332. if (!checkAlerta($imei, 'Cerca')) {
  1333. $body = "Geofence Violation!";
  1334. $msg = str_replace("#TIPOALERTA", "Seu veiculo saiu da cerca virtual", $msg);
  1335. mysql_query("INSERT INTO message (imei, message) VALUES ('$imei', 'Cerca')", $con);
  1336. }
  1337. //Envia comando de resposta: alerta recebido
  1338. $send_cmd = "**,imei:". $conn_imei .",E";
  1339. socket_send($socket, $send_cmd, strlen($send_cmd), 0);
  1340. //printLog($fh, "Comando de resposta (stockade): " . $send_cmd . " imei: " . $conn_imei);
  1341. break;
  1342.  
  1343. case "door alarm":
  1344. if (!checkAlerta($imei, 'Porta')) {
  1345. $body = "Open door!";
  1346. mysql_query("INSERT INTO message (imei, message) VALUES ('$imei', 'Porta')", $con);
  1347. }
  1348. //Envia comando de resposta: alerta recebido
  1349. $send_cmd = "**,imei:". $conn_imei .",E";
  1350. socket_send($socket, $send_cmd, strlen($send_cmd), 0);
  1351. //printLog($fh, "Comando de resposta (door alarm): " . $send_cmd . " imei: " . $conn_imei);
  1352. break;
  1353.  
  1354. case "acc alarm":
  1355. if (!checkAlerta($imei, 'Alarme Disparado')) {
  1356. $body = "ACC alarm!";
  1357. $msg = str_replace("#TIPOALERTA", "Alarme disparado", $msg);
  1358. mysql_query("INSERT INTO message (imei, message) VALUES ('$imei', 'Alarme Disparado')", $con);
  1359. }
  1360. //Envia comando de resposta: alerta recebido
  1361. $send_cmd = "**,imei:". $conn_imei .",E";
  1362. socket_send($socket, $send_cmd, strlen($send_cmd), 0);
  1363. //printLog($fh, "Comando de resposta (acc alarm): " . $send_cmd . " imei: " . $conn_imei);
  1364. break;
  1365.  
  1366. case "acc off":
  1367. $body = "Ignicao Desligada!";
  1368. $msg = str_replace("#TIPOALERTA", "Seu veiculo esta com a chave desligada", $msg);
  1369. //mysql_query("INSERT INTO message (imei, message) VALUES ('$imei', 'Ignição')", $cnx);
  1370. mysql_query("UPDATE bem SET ligado = 'N' where imei = '$imei'", $con);
  1371. //Envia comando de resposta: alerta recebido
  1372. $send_cmd = "**,imei:". $conn_imei .",E";
  1373. socket_send($socket, $send_cmd, strlen($send_cmd), 0);
  1374. //printLog($fh, "Comando de resposta (acc alarm): " . $send_cmd . " imei: " . $conn_imei);
  1375. break;
  1376.  
  1377. case "acc on":
  1378. $body = "Ignicao Ligada!";
  1379. $msg = str_replace("#TIPOALERTA", "Seu veiculo esta com a chave ligada", $msg);
  1380. //mysql_query("INSERT INTO message (imei, message) VALUES ('$imei', 'Ignição')", $cnx);
  1381. mysql_query("UPDATE bem SET ligado = 'S' where imei = '$imei'", $cnx);
  1382. //Envia comando de resposta: alerta recebido
  1383. $send_cmd = "**,imei:". $conn_imei .",E";
  1384. socket_send($socket, $send_cmd, strlen($send_cmd), 0);
  1385. //printLog($fh, "Comando de resposta (acc alarm): " . $send_cmd . " imei: " . $conn_imei);
  1386. break;
  1387. } //switch
  1388. $msg = str_replace(' ', '+', $msg);
  1389. //if($dataCliente['envia_sms'] == 'S' && $dataBem['envia_sms'] == 'S' && $infotext != 'acc on'&& $infotext != 'acc off' && $infotext != 'et')
  1390. // sendSMS($dataCliente['celular'], $msg, '');
  1391. //Enviando e-mail de alerta
  1392.  
  1393. /*$headers = "From: $email_from" . "\r\n" . "Reply-To: $email_from" . "\r\n";
  1394. $responsible = $data['responsible'];
  1395. $rv = mail($responsible, "Tracker - $imei", $body, $headers);*/
  1396.  
  1397. if (isset($body)) {
  1398. enviaEmail($dataCliente['email'], "Rastreador - $imei", $body);
  1399. }
  1400.  
  1401. } //while
  1402. }
  1403. }else {
  1404. echo 'Cliente não encontrado. Erro: '.mysql_error($con);
  1405. }
  1406. } else {
  1407. echo 'Veículo não encontrado. Erro: '.mysql_error($con);
  1408. }
  1409. mysql_close($con);
  1410. } else {
  1411. echo 'Não foi possivel conectar ao banco. Erro: '.mysql_error();
  1412. }
  1413. }
  1414.  
  1415. function atualizarBemSerial($imei, $serial){
  1416. $con = mysql_connect("localhost", "user_database", "pass_database");
  1417. if($con !== false){
  1418. mysql_select_db('tracker', $con);
  1419.  
  1420. mysql_query("UPDATE bem SET serial_tracker = '$serial' WHERE imei = '$imei'", $con);
  1421.  
  1422. mysql_close($con);
  1423. } else {
  1424. echo "Erro: ".mysql_error($con);
  1425. }
  1426. }
  1427.  
  1428. function recuperaBemSerial($imei){
  1429. $con = mysql_connect("localhost", "user_database", "pass_database");
  1430. $serial = '';
  1431. if($con !== false){
  1432. mysql_select_db('tracker', $con);
  1433.  
  1434. $res = mysql_query("select serial_tracker from bem where imei = '$imei'", $con);
  1435. if($res !== false){
  1436. $dataRes = mysql_fetch_assoc($res);
  1437. $serial = $dataRes['serial_tracker'];
  1438. }
  1439. mysql_close($con);
  1440. }
  1441. return $serial;
  1442. }
  1443.  
  1444. function trataCommand($send_cmd, $conn_imei){
  1445. $sizeData = 0;
  1446. $serial = recuperaBemSerial($conn_imei);
  1447.  
  1448. $serial = str_replace(' ', '', $serial);
  1449.  
  1450. $decSerial = hexdec($serial);
  1451.  
  1452. $decSerial = $decSerial+1;
  1453.  
  1454. if($decSerial > 65535){
  1455. $decSerial = 1;
  1456. }
  1457.  
  1458. $serial = dechex($decSerial);
  1459.  
  1460. while(strlen($serial) < 4) $serial = '0'.$serial;
  1461.  
  1462. $serial = substr($serial, 0, 2).' '.substr($serial, 2, 2);
  1463.  
  1464. $sizeData = dechex(11 + strlen($send_cmd));
  1465.  
  1466. while(strlen($sizeData) < 2) $sizeData = '0'.$sizeData;
  1467.  
  1468. $lengthCommand = dechex(4+strlen($send_cmd));
  1469.  
  1470. while(strlen($lengthCommand) < 2) $lengthCommand = '0'.$lengthCommand;
  1471.  
  1472. $temp = $sizeData.' 80 '.$lengthCommand.' 00 00 00 00 '.$send_cmd.' '.$serial;
  1473.  
  1474. $sendCommands = array();
  1475.  
  1476. $crc = crcx25($temp);
  1477.  
  1478. $crc = str_replace('ffff','',dechex($crc));
  1479.  
  1480. $crc = strtoupper(substr($crc,0,2)).' '.strtoupper(substr($crc,2,2));
  1481.  
  1482. $sendcmd = '78 78 '.$temp. ' ' . $crc . ' 0D 0A';
  1483.  
  1484. $sendCommands = explode(' ', $sendcmd);
  1485.  
  1486. $sendcmd = '';
  1487. for($i=0; $i<count($sendCommands); $i++){
  1488. if($i < 9 || $i >=10){
  1489. $sendcmd .= chr(hexdec(trim($sendCommands[$i])));
  1490. } else {
  1491. $sendcmd .= trim($sendCommands[$i]);
  1492. }
  1493. }
  1494.  
  1495. return $sendcmd;
  1496. }
  1497.  
  1498.  
  1499. function GetCrc16($pData, $nLength) {
  1500. $crctab16 = array(
  1501. 0X0000, 0X1189, 0X2312, 0X329B, 0X4624, 0X57AD, 0X6536, 0X74BF,
  1502. 0X8C48, 0X9DC1, 0XAF5A, 0XBED3, 0XCA6C, 0XDBE5, 0XE97E, 0XF8F7,
  1503. 0X1081, 0X0108, 0X3393, 0X221A, 0X56A5, 0X472C, 0X75B7, 0X643E,
  1504. 0X9CC9, 0X8D40, 0XBFDB, 0XAE52, 0XDAED, 0XCB64, 0XF9FF, 0XE876,
  1505. 0X2102, 0X308B, 0X0210, 0X1399, 0X6726, 0X76AF, 0X4434, 0X55BD,
  1506. 0XAD4A, 0XBCC3, 0X8E58, 0X9FD1, 0XEB6E, 0XFAE7, 0XC87C, 0XD9F5,
  1507. 0X3183, 0X200A, 0X1291, 0X0318, 0X77A7, 0X662E, 0X54B5, 0X453C,
  1508. 0XBDCB, 0XAC42, 0X9ED9, 0X8F50, 0XFBEF, 0XEA66, 0XD8FD, 0XC974,
  1509. 0X4204, 0X538D, 0X6116, 0X709F, 0X0420, 0X15A9, 0X2732, 0X36BB,
  1510. 0XCE4C, 0XDFC5, 0XED5E, 0XFCD7, 0X8868, 0X99E1, 0XAB7A, 0XBAF3,
  1511. 0X5285, 0X430C, 0X7197, 0X601E, 0X14A1, 0X0528, 0X37B3, 0X263A,
  1512. 0XDECD, 0XCF44, 0XFDDF, 0XEC56, 0X98E9, 0X8960, 0XBBFB, 0XAA72,
  1513. 0X6306, 0X728F, 0X4014, 0X519D, 0X2522, 0X34AB, 0X0630, 0X17B9,
  1514. 0XEF4E, 0XFEC7, 0XCC5C, 0XDDD5, 0XA96A, 0XB8E3, 0X8A78, 0X9BF1,
  1515. 0X7387, 0X620E, 0X5095, 0X411C, 0X35A3, 0X242A, 0X16B1, 0X0738,
  1516. 0XFFCF, 0XEE46, 0XDCDD, 0XCD54, 0XB9EB, 0XA862, 0X9AF9, 0X8B70,
  1517. 0X8408, 0X9581, 0XA71A, 0XB693, 0XC22C, 0XD3A5, 0XE13E, 0XF0B7,
  1518. 0X0840, 0X19C9, 0X2B52, 0X3ADB, 0X4E64, 0X5FED, 0X6D76, 0X7CFF,
  1519. 0X9489, 0X8500, 0XB79B, 0XA612, 0XD2AD, 0XC324, 0XF1BF, 0XE036,
  1520. 0X18C1, 0X0948, 0X3BD3, 0X2A5A, 0X5EE5, 0X4F6C, 0X7DF7, 0X6C7E,
  1521. 0XA50A, 0XB483, 0X8618, 0X9791, 0XE32E, 0XF2A7, 0XC03C, 0XD1B5,
  1522. 0X2942, 0X38CB, 0X0A50, 0X1BD9, 0X6F66, 0X7EEF, 0X4C74, 0X5DFD,
  1523. 0XB58B, 0XA402, 0X9699, 0X8710, 0XF3AF, 0XE226, 0XD0BD, 0XC134,
  1524. 0X39C3, 0X284A, 0X1AD1, 0X0B58, 0X7FE7, 0X6E6E, 0X5CF5, 0X4D7C,
  1525. 0XC60C, 0XD785, 0XE51E, 0XF497, 0X8028, 0X91A1, 0XA33A, 0XB2B3,
  1526. 0X4A44, 0X5BCD, 0X6956, 0X78DF, 0X0C60, 0X1DE9, 0X2F72, 0X3EFB,
  1527. 0XD68D, 0XC704, 0XF59F, 0XE416, 0X90A9, 0X8120, 0XB3BB, 0XA232,
  1528. 0X5AC5, 0X4B4C, 0X79D7, 0X685E, 0X1CE1, 0X0D68, 0X3FF3, 0X2E7A,
  1529. 0XE70E, 0XF687, 0XC41C, 0XD595, 0XA12A, 0XB0A3, 0X8238, 0X93B1,
  1530. 0X6B46, 0X7ACF, 0X4854, 0X59DD, 0X2D62, 0X3CEB, 0X0E70, 0X1FF9,
  1531. 0XF78F, 0XE606, 0XD49D, 0XC514, 0XB1AB, 0XA022, 0X92B9, 0X8330,
  1532. 0X7BC7, 0X6A4E, 0X58D5, 0X495C, 0X3DE3, 0X2C6A, 0X1EF1, 0X0F78,
  1533. );
  1534. $fcs = 0xffff;
  1535. $i = 0;
  1536. while($nLength>0){
  1537. $fcs = ($fcs >> 8) ^ $crctab16[($fcs ^ ord($pData{$i})) & 0xff];
  1538. $nLength--;
  1539. $i++;
  1540. }
  1541. return ~$fcs & 0xffff;
  1542. }
  1543. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement