gpt4 book ai didi

php - 用php在ubuntu上监听串口

转载 作者:太空宇宙 更新时间:2023-11-04 05:55:47 29 4
gpt4 key购买 nike

我需要从连接到我的 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);
}
?>

这将向串口发送命令并从串口读取任何更新

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

有没有什么方法可以实时监听端口,或者我必须用 c o python 为我的 Apache 网络服务器编写一个包装器?

最佳答案

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 有很好的工具来处理监听端口所需的异常

完整信息见链接: Full examples of using pySerial package

关于php - 用php在ubuntu上监听串口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27900744/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com