blob: 55e376550c2e279af4a64605dba941a2cd9c3be4 [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 Liechti9e3b4f32021-05-23 00:02:32 +020025import logging
Chris Liechtiece60cf2015-08-18 02:39:03 +020026import sys
Chris Liechti730e9f22015-08-19 03:07:05 +020027import time
28
Chris Liechtiece60cf2015-08-18 02:39:03 +020029import serial
Chris Liechtibc88b922020-11-23 04:52:03 +010030from serial.serialutil import to_bytes
Chris Liechtiece60cf2015-08-18 02:39:03 +020031
32try:
33 import urlparse
34except ImportError:
35 import urllib.parse as urlparse
Chris Liechtiece60cf2015-08-18 02:39:03 +020036
Chris Liechti730e9f22015-08-19 03:07:05 +020037
38def sixteen(data):
Chris Liechti9dcb4232015-08-20 01:15:37 +020039 """\
40 yield tuples of hex and ASCII display in multiples of 16. Includes a
41 space after 8 bytes and (None, None) after 16 bytes and at the end.
42 """
Chris Liechti730e9f22015-08-19 03:07:05 +020043 n = 0
44 for b in serial.iterbytes(data):
Chris Liechti165388c2015-08-22 00:24:08 +020045 yield ('{:02X} '.format(ord(b)), b.decode('ascii') if b' ' <= b < b'\x7f' else '.')
Chris Liechti730e9f22015-08-19 03:07:05 +020046 n += 1
47 if n == 8:
Chris Liechti335242b2015-08-23 01:04:39 +020048 yield (' ', '')
Chris Liechti12a439f2015-08-20 23:01:53 +020049 elif n >= 16:
Chris Liechti9dcb4232015-08-20 01:15:37 +020050 yield (None, None)
Chris Liechti730e9f22015-08-19 03:07:05 +020051 n = 0
Chris Liechti12a439f2015-08-20 23:01:53 +020052 if n > 0:
53 while n < 16:
54 n += 1
55 if n == 8:
Chris Liechti335242b2015-08-23 01:04:39 +020056 yield (' ', '')
Chris Liechti12a439f2015-08-20 23:01:53 +020057 yield (' ', ' ')
58 yield (None, None)
Chris Liechti730e9f22015-08-19 03:07:05 +020059
60
61def hexdump(data):
Chris Liechti9dcb4232015-08-20 01:15:37 +020062 """yield lines with hexdump of data"""
Chris Liechti730e9f22015-08-19 03:07:05 +020063 values = []
64 ascii = []
Chris Liechti4e8896b2015-08-20 23:44:52 +020065 offset = 0
Chris Liechti730e9f22015-08-19 03:07:05 +020066 for h, a in sixteen(data):
67 if h is None:
Chris Liechti92df95a2016-02-09 23:30:37 +010068 yield (offset, ' '.join([''.join(values), ''.join(ascii)]))
Chris Liechti730e9f22015-08-19 03:07:05 +020069 del values[:]
70 del ascii[:]
Chris Liechti4e8896b2015-08-20 23:44:52 +020071 offset += 0x10
Chris Liechti730e9f22015-08-19 03:07:05 +020072 else:
73 values.append(h)
74 ascii.append(a)
75
76
Chris Liechti730e9f22015-08-19 03:07:05 +020077class FormatRaw(object):
Chris Liechti335242b2015-08-23 01:04:39 +020078 """Forward only RX and TX data to output."""
Chris Liechti9dcb4232015-08-20 01:15:37 +020079
Chris Liechti730e9f22015-08-19 03:07:05 +020080 def __init__(self, output, color):
81 self.output = output
82 self.color = color
83 self.rx_color = '\x1b[32m'
84 self.tx_color = '\x1b[31m'
85
86 def rx(self, data):
Chris Liechti9eaa40c2016-02-12 23:32:59 +010087 """show received data"""
Chris Liechti730e9f22015-08-19 03:07:05 +020088 if self.color:
89 self.output.write(self.rx_color)
90 self.output.write(data)
91 self.output.flush()
92
93 def tx(self, data):
Chris Liechti9eaa40c2016-02-12 23:32:59 +010094 """show transmitted data"""
Chris Liechti730e9f22015-08-19 03:07:05 +020095 if self.color:
96 self.output.write(self.tx_color)
97 self.output.write(data)
98 self.output.flush()
99
100 def control(self, name, value):
Chris Liechti9eaa40c2016-02-12 23:32:59 +0100101 """(do not) show control calls"""
Chris Liechti730e9f22015-08-19 03:07:05 +0200102 pass
103
104
105class FormatHexdump(object):
Chris Liechti9dcb4232015-08-20 01:15:37 +0200106 """\
107 Create a hex dump of RX ad TX data, show when control lines are read or
108 written.
109
110 output example::
111
Chris Liechti335242b2015-08-23 01:04:39 +0200112 000000.000 Q-RX flushInput
Chris Liechti9dcb4232015-08-20 01:15:37 +0200113 000002.469 RTS inactive
114 000002.773 RTS active
Chris Liechti12a439f2015-08-20 23:01:53 +0200115 000003.001 TX 48 45 4C 4C 4F HELLO
116 000003.102 RX 48 45 4C 4C 4F HELLO
117
Chris Liechti9dcb4232015-08-20 01:15:37 +0200118 """
119
Chris Liechti730e9f22015-08-19 03:07:05 +0200120 def __init__(self, output, color):
121 self.start_time = time.time()
122 self.output = output
123 self.color = color
124 self.rx_color = '\x1b[32m'
125 self.tx_color = '\x1b[31m'
126 self.control_color = '\x1b[37m'
127
Chris Liechti4e8896b2015-08-20 23:44:52 +0200128 def write_line(self, timestamp, label, value, value2=''):
129 self.output.write('{:010.3f} {:4} {}{}\n'.format(timestamp, label, value, value2))
Chris Liechti730e9f22015-08-19 03:07:05 +0200130 self.output.flush()
131
132 def rx(self, data):
Chris Liechti9eaa40c2016-02-12 23:32:59 +0100133 """show received data as hex dump"""
Chris Liechti730e9f22015-08-19 03:07:05 +0200134 if self.color:
135 self.output.write(self.rx_color)
Chris Liechti686117d2015-08-22 00:19:08 +0200136 if data:
137 for offset, row in hexdump(data):
138 self.write_line(time.time() - self.start_time, 'RX', '{:04X} '.format(offset), row)
139 else:
140 self.write_line(time.time() - self.start_time, 'RX', '<empty>')
Chris Liechti730e9f22015-08-19 03:07:05 +0200141
142 def tx(self, data):
Chris Liechti9eaa40c2016-02-12 23:32:59 +0100143 """show transmitted data as hex dump"""
Chris Liechti730e9f22015-08-19 03:07:05 +0200144 if self.color:
145 self.output.write(self.tx_color)
Chris Liechti4e8896b2015-08-20 23:44:52 +0200146 for offset, row in hexdump(data):
147 self.write_line(time.time() - self.start_time, 'TX', '{:04X} '.format(offset), row)
Chris Liechti730e9f22015-08-19 03:07:05 +0200148
149 def control(self, name, value):
Chris Liechti9eaa40c2016-02-12 23:32:59 +0100150 """show control calls"""
Chris Liechti730e9f22015-08-19 03:07:05 +0200151 if self.color:
152 self.output.write(self.control_color)
153 self.write_line(time.time() - self.start_time, name, value)
154
155
Chris Liechti9e3b4f32021-05-23 00:02:32 +0200156class FormatLog(object):
157 """\
158 Write data to logging module.
159 """
160
161 def __init__(self, output, color):
162 # output and color is ignored
163 self.log = logging.getLogger(output)
164
165 def rx(self, data):
166 """show received data"""
167 if data:
168 self.log.info('RX {!r}'.format(data))
169
170 def tx(self, data):
171 """show transmitted data"""
172 self.log.info('TX {!r}'.format(data))
173
174 def control(self, name, value):
175 """show control calls"""
176 self.log.info('{}: {}'.format(name, value))
177
178
179class FormatLogHex(FormatLog):
180 """\
181 Write data to logging module.
182 """
183
184 def rx(self, data):
185 """show received data"""
186 if data:
187 for offset, row in hexdump(data):
188 self.log.info('RX {}{}'.format('{:04X} '.format(offset), row))
189
190 def tx(self, data):
191 """show transmitted data"""
192 for offset, row in hexdump(data):
193 self.log.info('TX {}{}'.format('{:04X} '.format(offset), row))
194
195
Chris Liechtiece60cf2015-08-18 02:39:03 +0200196class Serial(serial.Serial):
Chris Liechtida73e892016-05-20 00:11:02 +0200197 """\
198 Inherit the native Serial port implementation and wrap all the methods and
199 attributes.
200 """
Chris Liechti409e10b2016-02-10 22:40:34 +0100201 # pylint: disable=no-member
Chris Liechtiece60cf2015-08-18 02:39:03 +0200202
203 def __init__(self, *args, **kwargs):
204 super(Serial, self).__init__(*args, **kwargs)
Chris Liechti730e9f22015-08-19 03:07:05 +0200205 self.formatter = None
Chris Liechti686117d2015-08-22 00:19:08 +0200206 self.show_all = False
Chris Liechtiece60cf2015-08-18 02:39:03 +0200207
208 @serial.Serial.port.setter
209 def port(self, value):
210 if value is not None:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200211 serial.Serial.port.__set__(self, self.from_url(value))
Chris Liechtiece60cf2015-08-18 02:39:03 +0200212
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200213 def from_url(self, url):
Chris Liechtiece60cf2015-08-18 02:39:03 +0200214 """extract host and port from an URL string"""
Chris Liechtiece60cf2015-08-18 02:39:03 +0200215 parts = urlparse.urlsplit(url)
Chris Liechti6c8887c2015-08-18 23:38:05 +0200216 if parts.scheme != 'spy':
Chris Liechti92df95a2016-02-09 23:30:37 +0100217 raise serial.SerialException(
218 'expected a string in the form '
219 '"spy://port[?option[=value][&option[=value]]]": '
Chris Liechtic8f3f822016-06-08 03:35:28 +0200220 'not starting with spy:// ({!r})'.format(parts.scheme))
Chris Liechtiece60cf2015-08-18 02:39:03 +0200221 # process options now, directly altering self
Chris Liechti730e9f22015-08-19 03:07:05 +0200222 formatter = FormatHexdump
223 color = False
224 output = sys.stderr
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200225 try:
226 for option, values in urlparse.parse_qs(parts.query, True).items():
Chris Liechti876801a2015-08-21 23:15:45 +0200227 if option == 'file':
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200228 output = open(values[0], 'w')
229 elif option == 'color':
230 color = True
231 elif option == 'raw':
232 formatter = FormatRaw
Chris Liechti9e3b4f32021-05-23 00:02:32 +0200233 elif option == 'rawlog':
234 formatter = FormatLog
235 output = values[0] if values[0] else 'serial'
236 elif option == 'log':
237 formatter = FormatLogHex
238 output = values[0] if values[0] else 'serial'
Chris Liechti686117d2015-08-22 00:19:08 +0200239 elif option == 'all':
240 self.show_all = True
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200241 else:
Chris Liechtic8f3f822016-06-08 03:35:28 +0200242 raise ValueError('unknown option: {!r}'.format(option))
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200243 except ValueError as e:
Chris Liechti92df95a2016-02-09 23:30:37 +0100244 raise serial.SerialException(
245 'expected a string in the form '
Chris Liechtic8f3f822016-06-08 03:35:28 +0200246 '"spy://port[?option[=value][&option[=value]]]": {}'.format(e))
Chris Liechti730e9f22015-08-19 03:07:05 +0200247 self.formatter = formatter(output, color)
Chris Liechtiece60cf2015-08-18 02:39:03 +0200248 return ''.join([parts.netloc, parts.path])
249
250 def write(self, tx):
Chris Liechtibc88b922020-11-23 04:52:03 +0100251 tx = to_bytes(tx)
Chris Liechti730e9f22015-08-19 03:07:05 +0200252 self.formatter.tx(tx)
Chris Liechtiece60cf2015-08-18 02:39:03 +0200253 return super(Serial, self).write(tx)
254
255 def read(self, size=1):
256 rx = super(Serial, self).read(size)
Chris Liechti686117d2015-08-22 00:19:08 +0200257 if rx or self.show_all:
Chris Liechti730e9f22015-08-19 03:07:05 +0200258 self.formatter.rx(rx)
Chris Liechtiece60cf2015-08-18 02:39:03 +0200259 return rx
260
Chris Liechtida73e892016-05-20 00:11:02 +0200261 if hasattr(serial.Serial, 'cancel_read'):
262 def cancel_read(self):
263 self.formatter.control('Q-RX', 'cancel_read')
264 super(Serial, self).cancel_read()
265
266 if hasattr(serial.Serial, 'cancel_write'):
267 def cancel_write(self):
268 self.formatter.control('Q-TX', 'cancel_write')
269 super(Serial, self).cancel_write()
270
Chris Liechtief1fe252015-08-27 23:25:21 +0200271 @property
272 def in_waiting(self):
273 n = super(Serial, self).in_waiting
Chris Liechti686117d2015-08-22 00:19:08 +0200274 if self.show_all:
Chris Liechtief1fe252015-08-27 23:25:21 +0200275 self.formatter.control('Q-RX', 'in_waiting -> {}'.format(n))
Chris Liechti686117d2015-08-22 00:19:08 +0200276 return n
277
Chris Liechti730e9f22015-08-19 03:07:05 +0200278 def flush(self):
Chris Liechti335242b2015-08-23 01:04:39 +0200279 self.formatter.control('Q-TX', 'flush')
Chris Liechti730e9f22015-08-19 03:07:05 +0200280 super(Serial, self).flush()
281
Chris Liechtief1fe252015-08-27 23:25:21 +0200282 def reset_input_buffer(self):
283 self.formatter.control('Q-RX', 'reset_input_buffer')
284 super(Serial, self).reset_input_buffer()
Chris Liechti730e9f22015-08-19 03:07:05 +0200285
Chris Liechtief1fe252015-08-27 23:25:21 +0200286 def reset_output_buffer(self):
287 self.formatter.control('Q-TX', 'reset_output_buffer')
288 super(Serial, self).reset_output_buffer()
Chris Liechti730e9f22015-08-19 03:07:05 +0200289
Chris Liechtief1fe252015-08-27 23:25:21 +0200290 def send_break(self, duration=0.25):
291 self.formatter.control('BRK', 'send_break {}s'.format(duration))
292 super(Serial, self).send_break(duration)
Chris Liechti730e9f22015-08-19 03:07:05 +0200293
Chris Liechtief1fe252015-08-27 23:25:21 +0200294 @serial.Serial.break_condition.setter
295 def break_condition(self, level):
Chris Liechti730e9f22015-08-19 03:07:05 +0200296 self.formatter.control('BRK', 'active' if level else 'inactive')
Chris Liechtief1fe252015-08-27 23:25:21 +0200297 serial.Serial.break_condition.__set__(self, level)
Chris Liechti730e9f22015-08-19 03:07:05 +0200298
Chris Liechtief1fe252015-08-27 23:25:21 +0200299 @serial.Serial.rts.setter
300 def rts(self, level):
Chris Liechti730e9f22015-08-19 03:07:05 +0200301 self.formatter.control('RTS', 'active' if level else 'inactive')
Chris Liechtief1fe252015-08-27 23:25:21 +0200302 serial.Serial.rts.__set__(self, level)
Chris Liechti730e9f22015-08-19 03:07:05 +0200303
Chris Liechtief1fe252015-08-27 23:25:21 +0200304 @serial.Serial.dtr.setter
305 def dtr(self, level):
Chris Liechti730e9f22015-08-19 03:07:05 +0200306 self.formatter.control('DTR', 'active' if level else 'inactive')
Chris Liechtief1fe252015-08-27 23:25:21 +0200307 serial.Serial.dtr.__set__(self, level)
Chris Liechti730e9f22015-08-19 03:07:05 +0200308
Chris Liechtief1fe252015-08-27 23:25:21 +0200309 @serial.Serial.cts.getter
310 def cts(self):
311 level = super(Serial, self).cts
Chris Liechti730e9f22015-08-19 03:07:05 +0200312 self.formatter.control('CTS', 'active' if level else 'inactive')
313 return level
314
Chris Liechtief1fe252015-08-27 23:25:21 +0200315 @serial.Serial.dsr.getter
316 def dsr(self):
317 level = super(Serial, self).dsr
Chris Liechti730e9f22015-08-19 03:07:05 +0200318 self.formatter.control('DSR', 'active' if level else 'inactive')
319 return level
320
Chris Liechtief1fe252015-08-27 23:25:21 +0200321 @serial.Serial.ri.getter
322 def ri(self):
323 level = super(Serial, self).ri
Chris Liechti730e9f22015-08-19 03:07:05 +0200324 self.formatter.control('RI', 'active' if level else 'inactive')
325 return level
326
Chris Liechtief1fe252015-08-27 23:25:21 +0200327 @serial.Serial.cd.getter
328 def cd(self):
329 level = super(Serial, self).cd
Chris Liechti12a439f2015-08-20 23:01:53 +0200330 self.formatter.control('CD', 'active' if level else 'inactive')
Chris Liechti730e9f22015-08-19 03:07:05 +0200331 return level
332
Chris Liechtiece60cf2015-08-18 02:39:03 +0200333# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
334if __name__ == '__main__':
Chris Liechti9eaa40c2016-02-12 23:32:59 +0100335 ser = Serial(None)
336 ser.port = 'spy:///dev/ttyS0'
337 print(ser)