blob: dae44a813d6b3f865321ea24f2233434866ec19b [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 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:
54 yield (' ', ' ')
55 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 Liechti4e8896b2015-08-20 23:44:52 +020066 yield (offset, ' '.join([
Chris Liechti730e9f22015-08-19 03:07:05 +020067 ''.join(values),
Chris Liechti4e8896b2015-08-20 23:44:52 +020068 ''.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 Liechti9dcb4232015-08-20 01:15:37 +020078 """forward rx and tx data to output"""
79
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):
87 if self.color:
88 self.output.write(self.rx_color)
89 self.output.write(data)
90 self.output.flush()
91
92 def tx(self, data):
93 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):
99 pass
100
101
102class FormatHexdump(object):
Chris Liechti9dcb4232015-08-20 01:15:37 +0200103 """\
104 Create a hex dump of RX ad TX data, show when control lines are read or
105 written.
106
107 output example::
108
109 000000.000 FLSH flushInput
110 000002.469 RTS inactive
111 000002.773 RTS active
Chris Liechti12a439f2015-08-20 23:01:53 +0200112 000003.001 TX 48 45 4C 4C 4F HELLO
113 000003.102 RX 48 45 4C 4C 4F HELLO
114
Chris Liechti9dcb4232015-08-20 01:15:37 +0200115 """
116
Chris Liechti730e9f22015-08-19 03:07:05 +0200117 def __init__(self, output, color):
118 self.start_time = time.time()
119 self.output = output
120 self.color = color
121 self.rx_color = '\x1b[32m'
122 self.tx_color = '\x1b[31m'
123 self.control_color = '\x1b[37m'
124
Chris Liechti4e8896b2015-08-20 23:44:52 +0200125 def write_line(self, timestamp, label, value, value2=''):
126 self.output.write('{:010.3f} {:4} {}{}\n'.format(timestamp, label, value, value2))
Chris Liechti730e9f22015-08-19 03:07:05 +0200127 self.output.flush()
128
129 def rx(self, data):
130 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):
139 if self.color:
140 self.output.write(self.tx_color)
Chris Liechti4e8896b2015-08-20 23:44:52 +0200141 for offset, row in hexdump(data):
142 self.write_line(time.time() - self.start_time, 'TX', '{:04X} '.format(offset), row)
Chris Liechti730e9f22015-08-19 03:07:05 +0200143
144 def control(self, name, value):
145 if self.color:
146 self.output.write(self.control_color)
147 self.write_line(time.time() - self.start_time, name, value)
148
149
Chris Liechtiece60cf2015-08-18 02:39:03 +0200150class Serial(serial.Serial):
151 """Just inherit the native Serial port implementation and patch the port property."""
152
153 def __init__(self, *args, **kwargs):
154 super(Serial, self).__init__(*args, **kwargs)
Chris Liechti730e9f22015-08-19 03:07:05 +0200155 self.formatter = None
Chris Liechti686117d2015-08-22 00:19:08 +0200156 self.show_all = False
Chris Liechtiece60cf2015-08-18 02:39:03 +0200157
158 @serial.Serial.port.setter
159 def port(self, value):
160 if value is not None:
161 serial.Serial.port.__set__(self, self.fromURL(value))
162
163 def fromURL(self, url):
164 """extract host and port from an URL string"""
Chris Liechtiece60cf2015-08-18 02:39:03 +0200165 parts = urlparse.urlsplit(url)
Chris Liechti6c8887c2015-08-18 23:38:05 +0200166 if parts.scheme != 'spy':
Chris Liechtiece60cf2015-08-18 02:39:03 +0200167 raise serial.SerialException('expected a string in the form "spy://port[?option[=value][&option[=value]]]": not starting with spy:// (%r)' % (parts.scheme,))
168 # process options now, directly altering self
Chris Liechti730e9f22015-08-19 03:07:05 +0200169 formatter = FormatHexdump
170 color = False
171 output = sys.stderr
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200172 try:
173 for option, values in urlparse.parse_qs(parts.query, True).items():
Chris Liechti876801a2015-08-21 23:15:45 +0200174 if option == 'file':
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200175 output = open(values[0], 'w')
176 elif option == 'color':
177 color = True
178 elif option == 'raw':
179 formatter = FormatRaw
Chris Liechti686117d2015-08-22 00:19:08 +0200180 elif option == 'all':
181 self.show_all = True
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200182 else:
183 raise ValueError('unknown option: %r' % (option,))
184 except ValueError as e:
Chris Liechti686117d2015-08-22 00:19:08 +0200185 raise serial.SerialException('expected a string in the form "spy://port[?option[=value][&option[=value]]]": %s' % e)
Chris Liechti730e9f22015-08-19 03:07:05 +0200186 self.formatter = formatter(output, color)
Chris Liechtiece60cf2015-08-18 02:39:03 +0200187 return ''.join([parts.netloc, parts.path])
188
189 def write(self, tx):
Chris Liechti730e9f22015-08-19 03:07:05 +0200190 self.formatter.tx(tx)
Chris Liechtiece60cf2015-08-18 02:39:03 +0200191 return super(Serial, self).write(tx)
192
193 def read(self, size=1):
194 rx = super(Serial, self).read(size)
Chris Liechti686117d2015-08-22 00:19:08 +0200195 if rx or self.show_all:
Chris Liechti730e9f22015-08-19 03:07:05 +0200196 self.formatter.rx(rx)
Chris Liechtiece60cf2015-08-18 02:39:03 +0200197 return rx
198
199
Chris Liechti686117d2015-08-22 00:19:08 +0200200 def inWaiting(self):
201 n = super(Serial, self).inWaiting()
202 if self.show_all:
203 self.formatter.control('QRX', 'inWaiting -> {}'.format(n))
204 return n
205
Chris Liechti730e9f22015-08-19 03:07:05 +0200206 def flush(self):
Chris Liechti686117d2015-08-22 00:19:08 +0200207 self.formatter.control('QTX', 'flush')
Chris Liechti730e9f22015-08-19 03:07:05 +0200208 super(Serial, self).flush()
209
210 def flushInput(self):
Chris Liechti686117d2015-08-22 00:19:08 +0200211 self.formatter.control('QRX', 'flushInput')
Chris Liechti12a439f2015-08-20 23:01:53 +0200212 super(Serial, self).flushInput()
Chris Liechti730e9f22015-08-19 03:07:05 +0200213
214 def flushOutput(self):
Chris Liechti686117d2015-08-22 00:19:08 +0200215 self.formatter.control('QTX', 'flushOutput')
Chris Liechti730e9f22015-08-19 03:07:05 +0200216 super(Serial, self).flushOutput()
217
218 def sendBreak(self, duration=0.25):
Chris Liechti686117d2015-08-22 00:19:08 +0200219 self.formatter.control('BRK', 'sendBreak {}s'.format(duration))
Chris Liechti730e9f22015-08-19 03:07:05 +0200220 super(Serial, self).sendBreak(duration)
221
222 def setBreak(self, level=1):
223 self.formatter.control('BRK', 'active' if level else 'inactive')
224 super(Serial, self).setBreak(level)
225
226 def setRTS(self, level=1):
227 self.formatter.control('RTS', 'active' if level else 'inactive')
228 super(Serial, self).setRTS(level)
229
230 def setDTR(self, level=1):
231 self.formatter.control('DTR', 'active' if level else 'inactive')
232 super(Serial, self).setDTR(level)
233
234 def getCTS(self):
235 level = super(Serial, self).getCTS()
236 self.formatter.control('CTS', 'active' if level else 'inactive')
237 return level
238
239 def getDSR(self):
240 level = super(Serial, self).getDSR()
241 self.formatter.control('DSR', 'active' if level else 'inactive')
242 return level
243
244 def getRI(self):
245 level = super(Serial, self).getRI()
246 self.formatter.control('RI', 'active' if level else 'inactive')
247 return level
248
249 def getCD(self):
Chris Liechti730e9f22015-08-19 03:07:05 +0200250 level = super(Serial, self).getCD()
Chris Liechti12a439f2015-08-20 23:01:53 +0200251 self.formatter.control('CD', 'active' if level else 'inactive')
Chris Liechti730e9f22015-08-19 03:07:05 +0200252 return level
253
Chris Liechtiece60cf2015-08-18 02:39:03 +0200254# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
255if __name__ == '__main__':
256 s = Serial(None)
257 s.port = 'spy:///dev/ttyS0'
258 print(s)
259