我需要从连接到我的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);
}
?>
这将向串行端口发送一个命令,并从端口内部读取任何更新
但我随时都要听波特的 我的意思是每一秒我都会收到设备的任何更新,我必须拥有它,我不能等待下一个更新周期
有什么方法可以实时监听端口吗?或者我必须为我的apacheweb服务器编写一个用c o python编写的包装器?在
实际上是的,用c或python为这样的工作编写一个包装器会更好。 python有很好的工具来处理监听端口所需的异常
有关完整信息,请参阅链接: Full examples of using pySerial package
相关问题 更多 >
编程相关推荐