PHP Classes

PHP Integration with Embedded Hardware Device Sensors

Recommend this page to a friend!
  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog PHP Integration with ...   Post a comment Post a comment   See comments See comments (5)   Trackbacks (0)  

Author:

Viewers: 1,760

Last month viewers: 125

Categories: PHP Tutorials

Nowadays it is common to find embedded hardware devices, based on Raspberry Pi for instance, that are accessible via a network, run Linux and come with Apache and PHP installed on the device.

Read this article to learn how you can use PHP on those devices to connect to sensors by the means sensor and actuator executable programs.




Loaded Article

Contents

Introduction

The popen and pclose functions

A Class Template for Sensors

A Class Template for Actuators

A Note on Network Security

Conclusion


Introduction

Many new embedded system boards with high-end computing capabilities have become the norm in the world of the Internet of (Every)Thing(s). Whether you use the Raspberry Pi, Beaglebone or many others, it is not unusual to find network-ready embedded hardware capable of supporting cloud or simple server functionality.

Many of these boards, as one would expect, can interface, via digital or analog pins, to a miriad of sensors and actuators. But, they also feature RJ45 connectors coupled to Ethernet controllers. And, their operating system is capable of hosting server software (e.g., Apache), which includes PHP.

So, can PHP be used to provide direct network access to, say, a sensor ? If so, how can it be done ?

The popen and pclose functions

Among the less known functions dealing with local file access in PHP, the popen and pclose functions provide a means to access the output or input of local executable programs. A quick glance at the definition of popen describes it as:

“popen — Opens process file pointer”

The function has 2 arguments:

popen( <command>, <mode>)

where,

<command> = a full path of an executable program as a string,

<mode> = same as the mode used for the function fopen and indicating direction of data flow (read, write, append, etc.)

An example of <command> using a Linux executable program is ls. However, it's full path is ”/bin/ls”. In effect, we access the streaming output (or input) of an executable as if it were a file.

popen returns a handle to the stream provided by the running executable which can be used to read from that stream, if in an output mode, or supplying messages to a device, if in an input mode. In effect, popen enables the executable and redirects its output or input stream to the PHP script invoking it. pclose simply closes the session opened through popen.

A Class Template for Sensors

Now, a local sensor to an embedded host may be accessible, say, through a serial port (USB, SPI, RS232, I2C). An executable, written in C, C++, or other embedded programming languages, is capable of translating the sensor's binary data to a processed text format. In effect, that executable can be the command accessible via popen.

To show how that can be done, one can build a simple PHP class, called Sensor, which takes as parameters for its constructor the full-path of the sensor access executable and the size in bytes of each of its processed text messages:

class Sensor
{
 public $Sensor_Err;
 public $Sensor_Stream;
 private $Sensor_Msg_Len;
 private $Sensor_Queue; // an internal queue of sensor messages read in
 private $Sensor_Exec; // record of the command used

 // enable the sensor access executable
 function __construct($SensorCommand, $MsgLen)
 {
  // flush the error message stream
  $this->Sensor_Err = "";

  // record the output message size of the sensor access executable
  // NOTE – This assumes every message received has the exact same size
  // If that is not the case, record both the maximum and minimum sizes
  // for the messages
  $this->Sensor_Msg_Len = $MsgLen;

  $this->Sensor_Exec = $SensorCommand;
 }

 // read one or more sensor messages
 function Extract($MsgCount)
 {
  // flush the internal sensor message queue
  $this->Sensor_Queue = "";

  // flush the error message stream
  $this->Sensor_Err = "";

  // provide the requested number of sensor data messages to the command
  $cmd = $this->Sensor_Exec." ".$MsgCount;

  // enable the command executable and its message output stream
  $this->Sensor_Stream = popen($cmd,"r");

  // if the command failed to be enabled ...
  if($this->Sensor_Stream == false)
  {
   // return the error message
   $this->Sensor_Err .= "1.".$this->Sensor_Exec." could not be enabled.";
   $this->Sensor_Err .= " Check first the file mode for this executable.";

   return $this->SensorQueue;
  }

  // read the number of messages requested
  $nxt = fread($this->Sensor_Stream, $MsgCount*$this->Sensor_Msg_Len);

  if($nxt == false)
  {
   // record the message count at the time of the error
   $this->Sensor_Err .= "\nFailed to read sensor stream from " . $this->Sensor_Exec;
  }
  else
  {
   // store the received message
   $this->Sensor_Queue =$nxt;

   // close the command executable stream
   if(fclose($this->Sensor_Stream) == false)
   {
    $this->Sensor_Err .= "\nFailed to close the sensor stream from " . $this->Sensor_Exec;
   }
  }
  return $this->Sensor_Queue;
 }
}

