我需要从连接到我的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编写一个包装器?
答案 0 :(得分:1)
有没有办法实时端口监听,或者我必须为我的Apache Web服务器用c o python编写一个包装器?
实际上是的,最好用c或python为这样的作业编写一个包装器。 python有很好的工具来处理侦听端口所需的异常
请参阅链接以获取完整信息: Full examples of using pySerial package