2 # Script that can read from a serial device and show timestamps.
4 # Copyright (C) 2009 Kevin O'Connor <kevin@koconnor.net>
6 # This file may be distributed under the terms of the GNU GPLv3 license.
9 # tools/readserial.py /dev/ttyUSB0 115200
16 # Reset time counter after this much idle time.
18 # Alter timing reports based on how much time would be spent writing
21 # Number of bits in a transmitted byte - 8N1 is 1 start bit + 8 data
25 def readserial(infile, logfile, baudrate):
29 byteadjust = float(BITSPERBYTE) / baudrate
33 res = select.select([infile, sys.stdin], [], [])
34 except KeyboardInterrupt:
35 sys.stdout.write("\n")
37 if sys.stdin in res[0]:
38 # Got keyboard input - force reset on next serial input
46 datatime = time.time()
48 datatime -= len(d) * byteadjust
50 # Reset start time if no data for some time
51 if datatime - lasttime > RESTARTINTERVAL:
55 msg = "\n\n======= %s (adjust=%d)\n" % (
56 time.asctime(time.localtime(datatime)), ADJUSTBAUD)
61 # Translate unprintable chars; add timestamps
65 delta = datatime - starttime - (charcount * byteadjust)
66 out += "%06.3f: " % delta
70 datatime += byteadjust
81 if oc < 0x20 or oc >= 0x7f and oc != 0x09:
92 usage = "%prog [options] [<serialdevice> [<baud>]]"
93 opts = optparse.OptionParser(usage)
94 opts.add_option("-f", "--file",
95 action="store_false", dest="serial", default=True,
96 help="read from file instead of serialdevice")
97 opts.add_option("-n", "--no-adjust",
98 action="store_false", dest="adjustbaud", default=True,
99 help="don't adjust times by serial rate")
100 options, args = opts.parse_args()
104 opts.error("Too many arguments")
110 ADJUSTBAUD=options.adjustbaud
113 # Read from serial port
115 ser = serial.Serial(serialport, baud, timeout=0)
118 ser = open(serialport, 'rb')
121 fcntl.fcntl(ser, fcntl.F_SETFL
122 , fcntl.fcntl(ser, fcntl.F_GETFL) | os.O_NONBLOCK)
124 logname = time.strftime("seriallog-%Y%m%d_%H%M%S.log")
125 f = open(logname, 'wb')
126 readserial(ser, f, baud)
128 if __name__ == '__main__':