繁体   English   中英

在Perl中测试是否在Device :: SerialPort上有可用数据

[英]Test in Perl if data is available on Device::SerialPort

我编写了一个Perl脚本,该脚本从串行端口读取数据。

use Device::SerialPort;
$PortObj = new Device::SerialPort ($PortName, $quiet, $lockfile);
$PortObj->read_const_time( 500 ); # timeout waiting for data after 500ms
...

主循环尝试从串行端口读取数据:

while ( 1 ) {
  ( $count, $data ) = $PortObj->read( $frameLength );
  process_my_data( $data );
  do_something_entirely_different_that_needs_being_done;
}

但是我不想让$ PortObj->读取超时(这会浪费很多时间),而是希望能够测试缓冲区中是否有数据,因此可以加快循环速度:

while ( 1 ) {
  if ( test_serial_data_available ) { ( $count, $data ) = $PortObj->read( $frameLength ); }
  do_something_entirely_different_that_needs_being_done;
}

我可以测试串行缓冲区的数据可用性吗?

EDIT1:今天上午我一直在重写问题,以使用串行设备作为文件句柄并读取数据,但是仍然阻塞了循环。 这可能会打开新选项,以检查缓冲区中是否有可用数据。 在伪Perl中:

use Symbol qw( gensym );
my $handle = gensym();
my $PortObj = tie( *$handle, "Device::SerialPort", $PortName );

while ( 1 ) {
  my $frameData;
  if ( test_serial_data_available ) { my $readLength = read( $handle , $frameData , $frameLength ); }
  do_something_entirely_different_that_needs_being_done;
}

所以我的问题是: test_serial_data_available应该是什么样?

由于您具有文件句柄,因此可以使用select

select将采用任意数量的文件描述符,并等待直到其中一个变为“就绪”为止,就绪状态由select gets的3组中的哪组定义包含文件句柄。 有关详细信息,请参见perldoc -f select

select接受超时,因此,如果将超时设置为0,它将成为轮询功能。 因此,此功能将满足您的需求:

sub poll {
    my ($fh) = @_;
    my $in = '';
    vec($in,fileno($fh),1) = 1;
    return select($in,undef,undef,0);
}

# ...

if ( poll($handle) ) { my $readLength = read( $handle , $frameData , $frameLength ); }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM