blob: 92aaa2eb08faf020f5d6807deeef9e4ecdfa6e31 [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
Kurt McKee057387c2018-02-07 22:10:38 -060023from __future__ import absolute_import
24
Chris Liechtiece60cf2015-08-18 02:39:03 +020025import 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):
Chris Liechti165388c2015-08-22 00:24:08 +020043 yield ('{:02X} '.format(ord(b)), b.decode('ascii') if b' ' <= b < b'\x7f' else '.')
Chris Liechti730e9f22015-08-19 03:07:05 +020044 n += 1
45 if n == 8:
Chris Liechti335242b2015-08-23 01:04:39 +020046 yield (' ', '')
Chris Liechti12a439f2015-08-20 23:01:53 +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
Chris Liechti12a439f2015-08-20 23:01:53 +020050 if n > 0:
51 while n < 16:
52 n += 1
53 if n == 8:
Chris Liechti335242b2015-08-23 01:04:39 +020054 yield (' ', '')
Chris Liechti12a439f2015-08-20 23:01:53 +020055 yield (' ', ' ')
56 yield (None, None)
Chris Liechti730e9f22015-08-19 03:07:05 +020057
58
59def hexdump(data):
Chris Liechti9dcb4232015-08-20 01:15:37 +020060 """yield lines with hexdump of data"""
Chris Liechti730e9f22015-08-19 03:07:05 +020061 values = []
62 ascii = []
Chris Liechti4e8896b2015-08-20 23:44:52 +020063 offset = 0
Chris Liechti730e9f22015-08-19 03:07:05 +020064 for h, a in sixteen(data):
65 if h is None:
Chris Liechti92df95a2016-02-09 23:30:37 +010066 yield (offset, ' '.join([''.join(values), ''.join(ascii)]))
Chris Liechti730e9f22015-08-19 03:07:05 +020067 del values[:]
68 del ascii[:]
Chris Liechti4e8896b2015-08-20 23:44:52 +020069 offset += 0x10
Chris Liechti730e9f22015-08-19 03:07:05 +020070 else:
71 values.append(h)
72 ascii.append(a)
73
74
Chris Liechti730e9f22015-08-19 03:07:05 +020075class FormatRaw(object):
Chris Liechti335242b2015-08-23 01:04:39 +020076 """Forward only RX and TX data to output."""
Chris Liechti9dcb4232015-08-20 01:15:37 +020077
Chris Liechti730e9f22015-08-19 03:07:05 +020078 def __init__(self, output, color):
79 self.output = output
80 self.color = color
81 self.rx_color = '\x1b[32m'
82 self.tx_color = '\x1b[31m'
83
84 def rx(self, data):
Chris Liechti9eaa40c2016-02-12 23:32:59 +010085 """show received data"""
Chris Liechti730e9f22015-08-19 03:07:05 +020086 if self.color:
87 self.output.write(self.rx_color)
88 self.output.write(data)
89 self.output.flush()
90
91 def tx(self, data):
Chris Liechti9eaa40c2016-02-12 23:32:59 +010092 """show transmitted data"""
Chris Liechti730e9f22015-08-19 03:07:05 +020093 if self.color:
94 self.output.write(self.tx_color)
95 self.output.write(data)
96 self.output.flush()
97
98 def control(self, name, value):
Chris Liechti9eaa40c2016-02-12 23:32:59 +010099 """(do not) show control calls"""
Chris Liechti730e9f22015-08-19 03:07:05 +0200100 pass
101
102
103class FormatHexdump(object):
Chris Liechti9dcb4232015-08-20 01:15:37 +0200104 """\
105 Create a hex dump of RX ad TX data, show when control lines are read or
106 written.
107
108 output example::
109
Chris Liechti335242b2015-08-23 01:04:39 +0200110 000000.000 Q-RX flushInput
Chris Liechti9dcb4232015-08-20 01:15:37 +0200111 000002.469 RTS inactive
112 000002.773 RTS active
Chris Liechti12a439f2015-08-20 23:01:53 +0200113 000003.001 TX 48 45 4C 4C 4F HELLO
114 000003.102 RX 48 45 4C 4C 4F HELLO
115
Chris Liechti9dcb4232015-08-20 01:15:37 +0200116 """
117
Chris Liechti730e9f22015-08-19 03:07:05 +0200118 def __init__(self, output, color):
119 self.start_time = time.time()
120 self.output = output
121 self.color = color
122 self.rx_color = '\x1b[32m'
123 self.tx_color = '\x1b[31m'
124 self.control_color = '\x1b[37m'
125
Chris Liechti4e8896b2015-08-20 23:44:52 +0200126 def write_line(self, timestamp, label, value, value2=''):
127 self.output.write('{:010.3f} {:4} {}{}\n'.format(timestamp, label, value, value2))
Chris Liechti730e9f22015-08-19 03:07:05 +0200128 self.output.flush()
129
130 def rx(self, data):
Chris Liechti9eaa40c2016-02-12 23:32:59 +0100131 """show received data as hex dump"""
Chris Liechti730e9f22015-08-19 03:07:05 +0200132 if self.color:
133 self.output.write(self.rx_color)
Chris Liechti686117d2015-08-22 00:19:08 +0200134 if data:
135 for offset, row in hexdump(data):
136 self.write_line(time.time() - self.start_time, 'RX', '{:04X} '.format(offset), row)
137 else:
138 self.write_line(time.time() - self.start_time, 'RX', '<empty>')
Chris Liechti730e9f22015-08-19 03:07:05 +0200139
140 def tx(self, data):
Chris Liechti9eaa40c2016-02-12 23:32:59 +0100141 """show transmitted data as hex dump"""
Chris Liechti730e9f22015-08-19 03:07:05 +0200142 if self.color:
143 self.output.write(self.tx_color)
Chris Liechti4e8896b2015-08-20 23:44:52 +0200144 for offset, row in hexdump(data):
145 self.write_line(time.time() - self.start_time, 'TX', '{:04X} '.format(offset), row)
Chris Liechti730e9f22015-08-19 03:07:05 +0200146
147 def control(self, name, value):
Chris Liechti9eaa40c2016-02-12 23:32:59 +0100148 """show control calls"""
Chris Liechti730e9f22015-08-19 03:07:05 +0200149 if self.color:
150 self.output.write(self.control_color)
151 self.write_line(time.time() - self.start_time, name, value)
152
153
Chris Liechtiece60cf2015-08-18 02:39:03 +0200154class Serial(serial.Serial):
Chris Liechtida73e892016-05-20 00:11:02 +0200155 """\
156 Inherit the native Serial port implementation and wrap all the methods and
157 attributes.
158 """
Chris Liechti409e10b2016-02-10 22:40:34 +0100159 # pylint: disable=no-member
Chris Liechtiece60cf2015-08-18 02:39:03 +0200160
161 def __init__(self, *args, **kwargs):
162 super(Serial, self).__init__(*args, **kwargs)
Chris Liechti730e9f22015-08-19 03:07:05 +0200163 self.formatter = None
Chris Liechti686117d2015-08-22 00:19:08 +0200164 self.show_all = False
Chris Liechtiece60cf2015-08-18 02:39:03 +0200165
166 @serial.Serial.port.setter
167 def port(self, value):
168 if value is not None:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200169 serial.Serial.port.__set__(self, self.from_url(value))
Chris Liechtiece60cf2015-08-18 02:39:03 +0200170
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200171 def from_url(self, url):
Chris Liechtiece60cf2015-08-18 02:39:03 +0200172 """extract host and port from an URL string"""
Chris Liechtiece60cf2015-08-18 02:39:03 +0200173 parts = urlparse.urlsplit(url)
Chris Liechti6c8887c2015-08-18 23:38:05 +0200174 if parts.scheme != 'spy':
Chris Liechti92df95a2016-02-09 23:30:37 +0100175 raise serial.SerialException(
176 'expected a string in the form '
177 '"spy://port[?option[=value][&option[=value]]]": '
Chris Liechtic8f3f822016-06-08 03:35:28 +0200178 'not starting with spy:// ({!r})'.format(parts.scheme))
Chris Liechtiece60cf2015-08-18 02:39:03 +0200179 # process options now, directly altering self
Chris Liechti730e9f22015-08-19 03:07:05 +0200180 formatter = FormatHexdump
181 color = False
182 output = sys.stderr
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200183 try:
184 for option, values in urlparse.parse_qs(parts.query, True).items():
Chris Liechti876801a2015-08-21 23:15:45 +0200185 if option == 'file':
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200186 output = open(values[0], 'w')
187 elif option == 'color':
188 color = True
189 elif option == 'raw':
190 formatter = FormatRaw
Chris Liechti686117d2015-08-22 00:19:08 +0200191 elif option == 'all':
192 self.show_all = True
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200193 else:
Chris Liechtic8f3f822016-06-08 03:35:28 +0200194 raise ValueError('unknown option: {!r}'.format(option))
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200195 except ValueError as e:
Chris Liechti92df95a2016-02-09 23:30:37 +0100196 raise serial.SerialException(
197 'expected a string in the form '
Chris Liechtic8f3f822016-06-08 03:35:28 +0200198 '"spy://port[?option[=value][&option[=value]]]": {}'.format(e))
Chris Liechti730e9f22015-08-19 03:07:05 +0200199 self.formatter = formatter(output, color)
Chris Liechtiece60cf2015-08-18 02:39:03 +0200200 return ''.join([parts.netloc, parts.path])
201
202 def write(self, tx):
Chris Liechti730e9f22015-08-19 03:07:05 +0200203 self.formatter.tx(tx)
Chris Liechtiece60cf2015-08-18 02:39:03 +0200204 return super(Serial, self).write(tx)
205
206 def read(self, size=1):
207 rx = super(Serial, self).read(size)
Chris Liechti686117d2015-08-22 00:19:08 +0200208 if rx or self.show_all:
Chris Liechti730e9f22015-08-19 03:07:05 +0200209 self.formatter.rx(rx)
Chris Liechtiece60cf2015-08-18 02:39:03 +0200210 return rx
211
Chris Liechtida73e892016-05-20 00:11:02 +0200212 if hasattr(serial.Serial, 'cancel_read'):
213 def cancel_read(self):
214 self.formatter.control('Q-RX', 'cancel_read')
215 super(Serial, self).cancel_read()
216
217 if hasattr(serial.Serial, 'cancel_write'):
218 def cancel_write(self):
219 self.formatter.control('Q-TX', 'cancel_write')
220 super(Serial, self).cancel_write()
221
Chris Liechtief1fe252015-08-27 23:25:21 +0200222 @property
223 def in_waiting(self):
224 n = super(Serial, self).in_waiting
Chris Liechti686117d2015-08-22 00:19:08 +0200225 if self.show_all:
Chris Liechtief1fe252015-08-27 23:25:21 +0200226 self.formatter.control('Q-RX', 'in_waiting -> {}'.format(n))
Chris Liechti686117d2015-08-22 00:19:08 +0200227 return n
228
Chris Liechti730e9f22015-08-19 03:07:05 +0200229 def flush(self):
Chris Liechti335242b2015-08-23 01:04:39 +0200230 self.formatter.control('Q-TX', 'flush')
Chris Liechti730e9f22015-08-19 03:07:05 +0200231 super(Serial, self).flush()
232
Chris Liechtief1fe252015-08-27 23:25:21 +0200233 def reset_input_buffer(self):
234 self.formatter.control('Q-RX', 'reset_input_buffer')
235 super(Serial, self).reset_input_buffer()
Chris Liechti730e9f22015-08-19 03:07:05 +0200236
Chris Liechtief1fe252015-08-27 23:25:21 +0200237 def reset_output_buffer(self):
238 self.formatter.control('Q-TX', 'reset_output_buffer')
239 super(Serial, self).reset_output_buffer()
Chris Liechti730e9f22015-08-19 03:07:05 +0200240
Chris Liechtief1fe252015-08-27 23:25:21 +0200241 def send_break(self, duration=0.25):
242 self.formatter.control('BRK', 'send_break {}s'.format(duration))
243 super(Serial, self).send_break(duration)
Chris Liechti730e9f22015-08-19 03:07:05 +0200244
Chris Liechtief1fe252015-08-27 23:25:21 +0200245 @serial.Serial.break_condition.setter
246 def break_condition(self, level):
Chris Liechti730e9f22015-08-19 03:07:05 +0200247 self.formatter.control('BRK', 'active' if level else 'inactive')
Chris Liechtief1fe252015-08-27 23:25:21 +0200248 serial.Serial.break_condition.__set__(self, level)
Chris Liechti730e9f22015-08-19 03:07:05 +0200249
Chris Liechtief1fe252015-08-27 23:25:21 +0200250 @serial.Serial.rts.setter
251 def rts(self, level):
Chris Liechti730e9f22015-08-19 03:07:05 +0200252 self.formatter.control('RTS', 'active' if level else 'inactive')
Chris Liechtief1fe252015-08-27 23:25:21 +0200253 serial.Serial.rts.__set__(self, level)
Chris Liechti730e9f22015-08-19 03:07:05 +0200254
Chris Liechtief1fe252015-08-27 23:25:21 +0200255 @serial.Serial.dtr.setter
256 def dtr(self, level):
Chris Liechti730e9f22015-08-19 03:07:05 +0200257 self.formatter.control('DTR', 'active' if level else 'inactive')
Chris Liechtief1fe252015-08-27 23:25:21 +0200258 serial.Serial.dtr.__set__(self, level)
Chris Liechti730e9f22015-08-19 03:07:05 +0200259
Chris Liechtief1fe252015-08-27 23:25:21 +0200260 @serial.Serial.cts.getter
261 def cts(self):
262 level = super(Serial, self).cts
Chris Liechti730e9f22015-08-19 03:07:05 +0200263 self.formatter.control('CTS', 'active' if level else 'inactive')
264 return level
265
Chris Liechtief1fe252015-08-27 23:25:21 +0200266 @serial.Serial.dsr.getter
267 def dsr(self):
268 level = super(Serial, self).dsr
Chris Liechti730e9f22015-08-19 03:07:05 +0200269 self.formatter.control('DSR', 'active' if level else 'inactive')
270 return level
271
Chris Liechtief1fe252015-08-27 23:25:21 +0200272 @serial.Serial.ri.getter
273 def ri(self):
274 level = super(Serial, self).ri
Chris Liechti730e9f22015-08-19 03:07:05 +0200275 self.formatter.control('RI', 'active' if level else 'inactive')
276 return level
277
Chris Liechtief1fe252015-08-27 23:25:21 +0200278 @serial.Serial.cd.getter
279 def cd(self):
280 level = super(Serial, self).cd
Chris Liechti12a439f2015-08-20 23:01:53 +0200281 self.formatter.control('CD', 'active' if level else 'inactive')
Chris Liechti730e9f22015-08-19 03:07:05 +0200282 return level
283
Chris Liechtiece60cf2015-08-18 02:39:03 +0200284# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
285if __name__ == '__main__':
Chris Liechti9eaa40c2016-02-12 23:32:59 +0100286 ser = Serial(None)
287 ser.port = 'spy:///dev/ttyS0'
288 print(ser)