Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

python - Using pySerial.readline with inconsistent data

I'm making an application that listens for data from a serial port. The data being read is all very simple and similar: 20-40 bytes, with an average of 30s between messages to a minimum of maybe .01s. However, the possible devices that will be used and the format of the data they send is all slightly different. Some devices end a message with ' ', some with ' ', some with ' ', some with something else. I've been testing with a device that sends messages that end with ' ', so the readline() function has been working just fine.

For example:

while True:
    if ser.in_waiting > 0:
        ser_data = ser.readline()
        yield ser_data.hex()
    else:
        time.sleep(0.0001)

However, that obviously won't work for a message that doesn't end with ' '. I've seen some examples that read one byte at a time until an arbitrary end character is reached. That's great, but I'd like to find a general solution that works for all different types of data without any settings or configuration from the user, if possible.

I've tried this:

while True:
    if ser.in_waiting > 0:
        ser_data = ser.read(ser.in_waiting)
        yield ser_data.hex()
    else:
        time.sleep(0.0001)

It seems to work, but I'm a little skeptical. What if ser.in_waiting is evaluated before the entire message is in the buffer? Wouldn't that result in a partial message, or am I just overthinking things?

Would love to find a better way.

question from:https://stackoverflow.com/questions/65897115/using-pyserial-readline-with-inconsistent-data

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...