blob: 4921990164016167ba5798fa47fa716219025c36 [file] [log] [blame]
Chris Liechtiece60cf2015-08-18 02:39:03 +02001#! python
2#
Chris Liechtiece60cf2015-08-18 02:39:03 +02003# This module implements a special URL handler that wraps an other port,
Chris Liechti6c8887c2015-08-18 23:38:05 +02004# print the traffic for debugging purposes. With this, it is possible
5# to debug the serial port traffic on every application that uses
6# serial_for_url.
Chris Liechtiece60cf2015-08-18 02:39:03 +02007#
Chris Liechti3e02f702015-12-16 23:06:04 +01008# This file is part of pySerial. https://github.com/pyserial/pyserial
Chris Liechtiece60cf2015-08-18 02:39:03 +02009# (C) 2015 Chris Liechti <cliechti@gmx.net>
10#
11# SPDX-License-Identifier: BSD-3-Clause
12#
13# URL format: spy://port[?option[=value][&option[=value]]]
14# options:
15# - dev=X a file or device to write to
16# - color use escape code to colorize output
Chris Liechti730e9f22015-08-19 03:07:05 +020017# - raw forward raw bytes instead of hexdump
Chris Liechtiece60cf2015-08-18 02:39:03 +020018#
19# example:
20# redirect output to an other terminal window on Posix (Linux):
Chris Liechti730e9f22015-08-19 03:07:05 +020021# python -m serial.tools.miniterm spy:///dev/ttyUSB0?dev=/dev/pts/14\&color
Chris Liechtiece60cf2015-08-18 02:39:03 +020022
23import sys
Chris Liechti730e9f22015-08-19 03:07:05 +020024import time
25
Chris Liechtiece60cf2015-08-18 02:39:03 +020026import serial
27
28try:
29 import urlparse
30except ImportError:
31 import urllib.parse as urlparse
Chris Liechtiece60cf2015-08-18 02:39:03 +020032
Chris Liechti730e9f22015-08-19 03:07:05 +020033
34def sixteen(data):
Chris Liechti9dcb4232015-08-20 01:15:37 +020035 """\
36 yield tuples of hex and ASCII display in multiples of 16. Includes a
37 space after 8 bytes and (None, None) after 16 bytes and at the end.
38 """
Chris Liechti730e9f22015-08-19 03:07:05 +020039 n = 0
40 for b in serial.iterbytes(data):
Chris Liechti165388c2015-08-22 00:24:08 +020041 yield ('{:02X} '.format(ord(b)), b.decode('ascii') if b' ' <= b < b'\x7f' else '.')
Chris Liechti730e9f22015-08-19 03:07:05 +020042 n += 1
43 if n == 8:
Chris Liechti335242b2015-08-23 01:04:39 +020044 yield (' ', '')
Chris Liechti12a439f2015-08-20 23:01:53 +020045 elif n >= 16:
Chris Liechti9dcb4232015-08-20 01:15:37 +020046 yield (None, None)
Chris Liechti730e9f22015-08-19 03:07:05 +020047 n = 0
Chris Liechti12a439f2015-08-20 23:01:53 +020048 if n > 0:
49 while n < 16:
50 n += 1
51 if n == 8:
Chris Liechti335242b2015-08-23 01:04:39 +020052 yield (' ', '')
Chris Liechti12a439f2015-08-20 23:01:53 +020053 yield (' ', ' ')
54 yield (None, None)
Chris Liechti730e9f22015-08-19 03:07:05 +020055
56
57def hexdump(data):
Chris Liechti9dcb4232015-08-20 01:15:37 +020058 """yield lines with hexdump of data"""
Chris Liechti730e9f22015-08-19 03:07:05 +020059 values = []
60 ascii = []
Chris Liechti4e8896b2015-08-20 23:44:52 +020061 offset = 0
Chris Liechti730e9f22015-08-19 03:07:05 +020062 for h, a in sixteen(data):
63 if h is None:
Chris Liechti92df95a2016-02-09 23:30:37 +010064 yield (offset, ' '.join([''.join(values), ''.join(ascii)]))
Chris Liechti730e9f22015-08-19 03:07:05 +020065 del values[:]
66 del ascii[:]
Chris Liechti4e8896b2015-08-20 23:44:52 +020067 offset += 0x10
Chris Liechti730e9f22015-08-19 03:07:05 +020068 else:
69 values.append(h)
70 ascii.append(a)
71
72
Chris Liechti730e9f22015-08-19 03:07:05 +020073class FormatRaw(object):
Chris Liechti335242b2015-08-23 01:04:39 +020074 """Forward only RX and TX data to output."""
Chris Liechti9dcb4232015-08-20 01:15:37 +020075
Chris Liechti730e9f22015-08-19 03:07:05 +020076 def __init__(self, output, color):
77 self.output = output
78 self.color = color
79 self.rx_color = '\x1b[32m'
80 self.tx_color = '\x1b[31m'
81
82 def rx(self, data):
Chris Liechti9eaa40c2016-02-12 23:32:59 +010083 """show received data"""
Chris Liechti730e9f22015-08-19 03:07:05 +020084 if self.color:
85 self.output.write(self.rx_color)
86 self.output.write(data)
87 self.output.flush()
88
89 def tx(self, data):
Chris Liechti9eaa40c2016-02-12 23:32:59 +010090 """show transmitted data"""
Chris Liechti730e9f22015-08-19 03:07:05 +020091 if self.color:
92 self.output.write(self.tx_color)
93 self.output.write(data)
94 self.output.flush()
95
96 def control(self, name, value):
Chris Liechti9eaa40c2016-02-12 23:32:59 +010097 """(do not) show control calls"""
Chris Liechti730e9f22015-08-19 03:07:05 +020098 pass
99
100
101class FormatHexdump(object):
Chris Liechti9dcb4232015-08-20 01:15:37 +0200102 """\
103 Create a hex dump of RX ad TX data, show when control lines are read or
104 written.
105
106 output example::
107
Chris Liechti335242b2015-08-23 01:04:39 +0200108 000000.000 Q-RX flushInput
Chris Liechti9dcb4232015-08-20 01:15:37 +0200109 000002.469 RTS inactive
110 000002.773 RTS active
Chris Liechti12a439f2015-08-20 23:01:53 +0200111 000003.001 TX 48 45 4C 4C 4F HELLO
112 000003.102 RX 48 45 4C 4C 4F HELLO
113
Chris Liechti9dcb4232015-08-20 01:15:37 +0200114 """
115
Chris Liechti730e9f22015-08-19 03:07:05 +0200116 def __init__(self, output, color):
117 self.start_time = time.time()
118 self.output = output
119 self.color = color
120 self.rx_color = '\x1b[32m'
121 self.tx_color = '\x1b[31m'
122 self.control_color = '\x1b[37m'
123
Chris Liechti4e8896b2015-08-20 23:44:52 +0200124 def write_line(self, timestamp, label, value, value2=''):
125 self.output.write('{:010.3f} {:4} {}{}\n'.format(timestamp, label, value, value2))
Chris Liechti730e9f22015-08-19 03:07:05 +0200126 self.output.flush()
127
128 def rx(self, data):
Chris Liechti9eaa40c2016-02-12 23:32:59 +0100129 """show received data as hex dump"""
Chris Liechti730e9f22015-08-19 03:07:05 +0200130 if self.color:
131 self.output.write(self.rx_color)
Chris Liechti686117d2015-08-22 00:19:08 +0200132 if data:
133 for offset, row in hexdump(data):
134 self.write_line(time.time() - self.start_time, 'RX', '{:04X} '.format(offset), row)
135 else:
136 self.write_line(time.time() - self.start_time, 'RX', '<empty>')
Chris Liechti730e9f22015-08-19 03:07:05 +0200137
138 def tx(self, data):
Chris Liechti9eaa40c2016-02-12 23:32:59 +0100139 """show transmitted data as hex dump"""
Chris Liechti730e9f22015-08-19 03:07:05 +0200140 if self.color:
141 self.output.write(self.tx_color)
Chris Liechti4e8896b2015-08-20 23:44:52 +0200142 for offset, row in hexdump(data):
143 self.write_line(time.time() - self.start_time, 'TX', '{:04X} '.format(offset), row)
Chris Liechti730e9f22015-08-19 03:07:05 +0200144
145 def control(self, name, value):
Chris Liechti9eaa40c2016-02-12 23:32:59 +0100146 """show control calls"""
Chris Liechti730e9f22015-08-19 03:07:05 +0200147 if self.color:
148 self.output.write(self.control_color)
149 self.write_line(time.time() - self.start_time, name, value)
150
151
Chris Liechtiece60cf2015-08-18 02:39:03 +0200152class Serial(serial.Serial):
153 """Just inherit the native Serial port implementation and patch the port property."""
Chris Liechti409e10b2016-02-10 22:40:34 +0100154 # pylint: disable=no-member
Chris Liechtiece60cf2015-08-18 02:39:03 +0200155
156 def __init__(self, *args, **kwargs):
157 super(Serial, self).__init__(*args, **kwargs)
Chris Liechti730e9f22015-08-19 03:07:05 +0200158 self.formatter = None
Chris Liechti686117d2015-08-22 00:19:08 +0200159 self.show_all = False
Chris Liechtiece60cf2015-08-18 02:39:03 +0200160
161 @serial.Serial.port.setter
162 def port(self, value):
163 if value is not None:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200164 serial.Serial.port.__set__(self, self.from_url(value))
Chris Liechtiece60cf2015-08-18 02:39:03 +0200165
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200166 def from_url(self, url):
Chris Liechtiece60cf2015-08-18 02:39:03 +0200167 """extract host and port from an URL string"""
Chris Liechtiece60cf2015-08-18 02:39:03 +0200168 parts = urlparse.urlsplit(url)
Chris Liechti6c8887c2015-08-18 23:38:05 +0200169 if parts.scheme != 'spy':
Chris Liechti92df95a2016-02-09 23:30:37 +0100170 raise serial.SerialException(
171 'expected a string in the form '
172 '"spy://port[?option[=value][&option[=value]]]": '
173 'not starting with spy:// (%r)' % (parts.scheme,))
Chris Liechtiece60cf2015-08-18 02:39:03 +0200174 # process options now, directly altering self
Chris Liechti730e9f22015-08-19 03:07:05 +0200175 formatter = FormatHexdump
176 color = False
177 output = sys.stderr
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200178 try:
179 for option, values in urlparse.parse_qs(parts.query, True).items():
Chris Liechti876801a2015-08-21 23:15:45 +0200180 if option == 'file':
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200181 output = open(values[0], 'w')
182 elif option == 'color':
183 color = True
184 elif option == 'raw':
185 formatter = FormatRaw
Chris Liechti686117d2015-08-22 00:19:08 +0200186 elif option == 'all':
187 self.show_all = True
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200188 else:
189 raise ValueError('unknown option: %r' % (option,))
190 except ValueError as e:
Chris Liechti92df95a2016-02-09 23:30:37 +0100191 raise serial.SerialException(
192 'expected a string in the form '
193 '"spy://port[?option[=value][&option[=value]]]": %s' % e)
Chris Liechti730e9f22015-08-19 03:07:05 +0200194 self.formatter = formatter(output, color)
Chris Liechtiece60cf2015-08-18 02:39:03 +0200195 return ''.join([parts.netloc, parts.path])
196
197 def write(self, tx):
Chris Liechti730e9f22015-08-19 03:07:05 +0200198 self.formatter.tx(tx)
Chris Liechtiece60cf2015-08-18 02:39:03 +0200199 return super(Serial, self).write(tx)
200
201 def read(self, size=1):
202 rx = super(Serial, self).read(size)
Chris Liechti686117d2015-08-22 00:19:08 +0200203 if rx or self.show_all:
Chris Liechti730e9f22015-08-19 03:07:05 +0200204 self.formatter.rx(rx)
Chris Liechtiece60cf2015-08-18 02:39:03 +0200205 return rx
206
Chris Liechtief1fe252015-08-27 23:25:21 +0200207 @property
208 def in_waiting(self):
209 n = super(Serial, self).in_waiting
Chris Liechti686117d2015-08-22 00:19:08 +0200210 if self.show_all:
Chris Liechtief1fe252015-08-27 23:25:21 +0200211 self.formatter.control('Q-RX', 'in_waiting -> {}'.format(n))
Chris Liechti686117d2015-08-22 00:19:08 +0200212 return n
213
Chris Liechti730e9f22015-08-19 03:07:05 +0200214 def flush(self):
Chris Liechti335242b2015-08-23 01:04:39 +0200215 self.formatter.control('Q-TX', 'flush')
Chris Liechti730e9f22015-08-19 03:07:05 +0200216 super(Serial, self).flush()
217
Chris Liechtief1fe252015-08-27 23:25:21 +0200218 def reset_input_buffer(self):
219 self.formatter.control('Q-RX', 'reset_input_buffer')
220 super(Serial, self).reset_input_buffer()
Chris Liechti730e9f22015-08-19 03:07:05 +0200221
Chris Liechtief1fe252015-08-27 23:25:21 +0200222 def reset_output_buffer(self):
223 self.formatter.control('Q-TX', 'reset_output_buffer')
224 super(Serial, self).reset_output_buffer()
Chris Liechti730e9f22015-08-19 03:07:05 +0200225
Chris Liechtief1fe252015-08-27 23:25:21 +0200226 def send_break(self, duration=0.25):
227 self.formatter.control('BRK', 'send_break {}s'.format(duration))
228 super(Serial, self).send_break(duration)
Chris Liechti730e9f22015-08-19 03:07:05 +0200229
Chris Liechtief1fe252015-08-27 23:25:21 +0200230 @serial.Serial.break_condition.setter
231 def break_condition(self, level):
Chris Liechti730e9f22015-08-19 03:07:05 +0200232 self.formatter.control('BRK', 'active' if level else 'inactive')
Chris Liechtief1fe252015-08-27 23:25:21 +0200233 serial.Serial.break_condition.__set__(self, level)
Chris Liechti730e9f22015-08-19 03:07:05 +0200234
Chris Liechtief1fe252015-08-27 23:25:21 +0200235 @serial.Serial.rts.setter
236 def rts(self, level):
Chris Liechti730e9f22015-08-19 03:07:05 +0200237 self.formatter.control('RTS', 'active' if level else 'inactive')
Chris Liechtief1fe252015-08-27 23:25:21 +0200238 serial.Serial.rts.__set__(self, level)
Chris Liechti730e9f22015-08-19 03:07:05 +0200239
Chris Liechtief1fe252015-08-27 23:25:21 +0200240 @serial.Serial.dtr.setter
241 def dtr(self, level):
Chris Liechti730e9f22015-08-19 03:07:05 +0200242 self.formatter.control('DTR', 'active' if level else 'inactive')
Chris Liechtief1fe252015-08-27 23:25:21 +0200243 serial.Serial.dtr.__set__(self, level)
Chris Liechti730e9f22015-08-19 03:07:05 +0200244
Chris Liechtief1fe252015-08-27 23:25:21 +0200245 @serial.Serial.cts.getter
246 def cts(self):
247 level = super(Serial, self).cts
Chris Liechti730e9f22015-08-19 03:07:05 +0200248 self.formatter.control('CTS', 'active' if level else 'inactive')
249 return level
250
Chris Liechtief1fe252015-08-27 23:25:21 +0200251 @serial.Serial.dsr.getter
252 def dsr(self):
253 level = super(Serial, self).dsr
Chris Liechti730e9f22015-08-19 03:07:05 +0200254 self.formatter.control('DSR', 'active' if level else 'inactive')
255 return level
256
Chris Liechtief1fe252015-08-27 23:25:21 +0200257 @serial.Serial.ri.getter
258 def ri(self):
259 level = super(Serial, self).ri
Chris Liechti730e9f22015-08-19 03:07:05 +0200260 self.formatter.control('RI', 'active' if level else 'inactive')
261 return level
262
Chris Liechtief1fe252015-08-27 23:25:21 +0200263 @serial.Serial.cd.getter
264 def cd(self):
265 level = super(Serial, self).cd
Chris Liechti12a439f2015-08-20 23:01:53 +0200266 self.formatter.control('CD', 'active' if level else 'inactive')
Chris Liechti730e9f22015-08-19 03:07:05 +0200267 return level
268
Chris Liechtiece60cf2015-08-18 02:39:03 +0200269# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
270if __name__ == '__main__':
Chris Liechti9eaa40c2016-02-12 23:32:59 +0100271 ser = Serial(None)
272 ser.port = 'spy:///dev/ttyS0'
273 print(ser)