使用PySerial是否可以等待数据?

Mik*_*ike 20 python serial-port pyserial

我有一个python程序,它通过read模块从串口读取数据.我需要记住的两个条件是:我不知道会有多少数据,我不知道何时需要数据.

基于此,我提出了以下代码snipets:

#Code from main loop, spawning thread and waiting for data
s = serial.Serial(5, timeout=5)  # Open COM5, 5 second timeout
s.baudrate = 19200

#Code from thread reading serial data
while 1:
  tdata = s.read(500)    # Read 500 characters or 5 seconds

  if(tdata.__len__() > 0):        #If we got data
    if(self.flag_got_data is 0):  #If it's the first data we recieved, store it
      self.data = tdata        
    else:                         #if it's not the first, append the data
      self.data += tdata
      self.flag_got_data = 1
Run Code Online (Sandbox Code Playgroud)

因此,此代码将永远循环从串行端口获取数据.我们最多可以存储500个字符的数据,然后通过设置标志来警告主循环.如果没有数据,我们就会回去睡觉并等待.

代码正常,但我不喜欢5s超时.我需要它,因为我不知道预期会有多少数据,但我不喜欢它即使没有数据也会每5秒唤醒一次.

有没有办法在做数据之前检查数据何时可用select?我在想inWaiting()Linux中的命令.

编辑:
我以为我注意到我找到了这个read方法,但实际上它似乎只是将我的"睡眠"改为民意调查,所以这不是我想要的.我只想睡觉直到数据进入,然后去获取它.

Mik*_*ike 18

好吧,我实际上得到了一些我喜欢的东西.使用read()没有超时的组合和inWaiting()方法:

#Modified code from main loop: 
s = serial.Serial(5)

#Modified code from thread reading the serial port
while 1:
  tdata = s.read()           # Wait forever for anything
  time.sleep(1)              # Sleep (or inWaiting() doesn't give the correct value)
  data_left = s.inWaiting()  # Get the number of characters ready to be read
  tdata += s.read(data_left) # Do the read and combine it with the first character

  ... #Rest of the code
Run Code Online (Sandbox Code Playgroud)

这似乎给出了我想要的结果,我想这种类型的功能在Python中不作为单个方法存在

  • `time.sleep(1)` 似乎是一个非常丑陋的 hack,它增加了大量延迟来获取你的数据。 (2认同)

TJD*_*TJD 13

你可以设置timeout = None,然后read调用将阻塞,直到所请求的字节数为止.如果您想等到数据到达,只需执行read(1)超时None.如果要在不阻塞的情况下检查数据,请执行a read(1)timeout with timeout,并检查它是否返回任何数据.

(参见文档http://pyserial.sourceforge.net/pyserial_api.html)