Friday, September 16, 2011

HTTP POST with Speedway Connect

Speedway Connect is an on-reader software application from Impinj. It allows users to graphically configure a Speedway Revolution reader and receive tag data over standard communication channels. One of the available output options is HTTP POST. When this is enabled, the reader will periodically send tag data to a web server. Here are the details of the POST format, along with a sample PHP script showing how to parse the data and put it into a MySQL database as well as a demonstration video of this feature.

These are the POST variables sent by Speedway Connect

reader_name : The name assigned to the reader in Speedway Connect
mac_address : The MAC address of the reader
line_ending : Line ending character specified in Speedway Connect
field_delim : Field delimiter character specified in Speedway Connect
field_names : A list of field names, separated by the specified delimiter
field_values : A list of field values, separated by the specified delimiter

<?php
   // Uncomment this block for debug.
   // It writes the raw POST data to a file.
   /*
   $fn = "log.txt";
   $fp = fopen($fn, "a");
   $rawPostData = file_get_contents('php://input');
   fwrite($fp, date("l F d, Y, h:i A") . "," . $rawPostData . "\n");    
   fclose($fp);
   */
   
   // Define the user name, password,
   // MySQL hostname and database name.
   define("DB_USER", "user");
   define("DB_PASS", "pass");
   define("DB_HOST", "mysql.myhost.com");
   define("DB_NAME", "dbname");
   
   // Store the POST variables.
   $readerName = $_POST[reader_name];
   $macAddress = $_POST[mac_address];
   $lineEnding = $_POST[line_ending];
   $fieldDelim = $_POST[field_delim];
   $fieldNames = $_POST[field_names];
   $fieldValues = $_POST[field_values];
   
   // Connect to the database.
   $con = mysql_connect(DB_HOST, DB_USER, DB_PASS);
   mysql_select_db(DB_NAME) or die( "Unable to select database");
   
   // Replace the field delimiter with a comma.
   str_replace($fieldDelim, ",", $fieldNames);
   
   // Break the field values up into rows.
   $rows = explode("\n", $fieldValues);
   
   // Remove the last row. It's always blank
   if (sizeof($rows)) array_pop($rows);
   
   $fieldNames = "reader_name,mac_address," . $fieldNames;                
   
   foreach ($rows as $row)
   {
      $row = $readerName . "," . $macAddress . "," .
      $row;
      $query = "INSERT INTO tags ($fieldNames) VALUES ($row)";
      echo $query . "\n";
      mysql_query($query);        
   }                
   
   mysql_close($con);
?>