用PHP在Ubuntu上收听串行端口


listen to serial port on ubuntu with php

我需要从连接到我的 ubuntu 服务器串行端口的设备获取一些数据,例如实时温度和风速

我也需要向设备发送一些命令,为此我找到了这样的脚本:

<?php
$portName = 'com9:';
$baudRate = 9600;
$bits = 8;
$spotBit = 1;
header( 'Content-type: text/plain; charset=utf-8' ); 
?>
Serial Port Test
================
<?php
function echoFlush($string){
    echo $string . "'n";
    flush();
    ob_flush();
}
if(!extension_loaded('dio')){
    echoFlush( "PHP Direct IO does not appear to be installed for more info see: http://www.php.net/manual/en/book.dio.php" );
    exit;
}
try{
    //the serial port resource
    $bbSerialPort;
    echoFlush(  "Connecting to serial port: {$portName}" );
    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'){
        $bbSerialPort = dio_open($portName, O_RDWR );
        //we're on windows configure com port from command line
        exec("mode {$portName} baud={$baudRate} data={$bits} stop={$spotBit} parity=n xon=on");
    }else{
        $bbSerialPort = dio_open($portName, O_RDWR | O_NOCTTY | O_NONBLOCK );
        dio_fcntl($bbSerialPort, F_SETFL, O_SYNC);
        //we're on 'nix configure com from php direct io function
        dio_tcsetattr($bbSerialPort, array(
            'baud' => $baudRate,
            'bits' => $bits,
            'stop'  => $spotBit,
            'parity' => 0
        ));
    }
    if(!$bbSerialPort){
        echoFlush( "Could not open Serial port {$portName} ");
        exit;
    }
    // send data
    $dataToSend = "HELLO WORLD!";
    echoFlush( "Writing to serial port data: '"{$dataToSend}'"" );
    $bytesSent = dio_write($bbSerialPort, $dataToSend );
    echoFlush( "Sent: {$bytesSent} bytes" );
    //date_default_timezone_set ("Europe/London");
    $runForSeconds = new DateInterval("PT10S"); //10 seconds
    $endTime = (new DateTime())->add($runForSeconds);
    echoFlush(  "Waiting for {$runForSeconds->format('%S')} seconds to recieve data on serial port" );
    while (new DateTime() < $endTime) {
        $data = dio_read($bbSerialPort, 256); //this is a blocking call
        if ($data){
            echoFlush(  "Data Recieved: ". $data );
        }
    }
    echoFlush(  "Closing Port" );
    dio_close($bbSerialPort);
} 
catch (Exception $e){
    echoFlush(  $e->getMessage() );
    exit(1);
}
?>

这将向串行端口发送命令,并从端口内部读取任何更新

但我需要随时收听端口我的意思是每一秒我都会从设备收到任何更新,我必须拥有它,我迫不及待地等待下一个更新周期

有没有办法实时端口侦听,或者我必须为我的 Apache Web 服务器编写一个带有 C o Python 的包装器?

有没有办法实时端口侦听,或者我必须为我的 Apache Web 服务器编写一个带有 C o Python 的包装器?

实际上是的,最好用 C 或 Python 为这样的工作编写一个包装器。python有很好的工具来处理侦听端口所需的异常

有关完整信息,请参阅链接:使用 pySerial 包的完整示例