blob: bc6db506c336c4da5fa18323c0bdcceabcce3d42 [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 = []
63 for h, a in sixteen(data):
64 if h is None:
65 yield ' '.join([
66 ''.join(values),
67 ''.join(ascii)])
68 del values[:]
69 del ascii[:]
70 else:
71 values.append(h)
72 ascii.append(a)
73
74
Chris Liechti730e9f22015-08-19 03:07:05 +020075class FormatRaw(object):
Chris Liechti9dcb4232015-08-20 01:15:37 +020076 """forward rx and tx data to output"""
77
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):
85 if self.color:
86 self.output.write(self.rx_color)
87 self.output.write(data)
88 self.output.flush()
89
90 def tx(self, data):
91 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):
97 pass
98
99
100class FormatHexdump(object):
Chris Liechti9dcb4232015-08-20 01:15:37 +0200101 """\
102 Create a hex dump of RX ad TX data, show when control lines are read or
103 written.
104
105 output example::
106
107 000000.000 FLSH flushInput
108 000002.469 RTS inactive
109 000002.773 RTS active
Chris Liechti12a439f2015-08-20 23:01:53 +0200110 000003.001 TX 48 45 4C 4C 4F HELLO
111 000003.102 RX 48 45 4C 4C 4F HELLO
112
Chris Liechti9dcb4232015-08-20 01:15:37 +0200113 """
114
Chris Liechti730e9f22015-08-19 03:07:05 +0200115 def __init__(self, output, color):
116 self.start_time = time.time()
117 self.output = output
118 self.color = color
119 self.rx_color = '\x1b[32m'
120 self.tx_color = '\x1b[31m'
121 self.control_color = '\x1b[37m'
122
123 def write_line(self, timestamp, label, value):
124 self.output.write('{:010.3f} {:4} {}\n'.format(timestamp, label, value))
125 self.output.flush()
126
127 def rx(self, data):
128 if self.color:
129 self.output.write(self.rx_color)
130 for row in hexdump(data):
131 self.write_line(time.time() - self.start_time, 'RX', row)
132
133 def tx(self, data):
134 if self.color:
135 self.output.write(self.tx_color)
136 for row in hexdump(data):
137 self.write_line(time.time() - self.start_time, 'TX', row)
138
139 def control(self, name, value):
140 if self.color:
141 self.output.write(self.control_color)
142 self.write_line(time.time() - self.start_time, name, value)
143
144
Chris Liechtiece60cf2015-08-18 02:39:03 +0200145class Serial(serial.Serial):
146 """Just inherit the native Serial port implementation and patch the port property."""
147
148 def __init__(self, *args, **kwargs):
149 super(Serial, self).__init__(*args, **kwargs)
Chris Liechti730e9f22015-08-19 03:07:05 +0200150 self.formatter = None
Chris Liechtiece60cf2015-08-18 02:39:03 +0200151
152 @serial.Serial.port.setter
153 def port(self, value):
154 if value is not None:
155 serial.Serial.port.__set__(self, self.fromURL(value))
156
157 def fromURL(self, url):
158 """extract host and port from an URL string"""
Chris Liechtiece60cf2015-08-18 02:39:03 +0200159 parts = urlparse.urlsplit(url)
Chris Liechti6c8887c2015-08-18 23:38:05 +0200160 if parts.scheme != 'spy':
Chris Liechtiece60cf2015-08-18 02:39:03 +0200161 raise serial.SerialException('expected a string in the form "spy://port[?option[=value][&option[=value]]]": not starting with spy:// (%r)' % (parts.scheme,))
162 # process options now, directly altering self
Chris Liechti730e9f22015-08-19 03:07:05 +0200163 formatter = FormatHexdump
164 color = False
165 output = sys.stderr
Chris Liechtiece60cf2015-08-18 02:39:03 +0200166 for option, values in urlparse.parse_qs(parts.query, True).items():
167 if option == 'dev':
Chris Liechti730e9f22015-08-19 03:07:05 +0200168 output = open(values[0], 'w')
Chris Liechtiece60cf2015-08-18 02:39:03 +0200169 elif option == 'color':
Chris Liechti730e9f22015-08-19 03:07:05 +0200170 color = True
171 elif option == 'raw':
172 formatter = FormatRaw
173 self.formatter = formatter(output, color)
Chris Liechtiece60cf2015-08-18 02:39:03 +0200174 return ''.join([parts.netloc, parts.path])
175
176 def write(self, tx):
Chris Liechti730e9f22015-08-19 03:07:05 +0200177 self.formatter.tx(tx)
Chris Liechtiece60cf2015-08-18 02:39:03 +0200178 return super(Serial, self).write(tx)
179
180 def read(self, size=1):
181 rx = super(Serial, self).read(size)
182 if rx:
Chris Liechti730e9f22015-08-19 03:07:05 +0200183 self.formatter.rx(rx)
Chris Liechtiece60cf2015-08-18 02:39:03 +0200184 return rx
185
186
Chris Liechti730e9f22015-08-19 03:07:05 +0200187 def flush(self):
188 self.formatter.control('FLSH', 'flush')
189 super(Serial, self).flush()
190
191 def flushInput(self):
192 self.formatter.control('FLSH', 'flushInput')
Chris Liechti12a439f2015-08-20 23:01:53 +0200193 super(Serial, self).flushInput()
Chris Liechti730e9f22015-08-19 03:07:05 +0200194
195 def flushOutput(self):
196 self.formatter.control('FLSH', 'flushOutput')
197 super(Serial, self).flushOutput()
198
199 def sendBreak(self, duration=0.25):
Chris Liechti9dcb4232015-08-20 01:15:37 +0200200 self.formatter.control('BRK', 'sendBreak {}'.format(duration))
Chris Liechti730e9f22015-08-19 03:07:05 +0200201 super(Serial, self).sendBreak(duration)
202
203 def setBreak(self, level=1):
204 self.formatter.control('BRK', 'active' if level else 'inactive')
205 super(Serial, self).setBreak(level)
206
207 def setRTS(self, level=1):
208 self.formatter.control('RTS', 'active' if level else 'inactive')
209 super(Serial, self).setRTS(level)
210
211 def setDTR(self, level=1):
212 self.formatter.control('DTR', 'active' if level else 'inactive')
213 super(Serial, self).setDTR(level)
214
215 def getCTS(self):
216 level = super(Serial, self).getCTS()
217 self.formatter.control('CTS', 'active' if level else 'inactive')
218 return level
219
220 def getDSR(self):
221 level = super(Serial, self).getDSR()
222 self.formatter.control('DSR', 'active' if level else 'inactive')
223 return level
224
225 def getRI(self):
226 level = super(Serial, self).getRI()
227 self.formatter.control('RI', 'active' if level else 'inactive')
228 return level
229
230 def getCD(self):
Chris Liechti730e9f22015-08-19 03:07:05 +0200231 level = super(Serial, self).getCD()
Chris Liechti12a439f2015-08-20 23:01:53 +0200232 self.formatter.control('CD', 'active' if level else 'inactive')
Chris Liechti730e9f22015-08-19 03:07:05 +0200233 return level
234
Chris Liechtiece60cf2015-08-18 02:39:03 +0200235# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
236if __name__ == '__main__':
237 s = Serial(None)
238 s.port = 'spy:///dev/ttyS0'
239 print(s)
240