title: PHP Ajax Serial Port String Command
body: <p>I"m very new to PHP and AJAX and have been learning some of the basics over the last few weeks.  I've used quite a few posts on this site for help along the way and when my current problem came up I figured this would be a good place to start.</p>
  
  <p>What I'm trying to do is pass a hexidecimal command string to PHP to be output using the serial port of my device.  The problem i'm seeing is that the string that i'm passing to the PHP for some reason is adding a hex character in the middle of it.  At first I thought this had something to do with special characters defined in the serial port but when I define the string within the PHP code I don't get the same error.  I've also noticed that the additional character is added before any character in my string that has \xA# in it where # could be any number 0-9.</p>
  
  <p>Basically i'm trying to send the hex command string \x55\x05\xA0\x05\x05 to php using ajax to be output on a serial port.  When I execute the command I see the following on the serial port.   U0x050xc20xa0x050x05
  Somewhere along the way the "0xc2" is being added to the serial output.  As mentioned previously it seems to be related to \xAO because when I replace that with \x04 making the string \x55\x05\x04\x05\x05 I get the correct output of u0x050x040x050x05.  This issue also occurs when I use \A1 I also get the same error.</p>
  
  <p>When I define the string in the PHP file I get the correct output of  U0x050xa0x050x05</p>
  
  <p>Any idea what is causing this?  Should I be sending the hex commands as an array instead of a string and putput them one at a time over the serial port?</p>
  
  <p>Here is my code with the javascript and ajax call.  Basically when I press a button I want to send a specific hex command string to the PHP function and output it over the serial port.</p>
  
  <pre><code>&lt;!doctype html&gt;
  &lt;html lang="en"&gt;
  &lt;head&gt;
      &lt;meta charset="utf-8" /&gt;
      &lt;title&gt;Button Test&lt;/title&gt;
  
      &lt;!-- CSS for presentation. --&gt;
      &lt;style&gt;
      h1 { font-size: 20px; color: red; }
      button { color: black; }
      &lt;/style&gt;
  &lt;script src="jquery.js"&gt;
  &lt;/script&gt;
  &lt;script&gt;
  function sercmd( stringcmd )
  {
  //Calling ajax and including the serial command to be sent out the serial port
  //$.ajax({url: "sendserial.php", type: "POST", data: {serstr: stringcmd}, dataType: "json"});
  $.ajax({
      url: "sendserial.php",
      type: "POST",
      data: {serstr: stringcmd},
      success: function ( resp ){
          if ( resp == 'true'){
              $( '.response' ).text( resp );
          } else {
              $( '.response' ).text( 'failure' );
          }
      }
  });
  }
  &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
  
      &lt;h1&gt;Test Page for MZC Control&lt;/h1&gt;
  
  
      &lt;button onclick="sercmd('\x55\x05\xA0\x05\x05') "&gt;Zone 3 Power On&lt;/button&gt;
      &lt;button onclick="sercmd('\x55\x04\xA1\x02\x04') "&gt;Zone 3 Power Off&lt;/button&gt;
      &lt;button onclick="sercmd('\x55\x05\xA3\x02\x00\x01') "&gt;Zone 3 Source 1&lt;/button&gt;
      &lt;button onclick="sercmd('\x55\x05\xA3\x02\x01\x00') "&gt;Zone 3 Source 2&lt;/button&gt;
  
  
      &lt;p&gt; Control The Zones using the commands above. &lt;/p&gt;   
  &lt;div class="response"&gt;&lt;/div&gt;
  
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>Here is the code from the PHP page being called by AJAX</p>
  
  <pre><code>&lt;?php
  error_reporting(E_ALL);
  ini_set('display_errors', '1');
  include "php_serial.class.php";
  
  $str = $_POST['serstr'];
  
  //$str = '\x55\x04\xA0\x02\x05';
  
  //$str = pack("H*",$str);
  
  $serial = new phpSerial;
  $serial-&gt;deviceSet("/dev/ttyUSB0");
  $serial-&gt;confBaudRate(57600);
  $serial-&gt;confParity("none");
  $serial-&gt;confCharacterLength(8);
  $serial-&gt;confStopBits(1);
  $serial-&gt;confFlowControl("none");
  
  $serial-&gt;deviceOpen();
  
  $serial-&gt;sendMessage($str);
  
  //$serial-&gt;sendMessage("\x55");
  
  //$read = $serial-&gt;readPort();
  
  $serial-&gt;deviceClose();
  
  echo $str;
  //echo "true";
  //echo $read;
  ?&gt;
  </code></pre>
  
  <p>Just in case someone is interested here is the code for the php serial class that i'm using.  I found this being used by others in this forum.</p>
  
  <pre><code>&lt;?php
  define ("SERIAL_DEVICE_NOTSET", 0);
  define ("SERIAL_DEVICE_SET", 1);
  define ("SERIAL_DEVICE_OPENED", 2);
  
  /**
   * Serial port control class
   *
   * THIS PROGRAM COMES WITH ABSOLUTELY NO WARANTIES !
   * USE IT AT YOUR OWN RISKS !
   *
   * @author Rémy Sanchez &lt;thenux@gmail.com&gt;
   * @thanks Aurélien Derouineau for finding how to open serial ports with windows
   * @thanks Alec Avedisyan for help and testing with reading
   * @copyright under GPL 2 licence
   */
  class phpSerial
  {
      var $_device = null;
      var $_windevice = null;
      var $_dHandle = null;
      var $_dState = SERIAL_DEVICE_NOTSET;
      var $_buffer = "";
      var $_os = "";
  
      /**
       * This var says if buffer should be flushed by sendMessage (true) or manualy (false)
       *
       * @var bool
       */
      var $autoflush = true;
  
      /**
       * Constructor. Perform some checks about the OS and setserial
       *
       * @return phpSerial
       */
      function phpSerial ()
      {
          setlocale(LC_ALL, "en_US");
  
          $sysname = php_uname();
  
          if (substr($sysname, 0, 5) === "Linux")
          {
              $this-&gt;_os = "linux";
  
              if($this-&gt;_exec("stty --version") === 0)
              {
                  register_shutdown_function(array($this, "deviceClose"));
              }
              else
              {
                  trigger_error("No stty availible, unable to run.", E_USER_ERROR);
              }
          }
          elseif(substr($sysname, 0, 7) === "Windows")
          {
              $this-&gt;_os = "windows";
              register_shutdown_function(array($this, "deviceClose"));
          }
          else
          {
              trigger_error("Host OS is neither linux nor windows, unable tu run.", E_USER_ERROR);
              exit();
          }
      }
  
      //
      // OPEN/CLOSE DEVICE SECTION -- {START}
      //
  
      /**
       * Device set function : used to set the device name/address.
       * -&gt; linux : use the device address, like /dev/ttyS0
       * -&gt; windows : use the COMxx device name, like COM1 (can also be used
       *     with linux)
       *
       * @param string $device the name of the device to be used
       * @return bool
       */
      function deviceSet ($device)
      {
          if ($this-&gt;_dState !== SERIAL_DEVICE_OPENED)
          {
              if ($this-&gt;_os === "linux")
              {
                  if (preg_match("@^COM(\d+):?$@i", $device, $matches))
                  {
                      $device = "/dev/ttyS" . ($matches[1] - 1);
                  }
  
                  if ($this-&gt;_exec("stty -F " . $device) === 0)
                  {
                      $this-&gt;_device = $device;
                      $this-&gt;_dState = SERIAL_DEVICE_SET;
                      return true;
                  }
              }
              elseif ($this-&gt;_os === "windows")
              {
                  if (preg_match("@^COM(\d+):?$@i", $device, $matches) and $this-&gt;_exec(exec("mode " . $device)) === 0)
                  {
                      $this-&gt;_windevice = "COM" . $matches[1];
                      $this-&gt;_device = "\\.\com" . $matches[1];
                      $this-&gt;_dState = SERIAL_DEVICE_SET;
                      return true;
                  }
              }
  
              trigger_error("Specified serial port is not valid", E_USER_WARNING);
              return false;
          }
          else
          {
              trigger_error("You must close your device before to set an other one", E_USER_WARNING);
              return false;
          }
      }
  
      /**
       * Opens the device for reading and/or writing.
       *
       * @param string $mode Opening mode : same parameter as fopen()
       * @return bool
       */
      function deviceOpen ($mode = "r+b")
      {
          if ($this-&gt;_dState === SERIAL_DEVICE_OPENED)
          {
              trigger_error("The device is already opened", E_USER_NOTICE);
              return true;
          }
  
          if ($this-&gt;_dState === SERIAL_DEVICE_NOTSET)
          {
              trigger_error("The device must be set before to be open", E_USER_WARNING);
              return false;
          }
  
          if (!preg_match("@^[raw]\+?b?$@", $mode))
          {
              trigger_error("Invalid opening mode : ".$mode.". Use fopen() modes.", E_USER_WARNING);
              return false;
          }
  
          $this-&gt;_dHandle = @fopen($this-&gt;_device, $mode);
  
          if ($this-&gt;_dHandle !== false)
          {
              stream_set_blocking($this-&gt;_dHandle, 0);
              $this-&gt;_dState = SERIAL_DEVICE_OPENED;
              return true;
          }
  
          $this-&gt;_dHandle = null;
          trigger_error("Unable to open the device", E_USER_WARNING);
          return false;
      }
  
      /**
       * Closes the device
       *
       * @return bool
       */
      function deviceClose ()
      {
          if ($this-&gt;_dState !== SERIAL_DEVICE_OPENED)
          {
              return true;
          }
  
          if (fclose($this-&gt;_dHandle))
          {
              $this-&gt;_dHandle = null;
              $this-&gt;_dState = SERIAL_DEVICE_SET;
              return true;
          }
  
          trigger_error("Unable to close the device", E_USER_ERROR);
          return false;
      }
  
      //
      // OPEN/CLOSE DEVICE SECTION -- {STOP}
      //
  
      //
      // CONFIGURE SECTION -- {START}
      //
  
      /**
       * Configure the Baud Rate
       * Possible rates : 110, 150, 300, 600, 1200, 2400, 4800, 9600, 38400,
       * 57600 and 115200.
       *
       * @param int $rate the rate to set the port in
       * @return bool
       */
      function confBaudRate ($rate)
      {
          if ($this-&gt;_dState !== SERIAL_DEVICE_SET)
          {
              trigger_error("Unable to set the baud rate : the device is either not set or opened", E_USER_WARNING);
              return false;
          }
  
          $validBauds = array (
              110    =&gt; 11,
              150    =&gt; 15,
              300    =&gt; 30,
              600    =&gt; 60,
              1200   =&gt; 12,
              2400   =&gt; 24,
              4800   =&gt; 48,
              9600   =&gt; 96,
              19200  =&gt; 19,
              38400  =&gt; 38400,
              57600  =&gt; 57600,
              115200 =&gt; 115200
          );
  
          if (isset($validBauds[$rate]))
          {
              if ($this-&gt;_os === "linux")
              {
                  $ret = $this-&gt;_exec("stty -F " . $this-&gt;_device . " " . (int) $rate, $out);
              }
              elseif ($this-&gt;_os === "windows")
              {
                  $ret = $this-&gt;_exec("mode " . $this-&gt;_windevice . " BAUD=" . $validBauds[$rate], $out);
              }
              else return false;
  
              if ($ret !== 0)
              {
                  trigger_error ("Unable to set baud rate: " . $out[1], E_USER_WARNING);
                  return false;
              }
          }
      }
  
      /**
       * Configure parity.
       * Modes : odd, even, none
       *
       * @param string $parity one of the modes
       * @return bool
       */
      function confParity ($parity)
      {
          if ($this-&gt;_dState !== SERIAL_DEVICE_SET)
          {
              trigger_error("Unable to set parity : the device is either not set or opened", E_USER_WARNING);
              return false;
          }
  
          $args = array(
              "none" =&gt; "-parenb",
              "odd"  =&gt; "parenb parodd",
              "even" =&gt; "parenb -parodd",
          );
  
          if (!isset($args[$parity]))
          {
              trigger_error("Parity mode not supported", E_USER_WARNING);
              return false;
          }
  
          if ($this-&gt;_os === "linux")
          {
              $ret = $this-&gt;_exec("stty -F " . $this-&gt;_device . " " . $args[$parity], $out);
          }
          else
          {
              $ret = $this-&gt;_exec("mode " . $this-&gt;_windevice . " PARITY=" . $parity{0}, $out);
          }
  
          if ($ret === 0)
          {
              return true;
          }
  
          trigger_error("Unable to set parity : " . $out[1], E_USER_WARNING);
          return false;
      }
  
      /**
       * Sets the length of a character.
       *
       * @param int $int length of a character (5 &lt;= length &lt;= 8)
       * @return bool
       */
      function confCharacterLength ($int)
      {
          if ($this-&gt;_dState !== SERIAL_DEVICE_SET)
          {
              trigger_error("Unable to set length of a character : the device is either not set or opened", E_USER_WARNING);
              return false;
          }
  
          $int = (int) $int;
          if ($int &lt; 5) $int = 5;
          elseif ($int &gt; 8) $int = 8;
  
          if ($this-&gt;_os === "linux")
          {
              $ret = $this-&gt;_exec("stty -F " . $this-&gt;_device . " cs" . $int, $out);
          }
          else
          {
              $ret = $this-&gt;_exec("mode " . $this-&gt;_windevice . " DATA=" . $int, $out);
          }
  
          if ($ret === 0)
          {
              return true;
          }
  
          trigger_error("Unable to set character length : " .$out[1], E_USER_WARNING);
          return false;
      }
  
      /**
       * Sets the length of stop bits.
       *
       * @param float $length the length of a stop bit. It must be either 1,
       * 1.5 or 2. 1.5 is not supported under linux and on some computers.
       * @return bool
       */
      function confStopBits ($length)
      {
          if ($this-&gt;_dState !== SERIAL_DEVICE_SET)
          {
              trigger_error("Unable to set the length of a stop bit : the device is either not set or opened", E_USER_WARNING);
              return false;
          }
  
          if ($length != 1 and $length != 2 and $length != 1.5 and !($length == 1.5 and $this-&gt;_os === "linux"))
          {
              trigger_error("Specified stop bit length is invalid", E_USER_WARNING);
              return false;
          }
  
          if ($this-&gt;_os === "linux")
          {
              $ret = $this-&gt;_exec("stty -F " . $this-&gt;_device . " " . (($length == 1) ? "-" : "") . "cstopb", $out);
          }
          else
          {
              $ret = $this-&gt;_exec("mode " . $this-&gt;_windevice . " STOP=" . $length, $out);
          }
  
          if ($ret === 0)
          {
              return true;
          }
  
          trigger_error("Unable to set stop bit length : " . $out[1], E_USER_WARNING);
          return false;
      }
  
      /**
       * Configures the flow control
       *
       * @param string $mode Set the flow control mode. Availible modes :
       *  -&gt; "none" : no flow control
       *  -&gt; "rts/cts" : use RTS/CTS handshaking
       *  -&gt; "xon/xoff" : use XON/XOFF protocol
       * @return bool
       */
      function confFlowControl ($mode)
      {
          if ($this-&gt;_dState !== SERIAL_DEVICE_SET)
          {
              trigger_error("Unable to set flow control mode : the device is either not set or opened", E_USER_WARNING);
              return false;
          }
  
          $linuxModes = array(
              "none"     =&gt; "clocal -crtscts -ixon -ixoff",
              "rts/cts"  =&gt; "-clocal crtscts -ixon -ixoff",
              "xon/xoff" =&gt; "-clocal -crtscts ixon ixoff"
          );
          $windowsModes = array(
              "none"     =&gt; "xon=off octs=off rts=on",
              "rts/cts"  =&gt; "xon=off octs=on rts=hs",
              "xon/xoff" =&gt; "xon=on octs=off rts=on",
          );
  
          if ($mode !== "none" and $mode !== "rts/cts" and $mode !== "xon/xoff") {
              trigger_error("Invalid flow control mode specified", E_USER_ERROR);
              return false;
          }
  
          if ($this-&gt;_os === "linux")
              $ret = $this-&gt;_exec("stty -F " . $this-&gt;_device . " " . $linuxModes[$mode], $out);
          else
              $ret = $this-&gt;_exec("mode " . $this-&gt;_windevice . " " . $windowsModes[$mode], $out);
  
          if ($ret === 0) return true;
          else {
              trigger_error("Unable to set flow control : " . $out[1], E_USER_ERROR);
              return false;
          }
      }
  
      /**
       * Sets a setserial parameter (cf man setserial)
       * NO MORE USEFUL !
       *  -&gt; No longer supported
       *  -&gt; Only use it if you need it
       *
       * @param string $param parameter name
       * @param string $arg parameter value
       * @return bool
       */
      function setSetserialFlag ($param, $arg = "")
      {
          if (!$this-&gt;_ckOpened()) return false;
  
          $return = exec ("setserial " . $this-&gt;_device . " " . $param . " " . $arg . " 2&gt;&amp;1");
  
          if ($return{0} === "I")
          {
              trigger_error("setserial: Invalid flag", E_USER_WARNING);
              return false;
          }
          elseif ($return{0} === "/")
          {
              trigger_error("setserial: Error with device file", E_USER_WARNING);
              return false;
          }
          else
          {
              return true;
          }
      }
  
      //
      // CONFIGURE SECTION -- {STOP}
      //
  
      //
      // I/O SECTION -- {START}
      //
  
      /**
       * Sends a string to the device
       *
       * @param string $str string to be sent to the device
       * @param float $waitForReply time to wait for the reply (in seconds)
       */
      function sendMessage ($str, $waitForReply = 0.1)
      {
          $this-&gt;_buffer .= $str;
  
          if ($this-&gt;autoflush === true) $this-&gt;flush();
  
          usleep((int) ($waitForReply * 1000000));
      }
  
      /**
       * Reads the port until no new datas are availible, then return the content.
       *
       * @pararm int $count number of characters to be read (will stop before
       *  if less characters are in the buffer)
       * @return string
       */
      function readPort ($count = 0)
      {
          if ($this-&gt;_dState !== SERIAL_DEVICE_OPENED)
          {
              trigger_error("Device must be opened to read it", E_USER_WARNING);
              return false;
          }
  
          if ($this-&gt;_os === "linux")
          {
              $content = ""; $i = 0;
  
              if ($count !== 0)
              {
                  do {
                      if ($i &gt; $count) $content .= fread($this-&gt;_dHandle, ($count - $i));
                      else $content .= fread($this-&gt;_dHandle, 128);
                  } while (($i += 128) === strlen($content));
              }
              else
              {
                  do {
                      $content .= fread($this-&gt;_dHandle, 128);
                  } while (($i += 128) === strlen($content));
              }
  
              return $content;
          }
          elseif ($this-&gt;_os === "windows")
          {
              /* Do nohting : not implented yet */
          }
  
          trigger_error("Reading serial port is not implemented for Windows", E_USER_WARNING);
          return false;
      }
  
      /**
       * Flushes the output buffer
       *
       * @return bool
       */
      function flush ()
      {
          if (!$this-&gt;_ckOpened()) return false;
  
          if (fwrite($this-&gt;_dHandle, $this-&gt;_buffer) !== false)
          {
              $this-&gt;_buffer = "";
              return true;
          }
          else
          {
              $this-&gt;_buffer = "";
              trigger_error("Error while sending message", E_USER_WARNING);
              return false;
          }
      }
  
      //
      // I/O SECTION -- {STOP}
      //
  
      //
      // INTERNAL TOOLKIT -- {START}
      //
  
      function _ckOpened()
      {
          if ($this-&gt;_dState !== SERIAL_DEVICE_OPENED)
          {
              trigger_error("Device must be opened", E_USER_WARNING);
              return false;
          }
  
          return true;
      }
  
      function _ckClosed()
      {
          if ($this-&gt;_dState !== SERIAL_DEVICE_CLOSED)
          {
              trigger_error("Device must be closed", E_USER_WARNING);
              return false;
          }
  
          return true;
      }
  
      function _exec($cmd, &amp;$out = null)
      {
          $desc = array(
              1 =&gt; array("pipe", "w"),
              2 =&gt; array("pipe", "w")
          );
  
          $proc = proc_open($cmd, $desc, $pipes);
  
          $ret = stream_get_contents($pipes[1]);
          $err = stream_get_contents($pipes[2]);
  
          fclose($pipes[1]);
          fclose($pipes[2]);
  
          $retVal = proc_close($proc);
  
          if (func_num_args() == 2) $out = array($ret, $err);
          return $retVal;
      }
  
      //
      // INTERNAL TOOLKIT -- {STOP}
      //
  }
  ?&gt;
  </code></pre>