The Extract method retrieves a requested set of points and handles the full access cycle via the executable. The executable, in effect handles both the sensor interface and raw data translation details. In turn, the Sensor class can be used to expose the formatted sensor data to a network request and optionally to perform additional processing.

As an example, we have an executable written in C, TempSim.c, that mimics access to a temperature and humidity sensor by random generation of temperature and humidity values. It must be supplied a requested sensor data point count as an input.

Using the Sensor class, we can instantiate the temperature-humidity sensor through TempSim in a PHP script as follows:

<?php

 include 'Sensor.php';

 $src = "/home/tf/TempSim";

 // define the temperature and humidity sensor
 $TempHum = new Sensor( $src, 7);

 if($TempHum->Sensor_Err == "")
 {
  $Pts = $TempHum->Extract( $argv[1] );
  print( $Pts . "\n");
 }
 else
 {
  print( $TempHum->Sensor_Err . "\n" );
 }

?>

Note that the requested sensor message count is passed within a PHP command line invocation ($argv).

Running this script through the PHP command line invocation,

$ php getS.php 10

046083

115077

055093

012086

061049

067062

019090

046063

066040

016072

getS.php is the PHP script shown just above. In each of the numbers above, the leftmost 3 digits represent temperature in degF and the rightmost 3 digits represent humidity in rH.

A Class Template for Actuators

Just as it was done in the prior section, we can also formulate a similar class template for actuators, Actuator, as a example of how they can be integrated with a PHP script. The class Actuator is structured as follows:

<?php

class Actuator
{
 public $Actuator_Err;
 public $Actuator_Stream;
 private $Actuator_Exec; // record of the command used

 // records the sensor access executable
 function __construct($ActuatorCommand)
 {
  // flush the error message stream
  $this->Actuator_Err = "";
  $this->Actuator_Exec = $ActuatorCommand;
 }

 // enable an actuator command
 function Enable($Act)
 {
  // flush the error message stream
  $this->Actuator_Err = "";

  // provide the actuator message to the command
  $cmd = $this->Actuator_Exec." ".$Act;

  // enable the command executable and its message input
  $this->Actuator_Stream = popen( $cmd, "w");

  // if the command failed to be enabled
  if($this->Actuator_Stream == false)
  {
   // return the error message
   $this->Actuator_Err .= "1.".$this->Actuator_Exec." could not be enabled.";
   $this->Actuator_Err .= " Check first the file mode for this executable.";
   return false;
  }
  else
  {
   // record the feedback from the actuator
   $nxt = fread($this->Actuator_Stream, $this->Actuator_Msg_Len);

   if($nxt == false)
   {
    // record an error message
    $this->Sensor_Err .= 
     "\nFailed to get actuator feedback from ".$this->Actuator_Exec;
    return false;
   }

   // close the command executable stream
   if(fclose($this->Actuator_Stream) == false)
   {
    $this->Actuator_Err .= 
    "\nFailed to close the actuator stream from ".$this->Actuator_Exec;
    return false;
   }
  }  
  return true;
 }
}

?>

Note that:

  1. The class operates around an executable command, as was the case in the Sensor class. This executable is software written, say, in C handling the actuator interface details. The executable provides a feedback message describing the status of the action taken.

  2. The requested actuator command is part of the executable enabled through popen. That is, the only argument to the actuator executable is the action that needs to take place, as illustrated in the Enable method of the Actuator class. So, popen , in effect, carries out the actuator command.

A Note on Network Security

A unique feature in this class is that any PHP script using this class enables an action carrying out a command transmitted through a network. This brings up the issue of security.

Any PHP script invoking this class must incorporate security features, such as encryption, in order to avoid malicious use of an actuator.

Conclusion

The process stream functions, popen and pclose provide a means to enable access to physical devices attached to a host through the use executables handling the interface details to the devices.

On that basis, classes, such as Sensor and Actuator, as described above can serve as templates for integrating devices into Web based services through the use of PHP.

Post a comment if you liked this article or have questions on how to use PHP to interface with sensors in embedded hardware devices.




You need to be a registered user or login to post a comment

Login Immediately with your account on:



Comments:

2. PHP Integration with Embedded Hardware Device Sensors - Garry Boag (2015-06-14 18:45)
Very exciting stuff... - 1 reply
Read the whole comment and replies

4. PHP to interface with devices with sensors - Abubakar Isah (2015-06-11 23:38)
This is great... - 0 replies
Read the whole comment and replies

3. This is the Shit - Jurgen_v_O (2015-06-10 21:57)
We need more of this.... - 0 replies
Read the whole comment and replies

1. Interacting with embedded hardware via PHP - Steve (2015-06-09 20:32)
nice article... - 0 replies
Read the whole comment and replies



  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog PHP Integration with ...   Post a comment Post a comment   See comments See comments (5)   Trackbacks (0)