问题描述
因此,较大项目的一部分需要使用树莓派从串行端口接收长十六进制字符串.我以为我一切正常,但后来发现它在字符串中间丢失了一大块数据.
So part of a larger project needs to receive a long hex character string from a serial port using a raspberry pi. I thought I had it all working but then discovered it was losing a chunk of data in the middle of the string.
def BUTTON_Clicked(self, widget, data= None):
ser = serial.Serial("/dev/ex_device", 115200, timeout=3)
RECEIVEDfile = open("RECIEVED.txt", "r+", 0) #unbuffered
#Commands sent out
ser.write("*n\r")
time.sleep(1)
ser.flush()
ser.write("*E")
ser.write("\r")
#Read back string rx'd
RECEIVED= ser.read()
RECEIVED= re.sub(r'[\W_]+', '', RECEIVED) #remove non-alphanumeric characters (caused by noise maybe?)
RECEIVEDfile.write(re.sub("(.{4})", "\\1\n", RECEIVED, 0, re.DOTALL)) #new line every 4 characters
RECEIVEDfile.close
ser.write("*i\r")
ser.close
这是用于检索数据的脚本,波特率和串行命令设置正确,脚本以无缓冲"(-u)运行,但未保存完整字符串.该字符串大约有 16384 个字符长,但只有大约 9520 个字符(它会有所不同)被保存(无法提供字符串进行分析).有谁知道我错过了什么?为你能给我的任何帮助干杯.
This is the script used to retrieve the data, the baud rate and serial commands are set right and the script is run as "unbuffered" (-u) but yet the full string is not saved. The string is approx 16384 characters long but only approx 9520 characters (it varies) are being saved (can't supply the string for analysis). Anyone know what I'm missing? Cheers for any help you can give me.
推荐答案
很高兴我的评论有帮助!
Glad my comment helped!
将超时设置为一个较低的数字,例如1秒.然后尝试这样的事情.它试图读取一个大块,但很快就会超时并且不会长时间阻塞.读取的任何内容都放入列表(rx_buf)中.然后永远循环,只要你有待读取的字节.真正的问题是知道"何时不应期待更多数据.
Set timeout to a low number, e.g. 1 second. Then try something like this. It tries to read a large chunk, but times out quickly and doesn't block for a long time. Whatever has been read is put into a list (rx_buf). Then loop forever, as long as you've got pending bytes to read. The real problem is to 'know' when not to expect any more data.
rx_buf = [ser.read(16384)] # Try reading a large chunk of data, blocking for timeout secs.
while True: # Loop to read remaining data, to end of receive buffer.
pending = ser.inWaiting()
if pending:
rx_buf.append(ser.read(pending)) # Append read chunks to the list.
else:
break
rx_data = ''.join(rx_buf) # Join the chunks, to get a string of serial data.
我将块放在列表中的原因是连接操作比字符串上的 '+=' 高效得多.
The reason I'm putting the chunks in a list is that the join operation is much more efficient than '+=' on strings.
这篇关于丢失接收到的串行字符串中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!