storedprocedure
storedprocedure

Reputation: 152

Socket programming with PHP and insert data to the database (continuous)

I have multiple gps devices. I cannot make changes to this device. It sends data to a port.

I break this incoming data and insert it to the database according to its type. But sometimes I have problems. Device sometimes sends id_number field blank. It sends all other data correctly. And sometimes the program just crashes.

<?php
set_time_limit (0);
$ip_address = "xxx.xxx.xxx.xxx";
$port = "yyy";
$server = stream_socket_server("tcp://$ip_address:$port", $errno, $errorMessage);
if ($server === false) {
    die("stream_socket_server error: $errorMessage");
}
$client_sockets = array();
while (true) {
    // prepare readable sockets
    $read_sockets = $client_sockets;
    $read_sockets[] = $server;
    // start reading and use a large timeout
    if(!stream_select($read_sockets, $write, $except, 300000)) {
        die('stream_select error.');
    }
    // new client
    if(in_array($server, $read_sockets)) {
        $new_client = stream_socket_accept($server);
        if ($new_client) {
            //print remote client information, ip and port number
            //echo 'new connection: ' . stream_socket_get_name($new_client, true) . "\n";
            $client_sockets[] = $new_client;
            //echo "total clients: ". count($client_sockets) . "\n";
            // $output = "hello new client.\n";
            // fwrite($new_client, $output);
        }
        //delete the server socket from the read sockets
        unset($read_sockets[ array_search($server, $read_sockets) ]);
    }
    // message from existing client
    foreach ($read_sockets as $socket) {
        $data = fread($socket, 2048);
        echo "data: " . $data . "\n";
        if($data[0]=='$')        {
        write_file($data);
        $explp = array();
        $explp = explode("#",$data);
        $i=0;
        $j=count($explp);
        while ($i < ($j-1)){
          $listexa= explode(";",$explp[$i]);
          $location= explode(",",$listexa[0]); 
          $response = ""; 
          $id_number = $location[2];    
          $package_type = substr($location[0],1);
            if ($package_type == 'DATA')
            {
                $lati = substr($listexa[2],1);
                $longi = substr($listexa[3],2);
                $speed = $listexa[4];
                if(count($speed)>2)
                data_package($id_number,$package_no,'DATA');
            }
            else if($package_type=='GEOLOC')
            {
                $lati = substr($listexa[3],1);
                $longi = substr($listexa[4],2);
                $speed = $listexa[5];
                if($location[3]=='-' || $location[3]=='2' || $location[3]=='R')
                {   
                    $speed= '0';
                    $package_type = 'GEO';
                    geo_package($id_number,$package_no,$package_type);
                }
            }
            else if($package_type=='ALIVE')
            {
                alive_package($package_no,$id_number);
            }
          $i = $i+1;
                
            }
            if (!$data) {
                unset($client_sockets[ array_search($socket, $client_sockets) ]);
                @fclose($socket);
                //echo "client disconnected. total clients: ". count($client_sockets) . "\n";
                continue;
            }
            //send the message back to client
            if (sizeof($response) > 0) {
                fwrite($socket, $response);
            }
        }
} } 


function alive_package($package_no,$id_number){
    $link=dbcon();
    try{
    $statement = $link->prepare('INSERT INTO alive_packages (package_no, id_number)
    VALUES (:package_no, :id_number)');
    $statement->execute([
        'package_no' => $package_no,
        'id_number' => $id_number,
    ]);
    } 
    catch (PDOException $e) {
      echo "DataBase Error: The user could not be added.<br>".$e->getMessage(); write_file_log($e->getMessage());
      $link = null;
    } catch (Exception $e) {
      echo "General Error: The user could not be added.<br>".$e->getMessage(); write_file_log($e->getMessage());
      $link = null;
    }
        $link = null;
}
function data_package($id_number,$package_no,$package_type){
    $link=dbcon();
    $typee= '-';
    try{
    $statement = $link->prepare('INSERT INTO data_package (id_number, package_no, package_type)
    VALUES (:id_number, :package_no, :package_type)');
    $statement->execute([
        'id_number' => $id_number,
        'package_no' => $package_no,
        'package_type' => $package_type,
    ]);
    } 
    catch (PDOException $e) {
      echo "DataBase Error: The user could not be added.<br> ".$e->getMessage(); write_file_log($e->getMessage());
      $link = null;
    } catch (Exception $e) {
      echo "General Error: The user could not be added.<br> ".$e->getMessage(); write_file_log($e->getMessage());
      $link = null;
    }
        $link = null;
}
function geo_package($id_number,$package_no,$package_type){
    $link=dbcon();
    $typee= '-';
    try{
    $statement = $link->prepare('INSERT INTO geo_package (id_number,package_no,package_type)
    VALUES (:id_number, :package_no, :package_type)');
    $statement->execute([
        'id_number' => $id_number,
        'package_no' => $package_no,
        'package_type' => $package_type,
    ]);
    } 
    catch (PDOException $e) {
      echo "DataBase Error: The user could not be added.<br> ".$e->getMessage(); write_file_log($e->getMessage());
      $link = null;
    } catch (Exception $e) {
      echo "General Error: The user could not be added.<br>  ".$e->getMessage(); write_file_log($e->getMessage());
      $link = null;
    }
        $link = null;
}
function dbcon(){
    $dbhost = '127.0.0.1';
    $dbname = 'examplename';
    $dbusername = 'exampleuser';
    $dbpassword = 'examplepassword';
    $link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);
    $link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $link;
}
function write_file($data){
   $filename = "xxx.txt"; 
   $file = fopen( $filename, "a+" );
   fwrite( $file, $data."\n" );
   fclose( $file );
}
function write_file_log($data){
   $filename = "yyy.txt"; 
   $file = fopen( $filename, "a+" );
   fwrite( $file, $data."\n" );
   fclose( $file );
}

I want it to run 24/7 and only restart that socket when something goes wrong. Or I want to take the id_number field of a device once and use it over and over again. Since there are more than one device, a separate socket is opened for each one. But when the id_number of a device is empty, I cannot insert the data to the database. How can I solve this problem?

Briefly, while a socket sends data normally, after a while it starts to send blank id_number and I lose the data until I restart the program. Other devices continue to work.

I have 2 options.

1st option: restart socket when id_number is empty.

2nd option: restart socket when id_number is empty.

But I don't know how to do these.

An additional problem or shortcut is to run the code again when an error occurs in the program. How can I do that?

Note: I am running a php program with a service in Centos 7.

Upvotes: 1

Views: 284

Answers (0)

Related Questions