blob: fec2811a7e557ef9333c8817c70a288162b1abb5 [file] [log] [blame]
Kevin O'Connor2547bb82009-04-19 11:04:59 -04001#!/usr/bin/env python
2# Script that can read from a serial device and show timestamps.
3#
4# Copyright (C) 2009 Kevin O'Connor <kevin@koconnor.net>
5#
6# This file may be distributed under the terms of the GNU GPLv3 license.
7
8# Usage:
9# tools/readserial.py /dev/ttyUSB0 115200
10
11import sys
12import time
13import select
14import serial
15
16# Reset time counter after this much idle time.
17RESTARTINTERVAL = 60
18# Alter timing reports based on how much time would be spent writing
19# to serial.
20ADJUSTBAUD = 1
21
22def readserial(infile, logfile, baudrate):
Kevin O'Connora1dadf42009-04-26 21:24:16 -040023 lasttime = 0
Kevin O'Connor2547bb82009-04-19 11:04:59 -040024 while 1:
25 # Read data
26 try:
27 res = select.select([infile, sys.stdin], [], [])
28 except KeyboardInterrupt:
29 sys.stdout.write("\n")
30 break
31 if sys.stdin in res[0]:
32 # Got keyboard input - force reset on next serial input
33 sys.stdin.read(1)
Kevin O'Connora1dadf42009-04-26 21:24:16 -040034 lasttime = 0
Kevin O'Connor2547bb82009-04-19 11:04:59 -040035 if len(res[0]) == 1:
36 continue
37 curtime = time.time()
38 d = infile.read(4096)
39
40 # Reset start time if no data for some time
Kevin O'Connora1dadf42009-04-26 21:24:16 -040041 if curtime - lasttime > RESTARTINTERVAL:
Kevin O'Connor2547bb82009-04-19 11:04:59 -040042 starttime = curtime
43 charcount = 0
44 isnewline = 1
Kevin O'Connora53ab002009-12-05 13:44:39 -050045 msg = "\n\n======= %s (adjust=%d)\n" % (
46 time.asctime(time.localtime(curtime)), ADJUSTBAUD)
47 sys.stdout.write(msg)
48 logfile.write(msg)
Kevin O'Connora1dadf42009-04-26 21:24:16 -040049 lasttime = curtime
Kevin O'Connor2547bb82009-04-19 11:04:59 -040050
51 # Translate unprintable chars; add timestamps
52 out = ""
53 for c in d:
54 if isnewline:
55 delta = curtime - starttime
56 if ADJUSTBAUD:
57 delta -= float(charcount * 9) / baudrate
58 out += "%06.3f: " % delta
59 isnewline = 0
60 oc = ord(c)
61 charcount += 1
62 if oc == 0x0d:
63 continue
64 if oc == 0x00:
65 out += "<00>\n"
66 isnewline = 1
67 continue
68 if oc == 0x0a:
69 out += "\n"
70 isnewline = 1
71 continue
72 if oc < 0x20 or oc >= 0x7f and oc != 0x09:
73 out += "<%02x>" % oc
74 continue
75 out += c
76
77 sys.stdout.write(out)
78 sys.stdout.flush()
79 logfile.write(out)
80 logfile.flush()
81
82def printUsage():
83 print "Usage:\n %s [<serialdevice> [<baud>]]" % (sys.argv[0],)
84 sys.exit(1)
85
86def main():
87 serialport = 0
88 baud = 115200
89 if len(sys.argv) > 3:
90 printUsage()
91 if len(sys.argv) > 1:
92 serialport = sys.argv[1]
93 if len(sys.argv) > 2:
94 baud = int(sys.argv[2])
95
96 ser = serial.Serial(serialport, baud, timeout=0)
97
98 logname = time.strftime("seriallog-%Y%m%d_%H%M%S.log")
99 f = open(logname, 'wb')
100 readserial(ser, f, baud)
101
102if __name__ == '__main__':
103 main()