Example #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
}
Example #2
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
}