blob: 0685e3e990cae789db561d2643298f19fc675359 [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):
Chris Liechti9dcb4232015-08-20 01:15:37 +020037 """\
38 yield tuples of hex and ASCII display in multiples of 16. Includes a
39 space after 8 bytes and (None, None) after 16 bytes and at the end.
40 """
Chris Liechti730e9f22015-08-19 03:07:05 +020041 n = 0
42 for b in serial.iterbytes(data):
43 yield ('{:02X} '.format(ord(b)), b if b' ' <= b < b'\x7f' else b'.')
44 n += 1
45 if n == 8:
Chris Liechti9dcb4232015-08-20 01:15:37 +020046 yield (' ', ' ')
Chris Liechti730e9f22015-08-19 03:07:05 +020047 elif n > 16:
Chris Liechti9dcb4232015-08-20 01:15:37 +020048 yield (None, None)
Chris Liechti730e9f22015-08-19 03:07:05 +020049 n = 0
50 while n < 16:
51 yield (' ', ' ')
52 n += 1
Chris Liechti9dcb4232015-08-20 01:15:37 +020053 yield (None, None)
Chris Liechti730e9f22015-08-19 03:07:05 +020054
55
56def hexdump(data):
Chris Liechti9dcb4232015-08-20 01:15:37 +020057 """yield lines with hexdump of data"""
Chris Liechti730e9f22015-08-19 03:07:05 +020058 values = []
59 ascii = []
60 for h, a in sixteen(data):
61 if h is None:
62 yield ' '.join([
63 ''.join(values),
64 ''.join(ascii)])
65 del values[:]
66 del ascii[:]
67 else:
68 values.append(h)
69 ascii.append(a)
70
71
Chris Liechti730e9f22015-08-19 03:07:05 +020072class FormatRaw(object):
Chris Liechti9dcb4232015-08-20 01:15:37 +020073 """forward rx and tx data to output"""
74
Chris Liechti730e9f22015-08-19 03:07:05 +020075 def __init__(self, output, color):
76 self.output = output
77 self.color = color
78 self.rx_color = '\x1b[32m'
79 self.tx_color = '\x1b[31m'
80
81 def rx(self, data):
82 if self.color:
83 self.output.write(self.rx_color)
84 self.output.write(data)
85 self.output.flush()
86
87 def tx(self, data):
88 if self.color:
89 self.output.write(self.tx_color)
90 self.output.write(data)
91 self.output.flush()
92
93 def control(self, name, value):
94 pass
95
96
97class FormatHexdump(object):
Chris Liechti9dcb4232015-08-20 01:15:37 +020098 """\
99 Create a hex dump of RX ad TX data, show when control lines are read or
100 written.
101
102 output example::
103
104 000000.000 FLSH flushInput
105 000002.469 RTS inactive
106 000002.773 RTS active
107 000003.106 TX C3 B6 ..
108 000003.107 RX C3 .
109 000003.108 RX B6 .
110 """
111
Chris Liechti730e9f22015-08-19 03:07:05 +0200112 def __init__(self, output, color):
113 self.start_time = time.time()
114 self.output = output
115 self.color = color
116 self.rx_color = '\x1b[32m'
117 self.tx_color = '\x1b[31m'
118 self.control_color = '\x1b[37m'
119
120 def write_line(self, timestamp, label, value):
121 self.output.write('{:010.3f} {:4} {}\n'.format(timestamp, label, value))
122 self.output.flush()
123
124 def rx(self, data):
125 if self.color:
126 self.output.write(self.rx_color)
127 for row in hexdump(data):
128 self.write_line(time.time() - self.start_time, 'RX', row)
129
130 def tx(self, data):
131 if self.color:
132 self.output.write(self.tx_color)
133 for row in hexdump(data):
134 self.write_line(time.time() - self.start_time, 'TX', row)
135
136 def control(self, name, value):
137 if self.color:
138 self.output.write(self.control_color)
139 self.write_line(time.time() - self.start_time, name, value)
140
141
Chris Liechtiece60cf2015-08-18 02:39:03 +0200142class Serial(serial.Serial):
143 """Just inherit the native Serial port implementation and patch the port property."""
144
145 def __init__(self, *args, **kwargs):
146 super(Serial, self).__init__(*args, **kwargs)
Chris Liechti730e9f22015-08-19 03:07:05 +0200147 self.formatter = None
Chris Liechtiece60cf2015-08-18 02:39:03 +0200148
149 @serial.Serial.port.setter
150 def port(self, value):
151 if value is not None:
152 serial.Serial.port.__set__(self, self.fromURL(value))
153
154 def fromURL(self, url):
155 """extract host and port from an URL string"""
Chris Liechtiece60cf2015-08-18 02:39:03 +0200156 parts = urlparse.urlsplit(url)
Chris Liechti6c8887c2015-08-18 23:38:05 +0200157 if parts.scheme != 'spy':
Chris Liechtiece60cf2015-08-18 02:39:03 +0200158 raise serial.SerialException('expected a string in the form "spy://port[?option[=value][&option[=value]]]": not starting with spy:// (%r)' % (parts.scheme,))
159 # process options now, directly altering self
Chris Liechti730e9f22015-08-19 03:07:05 +0200160 formatter = FormatHexdump
161 color = False
162 output = sys.stderr
Chris Liechtiece60cf2015-08-18 02:39:03 +0200163 for option, values in urlparse.parse_qs(parts.query, True).items():
164 if option == 'dev':
Chris Liechti730e9f22015-08-19 03:07:05 +0200165 output = open(values[0], 'w')
Chris Liechtiece60cf2015-08-18 02:39:03 +0200166 elif option == 'color':
Chris Liechti730e9f22015-08-19 03:07:05 +0200167 color = True
168 elif option == 'raw':
169 formatter = FormatRaw
170 self.formatter = formatter(output, color)
Chris Liechtiece60cf2015-08-18 02:39:03 +0200171 return ''.join([parts.netloc, parts.path])
172
173 def write(self, tx):
Chris Liechti730e9f22015-08-19 03:07:05 +0200174 self.formatter.tx(tx)
Chris Liechtiece60cf2015-08-18 02:39:03 +0200175 return super(Serial, self).write(tx)
176
177 def read(self, size=1):
178 rx = super(Serial, self).read(size)
179 if rx:
Chris Liechti730e9f22015-08-19 03:07:05 +0200180 self.formatter.rx(rx)
Chris Liechtiece60cf2015-08-18 02:39:03 +0200181 return rx
182
183
Chris Liechti730e9f22015-08-19 03:07:05 +0200184 def flush(self):
185 self.formatter.control('FLSH', 'flush')
186 super(Serial, self).flush()
187
188 def flushInput(self):
189 self.formatter.control('FLSH', 'flushInput')
190 super(Serial, self).flush()
191
192 def flushOutput(self):
193 self.formatter.control('FLSH', 'flushOutput')
194 super(Serial, self).flushOutput()
195
196 def sendBreak(self, duration=0.25):
Chris Liechti9dcb4232015-08-20 01:15:37 +0200197 self.formatter.control('BRK', 'sendBreak {}'.format(duration))
Chris Liechti730e9f22015-08-19 03:07:05 +0200198 super(Serial, self).sendBreak(duration)
199
200 def setBreak(self, level=1):
201 self.formatter.control('BRK', 'active' if level else 'inactive')
202 super(Serial, self).setBreak(level)
203
204 def setRTS(self, level=1):
205 self.formatter.control('RTS', 'active' if level else 'inactive')
206 super(Serial, self).setRTS(level)
207
208 def setDTR(self, level=1):
209 self.formatter.control('DTR', 'active' if level else 'inactive')
210 super(Serial, self).setDTR(level)
211
212 def getCTS(self):
213 level = super(Serial, self).getCTS()
214 self.formatter.control('CTS', 'active' if level else 'inactive')
215 return level
216
217 def getDSR(self):
218 level = super(Serial, self).getDSR()
219 self.formatter.control('DSR', 'active' if level else 'inactive')
220 return level
221
222 def getRI(self):
223 level = super(Serial, self).getRI()
224 self.formatter.control('RI', 'active' if level else 'inactive')
225 return level
226
227 def getCD(self):
228 self.formatter.control('CD', 'active' if level else 'inactive')
229 level = super(Serial, self).getCD()
230 return level
231
Chris Liechtiece60cf2015-08-18 02:39:03 +0200232# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
233if __name__ == '__main__':
234 s = Serial(None)
235 s.port = 'spy:///dev/ttyS0'
236 print(s)
237