blob: 3db8773a41ac3f5e086417578dc1c1ea9bb71503 [file] [log] [blame]
Chris Liechtiece60cf2015-08-18 02:39:03 +02001#! python
2#
3# Python Serial Port Extension for Win32, Linux, BSD, Jython
4# see __init__.py
5#
6# This module implements a special URL handler that wraps an other port,
Chris Liechti6c8887c2015-08-18 23:38:05 +02007# print the traffic for debugging purposes. With this, it is possible
8# to debug the serial port traffic on every application that uses
9# serial_for_url.
Chris Liechtiece60cf2015-08-18 02:39:03 +020010#
11# (C) 2015 Chris Liechti <cliechti@gmx.net>
12#
13# SPDX-License-Identifier: BSD-3-Clause
14#
15# URL format: spy://port[?option[=value][&option[=value]]]
16# options:
17# - dev=X a file or device to write to
18# - color use escape code to colorize output
Chris Liechti730e9f22015-08-19 03:07:05 +020019# - raw forward raw bytes instead of hexdump
Chris Liechtiece60cf2015-08-18 02:39:03 +020020#
21# example:
22# redirect output to an other terminal window on Posix (Linux):
Chris Liechti730e9f22015-08-19 03:07:05 +020023# python -m serial.tools.miniterm spy:///dev/ttyUSB0?dev=/dev/pts/14\&color
Chris Liechtiece60cf2015-08-18 02:39:03 +020024
25import sys
Chris Liechti730e9f22015-08-19 03:07:05 +020026import time
27
Chris Liechtiece60cf2015-08-18 02:39:03 +020028import serial
29
30try:
31 import urlparse
32except ImportError:
33 import urllib.parse as urlparse
Chris Liechtiece60cf2015-08-18 02:39:03 +020034
Chris Liechti730e9f22015-08-19 03:07:05 +020035
36def sixteen(data):
37 n = 0
38 for b in serial.iterbytes(data):
39 yield ('{:02X} '.format(ord(b)), b if b' ' <= b < b'\x7f' else b'.')
40 n += 1
41 if n == 8:
42 yield ' ', ' '
43 elif n > 16:
44 yield None, None
45 n = 0
46 while n < 16:
47 yield (' ', ' ')
48 n += 1
49 yield None, None
50
51
52
53def hexdump(data):
54 values = []
55 ascii = []
56 for h, a in sixteen(data):
57 if h is None:
58 yield ' '.join([
59 ''.join(values),
60 ''.join(ascii)])
61 del values[:]
62 del ascii[:]
63 else:
64 values.append(h)
65 ascii.append(a)
66
67
68
69class FormatRaw(object):
70 def __init__(self, output, color):
71 self.output = output
72 self.color = color
73 self.rx_color = '\x1b[32m'
74 self.tx_color = '\x1b[31m'
75
76 def rx(self, data):
77 if self.color:
78 self.output.write(self.rx_color)
79 self.output.write(data)
80 self.output.flush()
81
82 def tx(self, data):
83 if self.color:
84 self.output.write(self.tx_color)
85 self.output.write(data)
86 self.output.flush()
87
88 def control(self, name, value):
89 pass
90
91
92class FormatHexdump(object):
93 def __init__(self, output, color):
94 self.start_time = time.time()
95 self.output = output
96 self.color = color
97 self.rx_color = '\x1b[32m'
98 self.tx_color = '\x1b[31m'
99 self.control_color = '\x1b[37m'
100
101 def write_line(self, timestamp, label, value):
102 self.output.write('{:010.3f} {:4} {}\n'.format(timestamp, label, value))
103 self.output.flush()
104
105 def rx(self, data):
106 if self.color:
107 self.output.write(self.rx_color)
108 for row in hexdump(data):
109 self.write_line(time.time() - self.start_time, 'RX', row)
110
111 def tx(self, data):
112 if self.color:
113 self.output.write(self.tx_color)
114 for row in hexdump(data):
115 self.write_line(time.time() - self.start_time, 'TX', row)
116
117 def control(self, name, value):
118 if self.color:
119 self.output.write(self.control_color)
120 self.write_line(time.time() - self.start_time, name, value)
121
122
Chris Liechtiece60cf2015-08-18 02:39:03 +0200123class Serial(serial.Serial):
124 """Just inherit the native Serial port implementation and patch the port property."""
125
126 def __init__(self, *args, **kwargs):
127 super(Serial, self).__init__(*args, **kwargs)
Chris Liechti730e9f22015-08-19 03:07:05 +0200128 self.formatter = None
Chris Liechtiece60cf2015-08-18 02:39:03 +0200129
130 @serial.Serial.port.setter
131 def port(self, value):
132 if value is not None:
133 serial.Serial.port.__set__(self, self.fromURL(value))
134
135 def fromURL(self, url):
136 """extract host and port from an URL string"""
Chris Liechtiece60cf2015-08-18 02:39:03 +0200137 parts = urlparse.urlsplit(url)
Chris Liechti6c8887c2015-08-18 23:38:05 +0200138 if parts.scheme != 'spy':
Chris Liechtiece60cf2015-08-18 02:39:03 +0200139 raise serial.SerialException('expected a string in the form "spy://port[?option[=value][&option[=value]]]": not starting with spy:// (%r)' % (parts.scheme,))
140 # process options now, directly altering self
Chris Liechti730e9f22015-08-19 03:07:05 +0200141 formatter = FormatHexdump
142 color = False
143 output = sys.stderr
Chris Liechtiece60cf2015-08-18 02:39:03 +0200144 for option, values in urlparse.parse_qs(parts.query, True).items():
145 if option == 'dev':
Chris Liechti730e9f22015-08-19 03:07:05 +0200146 output = open(values[0], 'w')
Chris Liechtiece60cf2015-08-18 02:39:03 +0200147 elif option == 'color':
Chris Liechti730e9f22015-08-19 03:07:05 +0200148 color = True
149 elif option == 'raw':
150 formatter = FormatRaw
151 self.formatter = formatter(output, color)
Chris Liechtiece60cf2015-08-18 02:39:03 +0200152 return ''.join([parts.netloc, parts.path])
153
154 def write(self, tx):
Chris Liechti730e9f22015-08-19 03:07:05 +0200155 self.formatter.tx(tx)
Chris Liechtiece60cf2015-08-18 02:39:03 +0200156 return super(Serial, self).write(tx)
157
158 def read(self, size=1):
159 rx = super(Serial, self).read(size)
160 if rx:
Chris Liechti730e9f22015-08-19 03:07:05 +0200161 self.formatter.rx(rx)
Chris Liechtiece60cf2015-08-18 02:39:03 +0200162 return rx
163
164
Chris Liechti730e9f22015-08-19 03:07:05 +0200165 def flush(self):
166 self.formatter.control('FLSH', 'flush')
167 super(Serial, self).flush()
168
169 def flushInput(self):
170 self.formatter.control('FLSH', 'flushInput')
171 super(Serial, self).flush()
172
173 def flushOutput(self):
174 self.formatter.control('FLSH', 'flushOutput')
175 super(Serial, self).flushOutput()
176
177 def sendBreak(self, duration=0.25):
178 self.formatter.control('FLSH', 'sendBreak')
179 super(Serial, self).sendBreak(duration)
180
181 def setBreak(self, level=1):
182 self.formatter.control('BRK', 'active' if level else 'inactive')
183 super(Serial, self).setBreak(level)
184
185 def setRTS(self, level=1):
186 self.formatter.control('RTS', 'active' if level else 'inactive')
187 super(Serial, self).setRTS(level)
188
189 def setDTR(self, level=1):
190 self.formatter.control('DTR', 'active' if level else 'inactive')
191 super(Serial, self).setDTR(level)
192
193 def getCTS(self):
194 level = super(Serial, self).getCTS()
195 self.formatter.control('CTS', 'active' if level else 'inactive')
196 return level
197
198 def getDSR(self):
199 level = super(Serial, self).getDSR()
200 self.formatter.control('DSR', 'active' if level else 'inactive')
201 return level
202
203 def getRI(self):
204 level = super(Serial, self).getRI()
205 self.formatter.control('RI', 'active' if level else 'inactive')
206 return level
207
208 def getCD(self):
209 self.formatter.control('CD', 'active' if level else 'inactive')
210 level = super(Serial, self).getCD()
211 return level
212
Chris Liechtiece60cf2015-08-18 02:39:03 +0200213# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
214if __name__ == '__main__':
215 s = Serial(None)
216 s.port = 'spy:///dev/ttyS0'
217 print(s)
218