示例#1
1
function interact($socket)
{
    global $fh;
    global $command_path;
    global $firstInteraction;
    global $remip;
    global $remport;
    global $imei;
    $loopcount = 0;
    $conn_imei = "";
    /* TALK TO YOUR CLIENT */
    $rec = "";
    // Variavel que indica se comando est� em banco ou arquivo.
    $tipoComando = "banco";
    //"arquivo";
    //Checando o protocolo
    $isGIMEI = false;
    $isGPRMC = false;
    $send_cmd = "";
    $last_status = "";
    # Read the socket but don't wait for data..
    while (@socket_recv($socket, $rec, 2048, 0x40) !== 0) {
        //if($last_status != ''){
        //	  socket_send($socket, $last_status, strlen($last_status), 0);
        // }
        # If we know the imei of the phone and there is a pending command send it.
        if ($conn_imei != "") {
            if ($tipoComando == "arquivo" and file_exists("{$command_path}/{$conn_imei}")) {
                $send_cmd = file_get_contents("{$command_path}/{$conn_imei}");
                /**/
                $sendcmd = trataCommand($send_cmd, $conn_imei);
                socket_send($socket, $sendcmd, strlen($sendcmd), 0);
                unlink("{$command_path}/{$conn_imei}");
                printLog($fh, "Arquivo de comandos apagado: " . $sendcmd . " imei: " . $conn_imei);
            } else {
                if ($tipoComando == "banco" and file_exists("{$command_path}/{$conn_imei}")) {
                    //Conecta e pega o comando pendente
                    $cnx = mysql_connect("cloudservice.cgejdsdl842e.sa-east-1.rds.amazonaws.com", "gpstracker", "d1\$1793689") or die("Could not connect: " . mysql_error());
                    mysql_select_db('tracker', $cnx);
                    $res = mysql_query("SELECT c.command FROM command c WHERE c.imei = '{$conn_imei}' ORDER BY date DESC LIMIT 1", $cnx);
                    $sendcmd = '';
                    while ($data = mysql_fetch_assoc($res)) {
                        $sendcmd = trataCommand($data['command'], $conn_imei);
                    }
                    // Deletando comando
                    //mysql_query("DELETE FROM command WHERE imei = $conn_imei");
                    socket_send($socket, $sendcmd, strlen($sendcmd), 0);
                    mysql_close($cnx);
                    unlink("{$command_path}/{$conn_imei}");
                    printLog($fh, "Comandos do arquivo apagado: " . $sendcmd . " imei: " . $conn_imei);
                } else {
                    //Se nao tiver comando na fila e for a primeira iteracao, obtem o ultimo comando v�lido enviado
                    if ($firstInteraction == true) {
                        sleep(1);
                        $firstInteraction = false;
                    }
                }
            }
        }
        if (file_exists("{$command_path}/{$conn_imei}")) {
            $send_cmd = file_get_contents("{$command_path}/{$conn_imei}");
            if ($send_cmd == 'shutdown') {
                unlink("{$command_path}/{$conn_imei}");
                socket_shutdown($socket, 2);
            }
        }
        # Some pacing to ensure we don't split any incoming data.
        sleep(1);
        # Timeout the socket if it's not talking...
        # Prevents duplicate connections, confusing the send commands
        $loopcount++;
        if ($loopcount > 120) {
            return;
        }
        #remove any whitespace from ends of string.
        if ($rec != "") {
            $isGt06 = false;
            $tempString = $rec . "";
            //verifica se é gt06
            $retTracker = hex_dump($rec . "");
            $arCommands = explode(' ', trim($retTracker));
            if (count($arCommands) > 0) {
                if ($arCommands[0] . $arCommands[1] == '7878') {
                    $isGt06 = true;
                }
            }
            if ($isGt06) {
                $arCommands = explode(' ', $retTracker);
                $tmpArray = array_count_values($arCommands);
                $count = $tmpArray[78];
                $count = $count / 2;
                $tmpArCommand = array();
                if ($count >= 1) {
                    $ar = array();
                    for ($i = 0; $i < count($arCommands); $i++) {
                        if (strtoupper(trim($arCommands[$i])) == "78" && isset($arCommands[$i + 1]) && strtoupper(trim($arCommands[$i + 1])) == "78") {
                            $ar = array();
                            if (strlen($arCommands[$i]) == 4) {
                                $ar[] = substr($arCommands[$i], 0, 2);
                                $ar[] = substr($arCommands[$i], 2, 2);
                            } else {
                                $ar[] = $arCommands[$i];
                            }
                        } 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") {
                            if (strlen($arCommands[$i]) == 4) {
                                $ar[] = substr($arCommands[$i], 0, 2);
                                $ar[] = substr($arCommands[$i], 2, 2);
                            } else {
                                $ar[] = $arCommands[$i];
                            }
                            $tmpArCommand[] = $ar;
                        } elseif ($i == count($arCommands) - 1) {
                            if (strlen($arCommands[$i]) == 4) {
                                $ar[] = substr($arCommands[$i], 0, 2);
                                $ar[] = substr($arCommands[$i], 2, 2);
                            } else {
                                $ar[] = $arCommands[$i];
                            }
                            $tmpArCommand[] = $ar;
                        } else {
                            if (strlen($arCommands[$i]) == 4) {
                                $ar[] = substr($arCommands[$i], 0, 2);
                                $ar[] = substr($arCommands[$i], 2, 2);
                            } else {
                                $ar[] = $arCommands[$i];
                            }
                        }
                    }
                }
                for ($i = 0; $i < count($tmpArCommand); $i++) {
                    $arCommands = $tmpArCommand[$i];
                    $sizeData = $arCommands[2];
                    $protocolNumber = strtoupper(trim($arCommands[3]));
                    if ($protocolNumber == '01') {
                        $imei = '';
                        for ($i = 4; $i < 12; $i++) {
                            $imei = $imei . $arCommands[$i];
                        }
                        $imei = substr($imei, 1, 15);
                        $conn_imei = $imei;
                        abrirArquivoLog($imei);
                        $sendCommands = array();
                        $send_cmd = '78 78 05 01 ' . strtoupper($arCommands[12]) . ' ' . strtoupper($arCommands[13]);
                        atualizarBemSerial($conn_imei, strtoupper($arCommands[12]) . ' ' . strtoupper($arCommands[13]));
                        $newString = '';
                        $newString = chr(0x5) . chr(0x1) . $rec[12] . $rec[13];
                        $crc16 = GetCrc16($newString, strlen($newString));
                        $crc16h = floor($crc16 / 256);
                        $crc16l = $crc16 - $crc16h * 256;
                        $crc = dechex($crc16h) . ' ' . dechex($crc16l);
                        //$crc = crcx25('05 '.$protocolNumber.' '.strtoupper($arCommands[12]).' '.strtoupper($arCommands[13]));
                        //$crc = str_replace('ffff','',dechex($crc));
                        //$crc = strtoupper(substr($crc,0,2)).' '.strtoupper(substr($crc,2,2));
                        $send_cmd = $send_cmd . ' ' . $crc . ' 0D 0A';
                        $sendCommands = explode(' ', $send_cmd);
                        printLog($fh, date("d-m-y h:i:sa") . " Imei: {$imei} Got: " . implode(" ", $arCommands));
                        printLog($fh, date("d-m-y h:i:sa") . " Imei: {$imei} Sent: {$send_cmd} Length: " . strlen($send_cmd));
                        $send_cmd = '';
                        for ($i = 0; $i < count($sendCommands); $i++) {
                            $send_cmd .= chr(hexdec(trim($sendCommands[$i])));
                        }
                        socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                    } else {
                        if ($protocolNumber == '12') {
                            printLog($fh, date("d-m-y h:i:sa") . " Imei: {$imei} Got: " . implode(" ", $arCommands));
                            $dataPosition = hexdec($arCommands[4]) . '-' . hexdec($arCommands[5]) . '-' . hexdec($arCommands[6]) . ' ' . hexdec($arCommands[7]) . ':' . hexdec($arCommands[8]) . ':' . hexdec($arCommands[9]);
                            $gpsQuantity = $arCommands[10];
                            $lengthGps = hexdec(substr($gpsQuantity, 0, 1));
                            $satellitesGps = hexdec(substr($gpsQuantity, 1, 1));
                            $latitudeHemisphere = '';
                            $longitudeHemisphere = '';
                            $speed = hexdec($arCommands[19]);
                            //78 78 1f 12 0e 05 1e 10 19 05 c4 01 2c 74 31 03 fa b2 b2 07 18 ab 02 d4 0b 00 b3 00 24 73 00 07 5b 59 0d 0a
                            //18 ab
                            //0001100010101011
                            //01 2b af f6
                            //03 fa 37 88
                            if (isset($arCommands[20]) && isset($arCommands[21])) {
                                $course = decbin(hexdec($arCommands[20]));
                                while (strlen($course) < 8) {
                                    $course = '0' . $course;
                                }
                                $status = decbin(hexdec($arCommands[21]));
                                while (strlen($status) < 8) {
                                    $status = '0' . $status;
                                }
                                $courseStatus = $course . $status;
                                $gpsRealTime = substr($courseStatus, 2, 1) == '0' ? 'F' : 'D';
                                $gpsPosition = substr($courseStatus, 3, 1) == '0' ? 'F' : 'L';
                                //$gpsPosition = 'S';
                                $gpsPosition == 'F' ? 'S' : 'N';
                                $latitudeHemisphere = substr($courseStatus, 5, 1) == '0' ? 'S' : 'N';
                                $longitudeHemisphere = substr($courseStatus, 4, 1) == '0' ? 'E' : 'W';
                            }
                            $latHex = hexdec($arCommands[11] . $arCommands[12] . $arCommands[13] . $arCommands[14]);
                            $lonHex = hexdec($arCommands[15] . $arCommands[16] . $arCommands[17] . $arCommands[18]);
                            $latitudeDecimalDegrees = $latHex * 90 / 162000000;
                            $longitudeDecimalDegrees = $lonHex * 180 / 324000000;
                            $latitudeHemisphere == 'S' && ($latitudeDecimalDegrees = $latitudeDecimalDegrees * -1);
                            $longitudeHemisphere == 'W' && ($longitudeDecimalDegrees = $longitudeDecimalDegrees * -1);
                            if (isset($arCommands[30]) && isset($arCommands[30])) {
                                atualizarBemSerial($conn_imei, strtoupper($arCommands[30]) . ' ' . strtoupper($arCommands[31]));
                            } else {
                                echo 'Imei: ' . $imei . ' Got:' . $retTracker;
                            }
                            $dados = array($gpsPosition, $latitudeDecimalDegrees, $longitudeDecimalDegrees, $latitudeHemisphere, $longitudeHemisphere, $speed, $imei, $dataPosition, 'tracker', '', 'S', $gpsRealTime);
                            tratarDados($dados);
                            // echo "[PROTOCOLO 12] Lat/Long: ".$latitudeDecimalDegrees.", ".$longitudeDecimalDegrees."****************";
                        } else {
                            if ($protocolNumber == '13') {
                                //heatbeat
                                $terminalInformation = decbin(hexdec($arCommands[4]));
                                while (strlen($terminalInformation) < 8) {
                                    $terminalInformation = '0' . $terminalInformation;
                                }
                                //00101110
                                $gasOil = substr($terminalInformation, 0, 1) == '0' ? 'S' : 'N';
                                $gpsTrack = substr($terminalInformation, 1, 1) == '1' ? 'S' : 'N';
                                $alarm = '';
                                //78 78 0a 13 05 06 04 00 02 00 18 68 47 0d 0a
                                //76543210
                                //00000101
                                //0d1$17936897
                                switch (substr($terminalInformation, 2, 3)) {
                                    case '100':
                                        $alarm = 'help me';
                                        break;
                                    case '011':
                                        $alarm = 'low battery';
                                        break;
                                    case '010':
                                        $alarm = 'dt';
                                        break;
                                    case '001':
                                        $alarm = 'move';
                                        break;
                                    case '000':
                                        $alarm = 'tracker';
                                        break;
                                }
                                $ativo = substr($terminalInformation, 7, 1) == '1' ? 'S' : 'S';
                                $charge = substr($terminalInformation, 5, 1) == '1' ? 'S' : 'N';
                                $acc = substr($terminalInformation, 6, 1) == '1' ? 'S' : 'N';
                                //$defense = substr($terminalInformation,7,1) == '1' ? 'S' : 'N';
                                $voltageLevel = hexdec($arCommands[5]);
                                $gsmSignal = hexdec($arCommands[6]);
                                $alarmLanguage = hexdec($arCommands[7]);
                                switch ($alarmLanguage) {
                                    case 0:
                                        $alarm = 'tracker';
                                        break;
                                    case 1:
                                        $alarm = 'help me';
                                        break;
                                    case 2:
                                        $alarm = 'dt';
                                        break;
                                    case 3:
                                        $alarm = 'move';
                                        break;
                                    case 4:
                                        $alarm = 'stockade';
                                        break;
                                    case 5:
                                        $alarm = 'stockade';
                                        break;
                                }
                                $sendCommands = array();
                                if (strlen($arCommands[9]) == 4 && count($arCommands) == 10) {
                                    $arCommands[9] = substr($terminalInformation, 0, 2);
                                    $arCommands[] = substr($terminalInformation, 2, 2);
                                }
                                $send_cmd = '78 78 05 13 ' . strtoupper($arCommands[9]) . ' ' . strtoupper($arCommands[10]);
                                $newString = '';
                                $newString = chr(0x5) . chr(0x13) . $rec[9] . $rec[10];
                                $crc16 = GetCrc16($newString, strlen($newString));
                                $crc16h = floor($crc16 / 256);
                                $crc16l = $crc16 - $crc16h * 256;
                                $crc = dechex($crc16h) . ' ' . dechex($crc16l);
                                //$crc = crcx25('05 13 '.strtoupper($arCommands[9]).' '.strtoupper($arCommands[10]));
                                //$crc = str_replace('ffff','',dechex($crc));
                                //$crc = strtoupper(substr($crc,0,2)).' '.strtoupper(substr($crc,2,2));
                                $send_cmd = $send_cmd . ' ' . $crc . ' 0D 0A';
                                $sendCommands = explode(' ', $send_cmd);
                                atualizarBemSerial($conn_imei, strtoupper($arCommands[9]) . ' ' . strtoupper($arCommands[10]));
                                printLog($fh, date("d-m-y h:i:sa") . " Imei: {$imei} Got: " . implode(" ", $arCommands));
                                printLog($fh, date("d-m-y h:i:sa") . " Imei: {$imei} Sent: {$send_cmd} Length: " . strlen($send_cmd));
                                $send_cmd = '';
                                for ($i = 0; $i < count($sendCommands); $i++) {
                                    $send_cmd .= chr(hexdec(trim($sendCommands[$i])));
                                }
                                socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                                $con = mysql_connect("cloudservice.cgejdsdl842e.sa-east-1.rds.amazonaws.com", "gpstracker", "d1\$1793689");
                                if ($con !== false) {
                                    mysql_select_db('tracker', $con);
                                    $res = mysql_query("SELECT * FROM loc_atual WHERE imei = '{$imei}'", $con);
                                    if ($res !== false) {
                                        $data = mysql_fetch_assoc($res);
                                        mysql_close($con);
                                        $dados = array($gpsTrack, $data['latitudeDecimalDegrees'], $data['longitudeDecimalDegrees'], $data['latitudeHemisphere'], $data['longitudeHemisphere'], 0, $imei, date('Y-m-d'), $alarm, $acc, $ativo);
                                        tratarDados($dados);
                                        // echo "[PROTOCOLO 13] Lat/Long: ".$data['latitudeDecimalDegrees'].", ".$data['longitudeDecimalDegrees']."****************";
                                    }
                                }
                            } else {
                                if ($protocolNumber == '15') {
                                    printLog($fh, date("d-m-y h:i:sa") . " Got: {$retTracker}");
                                    $msg = '';
                                    for ($i = 9; $i < count($arCommands) - 8; $i++) {
                                        $msg .= chr(hexdec($arCommands[$i]));
                                    }
                                    $con = mysql_connect("cloudservice.cgejdsdl842e.sa-east-1.rds.amazonaws.com", "gpstracker", "d1\$1793689");
                                    if ($con !== false) {
                                        mysql_select_db('tracker', $con);
                                        $alerta = '';
                                        if (strpos($msg, 'Already') > -1) {
                                            $alerta = 'Bloqueio já efetuado!';
                                        }
                                        if (strpos($msg, 'DYD=Suc') > -1) {
                                            $alerta = 'Bloqueio efetuado!';
                                        }
                                        if (strpos($msg, 'HFYD=Su') > -1) {
                                            $alerta = 'Desbloqueio efetuado!';
                                        }
                                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$conn_imei}', '{$alerta}')", $con);
                                        mysql_close($con);
                                    }
                                } else {
                                    if ($protocolNumber == '16') {
                                        printLog($fh, date("d-m-y h:i:sa") . " Got: " . implode(" ", $arCommands));
                                        $dataPosition = hexdec($arCommands[4]) . '-' . hexdec($arCommands[5]) . '-' . hexdec($arCommands[6]) . ' ' . hexdec($arCommands[7]) . ':' . hexdec($arCommands[8]) . ':' . hexdec($arCommands[9]);
                                        $gpsQuantity = $arCommands[10];
                                        $lengthGps = hexdec(substr($gpsQuantity, 0, 1));
                                        $satellitesGps = hexdec(substr($gpsQuantity, 1, 1));
                                        $latitudeHemisphere = '';
                                        $longitudeHemisphere = '';
                                        $speed = hexdec($arCommands[19]);
                                        $course = decbin(hexdec($arCommands[20]));
                                        while (strlen($course) < 8) {
                                            $course = '0' . $course;
                                        }
                                        $status = decbin(hexdec($arCommands[21]));
                                        while (strlen($status) < 8) {
                                            $status = '0' . $status;
                                        }
                                        $courseStatus = $course . $status;
                                        $gpsRealTime = substr($courseStatus, 2, 1);
                                        $gpsPosition = substr($courseStatus, 3, 1) == '0' ? 'F' : 'L';
                                        $gpsPosition = 'S';
                                        $latitudeHemisphere = substr($courseStatus, 5, 1) == '0' ? 'S' : 'N';
                                        $longitudeHemisphere = substr($courseStatus, 4, 1) == '0' ? 'E' : 'W';
                                        $latHex = hexdec($arCommands[11] . $arCommands[12] . $arCommands[13] . $arCommands[14]);
                                        $lonHex = hexdec($arCommands[15] . $arCommands[16] . $arCommands[17] . $arCommands[18]);
                                        $latitudeDecimalDegrees = $latHex * 90 / 162000000;
                                        $longitudeDecimalDegrees = $lonHex * 180 / 324000000;
                                        $latitudeHemisphere == 'S' && ($latitudeDecimalDegrees = $latitudeDecimalDegrees * -1);
                                        $longitudeHemisphere == 'W' && ($longitudeDecimalDegrees = $longitudeDecimalDegrees * -1);
                                        //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
                                        //66 01100110
                                        $terminalInformation = decbin(hexdec($arCommands[31]));
                                        while (strlen($terminalInformation) < 8) {
                                            $terminalInformation = '0' . $terminalInformation;
                                        }
                                        $gasOil = substr($terminalInformation, 0, 1) == '0' ? 'S' : 'N';
                                        $gpsTrack = substr($terminalInformation, 1, 1) == '1' ? 'S' : 'N';
                                        $alarm = '';
                                        switch (substr($terminalInformation, 2, 3)) {
                                            case '100':
                                                $alarm = 'help me';
                                                break;
                                            case '011':
                                                $alarm = 'low battery';
                                                break;
                                            case '010':
                                                $alarm = 'dt';
                                                break;
                                            case '001':
                                                $alarm = 'move';
                                                break;
                                            case '000':
                                                $alarm = 'tracker';
                                                break;
                                        }
                                        $con = mysql_connect("cloudservice.cgejdsdl842e.sa-east-1.rds.amazonaws.com", "gpstracker", "d1\$1793689");
                                        if ($con !== false) {
                                            mysql_select_db('tracker', $con);
                                            if ($alarm == "help me") {
                                                mysql_query("INSERT INTO message (imei, message) VALUES ('{$conn_imei}', 'SOS!')", $con);
                                            }
                                            mysql_close($con);
                                        }
                                        $charge = substr($terminalInformation, 5, 1) == '1' ? 'S' : 'N';
                                        $acc = substr($terminalInformation, 6, 1) == '1' ? 'acc on' : 'acc off';
                                        $defense = substr($terminalInformation, 7, 1) == '1' ? 'S' : 'N';
                                        $voltageLevel = hexdec($arCommands[32]);
                                        $gsmSignal = hexdec($arCommands[33]);
                                        $alarmLanguage = hexdec($arCommands[34]);
                                        /*
                                        switch($alarmLanguage){
                                        	case 0: $alarm = 'normal'; break;
                                        	case 1: $alarm = 'help me'; break;
                                        	case 2: $alarm = 'dt'; break;
                                        	case 3: $alarm = 'move'; break;
                                        	case 4: $alarm = 'stockade'; break;
                                        	case 5: $alarm = 'stockade'; break;
                                        }
                                        */
                                        $dados = array($gpsPosition, $latitudeDecimalDegrees, $longitudeDecimalDegrees, $latitudeHemisphere, $longitudeHemisphere, $speed, $imei, $dataPosition, $alarm, $acc);
                                        tratarDados($dados);
                                        // echo "[PROTOCOLO 16] Lat/Long: ".$latitudeDecimalDegrees.", ".$longitudeDecimalDegrees."****************";
                                        $send_cmd = '78 78 05 16 ' . strtoupper($arCommands[36]) . ' ' . strtoupper($arCommands[37]);
                                        //$crc = crcx25('05 16 '.strtoupper($arCommands[36]).' '.strtoupper($arCommands[37]));
                                        atualizarBemSerial($conn_imei, strtoupper($arCommands[36]) . ' ' . strtoupper($arCommands[37]));
                                        //$crc = str_replace('ffff','',dechex($crc));
                                        //$crc = strtoupper(substr($crc,0,2)).' '.strtoupper(substr($crc,2,2));
                                        $newString = '';
                                        $newString = chr(0x5) . chr(0x16) . $rec[36] . $rec[37];
                                        $crc16 = GetCrc16($newString, strlen($newString));
                                        $crc16h = floor($crc16 / 256);
                                        $crc16l = $crc16 - $crc16h * 256;
                                        $crc = dechex($crc16h) . ' ' . dechex($crc16l);
                                        $send_cmd = $send_cmd . ' ' . $crc . ' 0D 0A';
                                        $sendCommands = explode(' ', $send_cmd);
                                        printLog($fh, date("d-m-y h:i:sa") . " Imei: {$imei} Sent: {$send_cmd} Length: " . strlen($send_cmd));
                                        $send_cmd = '';
                                        for ($i = 0; $i < count($sendCommands); $i++) {
                                            $send_cmd .= chr(hexdec(trim($sendCommands[$i])));
                                        }
                                        socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                                    } else {
                                        if ($protocolNumber == '1A') {
                                            printLog($fh, date("d-m-y h:i:sa") . " Got: " . implode(" ", $arCommands));
                                        } else {
                                            if ($protocolNumber == '80') {
                                                printLog($fh, date("d-m-y h:i:sa") . " Got: " . implode(" ", $arCommands));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        $rec = "";
    }
    //while
}
示例#2
0
function interact($socket)
{
    global $fh;
    global $command_path;
    global $firstInteraction;
    global $remip;
    global $remport;
    $loopcount = 0;
    $conn_imei = "";
    /* TALK TO YOUR CLIENT */
    $rec = "";
    // Variavel que indica se comando está em banco ou arquivo.
    $tipoComando = "banco";
    //"arquivo";
    //Checando o protocolo
    $isGIMEI = false;
    $isGPRMC = false;
    $send_cmd = "";
    # Read the socket but don't wait for data..
    while (@socket_recv($socket, $rec, 2048, 0x40) !== 0) {
        sleep(1);
        # Timeout the socket if it's not talking...
        # Prevents duplicate connections, confusing the send commands
        $loopcount++;
        if ($loopcount > 120) {
            return;
        }
        $rec = trim($rec);
        //Conecta e pega o comando pendente
        $cnx = mysql_connect("cloudservice.cgejdsdl842e.sa-east-1.rds.amazonaws.com", "gpstracker", "d1\$1793689") or die("Could not connect: " . mysql_error());
        mysql_select_db('tracker', $cnx);
        if ($rec != "") {
            mysql_close($cnx);
            /* MODULO GPRMC - COMANDOS A SEREM EXECUTADDOS PARA SUNTECH*/
            if (strpos($rec, "SA200") === true) {
                $isGPRMC = true;
            }
            $loopcount = 0;
            $parts = explode(';', $rec);
            $cnx = mysql_connect("cloudservice.cgejdsdl842e.sa-east-1.rds.amazonaws.com", "gpstracker", "d1\$1793689");
            if ($parts[1] != 'Res' and count($parts) >= 17) {
                $model = $parts[0];
                $imei = $parts[1];
                $satelliteFixStatus = 'A';
                $latitudeDecimalDegrees = $parts[6];
                $latitudeHemisphere = 'S';
                $lgt = substr($parts[7], 2);
                $lgt1 = '-';
                $longitudeDecimalDegrees = "{$lgt1}{$lgt}";
                $longitudeHemisphere = 'W';
                $speed = $parts[8];
                $gpsSignalIndicator = 'F';
                $hodometro = $parts[12];
                $ignicao = $parts[14];
                $alerta = $parts[15];
                if ((int) $speed <= 0) {
                    $movimento = 'N';
                } else {
                    $movimento = 'S';
                }
                $infotext = "gprmc";
                if ($infotext == "") {
                    $infotext = "gprmc";
                }
                $conn_imei = $imei;
                abrirArquivoLog($conn_imei);
                printLog($fh, date("d-m-y h:i:sa") . " Connection from {$remip}:{$remport}");
                printLog($fh, date("d-m-y h:i:sa") . " Got : {$rec}");
                mysql_select_db('tracker', $cnx);
                if ($gpsSignalIndicator != 'L') {
                    $address = null;
                    $phone = '7097';
                    // hodonetro
                    $resBem = mysql_query("SELECT * FROM bem WHERE imei={$imei} ORDER BY date DESC LIMIT 1");
                    $dataBem = mysql_fetch_assoc($resBem);
                    $resGprmc = mysql_query("SELECT * FROM gprmc WHERE imei={$imei} ORDER BY date DESC LIMIT 1");
                    $dataGprmc = mysql_fetch_assoc($resGprmc);
                    $geoDistance = $hodometro - $dataBem['hodometro'];
                    $alertaACada = $dataBem['alerta_hodometro'];
                    $alertaACadaSaldo = $dataBem['alerta_hodometro_saldo'];
                    $alertaACadaSaldo = $alertaACadaSaldo - $geoDistance;
                    $hodometro = $geoDistance + $dataBem['hodometro'];
                    $kmRodado = $geoDistance + $dataGprmc['km_rodado'];
                    if ($alertaACadaSaldo > 0) {
                        mysql_query("UPDATE bem set date = now(), status_sinal = 'R', movimento = '{$movimento}', hodometro = '{$hodometro}', alerta_hodometro_saldo = {$alertaACadaSaldo} WHERE imei = '{$imei}'", $cnx);
                    } else {
                        mysql_query("UPDATE bem set date = now(), status_sinal = 'R', movimento = '{$movimento}', hodometro = '{$hodometro}', alerta_hodometro_saldo = {$alertaACada} WHERE imei = '{$imei}'", $cnx);
                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Hodometro:')", $cnx);
                    }
                    // fim hodometro
                    // LOC_ATUAL
                    $resLocAtual = mysql_query("select id, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere from loc_atual where imei = '{$imei}' limit 1", $cnx);
                    $numRows = mysql_num_rows($resLocAtual);
                    if ($numRows == 0) {
                        mysql_query("INSERT INTO loc_atual (date, imei, phone, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator, converte) VALUES (now(), '{$imei}', '{$phone}', '{$satelliteFixStatus}', '{$latitudeDecimalDegrees}', '{$latitudeHemisphere}', '{$longitudeDecimalDegrees}', '{$longitudeHemisphere}', '{$speed}', '{$infotext}', '{$gpsSignalIndicator}', 0)", $cnx);
                    } else {
                        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 where imei = '{$imei}'", $cnx);
                    }
                    // FIM LOC_ATUAL
                    if ($ignicao == '000000') {
                        mysql_query("UPDATE bem set date = now(), ligado = 'N' WHERE imei = '{$imei}'", $cnx);
                    } else {
                        mysql_query("UPDATE bem set date = now(), ligado = 'S' WHERE imei = '{$imei}'", $cnx);
                    }
                    mysql_query("UPDATE bem set date = now(), status_sinal = 'R' WHERE imei = '{$imei}'", $cnx);
                    mysql_query("INSERT INTO gprmc (date, imei, phone, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator, address, km_rodado) VALUES (now(), '{$imei}', '{$phone}', '{$satelliteFixStatus}', '{$latitudeDecimalDegrees}', '{$latitudeHemisphere}', '{$longitudeDecimalDegrees}', '{$longitudeHemisphere}', '{$speed}', '{$infotext}', '{$gpsSignalIndicator}', '{$address}','{$kmRodado}')", $cnx);
                } else {
                    mysql_query("UPDATE bem set date = now(), status_sinal = 'S' WHERE imei = '{$imei}'", $cnx);
                }
                if ($parts[0] === 'SA200ALT') {
                    $res = mysql_query("SELECT * FROM bem WHERE imei='{$imei}'", $cnx);
                    while ($data = mysql_fetch_assoc($res)) {
                        switch ($alerta) {
                            case "dt":
                                $body = "Disable Track OK";
                                break;
                            case "et":
                                $body = "Stop Alarm OK";
                                break;
                            case "gt":
                                $body = "Move Alarm set OK";
                                break;
                            case "help me":
                                $body = "Help!";
                                mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'SOS!')", $cnx);
                                break;
                            case "ht":
                                $body = "Speed alarm set OK";
                                break;
                            case "it":
                                $body = "Timezone set OK";
                                break;
                            case "low battery":
                                $body = "Low battery!\nYou have about 2 minutes...";
                                mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Bat. Fraca')", $cnx);
                                break;
                            case " bat:":
                                $body = "Low battery!\nYou have about 2 minutes...";
                                mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Bat. Fraca')", $cnx);
                                break;
                            case "Low batt":
                                $body = "Low battery!\nYou have about 2 minutes...";
                                mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Bat. Fraca')", $cnx);
                                break;
                            case "move":
                                $body = "Move Alarm!";
                                mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Movimento')", $cnx);
                                break;
                            case "nt":
                                $body = "Returned to SMS mode OK";
                                break;
                            case "1":
                                mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Velocidade: Fora do Limite')", $cnx);
                                break;
                            case "2":
                                mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Velocidade: Dentro do Limite')", $cnx);
                                break;
                            case "5":
                                mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Cerca: Fora do Limite')", $cnx);
                                break;
                        }
                        //switch
                    }
                    //while
                }
            } else {
                //GRPMC nao precisa reter a sessao
            }
            //No protocolo GPRMC cada nova conexão é um IP. Enviando comando no fim da conexao, após obter os dados.
            if ($conn_imei != "") {
                //CERCA
                $consulta = mysql_query("SELECT * FROM geo_fence WHERE imei = '{$imei}'", $cnx);
                while ($data = mysql_fetch_assoc($consulta)) {
                    $idCerca = $data['id'];
                    $imeiCerca = $data['imei'];
                    $nomeCerca = $data['nome'];
                    $coordenadasCerca = $data['coordenadas'];
                    $resultCerca = $data['tipo'];
                    $tipoEnvio = $data['tipoEnvio'];
                    $lat_point = $latitudeDecimalDegrees;
                    $lng_point = $longitudeDecimalDegrees;
                    $exp = explode("|", $coordenadasCerca);
                    if (count($exp) < 5) {
                        $strExp = explode(",", $exp[0]);
                        $strExp1 = explode(",", $exp[2]);
                    } else {
                        $int = count($exp) / 2;
                        $strExp = explode(",", $exp[0]);
                        $strExp1 = explode(",", $exp[$int]);
                    }
                    $lat_vertice_1 = $strExp[0];
                    $lng_vertice_1 = $strExp[1];
                    $lat_vertice_2 = $strExp1[0];
                    $lng_vertice_2 = $strExp1[1];
                    if ($lat_vertice_1 < $lat_point or $lat_point < $lat_vertice_2 and $lng_point < $lng_vertice_1 or $lng_vertice_2 < $lng_point) {
                        $result = '0';
                        $situacao = 'fora';
                    } else {
                        $result = '1';
                        $situacao = 'dentro';
                    }
                    if ($result != $resultCerca and round($speed * 1.852, 0) > 0) {
                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Cerca " . $nomeCerca . " Violada!')", $cnx);
                    }
                }
                //FIM CERCA
                if ($tipoComando == "banco") {
                    //Conecta e pega o comando pendente
                    $cnx = mysql_connect("cloudservice.cgejdsdl842e.sa-east-1.rds.amazonaws.com", "gpstracker", "d1\$1793689") or die("Could not connect: " . mysql_error());
                    mysql_select_db('tracker', $cnx);
                    $res = mysql_query("SELECT c.command FROM command c WHERE c.imei = '{$conn_imei}' ORDER BY date DESC LIMIT 1");
                    while ($data = mysql_fetch_assoc($res)) {
                        $send_cmd = $data['command'];
                        socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                    }
                    //$send_cmd = trim($send_cmd);
                    //unlink("$command_path/$conn_imei");
                    mysql_query("DELETE FROM command WHERE imei = {$conn_imei}");
                    mysql_query("insert into teste(id,string) values(null, '{$send_cmd}')", $cnx);
                    mysql_close($cnx);
                    printLog($fh, "Comandos do arquivo apagado: " . $send_cmd . " imei: " . $conn_imei);
                }
                // Comando enviado
                //printLog($fh, date("d-m-y h:i:sa") . " Sent: $send_cmd");
                if (file_exists("{$command_path}{$conn_imei}")) {
                    $send_cmd = file_get_contents("{$command_path}{$conn_imei}");
                    socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                    mysql_query("DELETE FROM command WHERE imei = {$conn_imei}");
                    unlink("{$command_path}{$conn_imei}");
                    printLog($fh, "Comandos do Banco e Arquivo apagados: " . $send_cmd . " imei: " . $conn_imei);
                }
                break;
            }
        }
        //Checando se utilizou os dois protocolos para uma escuta
        if ($isGIMEI == true and $isGPRMC == true) {
            //printLog($fh, "ATENCAO: falha na obtencao do protocolo. Kill pid.");
        }
        $rec = "";
    }
    //while
}
示例#3
0
function interact($socket)
{
    global $fh;
    global $command_path;
    global $firstInteraction;
    global $remip;
    global $remport;
    $loopcount = 0;
    $conn_imei = "";
    /* TALK TO YOUR CLIENT */
    $rec = "";
    $conexao = mysql_connect("cloudservice.cgejdsdl842e.sa-east-1.rds.amazonaws.com", "gpstracker", "d1\$1793689");
    mysql_select_db('tracker', $conexao);
    # Read the socket but don't wait for data..
    while (@socket_recv($socket, $rec, 2048, 0x40) !== 0) {
        # Some pacing to ensure we don't split any incoming data.
        sleep(1);
        # Timeout the socket if it's not talking...
        # Prevents duplicate connections, confusing the send commands
        $loopcount++;
        if ($loopcount > 120) {
            return;
        }
        #remove any whitespace from ends of string.
        $rec = trim($rec);
        if ($rec != "") {
            if (preg_match("/TLT/i", $rec) or preg_match("/V500/i", $rec)) {
                $loopcount = 0;
                $partsx = explode('#', $rec);
                $imei = mysql_real_escape_string($partsx[1]);
                $status = mysql_real_escape_string($partsx[4]);
                $quantidadecoordenadas = mysql_real_escape_string($partsx[5]);
                mysql_set_charset('utf8', $conexao);
                switch ($status) {
                    case "SOS":
                        $body = "SOS! Alerta emitido";
                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', '{$body}')", $conexao);
                        printLog($fh, date("d-m-Y H:i:s") . " Alerta: " . $body);
                        break;
                    case "DEF":
                        $body = "Bateria principal desligada";
                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', '{$body}')", $conexao);
                        printLog($fh, date("d-m-Y H:i:s") . " Alerta: " . $body);
                        break;
                    case "LP":
                        $body = "Bateria Interna Fraca";
                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', '{$body}')", $conexao);
                        printLog($fh, date("d-m-Y H:i:s") . " Alerta: " . $body);
                        break;
                    case "TOWED":
                        $body = "Rebocado";
                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', '{$body}')", $conexao);
                        printLog($fh, date("d-m-Y H:i:s") . " Alerta: " . $body);
                        break;
                }
                //
                $conn_imei = $imei;
                abrirArquivoLog($conn_imei);
                printLog($fh, date("d-m-Y H:i:s") . " CONEXAO DE {$remip}:{$remport}");
                printLog($fh, date("d-m-Y H:i:s") . " RECEBEU : {$rec}");
            }
            // SE TIVER A STRING GPRMC
            if (preg_match("/GPRMC/i", $rec)) {
                $explode = explode("GPRMC", $rec);
                //echo "Quantidade >> " . $quantidadecoordenadas . "\n";
                for ($i = 1; $i <= $quantidadecoordenadas; $i++) {
                    //echo "Linha " . $i . " >> " . $explode[$i] . "\n";
                    $loopcount = 0;
                    $linha = $explode[$i];
                    $parts = explode(',', $linha);
                    $gpsSignalIndicator = mysql_real_escape_string($parts[2]);
                    if (count($parts) > 1 and $gpsSignalIndicator == 'A') {
                        // HORA GMT
                        $hora = mysql_real_escape_string($parts[1]);
                        $hora = substr($hora, 0, 2) . ":" . substr($hora, 2, 2) . ":" . substr($hora, 4, 2);
                        // DATA
                        $data = mysql_real_escape_string($parts[9]);
                        $data = "20" . substr($data, 4, 2) . "-" . substr($data, 2, 2) . "-" . substr($data, 0, 2);
                        // DATETIME
                        $datetime = $data . " " . $hora;
                        //
                        $latitudeDecimalDegrees = mysql_real_escape_string($parts[3]);
                        $latitudeHemisphere = mysql_real_escape_string($parts[4]);
                        $longitudeDecimalDegrees = mysql_real_escape_string($parts[5]);
                        $longitudeHemisphere = mysql_real_escape_string($parts[6]);
                        $velocidadekn = mysql_real_escape_string($parts[7]);
                        $velocidadekm = $velocidadekn * 1.852;
                        $velocidadekm = str_replace(',', '.', $velocidadekm);
                        $angulo = mysql_real_escape_string($parts[8]);
                        if ($angulo == "") {
                            $angulo = 0;
                        }
                        strlen($latitudeDecimalDegrees) == 9 && ($latitudeDecimalDegrees = '0' . $latitudeDecimalDegrees);
                        $g = substr($latitudeDecimalDegrees, 0, 3);
                        $d = substr($latitudeDecimalDegrees, 3);
                        $strLatitudeDecimalDegrees = $g + $d / 60;
                        $latitudeHemisphere == "S" && ($strLatitudeDecimalDegrees = $strLatitudeDecimalDegrees * -1);
                        strlen($longitudeDecimalDegrees) == 9 && ($longitudeDecimalDegrees = '0' . $longitudeDecimalDegrees);
                        $g = substr($longitudeDecimalDegrees, 0, 3);
                        $d = substr($longitudeDecimalDegrees, 3);
                        $strLongitudeDecimalDegrees = $g + $d / 60;
                        $longitudeHemisphere == "W" && ($strLongitudeDecimalDegrees = $strLongitudeDecimalDegrees * -1);
                        $latitude = $strLatitudeDecimalDegrees;
                        $longitude = $strLongitudeDecimalDegrees;
                        $lat_point = $latitude;
                        $lng_point = $longitude;
                        if ($velocidadekn < 1 and $velocidadekn > 0) {
                            $velocidadekn = 0;
                        }
                        $speed = $velocidadekn;
                        # GRAVANDO DADOS NAS TABELAS
                        mysql_query("UPDATE bem set date = date, status_sinal = 'R' WHERE imei = '{$imei}'", $conexao);
                        mysql_query("INSERT INTO gprmc (date, imei, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator) VALUES (now(), '{$imei}', 'A', '{$latitudeDecimalDegrees}', '{$latitudeHemisphere}', '{$longitudeDecimalDegrees}', '{$longitudeHemisphere}', '{$speed}', '{$status}', 'F')", $conexao);
                        # VERIFICA CERCA VIRTUAL
                        $consulta = mysql_query("SELECT * FROM geo_fence WHERE imei = '{$imei}'", $conexao);
                        while ($data = mysql_fetch_assoc($consulta)) {
                            $idCerca = $data['id'];
                            $imeiCerca = $data['imei'];
                            $nomeCerca = $data['nome'];
                            $coordenadasCerca = $data['coordenadas'];
                            $resultCerca = $data['tipo'];
                            $tipoEnvio = $data['tipoEnvio'];
                            $exp = explode("|", $coordenadasCerca);
                            if (count($exp) < 5) {
                                $strExp = explode(",", $exp[0]);
                                $strExp1 = explode(",", $exp[2]);
                            } else {
                                $int = count($exp) / 2;
                                $strExp = explode(",", $exp[0]);
                                $strExp1 = explode(",", $exp[$int]);
                            }
                            $lat_vertice_1 = $strExp[0];
                            $lng_vertice_1 = $strExp[1];
                            $lat_vertice_2 = $strExp1[0];
                            $lng_vertice_2 = $strExp1[1];
                            if ($lat_vertice_1 < $lat_point or $lat_point < $lat_vertice_2 and $lng_point < $lng_vertice_1 or $lng_vertice_2 < $lng_point) {
                                $result = '0';
                                $situacao = 'fora';
                            } else {
                                $result = '1';
                                $situacao = 'dentro';
                            }
                            if ($result != $resultCerca and round($speed * 1.852, 0) > 0) {
                                mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Cerca " . $nomeCerca . " Violada!')", $conexao);
                                if ($tipoEnvio == 0) {
                                    # Convert the GPS coordinates to a human readable address
                                    $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
                                    $rev_geo_str = file_get_contents($tempstr);
                                    $rev_geo_str = preg_replace("/\"/", "", $rev_geo_str);
                                    $rev_geo = explode(',', $rev_geo_str);
                                    $logradouro = $rev_geo[2] . "," . $rev_geo[3];
                                    require "lib/class.phpmailer.php";
                                    $consulta1 = mysql_query("SELECT a.*, b.* FROM cliente a INNER JOIN bem b ON (a.id = b.cliente) WHERE b.imei = '{$imei}'", $conexao);
                                    while ($data = mysql_fetch_assoc($consulta1)) {
                                        $emailDestino = $data['email'];
                                        $nameBem = $data['name'];
                                        $mensagem = "O veiculo " . $nameBem . ", esta " . $situacao . " do perimetro " . $nomeCerca . ", as " . date("H:i:s") . " do dia " . date("d/m/Y") . ", no local " . $logradouro . " e trafegando a " . round($speed * 1.852, 0) . " km/h.";
                                        $msg = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">";
                                        $msg .= "<html>";
                                        $msg .= "<head></head>";
                                        $msg .= "<body style=\"background-color:#fff;\" >";
                                        $msg .= "<p><strong>Alerta de Violacao de Perimetro:</strong><br /><br />";
                                        $msg .= $mensagem . "<br /><br />";
                                        $msg .= "Equipe BarukSat<br />";
                                        $msg .= "(85)88462069<br />";
                                        $msg .= "<a href=\"http://www.systemtracker.com.br\">www.systemtracker.com.br</a></p>";
                                        $msg .= "</body>";
                                        $msg .= "</html>";
                                        $mail = new PHPMailer();
                                        $mail->Mailer = "smtp";
                                        $mail->IsHTML(true);
                                        $mail->CharSet = "utf-8";
                                        $mail->SMTPSecure = "tls";
                                        $mail->Host = "smtp.gmail.com";
                                        $mail->Port = "587";
                                        $mail->SMTPAuth = "true";
                                        $mail->Username = "******";
                                        $mail->Password = "******";
                                        $mail->From = "*****@*****.**";
                                        $mail->FromName = "BarukSat";
                                        $mail->AddAddress($emailDestino);
                                        $mail->AddReplyTo($mail->From, $mail->FromName);
                                        $mail->Subject = "BarukSat - Alerta de Violacao de Perimetro";
                                        $mail->Body = $msg;
                                        if (!$mail->Send()) {
                                            echo "Erro de envio: " . $mail->ErrorInfo;
                                        } else {
                                            echo "Mensagem enviada com sucesso!";
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                // DADOS INCORRETOS PARA COLETA
            }
        }
        $rec = "";
    }
    //while
}
示例#4
0
function interact($socket)
{
    global $fh;
    global $command_path;
    global $firstInteraction;
    global $remip;
    global $remport;
    $loopcount = 0;
    $conn_imei = "";
    /* TALK TO YOUR CLIENT */
    $rec = "";
    // Variavel que indica se comando est� em banco ou arquivo.
    $tipoComando = "arquivo";
    //"arquivo";
    //Checando o protocolo
    $isGIMEI = false;
    $isGPRMC = false;
    $send_cmd = "";
    # Read the socket but don't wait for data..
    while (@socket_recv($socket, $rec, 2048, 0x40) !== 0) {
        # If we know the imei of the phone and there is a pending command send it.
        if ($conn_imei != "") {
            if ($tipoComando == "arquivo" and file_exists("{$command_path}/{$conn_imei}")) {
                $send_cmd = file_get_contents("{$command_path}/{$conn_imei}");
                error_log($send_cmd);
                socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                unlink("{$command_path}/{$conn_imei}");
                printLog($fh, "Arquivo de comandos apagado: " . $send_cmd . " imei: " . $conn_imei);
            } else {
                if ($tipoComando == "banco" and file_exists("{$command_path}/{$conn_imei}")) {
                    //Conecta e pega o comando pendente
                    $cnx = mysql_connect("cloudservice.cgejdsdl842e.sa-east-1.rds.amazonaws.com", "gpstracker", "d1\$1793689") or die("Could not connect: " . mysql_error());
                    mysql_select_db('tracker', $cnx);
                    $res = mysql_query("SELECT c.command FROM command c WHERE c.imei = '{$conn_imei}' ORDER BY date DESC LIMIT 1", $cnx);
                    while ($data = mysql_fetch_assoc($res)) {
                        $send_cmd = $data['command'];
                        echo 'acessou o comando';
                    }
                    // Deletando comando
                    //mysql_query("DELETE FROM command WHERE imei = $conn_imei");
                    mysql_close($cnx);
                    socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                    unlink("{$command_path}/{$conn_imei}");
                    printLog($fh, "Comandos do arquivo apagado: " . $send_cmd . " imei: " . $conn_imei);
                } else {
                    //Se nao tiver comando na fila e for a primeira iteracao, obtem o ultimo comando v�lido enviado
                    if ($firstInteraction == true) {
                        sleep(1);
                        $send_cmd = "**,imei:" . $conn_imei . ",C,02m";
                        //Obtendo o ultimo comando
                        $cnx = mysql_connect("cloudservice.cgejdsdl842e.sa-east-1.rds.amazonaws.com", "gpstracker", "d1\$1793689") or die("Could not connect: " . mysql_error());
                        mysql_select_db('tracker', $cnx);
                        $res = mysql_query("SELECT c.command FROM command c WHERE c.command like '**,imei:" . $conn_imei . ",C,%' and c.imei = {$conn_imei} ORDER BY date DESC LIMIT 1", $cnx);
                        while ($data = mysql_fetch_assoc($res)) {
                            $send_cmd = $data['command'];
                        }
                        mysql_close($cnx);
                        socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                        printLog($fh, "Comando de start: " . $send_cmd . " imei: " . $conn_imei);
                        $firstInteraction = false;
                    }
                }
            }
            // Comando enviado
            printLog($fh, date("d-m-y h:i:sa") . " Sent: {$send_cmd}");
        }
        # Some pacing to ensure we don't split any incoming data.
        sleep(1);
        # Timeout the socket if it's not talking...
        # Prevents duplicate connections, confusing the send commands
        $loopcount++;
        //if ($loopcount > 120) return;
        if ($loopcount > 60) {
            return;
        }
        #remove any whitespace from ends of string.
        $cnx = mysql_connect("cloudservice.cgejdsdl842e.sa-east-1.rds.amazonaws.com", "gpstracker", "d1\$1793689");
        mysql_select_db('tracker', $cnx);
        if ($rec != "") {
            $rec = trim($rec);
            if (strpos($rec, "GPRMC") === false) {
                /* M�DULO IMEI GEN�RICO */
                $isGIMEI = true;
                $loopcount = 0;
                if ($fh != null) {
                    printLog($fh, date("d-m-y h:i:sa") . " Got : {$rec}");
                }
                $parts = explode(',', $rec);
                if (strpos($parts[0], "#") === FALSE) {
                    /* Andrew's tracker is different....
                    			Array
                    			(
                    				[0] => imei:354779030525274
                    				[1] => tracker
                    				[2] => 0909221022
                    				[3] => +61417801658
                    				[4] => F
                    				[5] => 022234.000
                    				[6] => A
                    				[7] => 3506.5232
                    				[8] => S
                    				[9] => 13829.5988
                    				[10] => E
                    				[11] => 0.00
                    				[12] =>
                    			)
                    			*/
                    # $imei                       = substr($parts[0],0, -1);
                    # Only worry about the rest if there is data to get
                    if (count($parts) > 1) {
                        $imei = substr($parts[0], 5);
                        $infotext = mysql_real_escape_string($parts[1]);
                        $trackerdate = mysql_real_escape_string($parts[2]);
                        $gpsSignalIndicator = mysql_real_escape_string($parts[4]);
                        $speed = 0;
                        //Se gpsSignalIndicator <> L, pega o outros dados
                        if ($gpsSignalIndicator != 'L') {
                            $phone = mysql_real_escape_string($parts[3]);
                            $satelliteFixStatus = mysql_real_escape_string($parts[6]);
                            $latitudeDecimalDegrees = mysql_real_escape_string($parts[7]);
                            $latitudeHemisphere = mysql_real_escape_string($parts[8]);
                            $longitudeDecimalDegrees = mysql_real_escape_string($parts[9]);
                            $longitudeHemisphere = mysql_real_escape_string($parts[10]);
                            $speed = mysql_real_escape_string($parts[11]);
                        }
                        //inicio verifica geofence
                        mysql_select_db('tracker', $cnx);
                        $texto_sms_localiza = "";
                        $texto_sms_alerta_hodometro = "";
                        $texto_sms_alerta = "";
                        $result = mysql_query("select * from preferencias", $cnx);
                        while ($dataPref = mysql_fetch_assoc($result)) {
                            if ($dataPref['nome'] == 'texto_sms_localiza') {
                                $texto_sms_localiza = $dataPref['valor'];
                            }
                            if ($dataPref['nome'] == 'texto_sms_alerta_hodometro') {
                                $texto_sms_alerta_hodometro = $dataPref['valor'];
                            }
                            if ($dataPref['nome'] == 'texto_sms_alerta') {
                                $texto_sms_alerta = $dataPref['valor'];
                            }
                        }
                        if ($imei != "") {
                            $consulta = mysql_query("SELECT * FROM geo_fence WHERE imei = '{$imei}'", $cnx);
                            while ($data = mysql_fetch_assoc($consulta)) {
                                $idCerca = $data['id'];
                                $imeiCerca = $data['imei'];
                                $nomeCerca = $data['nome'];
                                $coordenadasCerca = $data['coordenadas'];
                                $resultCerca = $data['tipo'];
                                $tipoEnvio = $data['tipoEnvio'];
                                strlen($latitudeDecimalDegrees) == 9 && ($latitudeDecimalDegrees = '0' . $latitudeDecimalDegrees);
                                $g = substr($latitudeDecimalDegrees, 0, 3);
                                $d = substr($latitudeDecimalDegrees, 3);
                                $strLatitudeDecimalDegrees = $g + $d / 60;
                                $latitudeHemisphere == "S" && ($strLatitudeDecimalDegrees = $strLatitudeDecimalDegrees * -1);
                                strlen($longitudeDecimalDegrees) == 9 && ($longitudeDecimalDegrees = '0' . $longitudeDecimalDegrees);
                                $g = substr($longitudeDecimalDegrees, 0, 3);
                                $d = substr($longitudeDecimalDegrees, 3);
                                $strLongitudeDecimalDegrees = $g + $d / 60;
                                $longitudeHemisphere == "S" && ($strLongitudeDecimalDegrees = $strLongitudeDecimalDegrees * -1);
                                $strLongitudeDecimalDegrees = $strLongitudeDecimalDegrees * -1;
                                $lat_point = $strLatitudeDecimalDegrees;
                                $lng_point = $strLongitudeDecimalDegrees;
                                $exp = explode("|", $coordenadasCerca);
                                if (count($exp) < 5) {
                                    $strExp = explode(",", $exp[0]);
                                    $strExp1 = explode(",", $exp[2]);
                                } else {
                                    $int = count($exp) / 2;
                                    $strExp = explode(",", $exp[0]);
                                    $strExp1 = explode(",", $exp[$int]);
                                }
                                $lat_vertice_1 = $strExp[0];
                                $lng_vertice_1 = $strExp[1];
                                $lat_vertice_2 = $strExp1[0];
                                $lng_vertice_2 = $strExp1[1];
                                if ($lat_vertice_1 < $lat_point or $lat_point < $lat_vertice_2 and $lng_point < $lng_vertice_1 or $lng_vertice_2 < $lng_point) {
                                    $result = '0';
                                    $situacao = 'fora';
                                } else {
                                    $result = '1';
                                    $situacao = 'dentro';
                                }
                                if ($result != $resultCerca and round($speed * 1.852, 0) > 0) {
                                    mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Cerca " . $nomeCerca . " Violada!')", $cnx);
                                    if ($tipoEnvio == 0) {
                                        # Convert the GPS coordinates to a human readable address
                                        $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
                                        $rev_geo_str = file_get_contents($tempstr);
                                        $rev_geo_str = preg_replace("/\"/", "", $rev_geo_str);
                                        $rev_geo = explode(',', $rev_geo_str);
                                        $logradouro = $rev_geo[2] . "," . $rev_geo[3];
                                        require "lib/class.phpmailer.php";
                                        $consulta1 = mysql_query("SELECT a.*, b.* FROM cliente a INNER JOIN bem b ON (a.id = b.cliente) WHERE b.imei = '{$imei}'", $cnx);
                                        while ($data = mysql_fetch_assoc($consulta1)) {
                                            $emailDestino = $data['email'];
                                            $nameBem = $data['name'];
                                            $mensagem = "O veiculo " . $nameBem . ", esta " . $situacao . " do perimetro " . $nomeCerca . ", as " . date("H:i:s") . " do dia " . date("d/m/Y") . ", no local " . $logradouro . " e trafegando a " . round($speed * 1.852, 0) . " km/h.";
                                            $msg = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">";
                                            $msg .= "<html>";
                                            $msg .= "<head></head>";
                                            $msg .= "<body style=\"background-color:#fff;\" >";
                                            $msg .= "<p><strong>Alerta de Violacao de Perimetro:</strong><br /><br />";
                                            $msg .= $mensagem . "<br /><br />";
                                            $msg .= "Equipe BarukSat<br />";
                                            $msg .= "(85)88462069<br />";
                                            $msg .= "<a href=\"http://www.systemtracker.com.br\">www.systemtracker.com.br</a></p>";
                                            $msg .= "</body>";
                                            $msg .= "</html>";
                                            $mail = new PHPMailer();
                                            $mail->Mailer = "smtp";
                                            $mail->IsHTML(true);
                                            $mail->CharSet = "utf-8";
                                            $mail->SMTPSecure = "tls";
                                            $mail->Host = "smtp.gmail.com";
                                            $mail->Port = "587";
                                            $mail->SMTPAuth = "true";
                                            $mail->Username = "******";
                                            $mail->Password = "******";
                                            $mail->From = "*****@*****.**";
                                            $mail->FromName = "BarukSat";
                                            $mail->AddAddress($emailDestino);
                                            $mail->AddReplyTo($mail->From, $mail->FromName);
                                            $mail->Subject = "BarukSat - Alerta de Violacao de Perimetro";
                                            $mail->Body = $msg;
                                            if (!$mail->Send()) {
                                                echo "Erro de envio: " . $mail->ErrorInfo;
                                            } else {
                                                echo "Mensagem enviada com sucesso!";
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        // if imei
                        //final verifica geofence
                        $dataBem = null;
                        $dataCliente = null;
                        $resBem = mysql_query("select id, cliente, envia_sms, name, alerta_hodometro, alerta_hodometro_saldo from bem where imei = '{$imei}'", $cnx);
                        $dataBem = mysql_fetch_assoc($resBem);
                        $resCliente = mysql_query("select id, celular, dt_ultm_sms, envia_sms, sms_acada, hour(timediff(convert_tz(now(), 'GMT', 'Brazil/East'), dt_ultm_sms)) horas, minute(timediff(convert_tz(now(), 'GMT', 'Brazil/East'), dt_ultm_sms)) minutos, nome from cliente where id = {$dataBem['cliente']}", $cnx);
                        $dataCliente = mysql_fetch_assoc($resCliente);
                        # Write it to the database...
                        if ($gpsSignalIndicator != 'L') {
                            $movimento = '';
                            if ($speed > 0) {
                                $movimento = 'S';
                            } else {
                                $movimento = 'N';
                            }
                            $gpsLat = gprsToGps($latitudeDecimalDegrees, $latitudeHemisphere);
                            $gpsLon = gprsToGps($longitudeDecimalDegrees, $longitudeHemisphere);
                            $gpsLatAnt = 0;
                            $gpsLatHemAnt = '';
                            $gpsLonAnt = 0;
                            $gpsLonHemAnt = '';
                            $alertaACadaSaldo = 0;
                            $resLocAtual = mysql_query("select id, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere from loc_atual where imei = '{$imei}' limit 1", $cnx);
                            $numRows = mysql_num_rows($resLocAtual);
                            if ($numRows == 0) {
                                //mysql_query("insert into logs evento values ('ok') ");
                                mysql_query("INSERT INTO loc_atual (date, imei, phone, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator, converte) VALUES (convert_tz(now(), 'GMT', 'Brazil/East'), '{$imei}', '{$phone}', '{$satelliteFixStatus}', '{$latitudeDecimalDegrees}', '{$latitudeHemisphere}', '{$longitudeDecimalDegrees}', '{$longitudeHemisphere}', '{$speed}', '{$infotext}', '{$gpsSignalIndicator}', 1)", $cnx);
                            } else {
                                mysql_query("UPDATE loc_atual set date = convert_tz(now(), 'GMT', 'Brazil/East'), phone = '{$phone}', satelliteFixStatus = '{$satelliteFixStatus}', latitudeDecimalDegrees = '{$latitudeDecimalDegrees}', latitudeHemisphere = '{$latitudeHemisphere}', longitudeDecimalDegrees = '{$longitudeDecimalDegrees}', longitudeHemisphere = '{$longitudeHemisphere}', speed = '{$speed}', infotext = '{$infotext}', gpsSignalIndicator = '{$gpsSignalIndicator}' where imei = '{$imei}'", $cnx);
                            }
                            $distance = 0;
                            try {
                                $bemId = $dataBem[id];
                                $countGeoDistance = mysql_query("select bem from geo_distance where bem = {$bemId}", $cnx);
                                if ($countGeoDistance === false || mysql_num_rows($countGeoDistance) == 0) {
                                    mysql_query("insert into geo_distance (bem, tipo) values({$bemId}, 'I')", $cnx);
                                    mysql_query("insert into geo_distance (bem, tipo) values({$bemId}, 'F')", $cnx);
                                }
                                /*envio de sms*/
                                if ($dataCliente['envia_sms'] == 'S' && $dataBem['envia_sms'] == 'S' && !empty($dataCliente['celular']) && !empty($dataCliente['sms_acada'])) {
                                    if (empty($dataCliente['dt_ultm_sms'])) {
                                        mysql_query("update cliente set dt_ultm_sms = convert_tz(now(), 'GMT', 'Brazil/East') where id = {$dataCliente['id']}", $cnx);
                                    } else {
                                        $horas = $dataCliente['horas'];
                                        $minutos = $dataCliente['minutos'];
                                        if (!empty($horas)) {
                                            $horas = $horas * 60;
                                        }
                                        $tempoTotal = $horas + $minutos;
                                        if ($tempoTotal > $dataCliente['sms_acada']) {
                                            $json = json_decode(file_get_contents("http://maps.google.com/maps/api/geocode/json?sensor=false&latlng={$gpsLat},{$gpsLon}&language=es-ES"));
                                            if (isset($json->status) && $json->status == 'OK' && isset($json->results[0]->formatted_address)) {
                                                $address = $json->results[0]->formatted_address;
                                                $address = utf8_decode($address);
                                                $aDataCliente = split(' ', $dataCliente['nome']);
                                                $msg = $texto_sms_localiza;
                                                $msg = str_replace("#CLIENTE", $aDataCliente[0], $msg);
                                                $msg = str_replace("#VEICULO", $dataBem['name'], $msg);
                                                $msg = str_replace("#LOCALIZACAO", $address, $msg);
                                                $msg = str_replace(' ', '+', $msg);
                                                sendSMS($dataCliente['celular'], $msg, '');
                                                if ($retorno < 0) {
                                                    mysql_query("insert into controle(texto) values('envio de sms retorno: {$retorno}')", $cnx);
                                                } else {
                                                    mysql_query("update cliente set dt_ultm_sms = convert_tz(now(), 'GMT', 'Brazil/East') where id = {$dataCliente['id']}", $cnx);
                                                }
                                            }
                                        }
                                    }
                                }
                                if ($movimento == 'S') {
                                    $resGeoDistance = mysql_query("select parou from geo_distance where bem = {$bemId} and tipo = 'I'", $cnx);
                                    $dataGeoDistance = mysql_fetch_assoc($resGeoDistance);
                                    if ($dataGeoDistance[parou] == 'S' || empty($dataGeoDistance[parou])) {
                                        mysql_query("update geo_distance set latitudeDecimalDegrees = '{$latitudeDecimalDegrees}', latitudeHemisphere = '{$latitudeHemisphere}', longitudeDecimalDegrees = '{$longitudeDecimalDegrees}', longitudeHemisphere = '{$longitudeHemisphere}', parou = 'N' where bem =  {$bemId} and tipo = 'I'", $cnx);
                                    }
                                } else {
                                    $resGeoDistance = mysql_query("select latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere from geo_distance where bem = {$bemId} and tipo = 'I'", $cnx);
                                    if (mysql_num_rows($resGeoDistance) > 0) {
                                        $update = mysql_query("update geo_distance set latitudeDecimalDegrees = '{$latitudeDecimalDegrees}', latitudeHemisphere = '{$latitudeHemisphere}', longitudeDecimalDegrees = '{$longitudeDecimalDegrees}', longitudeHemisphere = '{$longitudeHemisphere}', parou = 'S' where bem =  {$bemId} and tipo = 'I'", $cnx);
                                        $dataGeoDistance = mysql_fetch_assoc($resGeoDistance);
                                        $gpsLatAnt = gprsToGps($dataGeoDistance["latitudeDecimalDegrees"], $dataGeoDistance[latitudeHemisphere]);
                                        $gpsLonAnt = gprsToGps($dataGeoDistance["longitudeDecimalDegrees"], $dataGeoDistance[longitudeHemisphere]);
                                        if ($gpsLatAnt != $gpsLat) {
                                            if ($gpsLatAnt != 0 && $gpsLonAnt != 0) {
                                                /*
                                                if(isset($json->rows[0]->elements[0]->distance)){
                                                	$strDistance = $json->rows[0]->elements[0]->distance->value;
                                                	$distance = $strDistance+0;
                                                
                                                	$alertaACada = $dataBem['alerta_hodometro'];
                                                	$alertaACadaSaldo = $dataBem['alerta_hodometro_saldo'];
                                                	$alertaACadaSaldo = ($alertaACadaSaldo*1000) - $distance;
                                                	if($alertaACadaSaldo <= 0 && $alertaACada > 0){
                                                		$msg = $texto_sms_alerta_hodometro;
                                                		$msg = str_replace("#CLIENTE", $aDataCliente[0], $msg);
                                                		$msg = str_replace("#VEICULO", $dataBem['name'], $msg);
                                                		$msg = str_replace("#HODOMETRO", $alertaACada, $msg);
                                                		$msg = str_replace(' ', '+', $msg);
                                                		sendSMS($dataCliente['celular'], $msg, '');
                                                		$alertaACadaSaldo = $alertaACada;
                                                	}
                                                	$alertaACadaSaldo = (int)$alertaACadaSaldo/1000;
                                                }
                                                */
                                                $geoDistance = distance($gpsLatAnt, $gpsLonAnt, $gpsLat, $gpsLon);
                                                //$strDistance = $json->rows[0]->elements[0]->distance->value;
                                                //$distance = (int)($geoDistance*1000);
                                                $distance = (double) $geoDistance;
                                                $alertaACada = $dataBem['alerta_hodometro'];
                                                $alertaACadaSaldo = $dataBem['alerta_hodometro_saldo'];
                                                $alertaACadaSaldo = $alertaACadaSaldo * 1000 - $distance;
                                                if ($alertaACadaSaldo <= 0 && $alertaACada > 0) {
                                                    $msg = $texto_sms_alerta_hodometro;
                                                    $msg = str_replace("#CLIENTE", $aDataCliente[0], $msg);
                                                    $msg = str_replace("#VEICULO", $dataBem['name'], $msg);
                                                    $msg = str_replace("#HODOMETRO", $alertaACada, $msg);
                                                    $msg = str_replace(' ', '+', $msg);
                                                    //sendSMS($dataCliente['celular'], $msg, '');
                                                    $alertaACadaSaldo = $alertaACada;
                                                }
                                                $alertaACadaSaldo = (int) $alertaACadaSaldo / 1000;
                                            }
                                        }
                                    }
                                }
                            } catch (Exception $e) {
                                mysql_query("INSERT INTO controle (texto) VALUES ({$e->getMessage}())", $cnx);
                            }
                            mysql_query("INSERT INTO gprmc (date, imei, phone, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator, km_rodado, address, converte) VALUES (convert_tz(now(), 'GMT', 'Brazil/East'), '{$imei}', '{$phone}', '{$satelliteFixStatus}', '{$latitudeDecimalDegrees}', '{$latitudeHemisphere}', '{$longitudeDecimalDegrees}', '{$longitudeHemisphere}', '{$speed}', '{$infotext}', '{$gpsSignalIndicator}', {$distance}, '{$address}', 1)", $cnx);
                            error_log("INSERT INTO gprmc (date, imei, phone, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator, km_rodado, address, converte) VALUES (convert_tz(now(), 'GMT', 'Brazil/East'), '{$imei}', '{$phone}', '{$satelliteFixStatus}', '{$latitudeDecimalDegrees}', '{$latitudeHemisphere}', '{$longitudeDecimalDegrees}', '{$longitudeHemisphere}', '{$speed}', '{$infotext}', '{$gpsSignalIndicator}', {$distance}, '{$address}', 1)");
                            // Otavio Gomes - 15012015 1427 - So atualizar o hodometro se a distancia for maior que 10m
                            if ($alertaACadaSaldo == 0) {
                                mysql_query("UPDATE bem set date = convert_tz(now(), 'GMT', 'Brazil/East'), status_sinal = 'R', movimento = '{$movimento}', hodometro = hodometro+{$distance} WHERE imei = '{$imei}'", $cnx);
                            } else {
                                mysql_query("UPDATE bem set date = convert_tz(now(), 'GMT', 'Brazil/East'), status_sinal = 'R', movimento = '{$movimento}', hodometro = hodometro+{$distance}, alerta_hodometro_saldo = {$alertaACadaSaldo} WHERE imei = '{$imei}'", $cnx);
                            }
                            /*
                            if($numRows == 0){
                            	mysql_query("INSERT INTO loc_atual (date, imei, phone, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator) VALUES (convert_tz(now(), 'GMT', 'Brazil/East'), '$imei', '$phone', '$satelliteFixStatus', '$latitudeDecimalDegrees', '$latitudeHemisphere', '$longitudeDecimalDegrees', '$longitudeHemisphere', '$speed', '$infotext', '$gpsSignalIndicator')", $cnx);
                            } else {
                            	mysql_query("UPDATE loc_atual set date = convert_tz(now(), 'GMT', 'Brazil/East'), phone = '$phone', satelliteFixStatus = '$satelliteFixStatus', latitudeDecimalDegrees = '$latitudeDecimalDegrees', latitudeHemisphere = '$latitudeHemisphere', longitudeDecimalDegrees = '$longitudeDecimalDegrees', longitudeHemisphere = '$longitudeHemisphere', speed = '$speed', infotext = '$infotext', gpsSignalIndicator = '$gpsSignalIndicator' where imei = '$imei'", $cnx);
                            }
                            */
                        } else {
                            mysql_query("UPDATE bem set date = convert_tz(now(), 'GMT', 'Brazil/East'), status_sinal = 'S' WHERE imei = '{$imei}'", $cnx);
                        }
                        # Now check to see if we need to send any alerts.
                        if ($infotext != "tracker") {
                            $msg = $texto_sms_alerta;
                            $msg = str_replace("#CLIENTE", $aDataCliente[0], $msg);
                            $msg = str_replace("#VEICULO", $dataBem['name'], $msg);
                            $res = mysql_query("SELECT responsible FROM bem WHERE imei='{$imei}'", $cnx);
                            while ($data = mysql_fetch_assoc($res)) {
                                switch ($infotext) {
                                    case "dt":
                                        $body = "Disable Track OK";
                                        $msg = str_replace("#TIPOALERTA", "Rastreador Desabilitado", $msg);
                                        break;
                                    case "et":
                                        $body = "Stop Alarm OK";
                                        $msg = str_replace("#TIPOALERTA", "Alarme parado", $msg);
                                        break;
                                    case "gt":
                                        $body = "Move Alarm set OK";
                                        $msg = str_replace("#TIPOALERTA", "Alarme de Movimento ativado", $msg);
                                        break;
                                    case "help me":
                                        $body = "Help!";
                                        mysql_query("INSERT INTO message (imei, message) VALUES ('\${$conn_imei}', 'SOS!')", $cnx);
                                        $msg = str_replace("#TIPOALERTA", "SOS", $msg);
                                        //Envia comando de resposta: alerta recebido
                                        $send_cmd = "**,imei:" . $conn_imei . ",E";
                                        socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                                        //printLog($fh, "Comando de resposta (help me): " . $send_cmd . " imei: " . $conn_imei);
                                        break;
                                    case "ht":
                                        $body = "Speed alarm set OK";
                                        $msg = str_replace("#TIPOALERTA", "Alarme de velocidade ativado", $msg);
                                        break;
                                    case "it":
                                        $body = "Timezone set OK";
                                        break;
                                    case "low battery":
                                        $body = "Low battery!\nYou have about 2 minutes...";
                                        $msg = str_replace("#TIPOALERTA", "Bateria fraca, voce tem 2 minutos", $msg);
                                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Bat. Fraca')", $cnx);
                                        //Envia comando de resposta: alerta recebido
                                        $send_cmd = "**,imei:" . $conn_imei . ",E";
                                        socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                                        //printLog($fh, "Comando de resposta (low battery): " . $send_cmd . " imei: " . $conn_imei);
                                        break;
                                    case "move":
                                        $body = "Move Alarm!";
                                        $msg = str_replace("#TIPOALERTA", "Seu veiculo esta em movimento", $msg);
                                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Movimento')", $cnx);
                                        //Envia comando de resposta: alerta recebido
                                        $send_cmd = "**,imei:" . $conn_imei . ",E";
                                        socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                                        //printLog($fh, "Comando de resposta (move): " . $send_cmd . " imei: " . $conn_imei);
                                        break;
                                    case "nt":
                                        $body = "Returned to SMS mode OK";
                                        break;
                                    case "speed":
                                        $body = "Speed alarm!";
                                        $msg = str_replace("#TIPOALERTA", "Seu veiculo ultrapassou o limite de velocidade", $msg);
                                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Velocidade')", $cnx);
                                        //Envia comando de resposta: alerta recebido
                                        $send_cmd = "**,imei:" . $conn_imei . ",E";
                                        socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                                        //printLog($fh, "Comando de resposta (speed): " . $send_cmd . " imei: " . $conn_imei);
                                        break;
                                    case "stockade":
                                        $body = "Geofence Violation!";
                                        $msg = str_replace("#TIPOALERTA", "Seu veiculo saiu da cerca virtual", $msg);
                                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Cerca')", $cnx);
                                        //Envia comando de resposta: alerta recebido
                                        $send_cmd = "**,imei:" . $conn_imei . ",E";
                                        socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                                        //printLog($fh, "Comando de resposta (stockade): " . $send_cmd . " imei: " . $conn_imei);
                                        break;
                                    case "door alarm":
                                        $body = "Open door!";
                                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Porta')", $cnx);
                                        //Envia comando de resposta: alerta recebido
                                        $send_cmd = "**,imei:" . $conn_imei . ",E";
                                        socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                                        //printLog($fh, "Comando de resposta (door alarm): " . $send_cmd . " imei: " . $conn_imei);
                                        break;
                                    case "acc alarm":
                                        $body = "ACC alarm!";
                                        $msg = str_replace("#TIPOALERTA", "Seu veiculo esta com a chave ligada", $msg);
                                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Ignição')", $cnx);
                                        //Envia comando de resposta: alerta recebido
                                        $send_cmd = "**,imei:" . $conn_imei . ",E";
                                        socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                                        //printLog($fh, "Comando de resposta (acc alarm): " . $send_cmd . " imei: " . $conn_imei);
                                        break;
                                    case "acc off":
                                        $body = "Ignicao Desligada!";
                                        $msg = str_replace("#TIPOALERTA", "Seu veiculo esta com a chave desligada", $msg);
                                        //mysql_query("INSERT INTO message (imei, message) VALUES ('$imei', 'Ignição')", $cnx);
                                        mysql_query("UPDATE bem SET ligado = 'N' where imei = '{$imei}'", $cnx);
                                        //Envia comando de resposta: alerta recebido
                                        $send_cmd = "**,imei:" . $conn_imei . ",E";
                                        socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                                        //printLog($fh, "Comando de resposta (acc alarm): " . $send_cmd . " imei: " . $conn_imei);
                                        break;
                                    case "acc on":
                                        $body = "Ignicao Ligada!";
                                        $msg = str_replace("#TIPOALERTA", "Seu veiculo esta com a chave ligada", $msg);
                                        //mysql_query("INSERT INTO message (imei, message) VALUES ('$imei', 'Ignição')", $cnx);
                                        mysql_query("UPDATE bem SET ligado = 'S' where imei = '{$imei}'", $cnx);
                                        //Envia comando de resposta: alerta recebido
                                        $send_cmd = "**,imei:" . $conn_imei . ",E";
                                        socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                                        //printLog($fh, "Comando de resposta (acc alarm): " . $send_cmd . " imei: " . $conn_imei);
                                        break;
                                }
                                //switch
                                $msg = str_replace(' ', '+', $msg);
                                //if($dataCliente['envia_sms'] == 'S' && $dataBem['envia_sms'] == 'S' && $infotext != 'acc on'&& $infotext != 'acc off' && $infotext != 'et')
                                //	sendSMS($dataCliente['celular'], $msg, '');
                                //Enviando e-mail de alerta
                                $headers = "From: {$email_from}" . "\r\n" . "Reply-To: {$email_from}" . "\r\n";
                                $responsible = $data['responsible'];
                                $rv = mail($responsible, "Tracker - {$imei}", $body, $headers);
                            }
                            //while
                        }
                        mysql_close($cnx);
                    } else {
                        /* If we got here, we got an imei ONLY - not even 'imei:' first
                        			This seems to be some sort of 'keepalive' packet
                        			The TK-201 is not stateless like the TK-102, it
                        			needs to retain a session.  Basically, we just reply with 'ON'
                        			anything else seems to cause the device to reset the connection.
                        		 */
                        @socket_send($socket, "ON", 2, 0);
                        printLog($fh, date("d-m-y h:i:sa") . " Sent: ON");
                    }
                } else {
                    /*Here is where we land on the first iteration of the loop
                    		on a new connection. We get from the gps: ##,imei:<IMEI>,A;
                    		It seems the correct reply is 'LOAD' so that's what we send.
                    	  */
                    $init = $parts[0];
                    $conn_imei = substr($parts[1], 5);
                    $cmd = $parts[2];
                    if ($cmd = "A") {
                        @socket_send($socket, "LOAD", 4, 0);
                        // Abrindo arquivo de log do imei
                        abrirArquivoLog($conn_imei);
                        printLog($fh, date("d-m-y h:i:sa") . " Connection from {$remip}:{$remport}");
                        printLog($fh, date("d-m-y h:i:sa") . " Got : {$rec}");
                        printLog($fh, date("d-m-y h:i:sa") . " Sent: LOAD");
                    }
                }
            } else {
                /* M�DULO GPRMC */
                if (strpos($rec, "GPRMC") > -1) {
                    $isGPRMC = true;
                }
                $loopcount = 0;
                //printLog($fh, date("d-m-y h:i:sa") . " Got : $rec");
                $parts = explode(',', $rec);
                $cnx = mysql_connect("cloudservice.cgejdsdl842e.sa-east-1.rds.amazonaws.com", "gpstracker", "d1\$1793689");
                /*
                Array
                (
                	[0] => 0908242216
                	[1] => 0033663282263
                	[2] => GPRMC
                	[3] => 212442.000
                	[4] => A
                	[5] => 4849.0475
                	[6] => N
                	[7] => 00219.4763
                	[8] => E
                	[9] => 2.29
                	[10] =>
                	[11] => 220809
                	[12] =>
                	[13] =>
                	[14] => A*70
                	[15] => L
                	[16] => imei:359587017313647
                	[17] => 101Q
                	[18] =>
                
                )
                */
                if (count($parts) > 1) {
                    $trackerdate = mysql_real_escape_string($parts[0]);
                    $phone = mysql_real_escape_string($parts[1]);
                    $gprmc = mysql_real_escape_string($parts[2]);
                    $satelliteDerivedTime = mysql_real_escape_string($parts[3]);
                    $satelliteFixStatus = mysql_real_escape_string($parts[4]);
                    $latitudeDecimalDegrees = mysql_real_escape_string($parts[5]);
                    $latitudeHemisphere = mysql_real_escape_string($parts[6]);
                    $longitudeDecimalDegrees = mysql_real_escape_string($parts[7]);
                    $longitudeHemisphere = mysql_real_escape_string($parts[8]);
                    $speed = mysql_real_escape_string($parts[9]);
                    $bearing = mysql_real_escape_string($parts[10]);
                    $utcDate = mysql_real_escape_string($parts[11]);
                    // = $parts[12];
                    // = $parts[13];
                    $checksum = mysql_real_escape_string($parts[14]);
                    $gpsSignalIndicator = mysql_real_escape_string($parts[15]);
                    if (preg_match("/imei/", $parts[16])) {
                        $infotext = "gprmc";
                        //Nenhum comando enviado pelo gps
                        $imei = mysql_real_escape_string($parts[16]);
                        $other = mysql_real_escape_string($parts[17]);
                    } else {
                        $infotext = mysql_real_escape_string($parts[16]);
                        $imei = mysql_real_escape_string($parts[17]);
                        $other = mysql_real_escape_string($parts[18] . ' ' . $parts[19]);
                    }
                    if ($infotext == "") {
                        $infotext = "gprmc";
                    }
                    if (preg_match("/:/", substr($imei, 5))) {
                        $imei = substr($imei, 6);
                    } else {
                        $imei = substr($imei, 5);
                    }
                    /*
                    $imei = split(':', trim($imei));
                    if(count($imei) > 1){
                    	$imei = $imei[1];
                    }
                    */
                    $conn_imei = $imei;
                    abrirArquivoLog($conn_imei);
                    printLog($fh, date("d-m-y h:i:sa") . " Connection from {$remip}:{$remport}");
                    printLog($fh, date("d-m-y h:i:sa") . " Got : {$rec}");
                    //inicio verifica geofence
                    mysql_select_db('tracker', $cnx);
                    if ($imei != "") {
                        $consulta = mysql_query("SELECT * FROM geo_fence WHERE imei = '{$imei}'", $cnx);
                        while ($data = mysql_fetch_assoc($consulta)) {
                            $idCerca = $data['id'];
                            $imeiCerca = $data['imei'];
                            $nomeCerca = $data['nome'];
                            $coordenadasCerca = $data['coordenadas'];
                            $resultCerca = $data['tipo'];
                            $tipoEnvio = $data['tipoEnvio'];
                            strlen($latitudeDecimalDegrees) == 9 && ($latitudeDecimalDegrees = '0' . $latitudeDecimalDegrees);
                            $g = substr($latitudeDecimalDegrees, 0, 3);
                            $d = substr($latitudeDecimalDegrees, 3);
                            $strLatitudeDecimalDegrees = $g + $d / 60;
                            $latitudeHemisphere == "S" && ($strLatitudeDecimalDegrees = $strLatitudeDecimalDegrees * -1);
                            strlen($longitudeDecimalDegrees) == 9 && ($longitudeDecimalDegrees = '0' . $longitudeDecimalDegrees);
                            $g = substr($longitudeDecimalDegrees, 0, 3);
                            $d = substr($longitudeDecimalDegrees, 3);
                            $strLongitudeDecimalDegrees = $g + $d / 60;
                            $longitudeHemisphere == "S" && ($strLongitudeDecimalDegrees = $strLongitudeDecimalDegrees * -1);
                            $strLongitudeDecimalDegrees = $strLongitudeDecimalDegrees * -1;
                            $lat_point = $strLatitudeDecimalDegrees;
                            $lng_point = $strLongitudeDecimalDegrees;
                            $exp = explode("|", $coordenadasCerca);
                            if (count($exp) < 5) {
                                $strExp = explode(",", $exp[0]);
                                $strExp1 = explode(",", $exp[2]);
                            } else {
                                $int = count($exp) / 2;
                                $strExp = explode(",", $exp[0]);
                                $strExp1 = explode(",", $exp[$int]);
                            }
                            $lat_vertice_1 = $strExp[0];
                            $lng_vertice_1 = $strExp[1];
                            $lat_vertice_2 = $strExp1[0];
                            $lng_vertice_2 = $strExp1[1];
                            if ($lat_vertice_1 < $lat_point or $lat_point < $lat_vertice_2 and $lng_point < $lng_vertice_1 or $lng_vertice_2 < $lng_point) {
                                $result = '0';
                                $situacao = 'fora';
                            } else {
                                $result = '1';
                                $situacao = 'dentro';
                            }
                            if ($result != $resultCerca and round($speed * 1.852, 0) > 0) {
                                mysql_query("INSERT INTO message (imei, message) VALUES ('{$imeiCerca}', 'Cerca " . $nomeCerca . " Violada!')", $cnx);
                                if ($tipoEnvio == 0) {
                                    # Convert the GPS coordinates to a human readable address
                                    $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
                                    $rev_geo_str = file_get_contents($tempstr);
                                    $rev_geo_str = preg_replace("/\"/", "", $rev_geo_str);
                                    $rev_geo = explode(',', $rev_geo_str);
                                    $logradouro = $rev_geo[2] . "," . $rev_geo[3];
                                    require "lib/class.phpmailer.php";
                                    $consulta1 = mysql_query("SELECT a.*, b.* FROM cliente a INNER JOIN bem b ON (a.id = b.cliente) WHERE b.imei = '{$imeiCerca}'", $cnx);
                                    while ($data = mysql_fetch_assoc($consulta1)) {
                                        $emailDestino = $data['email'];
                                        $nameBem = $data['name'];
                                        $mensagem = "O veiculo " . $nameBem . ", esta " . $situacao . " do perimetro " . $nomeCerca . ", as " . date("H:i:s") . " do dia " . date("d/m/Y") . ", no local " . $logradouro . " e trafegando a " . round($speed * 1.852, 0) . " km/h.";
                                        $msg = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">";
                                        $msg .= "<html>";
                                        $msg .= "<head></head>";
                                        $msg .= "<body style=\"background-color:#fff;\" >";
                                        $msg .= "<p><strong>Alerta de Violacao de Perimetro:</strong><br /><br />";
                                        $msg .= $mensagem . "<br /><br />";
                                        $msg .= "Equipe BarukSat<br />";
                                        $msg .= "(85)88462069<br />";
                                        $msg .= "<a href=\"http://www.systemtracker.com.br\">www.systemtracker.com.br</a></p>";
                                        $msg .= "</body>";
                                        $msg .= "</html>";
                                        $mail = new PHPMailer();
                                        $mail->Mailer = "smtp";
                                        $mail->IsHTML(true);
                                        $mail->CharSet = "utf-8";
                                        $mail->SMTPSecure = "tls";
                                        $mail->Host = "smtp.gmail.com";
                                        $mail->Port = "587";
                                        $mail->SMTPAuth = "true";
                                        $mail->Username = "******";
                                        $mail->Password = "******";
                                        $mail->From = "*****@*****.**";
                                        $mail->FromName = "BarukSat";
                                        $mail->AddAddress($emailDestino);
                                        $mail->AddReplyTo($mail->From, $mail->FromName);
                                        $mail->Subject = "BarukSat - Alerta de Violacao de Perimetro";
                                        $mail->Body = $msg;
                                        if (!$mail->Send()) {
                                            echo "Erro de envio: " . $mail->ErrorInfo;
                                        } else {
                                            echo "Mensagem enviada com sucesso!";
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // if imei
                    //final verifica geofence
                    if ($gpsSignalIndicator != 'L') {
                        $movimento = '';
                        if ($speed > 0) {
                            $movimento = 'S';
                        } else {
                            $movimento = 'N';
                        }
                        $gpsLat = gprsToGps($latitudeDecimalDegrees, $latitudeHemisphere);
                        $gpsLon = gprsToGps($longitudeDecimalDegrees, $longitudeHemisphere);
                        $gpsLatAnt = 0;
                        $gpsLatHemAnt = '';
                        $gpsLonAnt = 0;
                        $gpsLonHemAnt = '';
                        $resLocAtual = mysql_query("select id from loc_atual where imei = '{$imei}' limit 1", $cnx);
                        $numRows = mysql_num_rows($resLocAtual);
                        if ($numRows == 0) {
                            mysql_query("INSERT INTO loc_atual (date, imei, phone, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator, converte) VALUES (convert_tz(now(), 'GMT', 'Brazil/East'), '{$imei}', '{$phone}', '{$satelliteFixStatus}', '{$latitudeDecimalDegrees}', '{$latitudeHemisphere}', '{$longitudeDecimalDegrees}', '{$longitudeHemisphere}', '{$speed}', '{$infotext}', '{$gpsSignalIndicator}', 1)", $cnx);
                        } else {
                            $dataLocAtual = mysql_fetch_assoc($resLocAtual);
                            $gpsLatAnt = $dataLocAtual[latitudeDecimalDegrees];
                            $gpsLatHemAnt = $dataLocAtual[latitudeHemisphere];
                            $gpsLonAnt = $dataLocAtual[longitudeDecimalDegrees];
                            $gpsLonHemAnt = $dataLocAtual[longitudeHemisphere];
                            mysql_query("UPDATE loc_atual set date = convert_tz(now(), 'GMT', 'Brazil/East'), phone = '{$phone}', satelliteFixStatus = '{$satelliteFixStatus}', latitudeDecimalDegrees = '{$latitudeDecimalDegrees}', latitudeHemisphere = '{$latitudeHemisphere}', longitudeDecimalDegrees = '{$longitudeDecimalDegrees}', longitudeHemisphere = '{$longitudeHemisphere}', speed = '{$speed}', infotext = '{$infotext}', gpsSignalIndicator = '{$gpsSignalIndicator}' where imei = '{$imei}'", $cnx);
                        }
                        $distance = 0;
                        try {
                            $bemId = $dataBem[id];
                            $countGeoDistance = mysql_query("select bem from geo_distance where bem = {$bemId}", $cnx);
                            if ($countGeoDistance === false || mysql_num_rows($countGeoDistance) == 0) {
                                mysql_query("insert into geo_distance (bem, tipo) values({$bemId}, 'I')", $cnx);
                                mysql_query("insert into geo_distance (bem, tipo) values({$bemId}, 'F')", $cnx);
                            }
                            /*envio de sms*/
                            if ($dataCliente['envia_sms'] == 'S' && $dataBem['envia_sms'] == 'S' && !empty($dataCliente['celular']) && !empty($dataCliente['sms_acada'])) {
                                if (empty($dataCliente['dt_ultm_sms'])) {
                                    mysql_query("update cliente set dt_ultm_sms = convert_tz(now(), 'GMT', 'Brazil/East') where id = {$dataCliente['id']}", $cnx);
                                } else {
                                    $horas = $dataCliente['horas'];
                                    $minutos = $dataCliente['minutos'];
                                    if (!empty($horas)) {
                                        $horas = $horas * 60;
                                    }
                                    $tempoTotal = $horas + $minutos;
                                    if ($tempoTotal > $dataCliente['sms_acada']) {
                                        $json = json_decode(file_get_contents("http://maps.google.com/maps/api/geocode/json?sensor=false&latlng={$gpsLat},{$gpsLon}&language=es-ES"));
                                        if (isset($json->status) && $json->status == 'OK' && isset($json->results[0]->formatted_address)) {
                                            $address = $json->results[0]->formatted_address;
                                            $address = utf8_decode($address);
                                            $aDataCliente = split(' ', $dataCliente['nome']);
                                            $msg = $texto_sms_localiza;
                                            $msg = str_replace("#CLIENTE", $aDataCliente[0], $msg);
                                            $msg = str_replace("#VEICULO", $dataBem['name'], $msg);
                                            $msg = str_replace("#LOCALIZACAO", $address, $msg);
                                            $msg = str_replace(' ', '+', $msg);
                                            sendSMS($dataCliente['celular'], $msg, '');
                                            if ($retorno < 0) {
                                                mysql_query("insert into controle(texto) values('envio de sms retorno: {$retorno}')", $cnx);
                                            } else {
                                                mysql_query("update cliente set dt_ultm_sms = convert_tz(now(), 'GMT', 'Brazil/East') where id = {$dataCliente['id']}", $cnx);
                                            }
                                        }
                                    }
                                }
                            }
                            if ($movimento == 'S') {
                                $resGeoDistance = mysql_query("select parou from geo_distance where bem = {$bemId} and tipo = 'I'", $cnx);
                                $dataGeoDistance = mysql_fetch_assoc($resGeoDistance);
                                if ($dataGeoDistance[parou] == 'S' || empty($dataGeoDistance[parou])) {
                                    mysql_query("update geo_distance set latitudeDecimalDegrees = '{$latitudeDecimalDegrees}', latitudeHemisphere = '{$latitudeHemisphere}', longitudeDecimalDegrees = '{$longitudeDecimalDegrees}', longitudeHemisphere = '{$longitudeHemisphere}', parou = 'N' where bem =  {$bemId} and tipo = 'I'", $cnx);
                                }
                            } else {
                                $resGeoDistance = mysql_query("select latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere from geo_distance where bem = {$bemId} and tipo = 'I'", $cnx);
                                if (mysql_num_rows($resGeoDistance) > 0) {
                                    $update = mysql_query("update geo_distance set latitudeDecimalDegrees = '{$latitudeDecimalDegrees}', latitudeHemisphere = '{$latitudeHemisphere}', longitudeDecimalDegrees = '{$longitudeDecimalDegrees}', longitudeHemisphere = '{$longitudeHemisphere}', parou = 'S' where bem =  {$bemId} and tipo = 'I'", $cnx);
                                    $dataGeoDistance = mysql_fetch_assoc($resGeoDistance);
                                    $gpsLatAnt = gprsToGps($dataGeoDistance[latitudeDecimalDegrees], $dataGeoDistance[latitudeHemisphere]);
                                    $gpsLonAnt = gprsToGps($dataGeoDistance[longitudeDecimalDegrees], $dataGeoDistance[longitudeHemisphere]);
                                    if ($gpsLatAnt != $gpsLat) {
                                        if ($gpsLatAnt != 0 && $gpsLonAnt != 0) {
                                            /*
                                            $json = json_decode(file_get_contents('http://dev.virtualearth.net/REST/V1/Routes/Driving?o=xml&wp.0=$gpsLatAnt,$gpsLonAnt&wp.1=$gpsLat,$gpsLon&avoid=minimizeTolls&key=AqMJv19uaRKDbu-wSgUt3paCfXETZjBafVBMDXX9Rc4XyqmM6l4R_A8TgEXuWT6G'));
                                            if(isset($json->rows[0]->elements[0]->distance)){
                                            }
                                            */
                                            /*
                                            $json = json_decode(file_get_contents("http://maps.googleapis.com/maps/api/distancematrix/json?sensor=false&origins=$gpsLatAnt,$gpsLonAnt&destinations=$gpsLat,$gpsLon"));
                                            if(isset($json->rows[0]->elements[0]->distance)){
                                            	$strDistance = $json->rows[0]->elements[0]->distance->value;
                                            	$distance = $strDistance+0;
                                            
                                            	$alertaACada = $dataBem['alerta_hodometro'];
                                            	$alertaACadaSaldo = $dataBem['alerta_hodometro_saldo'];
                                            	$alertaACadaSaldo = ($alertaACadaSaldo*1000) - $distance;
                                            	if($alertaACadaSaldo <= 0 && $alertaACada > 0){
                                            		$msg = $texto_sms_alerta_hodometro;
                                            		$msg = str_replace("#CLIENTE", $aDataCliente[0], $msg);
                                            		$msg = str_replace("#VEICULO", $dataBem['name'], $msg);
                                            		$msg = str_replace("#HODOMETRO", $alertaACada, $msg);
                                            		$msg = str_replace(' ', '+', $msg);
                                            		sendSMS($dataCliente['celular'], $msg, '');
                                            		$alertaACadaSaldo = $alertaACada;
                                            	}
                                            	$alertaACadaSaldo = (int)$alertaACadaSaldo/1000;
                                            }
                                            */
                                            $geoDistance = distance($gpsLatAnt, $gpsLonAnt, $gpsLat, $gpsLon, 'K');
                                            //$strDistance = $json->rows[0]->elements[0]->distance->value;
                                            $distance = (int) ($geoDistance * 1000);
                                            $alertaACada = $dataBem['alerta_hodometro'];
                                            $alertaACadaSaldo = $dataBem['alerta_hodometro_saldo'];
                                            $alertaACadaSaldo = $alertaACadaSaldo * 1000 - $distance;
                                            if ($alertaACadaSaldo <= 0 && $alertaACada > 0) {
                                                $msg = $texto_sms_alerta_hodometro;
                                                $msg = str_replace("#CLIENTE", $aDataCliente[0], $msg);
                                                $msg = str_replace("#VEICULO", $dataBem['name'], $msg);
                                                $msg = str_replace("#HODOMETRO", $alertaACada, $msg);
                                                $msg = str_replace(' ', '+', $msg);
                                                //sendSMS($dataCliente['celular'], $msg, '');
                                                $alertaACadaSaldo = $alertaACada;
                                            }
                                            $alertaACadaSaldo = (int) $alertaACadaSaldo / 1000;
                                        }
                                    }
                                }
                            }
                        } catch (Exception $e) {
                            mysql_query("INSERT INTO controle (texto) VALUES ({$e->getMessage}())", $cnx);
                        }
                        mysql_query("UPDATE bem set date = date, status_sinal = 'R', movimento = '{$movimento}', hodometro=hodometro+{$distance} WHERE imei = '{$imei}'", $cnx);
                        mysql_query("INSERT INTO gprmc (date, imei, phone, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator, km_rodado, converte) VALUES (convert_tz(now(), 'GMT', 'Brazil/East'), '{$imei}', '{$phone}', '{$satelliteFixStatus}', '{$latitudeDecimalDegrees}', '{$latitudeHemisphere}', '{$longitudeDecimalDegrees}', '{$longitudeHemisphere}', '{$speed}', '{$infotext}', '{$gpsSignalIndicator}', {$distance}, 1)", $cnx);
                        error_log("INSERT INTO gprmc (date, imei, phone, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator, km_rodado, converte) VALUES (convert_tz(now(), 'GMT', 'Brazil/East'), '{$imei}', '{$phone}', '{$satelliteFixStatus}', '{$latitudeDecimalDegrees}', '{$latitudeHemisphere}', '{$longitudeDecimalDegrees}', '{$longitudeHemisphere}', '{$speed}', '{$infotext}', '{$gpsSignalIndicator}', {$distance}, 1)");
                    } else {
                        mysql_query("UPDATE bem set date = date, status_sinal = 'S' WHERE imei = '{$imei}'", $cnx);
                    }
                    # Now check to see if we need to send any alerts.
                    if (trim($infotext) != "gprmc") {
                        $res = mysql_query("SELECT responsible FROM bem WHERE imei='{$imei}'", $cnx);
                        while ($data = mysql_fetch_assoc($res)) {
                            switch ($infotext) {
                                case "dt":
                                    $body = "Disable Track OK";
                                    break;
                                case "et":
                                    $body = "Stop Alarm OK";
                                    break;
                                case "gt":
                                    $body = "Move Alarm set OK";
                                    break;
                                case "help me":
                                    $body = "Help!";
                                    mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'SOS!')", $cnx);
                                    break;
                                case "ht":
                                    $body = "Speed alarm set OK";
                                    break;
                                case "it":
                                    $body = "Timezone set OK";
                                    break;
                                case "low battery":
                                    $body = "Low battery!\nYou have about 2 minutes...";
                                    mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Bat. Fraca')", $cnx);
                                    break;
                                case " bat:":
                                    $body = "Low battery!\nYou have about 2 minutes...";
                                    mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Bat. Fraca')", $cnx);
                                    break;
                                case "Low batt":
                                    $body = "Low battery!\nYou have about 2 minutes...";
                                    mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Bat. Fraca')", $cnx);
                                    break;
                                case "move":
                                    $body = "Move Alarm!";
                                    mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Movimento')", $cnx);
                                    break;
                                case "nt":
                                    $body = "Returned to SMS mode OK";
                                    break;
                                case "speed":
                                    $body = "Speed alarm!";
                                    mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Velocidade')", $cnx);
                                    break;
                                case "stockade":
                                    $body = "Geofence Violation!";
                                    mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Cerca')", $cnx);
                                    break;
                            }
                            //switch
                            //Enviando e-mail de alerta
                            $headers = "From: {$email_from}" . "\r\n" . "Reply-To: {$email_from}" . "\r\n";
                            $responsible = $data['responsible'];
                            $rv = mail($responsible, "Tracker - {$imei}", $body, $headers);
                        }
                        //while
                    }
                } else {
                    //GRPMC nao precisa reter a sessao
                }
                //No protocolo GPRMC cada nova conex�o � um IP. Enviando comando no fim da conexao, ap�s obter os dados.
                if (file_exists("{$command_path}/{$conn_imei}")) {
                    $send_cmd = file_get_contents("{$command_path}/{$conn_imei}");
                    socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                    mysql_query("DELETE FROM command WHERE imei = {$conn_imei}");
                    unlink("{$command_path}/{$conn_imei}");
                    printLog($fh, "Comandos do Banco e Arquivo apagados: " . $send_cmd . " imei: " . $conn_imei);
                }
                mysql_close($cnx);
                break;
            }
        }
        //Checando se utilizou os dois protocolos para uma escuta
        if ($isGIMEI == true and $isGPRMC == true) {
            //printLog($fh, "ATENCAO: falha na obtencao do protocolo. Kill pid.");
        }
        $rec = "";
    }
    //while
}
示例#5
0
function interact($socket)
{
    global $fh;
    global $command_path;
    global $firstInteraction;
    global $remip;
    global $remport;
    $loopcount = 0;
    $conn_imei = "";
    /* TALK TO YOUR CLIENT */
    $rec = "";
    // Variavel que indica se comando está em banco ou arquivo.
    $tipoComando = "banco";
    //"arquivo";
    //Checando o protocolo
    $isGIMEI = false;
    $isGPRMC = false;
    $send_cmd = "";
    # Read the socket but don't wait for data..
    while (@socket_recv($socket, $rec, 2048, 0x40) !== 0) {
        # If we know the imei of the phone and there is a pending command send it.
        # Some pacing to ensure we don't split any incoming data.
        sleep(1);
        # Timeout the socket if it's not talking...
        # Prevents duplicate connections, confusing the send commands
        $loopcount++;
        if ($loopcount > 120) {
            return;
        }
        #remove any whitespace from ends of string.
        $rec = trim($rec);
        //Conecta e pega o comando pendente
        $cnx = mysql_connect("cloudservice.cgejdsdl842e.sa-east-1.rds.amazonaws.com", "gpstracker", "d1\$1793689") or die("Could not connect: " . mysql_error());
        mysql_select_db('tracker', $cnx);
        //mysql_select_db('tracker', $cnx);
        if ($rec != "" and $rec != '?') {
            mysql_close($cnx);
            if (strpos($rec, "\$") === true) {
                $isGPRMC = true;
            }
            $loopcount = 0;
            $parts = explode(',', $rec);
            $cnx = mysql_connect("localhost", "gpstracker", "d1\$1793689");
            if ($parts[1] !== "" and $parts[0] !== "?") {
                if (strpos($rec, 'CEL') == true) {
                    $imei = substr($parts[0], 1);
                    $satelliteFixStatus = 'A';
                    $latitude = substr($parts[2], 1);
                    $latitudeHemisphere = 'S';
                    $longitude = substr($parts[3], 2);
                    $longitudeHemisphere = 'W';
                    $speed = $parts[4];
                    $gpsSignalIndicator = 'F';
                    $infotext = "tracker";
                    $ignicao = $parts[14];
                    $latitudeDecimalDegrees = "-{$latitude}";
                    $longitudeDecimalDegrees = "-{$longitude}";
                } else {
                    $imei = substr($parts[0], 1);
                    $satelliteFixStatus = 'A';
                    $latitude = substr($parts[1], 1);
                    $latitudeHemisphere = 'S';
                    $longitude = substr($parts[2], 1);
                    $longitudeHemisphere = 'W';
                    $speed = $parts[3];
                    $gpsSignalIndicator = 'F';
                    $infotext = "tracker";
                    $ignicao = $parts[13];
                    $latitudeDecimalDegrees = "{$latitude}";
                    $longitudeDecimalDegrees = "{$longitude}";
                    // Calculo das coordenadas. Convertendo coordenadas do modo GPRS para GPS
                    strlen($latitudeDecimalDegrees) == 9 && ($latitudeDecimalDegrees = '0' . $latitudeDecimalDegrees);
                    $g = substr($latitudeDecimalDegrees, 0, 3);
                    $d = substr($latitudeDecimalDegrees, 3);
                    $latitudeDecimalDegrees = $g + $d / 60;
                    $latitudeHemisphere == "S" && ($latitudeDecimalDegrees = $latitudeDecimalDegrees * -1);
                    strlen($longitudeDecimalDegrees) == 9 && ($longitudeDecimalDegrees = '0' . $longitudeDecimalDegrees);
                    $g = substr($longitudeDecimalDegrees, 0, 3);
                    $d = substr($longitudeDecimalDegrees, 3);
                    $longitudeDecimalDegrees = $g + $d / 60;
                    $longitudeHemisphere == "W" && ($longitudeDecimalDegrees = $longitudeDecimalDegrees * -1);
                }
                if ($ignicao == 0) {
                    $ligado = 'N';
                } else {
                    $ligado = 'S';
                }
                if ($infotext == "") {
                    $infotext = "tracker";
                }
                $conn_imei = $imei;
                abrirArquivoLog($conn_imei);
                printLog($fh, date("d-m-y h:i:sa") . " Connection from {$remip}:{$remport}");
                printLog($fh, date("d-m-y h:i:sa") . " Got : {$rec}");
                mysql_select_db('tracker', $cnx);
                if ($gpsSignalIndicator != 'L') {
                    $address = null;
                    $phone = '7097';
                    $resLocAtual = mysql_query("select id, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere from loc_atual where imei = '{$imei}' limit 1", $cnx);
                    $numRows = mysql_num_rows($resLocAtual);
                    if ($numRows == 0) {
                        mysql_query("INSERT INTO loc_atual (date, imei, phone, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator, converte) VALUES (now(), '{$imei}', '{$phone}', '{$satelliteFixStatus}', '{$latitudeDecimalDegrees}', '{$latitudeHemisphere}', '{$longitudeDecimalDegrees}', '{$longitudeHemisphere}', '{$speed}', '{$infotext}', '{$gpsSignalIndicator}', 0)", $cnx);
                    } else {
                        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 where imei = '{$imei}'", $cnx);
                    }
                    /* MUDA O STATUS LIGADO / DESLIGADO*/
                    if ($ignicao == '0') {
                        mysql_query("UPDATE bem set date = now(), ligado = 'N' WHERE imei = '{$imei}'", $cnx);
                    } else {
                        mysql_query("UPDATE bem set date = now(), ligado = 'S' WHERE imei = '{$imei}'", $cnx);
                    }
                    mysql_query("UPDATE bem set date = now(), status_sinal = 'R' WHERE imei = '{$imei}'", $cnx);
                    mysql_query("INSERT INTO gprmc (date, imei, phone, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator, address, ligado) VALUES (now(), '{$imei}', '{$phone}', '{$satelliteFixStatus}', '{$latitudeDecimalDegrees}', '{$latitudeHemisphere}', '{$longitudeDecimalDegrees}', '{$longitudeHemisphere}', '{$speed}', '{$infotext}', '{$gpsSignalIndicator}', '{$address}', '{$ligado}')", $cnx);
                } else {
                    mysql_query("UPDATE bem set date = now(), status_sinal = 'S' WHERE imei = '{$imei}'", $cnx);
                }
                # Now check to see if we need to send any alerts.
                if (trim($infotext) != "gprmc") {
                    $res = mysql_query("SELECT * FROM bem WHERE imei='{$imei}'", $cnx);
                    while ($data = mysql_fetch_assoc($res)) {
                        switch ($infotext) {
                            case "dt":
                                $body = "Disable Track OK";
                                break;
                            case "et":
                                $body = "Stop Alarm OK";
                                break;
                            case "gt":
                                $body = "Move Alarm set OK";
                                break;
                            case "help me":
                                $body = "Help!";
                                mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'SOS!')", $cnx);
                                break;
                            case "ht":
                                $body = "Speed alarm set OK";
                                break;
                            case "it":
                                $body = "Timezone set OK";
                                break;
                            case "low battery":
                                $body = "Low battery!\nYou have about 2 minutes...";
                                mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Bat. Fraca')", $cnx);
                                break;
                            case " bat:":
                                $body = "Low battery!\nYou have about 2 minutes...";
                                mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Bat. Fraca')", $cnx);
                                break;
                            case "Low batt":
                                $body = "Low battery!\nYou have about 2 minutes...";
                                mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Bat. Fraca')", $cnx);
                                break;
                            case "move":
                                $body = "Move Alarm!";
                                mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Movimento')", $cnx);
                                break;
                            case "nt":
                                $body = "Returned to SMS mode OK";
                                break;
                            case "speed":
                                $body = "Speed alarm!";
                                mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Velocidade')", $cnx);
                                break;
                            case "stockade":
                                $body = "Geofence Violation!";
                                mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Cerca')", $cnx);
                                break;
                        }
                        //switch
                        //Enviando e-mail de alerta
                        //$headers = "From: $email_from" . "\r\n" . "Reply-To: $email_from" . "\r\n";
                        //$responsible = $data['responsible'];
                        //$rv = mail($responsible, "Tracker - $imei", $body, $headers);
                    }
                    //while
                }
            } else {
                //GRPMC nao precisa reter a sessao
            }
            //No protocolo GPRMC cada nova conexão é um IP. Enviando comando no fim da conexao, após obter os dados.
            if ($conn_imei != "") {
                if ($tipoComando == "banco") {
                    //Conecta e pega o comando pendente
                    $cnx = mysql_connect("cloudservice.cgejdsdl842e.sa-east-1.rds.amazonaws.com", "gpstracker", "d1\$1793689") or die("Could not connect: " . mysql_error());
                    mysql_select_db('tracker', $cnx);
                    $res = mysql_query("SELECT c.command FROM command c WHERE c.imei = '{$conn_imei}' ORDER BY date DESC LIMIT 1");
                    while ($data = mysql_fetch_assoc($res)) {
                        $send_cmd = $data['command'];
                        socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                    }
                    // Deletando comando
                    //$send_cmd = trim($send_cmd);
                    //unlink("$command_path/$conn_imei");
                    mysql_query("DELETE FROM command WHERE imei = {$conn_imei}");
                    mysql_query("insert into teste(id,string) values(null, '{$send_cmd}')", $cnx);
                    mysql_close($cnx);
                    printLog($fh, "Comandos do arquivo apagado: " . $send_cmd . " imei: " . $conn_imei);
                }
                // Comando enviado
                //printLog($fh, date("d-m-y h:i:sa") . " Sent: $send_cmd");
            }
            //				if (file_exists("$command_path$conn_imei"))
            //				{
            //					$send_cmd = file_get_contents("$command_path$conn_imei");
            //					socket_send($socket, $send_cmd, strlen($send_cmd), 0);
            //					//mysql_query("DELETE FROM command WHERE imei = $conn_imei");
            //					unlink("$command_path$conn_imei");
            //					printLog($fh, "Comandos do Banco e Arquivo apagados: " . $send_cmd . " imei: " . $conn_imei);
            //				}
            /*
            				$cnx = mysql_connect("cloudservice.cgejdsdl842e.sa-east-1.rds.amazonaws.com", "gpstracker", "d1$1793689") 
            						  or die("Could not connect: " . mysql_error());
            				mysql_select_db('tracker', $cnx);
            				//$res = mysql_query("SELECT c.command FROM command c WHERE c.command like '**,imei:". $conn_imei .",C,%' and c.imei = $conn_imei ORDER BY date DESC LIMIT 1");
            				$res = mysql_query("SELECT c.command FROM command c WHERE c.imei = '$conn_imei' ORDER BY date DESC LIMIT 1");
            				while($data = mysql_fetch_assoc($res))
            					{
            						$send_cmd = $data['command'];
            					
            						
            						
            						socket_send($socket, $send_cmd, strlen($send_cmd), 0);
            						mysql_query("DELETE FROM command WHERE imei = $conn_imei");
            					
            					}
            				mysql_close($cnx);
            */
            break;
        }
        //Checando se utilizou os dois protocolos para uma escuta
        if ($isGIMEI == true and $isGPRMC == true) {
            //printLog($fh, "ATENCAO: falha na obtencao do protocolo. Kill pid.");
        }
        $rec = "";
    }
    //while
}
示例#6
0
function interact($socket)
{
    global $fh;
    global $command_path;
    global $firstInteraction;
    global $remip;
    global $remport;
    $loopcount = 0;
    $conn_imei = "";
    /* TALK TO YOUR CLIENT */
    $rec = "";
    // Variavel que indica se comando está em banco ou arquivo.
    $tipoComando = "banco";
    //"arquivo";
    //Checando o protocolo
    $isGIMEI = false;
    $isGPRMC = false;
    $send_cmd = "";
    # Read the socket but don't wait for data..
    while (@socket_recv($socket, $rec, 2048, 0x40) !== 0) {
        # If we know the imei of the phone and there is a pending command send it.
        if ($conn_imei != "") {
            if ($tipoComando == "arquivo" and file_exists("{$command_path}/{$conn_imei}")) {
                $send_cmd = file_get_contents("{$command_path}/{$conn_imei}");
                socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                unlink("{$command_path}/{$conn_imei}");
                printLog($fh, "Arquivo de comandos apagado: " . $send_cmd . " imei: " . $conn_imei);
            } else {
                if ($tipoComando == "banco" and file_exists("{$command_path}/{$conn_imei}")) {
                    //Conecta e pega o comando pendente
                    $cnx = mysql_connect("cloudservice.cgejdsdl842e.sa-east-1.rds.amazonaws.com", "gpstracker", "d1\$1793689") or die("Could not connect: " . mysql_error());
                    mysql_select_db('tracker', $cnx);
                    $res = mysql_query("SELECT c.command FROM command c WHERE c.imei = '{$conn_imei}' ORDER BY date DESC LIMIT 1");
                    while ($data = mysql_fetch_assoc($res)) {
                        $send_cmd = $data['command'];
                    }
                    // Deletando comando
                    //mysql_query("DELETE FROM command WHERE imei = $conn_imei");
                    mysql_close($cnx);
                    socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                    unlink("{$command_path}/{$conn_imei}");
                    printLog($fh, "Comandos do arquivo apagado: " . $send_cmd . " imei: " . $conn_imei);
                } else {
                    //Se nao tiver comando na fila e for a primeira iteracao, obtem o ultimo comando válido enviado
                    if ($firstInteraction == true) {
                        sleep(1);
                        $send_cmd = "**,imei:" . $conn_imei . ",C,02m";
                        //Obtendo o ultimo comando
                        $cnx = mysql_connect("cloudservice.cgejdsdl842e.sa-east-1.rds.amazonaws.com", "gpstracker", "d1\$1793689") or die("Could not connect: " . mysql_error());
                        mysql_select_db('tracker', $cnx);
                        $res = mysql_query("SELECT c.command FROM command c WHERE c.command like '**,imei:" . $conn_imei . ",C,%' and c.imei = {$conn_imei} ORDER BY date DESC LIMIT 1");
                        while ($data = mysql_fetch_assoc($res)) {
                            $send_cmd = $data['command'];
                        }
                        mysql_close($cnx);
                        socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                        printLog($fh, "Comando de start: " . $send_cmd . " imei: " . $conn_imei);
                        $firstInteraction = false;
                    }
                }
            }
            // Comando enviado
            //printLog($fh, date("d-m-y h:i:sa") . " Sent: $send_cmd");
        }
        # Some pacing to ensure we don't split any incoming data.
        sleep(1);
        # Timeout the socket if it's not talking...
        # Prevents duplicate connections, confusing the send commands
        $loopcount++;
        if ($loopcount > 120) {
            return;
        }
        #remove any whitespace from ends of string.
        $rec = trim($rec);
        //Conecta e pega o comando pendente
        $cnx = mysql_connect("cloudservice.cgejdsdl842e.sa-east-1.rds.amazonaws.com", "gpstracker", "d1\$1793689") or die("Could not connect: " . mysql_error());
        mysql_select_db('tracker', $cnx);
        //mysql_select_db('tracker', $cnx);
        if ($rec != "") {
            mysql_query("INSERT INTO teste (id,string) VALUES (null,'{$rec}')", $cnx);
            mysql_close($cnx);
            if (strpos($rec, "GPRMC") === false) {
                /* MÓDULO IMEI GENÉRICO */
                $isGIMEI = true;
                $loopcount = 0;
                if ($fh != null) {
                    printLog($fh, date("d-m-y h:i:sa") . " Got : {$rec}");
                }
                $line = explode("#", $rec);
                printLog($fh, date("d-m-y h:i:sa") . " Equipamento (IMEI GENERICO) : " . $line[2]);
                $parts = explode(',', $rec);
                if (strpos($parts[0], "#") === FALSE) {
                    $cnx = mysql_connect("cloudservice.cgejdsdl842e.sa-east-1.rds.amazonaws.com", "gpstracker", "d1\$1793689");
                    /* Andrew's tracker is different....
                    			Array
                    			(       
                    				[0] => imei:354779030525274
                    				[1] => tracker
                    				[2] => 0909221022
                    				[3] => +61417801658
                    				[4] => F
                    				[5] => 022234.000
                    				[6] => A
                    				[7] => 3506.5232
                    				[8] => S
                    				[9] => 13829.5988
                    				[10] => E
                    				[11] => 0.00
                    				[12] => 
                    			)
                    			*/
                    # $imei                       = substr($parts[0],0, -1);
                    # Only worry about the rest if there is data to get
                    if (count($parts) > 1) {
                        $imei = substr($parts[0], 5);
                        if ($imei == "") {
                            $imei = explode("#", $rec);
                            $imei = $imei[1];
                        }
                        $infotext = mysql_real_escape_string($parts[1]);
                        $trackerdate = mysql_real_escape_string($parts[2]);
                        $gpsSignalIndicator = mysql_real_escape_string($parts[4]);
                        //Se gpsSignalIndicator <> L, pega o outros dados
                        if ($gpsSignalIndicator != 'L') {
                            $phone = mysql_real_escape_string($parts[3]);
                            $satelliteFixStatus = mysql_real_escape_string($parts[6]);
                            $latitudeDecimalDegrees = mysql_real_escape_string($parts[7]);
                            $latitudeHemisphere = mysql_real_escape_string($parts[8]);
                            $longitudeDecimalDegrees = mysql_real_escape_string($parts[9]);
                            $longitudeHemisphere = mysql_real_escape_string($parts[10]);
                            $speed = mysql_real_escape_string($parts[11]);
                        }
                        # Write it to the database...
                        mysql_select_db('tracker', $cnx);
                        if ($gpsSignalIndicator != 'L') {
                            mysql_query("UPDATE bem set date = date, status_sinal = 'R' WHERE imei = '{$imei}'", $cnx);
                            mysql_query("INSERT INTO gprmc (date, imei, phone, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator) VALUES (now(), '{$imei}', '{$phone}', '{$satelliteFixStatus}', '{$latitudeDecimalDegrees}', '{$latitudeHemisphere}', '{$longitudeDecimalDegrees}', '{$longitudeHemisphere}', '{$speed}', '{$infotext}', '{$gpsSignalIndicator}')", $cnx);
                        } else {
                            mysql_query("UPDATE bem set date = date, status_sinal = 'S' WHERE imei = '{$imei}'", $cnx);
                        }
                        # Now check to see if we need to send any alerts.
                        if ($infotext != "tracker") {
                            $res = mysql_query("SELECT * FROM bem WHERE imei='{$imei}'", $cnx);
                            while ($data = mysql_fetch_assoc($res)) {
                                switch ($infotext) {
                                    case "dt":
                                        $body = "Disable Track OK";
                                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Rast. Desabilitado')", $cnx);
                                        break;
                                    case "pt":
                                        $body = "Cerca Cancelada";
                                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Cerca Cancelada')", $cnx);
                                        break;
                                    case "ot":
                                        $body = "Cerca Ativada";
                                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Cerca Ativada')", $cnx);
                                        break;
                                    case "gt":
                                        $body = "Move Alarm set OK";
                                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Alarme Ativado')", $cnx);
                                        break;
                                    case "help me":
                                        $body = "Help!";
                                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'SOS')", $cnx);
                                        //Envia comando de resposta: alerta recebido
                                        $send_cmd = "**,imei:" . $conn_imei . ",E";
                                        socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                                        //printLog($fh, "Comando de resposta (help me): " . $send_cmd . " imei: " . $conn_imei);
                                        break;
                                    case "ht":
                                        $body = "Speed alarm set OK";
                                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Alarme Ativado')", $cnx);
                                        break;
                                    case "it":
                                        $body = "Timezone set OK";
                                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Fuso Modificado')", $cnx);
                                        break;
                                    case "low battery":
                                        $body = "Low battery!\nYou have about 2 minutes...";
                                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Bat. Fraca')", $cnx);
                                        //Envia comando de resposta: alerta recebido
                                        $send_cmd = "**,imei:" . $conn_imei . ",E";
                                        socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                                        //printLog($fh, "Comando de resposta (low battery): " . $send_cmd . " imei: " . $conn_imei);
                                        break;
                                    case "move":
                                        $body = "Move Alarm!";
                                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Movimento')", $cnx);
                                        //Envia comando de resposta: alerta recebido
                                        $send_cmd = "**,imei:" . $conn_imei . ",E";
                                        socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                                        //printLog($fh, "Comando de resposta (move): " . $send_cmd . " imei: " . $conn_imei);
                                        break;
                                    case "nt":
                                        $body = "Returned to SMS mode OK";
                                        break;
                                    case "speed":
                                        $body = "Speed alarm!";
                                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Velocidade')", $cnx);
                                        //Envia comando de resposta: alerta recebido
                                        $send_cmd = "**,imei:" . $conn_imei . ",E";
                                        socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                                        //printLog($fh, "Comando de resposta (speed): " . $send_cmd . " imei: " . $conn_imei);
                                        break;
                                    case "stockade":
                                        $body = "Geofence Violation!";
                                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Cerca Violada')", $cnx);
                                        //Envia comando de resposta: alerta recebido
                                        $send_cmd = "**,imei:" . $conn_imei . ",E";
                                        socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                                        //printLog($fh, "Comando de resposta (stockade): " . $send_cmd . " imei: " . $conn_imei);
                                        break;
                                    case "door alarm":
                                        $body = "Open door!";
                                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Sensor')", $cnx);
                                        //Envia comando de resposta: alerta recebido
                                        $send_cmd = "**,imei:" . $conn_imei . ",E";
                                        socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                                        //printLog($fh, "Comando de resposta (door alarm): " . $send_cmd . " imei: " . $conn_imei);
                                        break;
                                    case "acc alarm":
                                        $body = "ACC alarm!";
                                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Ignicao')", $cnx);
                                        //Envia comando de resposta: alerta recebido
                                        $send_cmd = "**,imei:" . $conn_imei . ",E";
                                        socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                                        //printLog($fh, "Comando de resposta (acc alarm): " . $send_cmd . " imei: " . $conn_imei);
                                        break;
                                }
                                //switch
                                //Enviando e-mail de alerta
                                //$headers = "From: $email_from" . "\r\n" . "Reply-To: $email_from" . "\r\n";
                                //$responsible = $data['responsible'];
                                //$rv = mail($responsible, "Tracker - $imei", $body, $headers);
                            }
                            //while
                        }
                        mysql_close($cnx);
                    } else {
                        /* If we got here, we got an imei ONLY - not even 'imei:' first
                        			This seems to be some sort of 'keepalive' packet
                        			The TK-201 is not stateless like the TK-102, it
                        			needs to retain a session.  Basically, we just reply with 'ON'
                        			anything else seems to cause the device to reset the connection.
                        		 */
                        @socket_send($socket, "ON", 2, 0);
                        printLog($fh, date("d-m-y h:i:sa") . " Sent: ON");
                    }
                } else {
                    /*Here is where we land on the first iteration of the loop
                    		on a new connection. We get from the gps: ##,imei:<IMEI>,A;
                    		It seems the correct reply is 'LOAD' so that's what we send.
                    	  */
                    $init = $parts[0];
                    $conn_imei = trim(substr($parts[1], 5));
                    if ($conn_imei == "") {
                        $conn_imei = explode("#", $rec);
                        $conn_imei = $conn_imei[1];
                    }
                    $cmd = $parts[2];
                    if ($cmd = "A") {
                        @socket_send($socket, "LOAD", 4, 0);
                        // Abrindo arquivo de log do imei
                        abrirArquivoLog($conn_imei);
                        printLog($fh, date("d-m-y h:i:sa") . " Connection from {$remip}:{$remport}");
                        printLog($fh, date("d-m-y h:i:sa") . " Got : {$rec}");
                        printLog($fh, date("d-m-y h:i:sa") . " Sent: LOAD");
                        printLog($fh, date("d-m-y h:i:sa") . " Equipamento (LOAD) : " . $line[2]);
                    }
                }
            } else {
                /* MODULO GPRMC */
                if (strpos($rec, "GPRMC") === true) {
                    $isGPRMC = true;
                }
                $loopcount = 0;
                //printLog($fh, date("d-m-y h:i:sa") . " Got : $rec");
                $parts = split(',', $rec);
                $cnx = mysql_connect("cloudservice.cgejdsdl842e.sa-east-1.rds.amazonaws.com", "gpstracker", "d1\$1793689");
                /*
                Array
                (
                	[0] => 0908242216
                	[1] => 0033663282263
                	[2] => GPRMC
                	[3] => 212442.000
                	[4] => A
                	[5] => 4849.0475
                	[6] => N
                	[7] => 00219.4763
                	[8] => E
                	[9] => 2.29
                	[10] =>
                	[11] => 220809
                	[12] =>
                	[13] =>
                	[14] => A*70
                	[15] => L
                	[16] => imei:359587017313647
                	[17] => 101Q
                	[18] =>
                
                )
                */
                $line = explode("#", $rec);
                printLog($fh, date("d-m-y h:i:sa") . " Equipamento (GPRMC) : " . $line[2]);
                $equipamento = trim($line[2]);
                if (count($parts) > 1) {
                    // INICIO MODULO PARA TLT-2H -->
                    if ($equipamento == "V500" or $equipamento == "V600") {
                        $trackerdate = date("Y-m-d H:i:s");
                        // ok
                        $phone = "";
                        //ok
                        $gprmc = "";
                        //ok
                        $satelliteDerivedTime = "";
                        //ok
                        $satelliteFixStatus = mysql_real_escape_string($parts[2]);
                        // ok
                        $latitudeDecimalDegrees = mysql_real_escape_string($parts[3]);
                        // ok
                        $latitudeHemisphere = mysql_real_escape_string($parts[4]);
                        // ok
                        $longitudeDecimalDegrees = mysql_real_escape_string($parts[5]);
                        // ok
                        $longitudeHemisphere = mysql_real_escape_string($parts[6]);
                        // ok
                        $speed = mysql_real_escape_string($parts[7]);
                        // ok
                        $bearing = "";
                        //mysql_real_escape_string($parts[8]);
                        $utcDate = mysql_real_escape_string($parts[9]);
                        // ok
                        // = $parts[12];
                        // = $parts[13];
                        $checksum = "";
                        //mysql_real_escape_string($parts[14]);
                        $gpsSignalIndicator = "";
                        //mysql_real_escape_string($parts[15]);
                        /*if(ereg("imei",$parts[16]))
                        		{
                        			$infotext           = "gprmc"; //Nenhum comando enviado pelo gps
                        			$imei 				= "";//mysql_real_escape_string($parts[16]);
                        			$other 				= "";//mysql_real_escape_string($parts[17]);
                        		}
                        		else
                        		{
                        			$infotext			= "";//mysql_real_escape_string($parts[16]);
                        			$imei 				= "";//mysql_real_escape_string($parts[17]);
                        			$other 				= mysql_real_escape_string($parts[18].' '.$parts[19]);
                        		}*/
                        if ($infotext == "") {
                            $infotext = "gprmc";
                        }
                        /*if(ereg(":", substr($imei,5)))
                        			$imei = substr($imei,6);
                        		else
                        			$imei = substr($imei,5);*/
                        if ($imei == "") {
                            $imei = explode("#", $rec);
                            $imei = $imei[1];
                        }
                        $conn_imei = $imei;
                    } else {
                        $trackerdate = mysql_real_escape_string($parts[0]);
                        $phone = mysql_real_escape_string($parts[1]);
                        $gprmc = mysql_real_escape_string($parts[2]);
                        $satelliteDerivedTime = mysql_real_escape_string($parts[3]);
                        $satelliteFixStatus = mysql_real_escape_string($parts[4]);
                        $latitudeDecimalDegrees = mysql_real_escape_string($parts[5]);
                        $latitudeHemisphere = mysql_real_escape_string($parts[6]);
                        $longitudeDecimalDegrees = mysql_real_escape_string($parts[7]);
                        $longitudeHemisphere = mysql_real_escape_string($parts[8]);
                        $speed = mysql_real_escape_string($parts[9]);
                        $bearing = mysql_real_escape_string($parts[10]);
                        $utcDate = mysql_real_escape_string($parts[11]);
                        // = $parts[12];
                        // = $parts[13];
                        $checksum = mysql_real_escape_string($parts[14]);
                        $gpsSignalIndicator = mysql_real_escape_string($parts[15]);
                        if (ereg("imei", $parts[16])) {
                            $infotext = "gprmc";
                            //Nenhum comando enviado pelo gps
                            $imei = mysql_real_escape_string($parts[16]);
                            $other = mysql_real_escape_string($parts[17]);
                        } else {
                            $infotext = mysql_real_escape_string($parts[16]);
                            $imei = mysql_real_escape_string($parts[17]);
                            $other = mysql_real_escape_string($parts[18] . ' ' . $parts[19]);
                        }
                        if ($infotext == "") {
                            $infotext = "gprmc";
                        }
                        if (ereg(":", substr($imei, 5))) {
                            $imei = substr($imei, 6);
                        } else {
                            $imei = substr($imei, 5);
                        }
                        if ($imei == "") {
                            $imei = explode("#", $rec);
                            $imei = $imei[1];
                        }
                        $conn_imei = $imei;
                    }
                    if (trim($gpsSignalIndicator) == "") {
                        $gpsSignalIndicator = "F";
                    }
                    abrirArquivoLog($conn_imei);
                    printLog($fh, date("d-m-y h:i:sa") . " Connection from {$remip}:{$remport}");
                    printLog($fh, date("d-m-y h:i:sa") . " Got : {$rec}");
                    //Imprimindo campos;
                    printLog($fh, " trackerdate : " . $trackerdate);
                    printLog($fh, " phone " . $phone);
                    printLog($fh, " gprmc " . $gprmc);
                    printLog($fh, " satelliteDerivedTime " . $satelliteDerivedTime);
                    printLog($fh, " satelliteFixStatus " . $satelliteFixStatus);
                    printLog($fh, " latitudeDecimalDegrees " . $latitudeDecimalDegrees);
                    printLog($fh, " latitudeHemisphere " . $latitudeHemisphere);
                    printLog($fh, " longitudeDecimalDegrees " . $longitudeDecimalDegrees);
                    printLog($fh, " longitudeHemisphere " . $longitudeHemisphere);
                    printLog($fh, " speed " . $speed);
                    $speedkmh = intval($speed * 1.609);
                    printLog($fh, " speed km " . $speedkmh);
                    printLog($fh, " bearing " . $bearing);
                    printLog($fh, " utcDate " . $utcDate);
                    printLog($fh, " checksum " . $checksum);
                    printLog($fh, " gpsSignalIndicator " . $gpsSignalIndicator);
                    printLog($fh, " infotext " . $infotext);
                    printLog($fh, " other " . $other);
                    printLog($fh, " imei " . $imei);
                    mysql_select_db('tracker', $cnx);
                    $result_vel = mysql_query("SELECT velocidade_maxima AS vel FROM bem WHERE imei='{$imei}'", $cnx);
                    $r_vel = mysql_fetch_assoc($result_vel);
                    printLog($fh, " vel max " . $r_vel[vel]);
                    if (isset($r_vel[vel]) and !empty($r_vel[vel]) and $speedkmh > $r_vel[vel]) {
                        if ($speedkmh < 100) {
                            $multiplo = intval($speedkmh / 10);
                            $acima_de = $multiplo * 10;
                        } else {
                            $multiplo = intval($speedkmh / 5);
                            $acima_de = $multiplo * 5;
                        }
                        $sql = "INSERT INTO message (imei, message) VALUES ('{$imei}', 'Velocidade superior a " . $acima_de . "Km/h')";
                        if (!mysql_query($sql, $cnx)) {
                            printLog($fh, " error message " . $sql . " - " . mysql_error());
                        }
                    }
                    if ($gpsSignalIndicator != 'L' and $satelliteFixStatus == "A" and trim($latitudeDecimalDegrees) != "" and trim($longitudeDecimalDegrees) != "") {
                        mysql_query("UPDATE bem set date = '" . date("Y-m-d H:i:s") . "', status_sinal = 'R' WHERE imei = '{$imei}'", $cnx);
                        mysql_query("INSERT INTO gprmc (date, imei, phone, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator) VALUES (now(), '{$imei}', '{$phone}', '{$satelliteFixStatus}', '{$latitudeDecimalDegrees}', '{$latitudeHemisphere}', '{$longitudeDecimalDegrees}', '{$longitudeHemisphere}', '{$speed}', '{$infotext}', '{$gpsSignalIndicator}')", $cnx);
                    } else {
                        mysql_query("UPDATE bem set date = '" . date("Y-m-d H:i:s") . "', status_sinal = 'S' WHERE imei = '{$imei}'", $cnx);
                    }
                    //inicio verifica geofence
                    if (trim($imei) != "") {
                        printLog($fh, " consulta cerca imei " . $imei);
                        $consulta = mysql_query("SELECT * FROM geo_fence WHERE imei = '{$imei}'", $cnx);
                        while ($data = mysql_fetch_assoc($consulta)) {
                            printLog($fh, " cerca encontrada " . $data);
                            $idCerca = $data['id'];
                            $imeiCerca = $data['imei'];
                            $nomeCerca = $data['nome'];
                            $coordenadasCerca = $data['coordenadas'];
                            $resultCerca = $data['tipo'];
                            $tipoEnvio = $data['tipoEnvio'];
                            strlen($latitudeDecimalDegrees) == 9 && ($latitudeDecimalDegrees = '0' . $latitudeDecimalDegrees);
                            $g = substr($latitudeDecimalDegrees, 0, 3);
                            $d = substr($latitudeDecimalDegrees, 3);
                            $strLatitudeDecimalDegrees = $g + $d / 60;
                            $latitudeHemisphere == "S" && ($strLatitudeDecimalDegrees = $strLatitudeDecimalDegrees * -1);
                            strlen($longitudeDecimalDegrees) == 9 && ($longitudeDecimalDegrees = '0' . $longitudeDecimalDegrees);
                            $g = substr($longitudeDecimalDegrees, 0, 3);
                            $d = substr($longitudeDecimalDegrees, 3);
                            $strLongitudeDecimalDegrees = $g + $d / 60;
                            $longitudeHemisphere == "S" && ($strLongitudeDecimalDegrees = $strLongitudeDecimalDegrees * -1);
                            $strLongitudeDecimalDegrees = $strLongitudeDecimalDegrees * -1;
                            $lat_point = $strLatitudeDecimalDegrees;
                            $lng_point = $strLongitudeDecimalDegrees;
                            $exp = explode("|", $coordenadasCerca);
                            if (count($exp) < 5) {
                                $strExp = explode(",", $exp[0]);
                                $strExp1 = explode(",", $exp[2]);
                            } else {
                                $int = count($exp) / 2;
                                $strExp = explode(",", $exp[0]);
                                $strExp1 = explode(",", $exp[$int]);
                            }
                            $lat_vertice_1 = $strExp[0];
                            $lng_vertice_1 = $strExp[1];
                            $lat_vertice_2 = $strExp1[0];
                            $lng_vertice_2 = $strExp1[1];
                            if (($lat_vertice_1 < $lat_point or $lat_point < $lat_vertice_2) and ($lng_point < $lng_vertice_1 or $lng_vertice_2 < $lng_point)) {
                                $result = '0';
                                $situacao = 'fora';
                            } else {
                                $result = '1';
                                $situacao = 'dentro';
                            }
                            if ($result != $resultCerca and round($speed * 1.852, 0) > 0) {
                                printLog($fh, " grava mensagem " . $imei);
                                mysql_query("INSERT INTO message (imei, message) VALUES ('{$imeiCerca}', 'Cerca " . $nomeCerca . " Violada!')", $cnx);
                                if ($tipoEnvio == 0) {
                                    # Convert the GPS coordinates to a human readable address
                                    $tempstr = "http://maps.google.com/maps/geo?q={$lat_point},{$lng_point}&oe=utf-8&sensor=true&key=AIzaSyDg_zMkThaMgP6dxJtsQvoyjwu62VtdQNM-tP3nj5rzgxeuwCgg&output=csv";
                                    //output = csv, xml, kml, json
                                    $rev_geo_str = file_get_contents($tempstr);
                                    $rev_geo_str = preg_replace("/\"/", "", $rev_geo_str);
                                    $rev_geo = explode(',', $rev_geo_str);
                                    $logradouro = $rev_geo[2] . "," . $rev_geo[3];
                                    require "/var/www/lib/phpMailer/class.phpmailer.php";
                                    printLog($fh, " consulta emails " . $imei);
                                    $consulta1 = mysql_query("SELECT a.*, b.* FROM cliente a INNER JOIN bem b ON (a.id = b.cliente) WHERE b.imei = '{$imeiCerca}'", $cnx);
                                    while ($data = mysql_fetch_assoc($consulta1)) {
                                        $emailDestino = $data['email'];
                                        $nameBem = $data['name'];
                                        $mensagem = "O veiculo " . $nameBem . ", esta " . $situacao . " do perimetro " . $nomeCerca . ", as " . date("H:i:s") . " do dia " . date("d/m/Y") . ", no local " . $logradouro . " e trafegando a " . round($speed * 1.852, 0) . " km/h.";
                                        $msg = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">";
                                        $msg .= "<html>";
                                        $msg .= "<head></head>";
                                        $msg .= "<body style=\"background-color:#fff;\" >";
                                        $msg .= "<p><strong>Alerta de Violacao de Perimetro:</strong><br /><br />";
                                        $msg .= $mensagem . "<br /><br />";
                                        $msg .= "Equipe <br />";
                                        $msg .= "(xx)xxxx-xxxx<br />";
                                        $msg .= "<a href=\"http://www.seu_site.com.br\">www.seu_site.com.br</a></p>";
                                        $msg .= "</body>";
                                        $msg .= "</html>";
                                        $mail = new PHPMailer();
                                        #Definimos o envio via SMTP
                                        $mail->IsSMTP();
                                        // Requisitando que e-mail seja autenticado via SMTP
                                        $mail->SMTPAuth = true;
                                        // Indicando que o e-mail est� no formato HTML
                                        $mail->IsHTML(true);
                                        // Indicando que o e-mail est� na codifica��o UTF8
                                        $mail->CharSet = "utf-8";
                                        // Indicando tipo de seguran�a
                                        $mail->SMTPSecure = "ssl";
                                        // Indicando o host que devemos nos conectar
                                        $mail->Host = "smtp.gmail.com";
                                        // Indicando a porta para envio de e-mail utilizada no servidor SMTP
                                        $mail->Port = "465";
                                        $mail->Username = "******";
                                        $mail->Password = "******";
                                        $mail->From = "*****@*****.**";
                                        $mail->FromName = "Rastreamento de Veiculos";
                                        $mail->AddAddress($emailDestino);
                                        $mail->AddReplyTo($mail->From, $mail->FromName);
                                        $mail->ConfirmReadingTo = $mail->From;
                                        $mail->Subject = "Alerta de Violacao de Perimetro";
                                        $mail->Body = $msg;
                                        if (!$mail->Send()) {
                                            echo "Erro de envio: " . $mail->ErrorInfo;
                                            printLog($fh, " envio de email, erro: " . $mail->ErrorInfo . " " . $imei);
                                        } else {
                                            printLog($fh, " envio de email, sucesso: " . $emailDestino . " - " . $imei);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // if imei
                    //final verifica geofence
                    # Now check to see if we need to send any alerts.
                    if (trim($infotext) != "gprmc") {
                        $res = mysql_query("SELECT * FROM bem WHERE imei='{$imei}'", $cnx);
                        while ($data = mysql_fetch_assoc($res)) {
                            switch ($infotext) {
                                case "dt":
                                    $body = "Disable Track OK";
                                    break;
                                case "et":
                                    $body = "Stop Alarm OK";
                                    break;
                                case "gt":
                                    $body = "Move Alarm set OK";
                                    break;
                                case "help me":
                                    $body = "Help!";
                                    mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'SOS!')", $cnx);
                                    break;
                                case "ht":
                                    $body = "Speed alarm set OK";
                                    break;
                                case "it":
                                    $body = "Timezone set OK";
                                    break;
                                case "low battery":
                                    $body = "Low battery!\nYou have about 2 minutes...";
                                    mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Bat. Fraca')", $cnx);
                                    break;
                                case " bat:":
                                    $body = "Low battery!\nYou have about 2 minutes...";
                                    mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Bat. Fraca')", $cnx);
                                    break;
                                case "Low batt":
                                    $body = "Low battery!\nYou have about 2 minutes...";
                                    mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Bat. Fraca')", $cnx);
                                    break;
                                case "move":
                                    $body = "Move Alarm!";
                                    mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Movimento')", $cnx);
                                    break;
                                case "nt":
                                    $body = "Returned to SMS mode OK";
                                    break;
                                case "speed":
                                    $body = "Speed alarm!";
                                    mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Velocidade')", $cnx);
                                    break;
                                case "stockade":
                                    $body = "Geofence Violation!";
                                    mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Cerca')", $cnx);
                                    break;
                            }
                            //switch
                            //Enviando e-mail de alerta
                            //$headers = "From: $email_from" . "\r\n" . "Reply-To: $email_from" . "\r\n";
                            //$responsible = $data['responsible'];
                            //$rv = mail($responsible, "Tracker - $imei", $body, $headers);
                        }
                        //while
                    }
                } else {
                    //GRPMC nao precisa reter a sessao
                }
                //No protocolo GPRMC cada nova conexão é um IP. Enviando comando no fim da conexao, após obter os dados.
                if (file_exists("{$command_path}/{$conn_imei}")) {
                    $send_cmd = file_get_contents("{$command_path}/{$conn_imei}");
                    socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                    mysql_query("DELETE FROM command WHERE imei = {$conn_imei}");
                    unlink("{$command_path}/{$conn_imei}");
                    printLog($fh, "Comandos do Banco e Arquivo apagados: " . $send_cmd . " imei: " . $conn_imei);
                }
                mysql_close($cnx);
                break;
            }
        }
        //Checando se utilizou os dois protocolos para uma escuta
        if ($isGIMEI == true and $isGPRMC == true) {
            printLog($fh, "ATENCAO: falha na obtencao do protocolo. Kill pid.");
        }
        $rec = "";
    }
    //while
}
示例#7
0
function interact($socket)
{
    global $fh;
    global $command_path;
    global $firstInteraction;
    global $remip;
    global $remport;
    global $imei;
    $loopcount = 0;
    $conn_imei = "";
    /* TALK TO YOUR CLIENT */
    $rec = "";
    // Variavel que indica se comando est� em banco ou arquivo.
    $tipoComando = "banco";
    //"arquivo";
    //Checando o protocolo
    $isGIMEI = false;
    $isGPRMC = false;
    $send_cmd = "";
    $last_status = "";
    # Read the socket but don't wait for data..
    while (@socket_recv($socket, $rec, 2048, 0x40) !== 0) {
        //if($last_status != ''){
        //	  socket_send($socket, $last_status, strlen($last_status), 0);
        // }
        # If we know the imei of the phone and there is a pending command send it.
        if ($conn_imei != "") {
            if ($tipoComando == "arquivo" and file_exists("{$command_path}/{$conn_imei}")) {
                $send_cmd = file_get_contents("{$command_path}/{$conn_imei}");
                /**/
                $sendcmd = trataCommand($send_cmd, $conn_imei);
                socket_send($socket, $sendcmd, strlen($sendcmd), 0);
                unlink("{$command_path}/{$conn_imei}");
                printLog($fh, "Arquivo de comandos apagado: " . $sendcmd . " imei: " . $conn_imei);
            } else {
                if ($tipoComando == "banco" and file_exists("{$command_path}/{$conn_imei}")) {
                    //Conecta e pega o comando pendente
                    $cnx = mysql_connect("cloudservice.cgejdsdl842e.sa-east-1.rds.amazonaws.com", "gpstracker", "d1\$1793689") or die("Could not connect: " . mysql_error());
                    mysql_select_db('tracker', $cnx);
                    $res = mysql_query("SELECT c.command FROM command c WHERE c.imei = '{$conn_imei}' ORDER BY date DESC LIMIT 1", $cnx);
                    $sendcmd = '';
                    while ($data = mysql_fetch_assoc($res)) {
                        $sendcmd = trataCommand($data['command'], $conn_imei);
                    }
                    // Deletando comando
                    //mysql_query("DELETE FROM command WHERE imei = $conn_imei");
                    socket_send($socket, $sendcmd, strlen($sendcmd), 0);
                    mysql_close($cnx);
                    unlink("{$command_path}/{$conn_imei}");
                    printLog($fh, "Comandos do arquivo apagado: " . $sendcmd . " imei: " . $conn_imei);
                } else {
                    //Se nao tiver comando na fila e for a primeira iteracao, obtem o ultimo comando v�lido enviado
                    if ($firstInteraction == true) {
                        sleep(1);
                        $firstInteraction = false;
                    }
                }
            }
        }
        if (file_exists("{$command_path}/{$conn_imei}")) {
            $send_cmd = file_get_contents("{$command_path}/{$conn_imei}");
            if ($send_cmd == 'shutdown') {
                unlink("{$command_path}/{$conn_imei}");
                socket_shutdown($socket, 2);
            }
        }
        # Some pacing to ensure we don't split any incoming data.
        sleep(1);
        # Timeout the socket if it's not talking...
        # Prevents duplicate connections, confusing the send commands
        $loopcount++;
        if ($loopcount > 120) {
            return;
        }
        #remove any whitespace from ends of string.
        if ($rec != "") {
            $isH08 = false;
            $arCommands = explode(',', $rec);
            if (substr($arCommands[0], 1, 2) == 'HQ') {
                $isH08 = true;
            }
            /*
            0 = *HQ,
            1 = 353505821000973,
            2 = V1,
            3 = 154850,
            4 = V,
            5 = 2251.0935,
            6 = S,
            7 = 04320.5078,
            8 = W,
            9 = 0.00,
            10 =0,
            11 = 200214,
            12 = FFFFFFFF,
            13 = 2d4,
            14 = 14,
            15 = 1401,
            16 = 2384#
            */
            if ($isH08) {
                $imei = $arCommands[1];
                $conn_imei = $imei;
                abrirArquivoLog($imei);
                printLog($fh, date("d-m-y h:i:sa") . " Imei: {$imei} Got: {$rec}");
                $latitudeDecimalDegrees = $arCommands[5];
                $latitudeHemisphere = $arCommands[6];
                $longitudeDecimalDegrees = $arCommands[7];
                $longitudeHemisphere = $arCommands[8];
                $speed = $arCommands[9];
                $alarms = $arCommands[12];
                $ligado = 'N';
                $alarms2 = substr($alarms, 2, 1);
                $alarms2 = hexdec($alarms2);
                while (strlen($alarms2) < 4) {
                    $alarms2 = '0' . $alarms2;
                }
                $ligado = $alarms2[2] == '0' ? 'S' : 'N';
                $dados = array('S', $latitudeDecimalDegrees, $longitudeDecimalDegrees, $latitudeHemisphere, $longitudeHemisphere, $speed, $imei, date('Y-m-d'), $alarm, 1);
                tratarDados($dados);
            }
        }
        $rec = "";
    }
    //while
}
示例#8
0
function interact($socket)
{
    global $fh;
    global $command_path;
    global $firstInteraction;
    global $remip;
    global $remport;
    $loopcount = 0;
    $conn_imei = "";
    /* TALK TO YOUR CLIENT */
    $rec = "";
    // Variavel que indica se comando est� em banco ou arquivo.
    $tipoComando = "arquivo";
    //"arquivo";
    //Checando o protocolo
    $isGIMEI = false;
    $isGPRMC = false;
    $send_cmd = "";
    # Read the socket but don't wait for data..
    while (@socket_recv($socket, $rec, 2048, 0x40) !== 0) {
        # If we know the imei of the phone and there is a pending command send it.
        if ($conn_imei != "") {
            if ($tipoComando == "arquivo" and file_exists("{$command_path}/{$conn_imei}")) {
                $send_cmd = file_get_contents("{$command_path}/{$conn_imei}");
                error_log($send_cmd);
                socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                unlink("{$command_path}/{$conn_imei}");
                printLog($fh, "Arquivo de comandos apagado: " . $send_cmd . " imei: " . $conn_imei);
            } else {
                if ($tipoComando == "banco" and file_exists("{$command_path}/{$conn_imei}")) {
                    //Conecta e pega o comando pendente
                    $conexao = mysql_connect("cloudservice.cgejdsdl842e.sa-east-1.rds.amazonaws.com", "gpstracker", "d1\$1793689") or die("Could not connect: " . mysql_error());
                    mysql_select_db('tracker', $conexao);
                    $res = mysql_query("SELECT c.command FROM command c WHERE c.imei = '{$conn_imei}' ORDER BY date DESC LIMIT 1", $conexao);
                    while ($data = mysql_fetch_assoc($res)) {
                        $send_cmd = $data['command'];
                        echo 'acessou o comando';
                    }
                    // Deletando comando
                    //mysql_query("DELETE FROM command WHERE imei = $conn_imei");
                    mysql_close($conexao);
                    socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                    unlink("{$command_path}/{$conn_imei}");
                    printLog($fh, "Comandos do arquivo apagado: " . $send_cmd . " imei: " . $conn_imei);
                } else {
                    //Se nao tiver comando na fila e for a primeira iteracao, obtem o ultimo comando v�lido enviado
                    if ($firstInteraction == true) {
                        sleep(1);
                        $send_cmd = "**,imei:" . $conn_imei . ",C,02m";
                        //Obtendo o ultimo comando
                        $conexao = mysql_connect("cloudservice.cgejdsdl842e.sa-east-1.rds.amazonaws.com", "gpstracker", "d1\$1793689") or die("Could not connect: " . mysql_error());
                        mysql_select_db('tracker', $conexao);
                        $res = mysql_query("SELECT c.command FROM command c WHERE c.command like '**,imei:" . $conn_imei . ",C,%' and c.imei = {$conn_imei} ORDER BY date DESC LIMIT 1", $conexao);
                        while ($data = mysql_fetch_assoc($res)) {
                            $send_cmd = $data['command'];
                        }
                        mysql_close($conexao);
                        $_cmmd = '#DCST##\\r\\n';
                        $connect_ = socket_send($socket, $_cmmd, strlen($_cmmd), MSG_EOR);
                        printLog($fh, $connect_ . " > Comando de DCST enviado: imei: " . $conn_imei);
                        //                       socket_send($socket, '#00#DCCM#9410000#5D##', strlen('#00#DCCM#9400000#5D##'), 0);
                        //                        printLog($fh, "Comando de DCCM enviado: imei: " . $conn_imei);
                        //socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                        //printLog($fh, "Comando de start: " . $send_cmd . " imei: " . $conn_imei);
                        $firstInteraction = false;
                    }
                }
            }
            // Comando enviado
            printLog($fh, date("d-m-y h:i:sa") . " Sent: {$send_cmd}");
        }
        # Some pacing to ensure we don't split any incoming data.
        sleep(1);
        # Timeout the socket if it's not talking...
        # Prevents duplicate connections, confusing the send commands
        $loopcount++;
        if ($loopcount > 60) {
            return;
        }
        #remove any whitespace from ends of string.
        $rec = trim($rec);
        $conexao = mysql_connect("cloudservice.cgejdsdl842e.sa-east-1.rds.amazonaws.com", "gpstracker", "d1\$1793689");
        mysql_select_db('tracker', $conexao);
        if ($rec != "") {
            if (preg_match("/TLT/i", $rec) or preg_match("/V500/i", $rec) or preg_match("/V600/i", $rec)) {
                $loopcount = 0;
                $partsx = explode('#', $rec);
                $imei = mysql_real_escape_string($partsx[1]);
                $status = mysql_real_escape_string($partsx[4]);
                $quantidadecoordenadas = mysql_real_escape_string($partsx[5]);
                mysql_set_charset('utf8', $conexao);
                error_log('STATUS TLT2n: ' . $status);
                switch ($status) {
                    case "AUTO":
                        printLog($fh, date("d-m-Y H:i:s") . " " . $status . ": " . $body);
                        //Envia comando de resposta: alerta recebido
                        break;
                    case "AUTOLOW":
                        printLog($fh, date("d-m-Y H:i:s") . " " . $status . ": " . $body);
                        //Envia comando de resposta: alerta recebido
                        break;
                    case "AUTOSTOP":
                        $body = "Ignicao Desligada!";
                        $msg = str_replace("#TIPOALERTA", "Seu veiculo esta com a chave desligada", $msg);
                        //mysql_query("INSERT INTO message (imei, message) VALUES ('$imei', 'Ignição')", $cnx);
                        mysql_query("UPDATE bem SET ligado = 'N' where imei = '{$imei}'", $conexao);
                        //Envia comando de resposta: alerta recebido
                        $send_cmd = "**,imei:" . $conn_imei . ",E";
                        socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                        //printLog($fh, "Comando de resposta (acc alarm): " . $send_cmd . " imei: " . $conn_imei);
                        break;
                    case "AUTOSTART":
                        $body = "Ignicao Ligada!";
                        $msg = str_replace("#TIPOALERTA", "Seu veiculo esta com a chave ligada", $msg);
                        //mysql_query("INSERT INTO message (imei, message) VALUES ('$imei', 'Ignição')", $cnx);
                        mysql_query("UPDATE bem SET ligado = 'S' where imei = '{$imei}'", $conexao);
                        //Envia comando de resposta: alerta recebido
                        $send_cmd = "**,imei:" . $conn_imei . ",E";
                        socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                        //printLog($fh, "Comando de resposta (acc alarm): " . $send_cmd . " imei: " . $conn_imei);
                        break;
                    case "SOS":
                        $body = "SOS! Alerta emitido";
                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', '{$body}')", $conexao);
                        printLog($fh, date("d-m-Y H:i:s") . " Alerta: " . $body);
                        break;
                    case "DEF":
                        $body = "Bateria principal desligada";
                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', '{$body}')", $conexao);
                        printLog($fh, date("d-m-Y H:i:s") . " Alerta: " . $body);
                        break;
                    case "LP":
                        $body = "Bateria Interna Fraca";
                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', '{$body}')", $conexao);
                        printLog($fh, date("d-m-Y H:i:s") . " Alerta: " . $body);
                        break;
                    case "TOWED":
                        $body = "Rebocado";
                        mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', '{$body}')", $conexao);
                        printLog($fh, date("d-m-Y H:i:s") . " Alerta: " . $body);
                        break;
                }
                //
                $conn_imei = $imei;
                abrirArquivoLog($conn_imei);
                printLog($fh, date("d-m-Y H:i:s") . " CONEXAO DE {$remip}:{$remport}");
                printLog($fh, date("d-m-Y H:i:s") . " RECEBEU : {$rec}");
            }
            // SE TIVER A STRING GPRMC
            if (preg_match("/GPRMC/i", $rec)) {
                $explode = explode("GPRMC", $rec);
                //echo "Quantidade >> " . $quantidadecoordenadas . "\n";
                for ($i = 1; $i <= $quantidadecoordenadas; $i++) {
                    //echo "Linha " . $i . " >> " . $explode[$i] . "\n";
                    $loopcount = 0;
                    $linha = $explode[$i];
                    $parts = explode(',', $linha);
                    $gpsSignalIndicator = mysql_real_escape_string($parts[2]);
                    if (count($parts) > 1 and $gpsSignalIndicator == 'A') {
                        // HORA GMT
                        $hora = mysql_real_escape_string($parts[1]);
                        $hora = substr($hora, 0, 2) . ":" . substr($hora, 2, 2) . ":" . substr($hora, 4, 2);
                        // DATA
                        $data = mysql_real_escape_string($parts[9]);
                        $data = "20" . substr($data, 4, 2) . "-" . substr($data, 2, 2) . "-" . substr($data, 0, 2);
                        // DATETIME
                        $datetime = $data . " " . $hora;
                        //
                        $latitudeDecimalDegrees = mysql_real_escape_string($parts[3]);
                        $latitudeHemisphere = mysql_real_escape_string($parts[4]);
                        $longitudeDecimalDegrees = mysql_real_escape_string($parts[5]);
                        $longitudeHemisphere = mysql_real_escape_string($parts[6]);
                        $velocidadekn = mysql_real_escape_string($parts[7]);
                        $velocidadekm = $velocidadekn * 1.852;
                        $velocidadekm = str_replace(',', '.', $velocidadekm);
                        $angulo = mysql_real_escape_string($parts[8]);
                        if ($angulo == "") {
                            $angulo = 0;
                        }
                        strlen($latitudeDecimalDegrees) == 9 && ($latitudeDecimalDegrees = '0' . $latitudeDecimalDegrees);
                        $g = substr($latitudeDecimalDegrees, 0, 3);
                        $d = substr($latitudeDecimalDegrees, 3);
                        $strLatitudeDecimalDegrees = $g + $d / 60;
                        $latitudeHemisphere == "S" && ($strLatitudeDecimalDegrees = $strLatitudeDecimalDegrees * -1);
                        strlen($longitudeDecimalDegrees) == 9 && ($longitudeDecimalDegrees = '0' . $longitudeDecimalDegrees);
                        $g = substr($longitudeDecimalDegrees, 0, 3);
                        $d = substr($longitudeDecimalDegrees, 3);
                        $strLongitudeDecimalDegrees = $g + $d / 60;
                        $longitudeHemisphere == "W" && ($strLongitudeDecimalDegrees = $strLongitudeDecimalDegrees * -1);
                        $latitude = $strLatitudeDecimalDegrees;
                        $longitude = $strLongitudeDecimalDegrees;
                        $lat_point = $latitude;
                        $lng_point = $longitude;
                        if ($velocidadekn < 1 and $velocidadekn > 0) {
                            $velocidadekn = 0;
                        }
                        $speed = $velocidadekn;
                        # GRAVANDO DADOS NAS TABELAS
                        mysql_query("UPDATE bem set date = date, status_sinal = 'R' WHERE imei = '{$imei}'", $conexao);
                        mysql_query("INSERT INTO gprmc (date, imei, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator) VALUES (convert_tz(now(), 'GMT', 'Brazil/East'), '{$imei}', 'A', '{$latitude}', '{$latitudeHemisphere}', '{$longitude}', '{$longitudeHemisphere}', '{$speed}', '{$status}', '" . $gpsSignalIndicator . "')", $conexao);
                        # GRAVANDO LOCAL ATUAL
                        $gpsLat = $latitudeDecimalDegrees;
                        //gprsToGps($latitudeDecimalDegrees, $latitudeHemisphere)
                        $gpsLon = $longitudeDecimalDegrees;
                        //gprsToGps($longitudeDecimalDegrees, $longitudeHemisphere)
                        $gpsLatAnt = 0;
                        $gpsLatHemAnt = '';
                        $gpsLonAnt = 0;
                        $gpsLonHemAnt = '';
                        $alertaACadaSaldo = 0;
                        $resLocAtual = mysql_query("SELECT id, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere FROM loc_atual WHERE imei = '" . $imei . "' LIMIT 1", $conexao);
                        $numRows = mysql_num_rows($resLocAtual);
                        mysql_query("insert into logs (dthr_evento, evento, imei) values (now(),'OK','" . $imei . "') ", $conexao);
                        if ($numRows == 0) {
                            mysql_query("\r\n\t\t\t\t\t\t\t\tinsert into loc_atual\r\n\t\t\t\t\t\t\t\t(date, imei, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed,\r\n\t\t\t\t\t\t\t\t gpsSignalIndicator, converte)\r\n\t\t\t\t\t\t\t\tvalues (convert_tz(now(), 'GMT', 'Brazil/East'), '{$imei}', '{$latitudeDecimalDegrees}', '{$latitudeHemisphere}', '{$longitudeDecimalDegrees}',\r\n\t\t\t\t\t\t\t\t        '{$longitudeHemisphere}', '{$speed}', '{$gpsSignalIndicator}', 1)", $conexao);
                        } else {
                            mysql_query("\r\n\t\t\t\t\t\t\t\tupdate loc_atual set date = convert_tz(now(), 'GMT', 'Brazil/East'), latitudeDecimalDegrees = '{$latitudeDecimalDegrees}',\r\n\t\t\t\t\t\t\t\t       latitudeHemisphere = '{$latitudeHemisphere}', longitudeDecimalDegrees = '{$longitudeDecimalDegrees}',\r\n\t\t\t\t\t\t\t\t\t   longitudeHemisphere = '{$longitudeHemisphere}', speed = '{$speed}', gpsSignalIndicator = '{$gpsSignalIndicator}',\r\n\t\t\t\t\t\t\t\t\t   converte = 1\r\n\t\t\t\t\t\t\t\t where imei = '{$imei}'", $conexao);
                        }
                        # VERIFICA CERCA VIRTUAL
                        $consulta = mysql_query("SELECT * FROM geo_fence WHERE imei = '{$imei}'", $conexao);
                        while ($data = mysql_fetch_assoc($consulta)) {
                            $idCerca = $data['id'];
                            $imeiCerca = $data['imei'];
                            $nomeCerca = $data['nome'];
                            $coordenadasCerca = $data['coordenadas'];
                            $resultCerca = $data['tipo'];
                            $tipoEnvio = $data['tipoEnvio'];
                            $exp = explode("|", $coordenadasCerca);
                            if (count($exp) < 5) {
                                $strExp = explode(",", $exp[0]);
                                $strExp1 = explode(",", $exp[2]);
                            } else {
                                $int = count($exp) / 2;
                                $strExp = explode(",", $exp[0]);
                                $strExp1 = explode(",", $exp[$int]);
                            }
                            $lat_vertice_1 = $strExp[0];
                            $lng_vertice_1 = $strExp[1];
                            $lat_vertice_2 = $strExp1[0];
                            $lng_vertice_2 = $strExp1[1];
                            if ($lat_vertice_1 < $lat_point or $lat_point < $lat_vertice_2 and $lng_point < $lng_vertice_1 or $lng_vertice_2 < $lng_point) {
                                $result = '0';
                                $situacao = 'fora';
                            } else {
                                $result = '1';
                                $situacao = 'dentro';
                            }
                            if ($result != $resultCerca and round($speed * 1.852, 0) > 0) {
                                mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Cerca " . $nomeCerca . " Violada!')", $conexao);
                                if ($tipoEnvio == 0) {
                                    # Convert the GPS coordinates to a human readable address
                                    $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
                                    $rev_geo_str = file_get_contents($tempstr);
                                    $rev_geo_str = preg_replace("/\"/", "", $rev_geo_str);
                                    $rev_geo = explode(',', $rev_geo_str);
                                    $logradouro = $rev_geo[2] . "," . $rev_geo[3];
                                    require "lib/class.phpmailer.php";
                                    $consulta1 = mysql_query("SELECT a.*, b.* FROM cliente a INNER JOIN bem b ON (a.id = b.cliente) WHERE b.imei = '{$imei}'", $conexao);
                                    while ($data = mysql_fetch_assoc($consulta1)) {
                                        $emailDestino = $data['email'];
                                        $nameBem = $data['name'];
                                        $mensagem = "O veiculo " . $nameBem . ", esta " . $situacao . " do perimetro " . $nomeCerca . ", as " . date("H:i:s") . " do dia " . date("d/m/Y") . ", no local " . $logradouro . " e trafegando a " . round($speed * 1.852, 0) . " km/h.";
                                        $msg = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">";
                                        $msg .= "<html>";
                                        $msg .= "<head></head>";
                                        $msg .= "<body style=\"background-color:#fff;\" >";
                                        $msg .= "<p><strong>Alerta de Violacao de Perimetro:</strong><br /><br />";
                                        $msg .= $mensagem . "<br /><br />";
                                        $msg .= "Equipe BarukSat<br />";
                                        $msg .= "(85)88462069<br />";
                                        $msg .= "<a href=\"http://www.systemtracker.com.br\">www.systemtracker.com.br</a></p>";
                                        $msg .= "</body>";
                                        $msg .= "</html>";
                                        $mail = new PHPMailer();
                                        $mail->Mailer = "smtp";
                                        $mail->IsHTML(true);
                                        $mail->CharSet = "utf-8";
                                        $mail->SMTPSecure = "tls";
                                        $mail->Host = "smtp.gmail.com";
                                        $mail->Port = "587";
                                        $mail->SMTPAuth = "true";
                                        $mail->Username = "******";
                                        $mail->Password = "******";
                                        $mail->From = "*****@*****.**";
                                        $mail->FromName = "BarukSat";
                                        $mail->AddAddress($emailDestino);
                                        $mail->AddReplyTo($mail->From, $mail->FromName);
                                        $mail->Subject = "BarukSat - Alerta de Violacao de Perimetro";
                                        $mail->Body = $msg;
                                        if (!$mail->Send()) {
                                            echo "Erro de envio: " . $mail->ErrorInfo;
                                        } else {
                                            echo "Mensagem enviada com sucesso!";
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                // DADOS INCORRETOS PARA COLETA
            }
        }
        $rec = "";
    }
    //while
}