Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Reading COM Port from Windows

The following is a library for serial communications via PHP: http://www.phpclasses.org/package/3679-PHP-Communicate-with-a-serial-port.html. The problem is that the method readPort is not fully implemented. It can read in a *nix environment, but apparently not in a Windows environment. The method:

/**
 * 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->_dState !== SERIAL_DEVICE_OPENED)
    {
        trigger_error("Device must be opened to read it", E_USER_WARNING);
        return false;
    }

    if ($this->_os === "linux")
    {
        $content = ""; $i = 0;

        if ($count !== 0)
        {
            do {
                if ($i > $count) $content .= fread($this->_dHandle, ($count - $i));
                else $content .= fread($this->_dHandle, 128);
            } while (($i += 128) === strlen($content));
        }
        else
        {
            do {
                $content .= fread($this->_dHandle, 128);
            } while (($i += 128) === strlen($content));
        }

        return $content;
    }
    elseif ($this->_os === "windows")
    {
        /* Do nohting : not implented yet */
    }

    trigger_error("Reading serial port is not implemented for Windows", E_USER_WARNING);
    return false;
}

The author states:

==> /!\ WARNING /!\ : it's working with linux for r/w, but with windows i've only been able to make write working. If you're a windows user, try to access the serial port through network with serproxy instead.

The limitation of the PHP class library has been mentioned in SO several times already. I haven't found a decent solution. Reading is imperative for my application.

Does anyone here know what to do?

like image 616
StackOverflowNewbie Avatar asked Feb 23 '12 02:02

StackOverflowNewbie


1 Answers

If you can guarantee that you're on Windows, I might recommend an interesting approach: Use either COM (as in, Microsoft's COM, not serial port) or .NET.

There's a free .NET class that I regularly use called CommStudio Express. I've found it to be very reliable, but you can always use the standard SerialPort class built into .NET if you don't need to worry about a USB-to-serial adapter getting unplugged randomly.

In any case, it's easy enough to get at a .NET class in PHP with the DOTNET class:

$serial = new DOTNET('system', 'System.IO.Ports.SerialPort');
$serial->PortName = 'COM3';
$serial->Open();

I haven't tested this code (not on Windows at the moment), but something like that should work just fine. You can then proceed to use all of the regular .NET methods within PHP.

like image 178
Brad Avatar answered Sep 28 '22 10:09

Brad