blob: d6ed458c6c84bc21e6210ddc572af0955352127d [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 Liechti4e8896b2015-08-20 23:44:52 +0200132 for offset, row in hexdump(data):
133 self.write_line(time.time() - self.start_time, 'RX', '{:04X} '.format(offset), row)
Chris Liechti730e9f22015-08-19 03:07:05 +0200134
135 def tx(self, data):
136 if self.color:
137 self.output.write(self.tx_color)
Chris Liechti4e8896b2015-08-20 23:44:52 +0200138 for offset, row in hexdump(data):
139 self.write_line(time.time() - self.start_time, 'TX', '{:04X} '.format(offset), row)
Chris Liechti730e9f22015-08-19 03:07:05 +0200140
141 def control(self, name, value):
142 if self.color:
143 self.output.write(self.control_color)
144 self.write_line(time.time() - self.start_time, name, value)
145
146
Chris Liechtiece60cf2015-08-18 02:39:03 +0200147class Serial(serial.Serial):
148 """Just inherit the native Serial port implementation and patch the port property."""
149
150 def __init__(self, *args, **kwargs):
151 super(Serial, self).__init__(*args, **kwargs)
Chris Liechti730e9f22015-08-19 03:07:05 +0200152 self.formatter = None
Chris Liechtiece60cf2015-08-18 02:39:03 +0200153
154 @serial.Serial.port.setter
155 def port(self, value):
156 if value is not None:
157 serial.Serial.port.__set__(self, self.fromURL(value))
158
159 def fromURL(self, url):
160 """extract host and port from an URL string"""
Chris Liechtiece60cf2015-08-18 02:39:03 +0200161 parts = urlparse.urlsplit(url)
Chris Liechti6c8887c2015-08-18 23:38:05 +0200162 if parts.scheme != 'spy':
Chris Liechtiece60cf2015-08-18 02:39:03 +0200163 raise serial.SerialException('expected a string in the form "spy://port[?option[=value][&option[=value]]]": not starting with spy:// (%r)' % (parts.scheme,))
164 # process options now, directly altering self
Chris Liechti730e9f22015-08-19 03:07:05 +0200165 formatter = FormatHexdump
166 color = False
167 output = sys.stderr
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200168 try:
169 for option, values in urlparse.parse_qs(parts.query, True).items():
170 if option == 'dev':
171 output = open(values[0], 'w')
172 elif option == 'color':
173 color = True
174 elif option == 'raw':
175 formatter = FormatRaw
176 else:
177 raise ValueError('unknown option: %r' % (option,))
178 except ValueError as e:
179 raise SerialException('expected a string in the form "spy://port[?option[=value][&option[=value]]]": %s' % e)
Chris Liechti730e9f22015-08-19 03:07:05 +0200180 self.formatter = formatter(output, color)
Chris Liechtiece60cf2015-08-18 02:39:03 +0200181 return ''.join([parts.netloc, parts.path])
182
183 def write(self, tx):
Chris Liechti730e9f22015-08-19 03:07:05 +0200184 self.formatter.tx(tx)
Chris Liechtiece60cf2015-08-18 02:39:03 +0200185 return super(Serial, self).write(tx)
186
187 def read(self, size=1):
188 rx = super(Serial, self).read(size)
189 if rx:
Chris Liechti730e9f22015-08-19 03:07:05 +0200190 self.formatter.rx(rx)
Chris Liechtiece60cf2015-08-18 02:39:03 +0200191 return rx
192
193
Chris Liechti730e9f22015-08-19 03:07:05 +0200194 def flush(self):
195 self.formatter.control('FLSH', 'flush')
196 super(Serial, self).flush()
197
198 def flushInput(self):
199 self.formatter.control('FLSH', 'flushInput')
Chris Liechti12a439f2015-08-20 23:01:53 +0200200 super(Serial, self).flushInput()
Chris Liechti730e9f22015-08-19 03:07:05 +0200201
202 def flushOutput(self):
203 self.formatter.control('FLSH', 'flushOutput')
204 super(Serial, self).flushOutput()
205
206 def sendBreak(self, duration=0.25):
Chris Liechti9dcb4232015-08-20 01:15:37 +0200207 self.formatter.control('BRK', 'sendBreak {}'.format(duration))
Chris Liechti730e9f22015-08-19 03:07:05 +0200208 super(Serial, self).sendBreak(duration)
209
210 def setBreak(self, level=1):
211 self.formatter.control('BRK', 'active' if level else 'inactive')
212 super(Serial, self).setBreak(level)
213
214 def setRTS(self, level=1):
215 self.formatter.control('RTS', 'active' if level else 'inactive')
216 super(Serial, self).setRTS(level)
217
218 def setDTR(self, level=1):
219 self.formatter.control('DTR', 'active' if level else 'inactive')
220 super(Serial, self).setDTR(level)
221
222 def getCTS(self):
223 level = super(Serial, self).getCTS()
224 self.formatter.control('CTS', 'active' if level else 'inactive')
225 return level
226
227 def getDSR(self):
228 level = super(Serial, self).getDSR()
229 self.formatter.control('DSR', 'active' if level else 'inactive')
230 return level
231
232 def getRI(self):
233 level = super(Serial, self).getRI()
234 self.formatter.control('RI', 'active' if level else 'inactive')
235 return level
236
237 def getCD(self):
Chris Liechti730e9f22015-08-19 03:07:05 +0200238 level = super(Serial, self).getCD()
Chris Liechti12a439f2015-08-20 23:01:53 +0200239 self.formatter.control('CD', 'active' if level else 'inactive')
Chris Liechti730e9f22015-08-19 03:07:05 +0200240 return level
241
Chris Liechtiece60cf2015-08-18 02:39:03 +0200242# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
243if __name__ == '__main__':
244 s = Serial(None)
245 s.port = 'spy:///dev/ttyS0'
246 print(s)
247