Search code examples
pythonserial-portpyserialsniffing

pyserial - how to continuously read and parse


I'm trying to capture data from a hardware device that's connected via usb to my linux computer that's running ubuntu. Here's the very simple script I currently have:

import serial
ser = serial.Serial('/dev/ttyUB0', 9600)
s = ser.read(10000)
print(s)
  1. How do I make this print continuously?
  2. The data is coming through in hexadecimal which I'd like to interpret. Should I have the continuous data save to a text file and then have another script analyze? Essentially, I'm trying to build a sniffer to grab the data and interpret.

Thanks for your help! I'm a newbie :)


Solution

  • 1) Just put the read and print within a while True: section.

    Example:

    import serial
    ser = serial.Serial('/dev/ttyUB0', 9600)
    while True:
        s = ser.read(10000)
        print(s)
    

    Checkout another answer for some more info if you need to sniff both send and receive. https://stackoverflow.com/a/19232484/3533874

    2) For speed I would save the data without processing to a file and have the other script do the decoding/processing of the hex data. Make sure you write to the file in binary mode.

    Example:

    import serial
    ser = serial.Serial('/dev/ttyUB0', 9600)
    
    # This will just keep going over and over again
    with open('hexdatafile.dat', 'wb') as datafile:
        datafile.write(ser.read(10000))