blob: 8b20fd27be33383ef979f489c49f424a7926146c [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):
23 starttime = 0
24 isnewline = 1
25 while 1:
26 # Read data
27 try:
28 res = select.select([infile, sys.stdin], [], [])
29 except KeyboardInterrupt:
30 sys.stdout.write("\n")
31 break
32 if sys.stdin in res[0]:
33 # Got keyboard input - force reset on next serial input
34 sys.stdin.read(1)
35 starttime = 0
36 if len(res[0]) == 1:
37 continue
38 curtime = time.time()
39 d = infile.read(4096)
40
41 # Reset start time if no data for some time
42 if curtime - starttime > RESTARTINTERVAL:
43 starttime = curtime
44 charcount = 0
45 isnewline = 1
46 sys.stdout.write("\n")
47 logfile.write("\n")
48
49 # Translate unprintable chars; add timestamps
50 out = ""
51 for c in d:
52 if isnewline:
53 delta = curtime - starttime
54 if ADJUSTBAUD:
55 delta -= float(charcount * 9) / baudrate
56 out += "%06.3f: " % delta
57 isnewline = 0
58 oc = ord(c)
59 charcount += 1
60 if oc == 0x0d:
61 continue
62 if oc == 0x00:
63 out += "<00>\n"
64 isnewline = 1
65 continue
66 if oc == 0x0a:
67 out += "\n"
68 isnewline = 1
69 continue
70 if oc < 0x20 or oc >= 0x7f and oc != 0x09:
71 out += "<%02x>" % oc
72 continue
73 out += c
74
75 sys.stdout.write(out)
76 sys.stdout.flush()
77 logfile.write(out)
78 logfile.flush()
79
80def printUsage():
81 print "Usage:\n %s [<serialdevice> [<baud>]]" % (sys.argv[0],)
82 sys.exit(1)
83
84def main():
85 serialport = 0
86 baud = 115200
87 if len(sys.argv) > 3:
88 printUsage()
89 if len(sys.argv) > 1:
90 serialport = sys.argv[1]
91 if len(sys.argv) > 2:
92 baud = int(sys.argv[2])
93
94 ser = serial.Serial(serialport, baud, timeout=0)
95
96 logname = time.strftime("seriallog-%Y%m%d_%H%M%S.log")
97 f = open(logname, 'wb')
98 readserial(ser, f, baud)
99
100if __name__ == '__main__':
101 main()