使用 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 的包装器?

is there any way for real time port listening or i must write a wrapper with c o python for my Apache web-server?

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

有关完整信息,请参阅 link: Full examples of using pySerial package