blob: 711edaf5922344e6264d389bd0b91f6890a13bf0 [file] [log] [blame]
cliechti576de252002-02-28 23:54:44 +00001#!/usr/bin/env python
Chris Liechtifbdd8a02015-08-09 02:37:45 +02002#
cliechtia128a702004-07-21 22:13:31 +00003# Very simple serial terminal
Chris Liechtifbdd8a02015-08-09 02:37:45 +02004#
Chris Liechti68340d72015-08-03 14:15:48 +02005# (C)2002-2015 Chris Liechti <cliechti@gmx.net>
Chris Liechtifbdd8a02015-08-09 02:37:45 +02006#
7# SPDX-License-Identifier: BSD-3-Clause
cliechtifc9eb382002-03-05 01:12:29 +00008
Chris Liechtic7a5d4c2015-08-11 23:32:20 +02009import codecs
Chris Liechtia1d5c6d2015-08-07 14:41:24 +020010import os
11import sys
12import threading
cliechti576de252002-02-28 23:54:44 +000013
Chris Liechtia1d5c6d2015-08-07 14:41:24 +020014import serial
Chris Liechti55ba7d92015-08-15 16:33:51 +020015from serial.tools.list_ports import comports
Chris Liechtia1d5c6d2015-08-07 14:41:24 +020016
Chris Liechti68340d72015-08-03 14:15:48 +020017try:
18 raw_input
19except NameError:
20 raw_input = input # in python3 it's "raw"
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020021 unichr = chr
Chris Liechti68340d72015-08-03 14:15:48 +020022
Chris Liechtic0c660a2015-08-25 00:55:51 +020023from . import hexlify_codec
24codecs.register(lambda c: hexlify_codec.getregentry() if c == 'hexlify' else None)
25
cliechti6c8eb2f2009-07-08 02:10:46 +000026
27def key_description(character):
28 """generate a readable description for a key"""
29 ascii_code = ord(character)
30 if ascii_code < 32:
31 return 'Ctrl+%c' % (ord('@') + ascii_code)
32 else:
33 return repr(character)
34
cliechti91165532011-03-18 02:02:52 +000035
Chris Liechti9a720852015-08-25 00:20:38 +020036# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020037class ConsoleBase(object):
38 def __init__(self):
39 if sys.version_info >= (3, 0):
40 self.byte_output = sys.stdout.buffer
41 else:
42 self.byte_output = sys.stdout
43 self.output = sys.stdout
cliechtif467aa82013-10-13 21:36:49 +000044
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020045 def setup(self):
Chris Liechti1df28272015-08-27 23:37:38 +020046 pass
cliechtif467aa82013-10-13 21:36:49 +000047
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020048 def cleanup(self):
Chris Liechti1df28272015-08-27 23:37:38 +020049 pass
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020050
51 def getkey(self):
52 return None
53
54 def write_bytes(self, s):
55 self.byte_output.write(s)
56 self.byte_output.flush()
57
58 def write(self, s):
59 self.output.write(s)
60 self.output.flush()
61
Chris Liechti269f77b2015-08-24 01:31:42 +020062 # - - - - - - - - - - - - - - - - - - - - - - - -
63 # context manager:
64 # switch terminal temporary to normal mode (e.g. to get user input)
65
66 def __enter__(self):
67 self.cleanup()
68 return self
69
70 def __exit__(self, *args, **kwargs):
71 self.setup()
72
cliechti9c592b32008-06-16 22:00:14 +000073
cliechtifc9eb382002-03-05 01:12:29 +000074if os.name == 'nt':
cliechti576de252002-02-28 23:54:44 +000075 import msvcrt
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020076 import ctypes
Chris Liechti9cc696b2015-08-28 00:54:22 +020077
78 class Out(object):
79 def __init__(self, fd):
80 self.fd = fd
81
82 def flush(self):
83 pass
84
85 def write(self, s):
86 os.write(self.fd, s)
87
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020088 class Console(ConsoleBase):
Chris Liechticbb00b22015-08-13 22:58:49 +020089 def __init__(self):
90 super(Console, self).__init__()
Chris Liechti1df28272015-08-27 23:37:38 +020091 self._saved_ocp = ctypes.windll.kernel32.GetConsoleOutputCP()
92 self._saved_icp = ctypes.windll.kernel32.GetConsoleCP()
Chris Liechticbb00b22015-08-13 22:58:49 +020093 ctypes.windll.kernel32.SetConsoleOutputCP(65001)
94 ctypes.windll.kernel32.SetConsoleCP(65001)
Chris Liechti9cc696b2015-08-28 00:54:22 +020095 self.output = codecs.getwriter('UTF-8')(Out(sys.stdout.fileno()), 'replace')
96 # the change of the code page is not propagated to Python, manually fix it
97 sys.stderr = codecs.getwriter('UTF-8')(Out(sys.stderr.fileno()), 'replace')
98 sys.stdout = self.output
Chris Liechticbb00b22015-08-13 22:58:49 +020099
Chris Liechti1df28272015-08-27 23:37:38 +0200100 def __del__(self):
101 ctypes.windll.kernel32.SetConsoleOutputCP(self._saved_ocp)
102 ctypes.windll.kernel32.SetConsoleCP(self._saved_icp)
103
cliechti3a8bf092008-09-17 11:26:53 +0000104 def getkey(self):
cliechti91165532011-03-18 02:02:52 +0000105 while True:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200106 z = msvcrt.getwch()
Chris Liechti3b454802015-08-26 23:39:59 +0200107 if z == u'\r':
108 return u'\n'
109 elif z in u'\x00\x0e': # functions keys, ignore
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200110 msvcrt.getwch()
cliechti9c592b32008-06-16 22:00:14 +0000111 else:
cliechti9c592b32008-06-16 22:00:14 +0000112 return z
cliechti53edb472009-02-06 21:18:46 +0000113
cliechti576de252002-02-28 23:54:44 +0000114elif os.name == 'posix':
Chris Liechtia1d5c6d2015-08-07 14:41:24 +0200115 import atexit
116 import termios
Chris Liechti9cc696b2015-08-28 00:54:22 +0200117
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200118 class Console(ConsoleBase):
cliechti9c592b32008-06-16 22:00:14 +0000119 def __init__(self):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200120 super(Console, self).__init__()
cliechti9c592b32008-06-16 22:00:14 +0000121 self.fd = sys.stdin.fileno()
Chris Liechti4d989c22015-08-24 00:24:49 +0200122 self.old = termios.tcgetattr(self.fd)
Chris Liechti89eb2472015-08-08 17:06:25 +0200123 atexit.register(self.cleanup)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200124 if sys.version_info < (3, 0):
Chris Liechtia7e7b692015-08-25 21:10:28 +0200125 self.enc_stdin = codecs.getreader(sys.stdin.encoding)(sys.stdin)
126 else:
127 self.enc_stdin = sys.stdin
cliechti9c592b32008-06-16 22:00:14 +0000128
129 def setup(self):
cliechti9c592b32008-06-16 22:00:14 +0000130 new = termios.tcgetattr(self.fd)
131 new[3] = new[3] & ~termios.ICANON & ~termios.ECHO & ~termios.ISIG
132 new[6][termios.VMIN] = 1
133 new[6][termios.VTIME] = 0
134 termios.tcsetattr(self.fd, termios.TCSANOW, new)
cliechti53edb472009-02-06 21:18:46 +0000135
cliechti9c592b32008-06-16 22:00:14 +0000136 def getkey(self):
Chris Liechtia7e7b692015-08-25 21:10:28 +0200137 c = self.enc_stdin.read(1)
Chris Liechti3b454802015-08-26 23:39:59 +0200138 if c == u'\x7f':
139 c = u'\b' # map the BS key (which yields DEL) to backspace
Chris Liechti9a720852015-08-25 00:20:38 +0200140 return c
cliechti53edb472009-02-06 21:18:46 +0000141
cliechti9c592b32008-06-16 22:00:14 +0000142 def cleanup(self):
Chris Liechti4d989c22015-08-24 00:24:49 +0200143 termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old)
cliechti9c592b32008-06-16 22:00:14 +0000144
cliechti576de252002-02-28 23:54:44 +0000145else:
cliechti8c2ea842011-03-18 01:51:46 +0000146 raise NotImplementedError("Sorry no implementation for your platform (%s) available." % sys.platform)
cliechti576de252002-02-28 23:54:44 +0000147
cliechti6fa76fb2009-07-08 23:53:39 +0000148
Chris Liechti9a720852015-08-25 00:20:38 +0200149# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200150
151class Transform(object):
Chris Liechticbb00b22015-08-13 22:58:49 +0200152 """do-nothing: forward all data unchanged"""
Chris Liechtid698af72015-08-24 20:24:55 +0200153 def rx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200154 """text received from serial port"""
155 return text
156
Chris Liechtid698af72015-08-24 20:24:55 +0200157 def tx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200158 """text to be sent to serial port"""
159 return text
160
161 def echo(self, text):
162 """text to be sent but displayed on console"""
163 return text
164
Chris Liechti442bf512015-08-15 01:42:24 +0200165
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200166class CRLF(Transform):
167 """ENTER sends CR+LF"""
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200168
Chris Liechtid698af72015-08-24 20:24:55 +0200169 def tx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200170 return text.replace('\n', '\r\n')
171
Chris Liechti442bf512015-08-15 01:42:24 +0200172
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200173class CR(Transform):
174 """ENTER sends CR"""
Chris Liechtid698af72015-08-24 20:24:55 +0200175
176 def rx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200177 return text.replace('\r', '\n')
178
Chris Liechtid698af72015-08-24 20:24:55 +0200179 def tx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200180 return text.replace('\n', '\r')
181
Chris Liechti442bf512015-08-15 01:42:24 +0200182
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200183class LF(Transform):
184 """ENTER sends LF"""
185
186
187class NoTerminal(Transform):
188 """remove typical terminal control codes from input"""
Chris Liechti9a720852015-08-25 00:20:38 +0200189
190 REPLACEMENT_MAP = dict((x, 0x2400 + x) for x in range(32) if unichr(x) not in '\r\n\b\t')
191 REPLACEMENT_MAP.update({
Chris Liechti033f17c2015-08-30 21:28:04 +0200192 0x7F: 0x2421, # DEL
193 0x9B: 0x2425, # CSI
Chris Liechti9a720852015-08-25 00:20:38 +0200194 })
195
Chris Liechtid698af72015-08-24 20:24:55 +0200196 def rx(self, text):
Chris Liechti9a720852015-08-25 00:20:38 +0200197 return text.translate(self.REPLACEMENT_MAP)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200198
Chris Liechtid698af72015-08-24 20:24:55 +0200199 echo = rx
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200200
201
Chris Liechti9a720852015-08-25 00:20:38 +0200202class NoControls(NoTerminal):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200203 """Remove all control codes, incl. CR+LF"""
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200204
Chris Liechti9a720852015-08-25 00:20:38 +0200205 REPLACEMENT_MAP = dict((x, 0x2400 + x) for x in range(32))
206 REPLACEMENT_MAP.update({
Chris Liechti033f17c2015-08-30 21:28:04 +0200207 32: 0x2423, # visual space
208 0x7F: 0x2421, # DEL
209 0x9B: 0x2425, # CSI
Chris Liechti9a720852015-08-25 00:20:38 +0200210 })
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200211
212
213class Printable(Transform):
Chris Liechtid698af72015-08-24 20:24:55 +0200214 """Show decimal code for all non-ASCII characters and replace most control codes"""
Chris Liechtic0c660a2015-08-25 00:55:51 +0200215
Chris Liechtid698af72015-08-24 20:24:55 +0200216 def rx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200217 r = []
218 for t in text:
Chris Liechti7e9cfd42015-08-12 15:28:19 +0200219 if ' ' <= t < '\x7f' or t in '\r\n\b\t':
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200220 r.append(t)
Chris Liechtid698af72015-08-24 20:24:55 +0200221 elif t < ' ':
222 r.append(unichr(0x2400 + ord(t)))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200223 else:
224 r.extend(unichr(0x2080 + ord(d) - 48) for d in '{:d}'.format(ord(t)))
225 r.append(' ')
226 return ''.join(r)
227
Chris Liechtid698af72015-08-24 20:24:55 +0200228 echo = rx
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200229
230
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200231class Colorize(Transform):
Chris Liechti442bf512015-08-15 01:42:24 +0200232 """Apply different colors for received and echo"""
Chris Liechtic0c660a2015-08-25 00:55:51 +0200233
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200234 def __init__(self):
235 # XXX make it configurable, use colorama?
236 self.input_color = '\x1b[37m'
237 self.echo_color = '\x1b[31m'
238
Chris Liechtid698af72015-08-24 20:24:55 +0200239 def rx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200240 return self.input_color + text
241
242 def echo(self, text):
243 return self.echo_color + text
244
Chris Liechti442bf512015-08-15 01:42:24 +0200245
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200246class DebugIO(Transform):
Chris Liechti442bf512015-08-15 01:42:24 +0200247 """Print what is sent and received"""
Chris Liechtic0c660a2015-08-25 00:55:51 +0200248
Chris Liechtid698af72015-08-24 20:24:55 +0200249 def rx(self, text):
Chris Liechtie1384382015-08-15 17:06:05 +0200250 sys.stderr.write(' [RX:{}] '.format(repr(text)))
251 sys.stderr.flush()
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200252 return text
253
Chris Liechtid698af72015-08-24 20:24:55 +0200254 def tx(self, text):
Chris Liechtie1384382015-08-15 17:06:05 +0200255 sys.stderr.write(' [TX:{}] '.format(repr(text)))
256 sys.stderr.flush()
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200257 return text
258
Chris Liechti442bf512015-08-15 01:42:24 +0200259
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200260# other ideas:
261# - add date/time for each newline
262# - insert newline after: a) timeout b) packet end character
263
Chris Liechtib3df13e2015-08-25 02:20:09 +0200264EOL_TRANSFORMATIONS = {
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200265 'crlf': CRLF,
266 'cr': CR,
267 'lf': LF,
Chris Liechtib3df13e2015-08-25 02:20:09 +0200268 }
269
270TRANSFORMATIONS = {
Chris Liechticbb00b22015-08-13 22:58:49 +0200271 'direct': Transform, # no transformation
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200272 'default': NoTerminal,
273 'nocontrol': NoControls,
274 'printable': Printable,
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200275 'colorize': Colorize,
276 'debug': DebugIO,
277 }
278
279
Chris Liechti033f17c2015-08-30 21:28:04 +0200280# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
cliechti1351dde2012-04-12 16:47:47 +0000281def dump_port_list():
282 if comports:
283 sys.stderr.write('\n--- Available ports:\n')
284 for port, desc, hwid in sorted(comports()):
285 #~ sys.stderr.write('--- %-20s %s [%s]\n' % (port, desc, hwid))
286 sys.stderr.write('--- %-20s %s\n' % (port, desc))
287
288
cliechti8c2ea842011-03-18 01:51:46 +0000289class Miniterm(object):
Chris Liechti3b454802015-08-26 23:39:59 +0200290 def __init__(self, serial_instance, echo=False, eol='crlf', filters=()):
Chris Liechti89eb2472015-08-08 17:06:25 +0200291 self.console = Console()
Chris Liechti3b454802015-08-26 23:39:59 +0200292 self.serial = serial_instance
cliechti6385f2c2005-09-21 19:51:19 +0000293 self.echo = echo
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200294 self.raw = False
Chris Liechti442bf512015-08-15 01:42:24 +0200295 self.input_encoding = 'UTF-8'
Chris Liechti442bf512015-08-15 01:42:24 +0200296 self.output_encoding = 'UTF-8'
Chris Liechtib3df13e2015-08-25 02:20:09 +0200297 self.eol = eol
298 self.filters = filters
299 self.update_transformations()
Chris Liechti442bf512015-08-15 01:42:24 +0200300 self.exit_character = 0x1d # GS/CTRL+]
301 self.menu_character = 0x14 # Menu: CTRL+T
cliechti576de252002-02-28 23:54:44 +0000302
cliechti8c2ea842011-03-18 01:51:46 +0000303 def _start_reader(self):
304 """Start reader thread"""
305 self._reader_alive = True
cliechti6fa76fb2009-07-08 23:53:39 +0000306 # start serial->console thread
Chris Liechti55ba7d92015-08-15 16:33:51 +0200307 self.receiver_thread = threading.Thread(target=self.reader, name='rx')
308 self.receiver_thread.daemon = True
cliechti6385f2c2005-09-21 19:51:19 +0000309 self.receiver_thread.start()
cliechti8c2ea842011-03-18 01:51:46 +0000310
311 def _stop_reader(self):
312 """Stop reader thread only, wait for clean exit of thread"""
313 self._reader_alive = False
314 self.receiver_thread.join()
315
cliechti8c2ea842011-03-18 01:51:46 +0000316 def start(self):
317 self.alive = True
318 self._start_reader()
cliechti6fa76fb2009-07-08 23:53:39 +0000319 # enter console->serial loop
Chris Liechti55ba7d92015-08-15 16:33:51 +0200320 self.transmitter_thread = threading.Thread(target=self.writer, name='tx')
321 self.transmitter_thread.daemon = True
cliechti6385f2c2005-09-21 19:51:19 +0000322 self.transmitter_thread.start()
Chris Liechti89eb2472015-08-08 17:06:25 +0200323 self.console.setup()
cliechti53edb472009-02-06 21:18:46 +0000324
cliechti6385f2c2005-09-21 19:51:19 +0000325 def stop(self):
326 self.alive = False
cliechti53edb472009-02-06 21:18:46 +0000327
cliechtibf6bb7d2006-03-30 00:28:18 +0000328 def join(self, transmit_only=False):
cliechti6385f2c2005-09-21 19:51:19 +0000329 self.transmitter_thread.join()
cliechtibf6bb7d2006-03-30 00:28:18 +0000330 if not transmit_only:
331 self.receiver_thread.join()
cliechti6385f2c2005-09-21 19:51:19 +0000332
Chris Liechtib3df13e2015-08-25 02:20:09 +0200333 def update_transformations(self):
334 transformations = [EOL_TRANSFORMATIONS[self.eol]] + [TRANSFORMATIONS[f] for f in self.filters]
335 self.tx_transformations = [t() for t in transformations]
336 self.rx_transformations = list(reversed(self.tx_transformations))
337
Chris Liechtid698af72015-08-24 20:24:55 +0200338 def set_rx_encoding(self, encoding, errors='replace'):
339 self.input_encoding = encoding
340 self.rx_decoder = codecs.getincrementaldecoder(encoding)(errors)
341
342 def set_tx_encoding(self, encoding, errors='replace'):
343 self.output_encoding = encoding
344 self.tx_encoder = codecs.getincrementalencoder(encoding)(errors)
345
cliechti6c8eb2f2009-07-08 02:10:46 +0000346 def dump_port_settings(self):
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200347 sys.stderr.write("\n--- Settings: {p.name} {p.baudrate},{p.bytesize},{p.parity},{p.stopbits}\n".format(
348 p=self.serial))
Chris Liechti442bf512015-08-15 01:42:24 +0200349 sys.stderr.write('--- RTS: {:8} DTR: {:8} BREAK: {:8}\n'.format(
Chris Liechti3b454802015-08-26 23:39:59 +0200350 ('active' if self.serial.rts else 'inactive'),
351 ('active' if self.serial.dtr else 'inactive'),
352 ('active' if self.serial.break_condition else 'inactive')))
cliechti10114572009-08-05 23:40:50 +0000353 try:
Chris Liechti442bf512015-08-15 01:42:24 +0200354 sys.stderr.write('--- CTS: {:8} DSR: {:8} RI: {:8} CD: {:8}\n'.format(
Chris Liechti3b454802015-08-26 23:39:59 +0200355 ('active' if self.serial.cts else 'inactive'),
356 ('active' if self.serial.dsr else 'inactive'),
357 ('active' if self.serial.ri else 'inactive'),
358 ('active' if self.serial.cd else 'inactive')))
cliechti10114572009-08-05 23:40:50 +0000359 except serial.SerialException:
Chris Liechti55ba7d92015-08-15 16:33:51 +0200360 # on RFC 2217 ports, it can happen if no modem state notification was
cliechti10114572009-08-05 23:40:50 +0000361 # yet received. ignore this error.
362 pass
Chris Liechti442bf512015-08-15 01:42:24 +0200363 sys.stderr.write('--- software flow control: {}\n'.format('active' if self.serial.xonxoff else 'inactive'))
364 sys.stderr.write('--- hardware flow control: {}\n'.format('active' if self.serial.rtscts else 'inactive'))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200365 #~ sys.stderr.write('--- data escaping: %s linefeed: %s\n' % (
366 #~ REPR_MODES[self.repr_mode],
367 #~ LF_MODES[self.convert_outgoing]))
Chris Liechti442bf512015-08-15 01:42:24 +0200368 sys.stderr.write('--- serial input encoding: {}\n'.format(self.input_encoding))
369 sys.stderr.write('--- serial output encoding: {}\n'.format(self.output_encoding))
Chris Liechtib3df13e2015-08-25 02:20:09 +0200370 sys.stderr.write('--- EOL: {}\n'.format(self.eol.upper()))
371 sys.stderr.write('--- filters: {}\n'.format(' '.join(self.filters)))
cliechti6c8eb2f2009-07-08 02:10:46 +0000372
cliechti6385f2c2005-09-21 19:51:19 +0000373 def reader(self):
374 """loop and copy serial->console"""
cliechti6963b262010-01-02 03:01:21 +0000375 try:
cliechti8c2ea842011-03-18 01:51:46 +0000376 while self.alive and self._reader_alive:
Chris Liechti188cf592015-08-22 00:28:19 +0200377 # read all that is there or wait for one byte
Chris Liechti3b454802015-08-26 23:39:59 +0200378 data = self.serial.read(self.serial.in_waiting or 1)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200379 if data:
380 if self.raw:
381 self.console.write_bytes(data)
cliechti6963b262010-01-02 03:01:21 +0000382 else:
Chris Liechtid698af72015-08-24 20:24:55 +0200383 text = self.rx_decoder.decode(data)
Chris Liechtie1384382015-08-15 17:06:05 +0200384 for transformation in self.rx_transformations:
Chris Liechtid698af72015-08-24 20:24:55 +0200385 text = transformation.rx(text)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200386 self.console.write(text)
Chris Liechti033f17c2015-08-30 21:28:04 +0200387 except serial.SerialException:
cliechti6963b262010-01-02 03:01:21 +0000388 self.alive = False
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200389 # XXX would be nice if the writer could be interrupted at this
390 # point... to exit completely
cliechti6963b262010-01-02 03:01:21 +0000391 raise
cliechti576de252002-02-28 23:54:44 +0000392
cliechti6385f2c2005-09-21 19:51:19 +0000393 def writer(self):
cliechti8c2ea842011-03-18 01:51:46 +0000394 """\
Chris Liechti442bf512015-08-15 01:42:24 +0200395 Loop and copy console->serial until self.exit_character character is
396 found. When self.menu_character is found, interpret the next key
cliechti8c2ea842011-03-18 01:51:46 +0000397 locally.
cliechti6c8eb2f2009-07-08 02:10:46 +0000398 """
399 menu_active = False
400 try:
401 while self.alive:
402 try:
Chris Liechti89eb2472015-08-08 17:06:25 +0200403 c = self.console.getkey()
cliechti6c8eb2f2009-07-08 02:10:46 +0000404 except KeyboardInterrupt:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200405 c = '\x03'
cliechti6c8eb2f2009-07-08 02:10:46 +0000406 if menu_active:
Chris Liechti7af7c752015-08-12 15:45:19 +0200407 self.handle_menu_key(c)
cliechti6c8eb2f2009-07-08 02:10:46 +0000408 menu_active = False
Chris Liechti442bf512015-08-15 01:42:24 +0200409 elif c == self.menu_character:
Chris Liechti7af7c752015-08-12 15:45:19 +0200410 menu_active = True # next char will be for menu
Chris Liechti442bf512015-08-15 01:42:24 +0200411 elif c == self.exit_character:
Chris Liechti7af7c752015-08-12 15:45:19 +0200412 self.stop() # exit app
413 break
cliechti6c8eb2f2009-07-08 02:10:46 +0000414 else:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200415 #~ if self.raw:
416 text = c
Chris Liechtie1384382015-08-15 17:06:05 +0200417 for transformation in self.tx_transformations:
Chris Liechtid698af72015-08-24 20:24:55 +0200418 text = transformation.tx(text)
Chris Liechtid698af72015-08-24 20:24:55 +0200419 self.serial.write(self.tx_encoder.encode(text))
cliechti6c8eb2f2009-07-08 02:10:46 +0000420 if self.echo:
Chris Liechti3b454802015-08-26 23:39:59 +0200421 echo_text = c
422 for transformation in self.tx_transformations:
423 echo_text = transformation.echo(echo_text)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200424 self.console.write(echo_text)
cliechti6c8eb2f2009-07-08 02:10:46 +0000425 except:
426 self.alive = False
427 raise
cliechti6385f2c2005-09-21 19:51:19 +0000428
Chris Liechti7af7c752015-08-12 15:45:19 +0200429 def handle_menu_key(self, c):
430 """Implement a simple menu / settings"""
Chris Liechti55ba7d92015-08-15 16:33:51 +0200431 if c == self.menu_character or c == self.exit_character:
432 # Menu/exit character again -> send itself
Chris Liechtid698af72015-08-24 20:24:55 +0200433 self.serial.write(self.tx_encoder.encode(c))
Chris Liechti7af7c752015-08-12 15:45:19 +0200434 if self.echo:
435 self.console.write(c)
Chris Liechtib7550bd2015-08-15 04:09:10 +0200436 elif c == '\x15': # CTRL+U -> upload file
Chris Liechti7af7c752015-08-12 15:45:19 +0200437 sys.stderr.write('\n--- File to upload: ')
438 sys.stderr.flush()
Chris Liechti269f77b2015-08-24 01:31:42 +0200439 with self.console:
440 filename = sys.stdin.readline().rstrip('\r\n')
441 if filename:
442 try:
443 with open(filename, 'rb') as f:
444 sys.stderr.write('--- Sending file {} ---\n'.format(filename))
445 while True:
446 block = f.read(1024)
447 if not block:
448 break
449 self.serial.write(block)
450 # Wait for output buffer to drain.
451 self.serial.flush()
452 sys.stderr.write('.') # Progress indicator.
453 sys.stderr.write('\n--- File {} sent ---\n'.format(filename))
454 except IOError as e:
455 sys.stderr.write('--- ERROR opening file {}: {} ---\n'.format(filename, e))
Chris Liechti7af7c752015-08-12 15:45:19 +0200456 elif c in '\x08hH?': # CTRL+H, h, H, ? -> Show help
Chris Liechti442bf512015-08-15 01:42:24 +0200457 sys.stderr.write(self.get_help_text())
Chris Liechti7af7c752015-08-12 15:45:19 +0200458 elif c == '\x12': # CTRL+R -> Toggle RTS
Chris Liechti3b454802015-08-26 23:39:59 +0200459 self.serial.rts = not self.serial.rts
460 sys.stderr.write('--- RTS {} ---\n'.format('active' if self.serial.rts else 'inactive'))
Chris Liechti7af7c752015-08-12 15:45:19 +0200461 elif c == '\x04': # CTRL+D -> Toggle DTR
Chris Liechti3b454802015-08-26 23:39:59 +0200462 self.serial.dtr = not self.serial.dtr
463 sys.stderr.write('--- DTR {} ---\n'.format('active' if self.serial.dtr else 'inactive'))
Chris Liechti7af7c752015-08-12 15:45:19 +0200464 elif c == '\x02': # CTRL+B -> toggle BREAK condition
Chris Liechti3b454802015-08-26 23:39:59 +0200465 self.serial.break_condition = not self.serial.break_condition
466 sys.stderr.write('--- BREAK {} ---\n'.format('active' if self.serial.break_condition else 'inactive'))
Chris Liechti7af7c752015-08-12 15:45:19 +0200467 elif c == '\x05': # CTRL+E -> toggle local echo
468 self.echo = not self.echo
Chris Liechti442bf512015-08-15 01:42:24 +0200469 sys.stderr.write('--- local echo {} ---\n'.format('active' if self.echo else 'inactive'))
Chris Liechtib3df13e2015-08-25 02:20:09 +0200470 elif c == '\x06': # CTRL+F -> edit filters
471 sys.stderr.write('\n--- Available Filters:\n')
472 sys.stderr.write('\n'.join(
473 '--- {:<10} = {.__doc__}'.format(k, v)
474 for k, v in sorted(TRANSFORMATIONS.items())))
475 sys.stderr.write('\n--- Enter new filter name(s) [{}]: '.format(' '.join(self.filters)))
476 with self.console:
477 new_filters = sys.stdin.readline().lower().split()
478 if new_filters:
479 for f in new_filters:
480 if f not in TRANSFORMATIONS:
481 sys.stderr.write('--- unknown filter: {}'.format(repr(f)))
482 break
483 else:
484 self.filters = new_filters
485 self.update_transformations()
486 sys.stderr.write('--- filters: {}\n'.format(' '.join(self.filters)))
487 elif c == '\x0c': # CTRL+L -> EOL mode
Chris Liechti033f17c2015-08-30 21:28:04 +0200488 modes = list(EOL_TRANSFORMATIONS) # keys
Chris Liechtib3df13e2015-08-25 02:20:09 +0200489 eol = modes.index(self.eol) + 1
490 if eol >= len(modes):
491 eol = 0
492 self.eol = modes[eol]
493 sys.stderr.write('--- EOL: {} ---\n'.format(self.eol.upper()))
494 self.update_transformations()
495 elif c == '\x01': # CTRL+A -> set encoding
496 sys.stderr.write('\n--- Enter new encoding name [{}]: '.format(self.input_encoding))
497 with self.console:
498 new_encoding = sys.stdin.readline().strip()
499 if new_encoding:
500 try:
501 codecs.lookup(new_encoding)
502 except LookupError:
503 sys.stderr.write('--- invalid encoding name: {}\n'.format(new_encoding))
504 else:
505 self.set_rx_encoding(new_encoding)
506 self.set_tx_encoding(new_encoding)
507 sys.stderr.write('--- serial input encoding: {}\n'.format(self.input_encoding))
508 sys.stderr.write('--- serial output encoding: {}\n'.format(self.output_encoding))
Chris Liechti7af7c752015-08-12 15:45:19 +0200509 elif c == '\x09': # CTRL+I -> info
510 self.dump_port_settings()
511 #~ elif c == '\x01': # CTRL+A -> cycle escape mode
512 #~ elif c == '\x0c': # CTRL+L -> cycle linefeed mode
513 elif c in 'pP': # P -> change port
514 dump_port_list()
515 sys.stderr.write('--- Enter port name: ')
516 sys.stderr.flush()
Chris Liechti269f77b2015-08-24 01:31:42 +0200517 with self.console:
518 try:
519 port = sys.stdin.readline().strip()
520 except KeyboardInterrupt:
521 port = None
Chris Liechti7af7c752015-08-12 15:45:19 +0200522 if port and port != self.serial.port:
523 # reader thread needs to be shut down
524 self._stop_reader()
525 # save settings
526 settings = self.serial.getSettingsDict()
527 try:
528 new_serial = serial.serial_for_url(port, do_not_open=True)
529 # restore settings and open
530 new_serial.applySettingsDict(settings)
531 new_serial.open()
532 new_serial.setRTS(self.rts_state)
533 new_serial.setDTR(self.dtr_state)
534 new_serial.setBreak(self.break_state)
535 except Exception as e:
Chris Liechti442bf512015-08-15 01:42:24 +0200536 sys.stderr.write('--- ERROR opening new port: {} ---\n'.format(e))
Chris Liechti7af7c752015-08-12 15:45:19 +0200537 new_serial.close()
538 else:
539 self.serial.close()
540 self.serial = new_serial
Chris Liechti442bf512015-08-15 01:42:24 +0200541 sys.stderr.write('--- Port changed to: {} ---\n'.format(self.serial.port))
Chris Liechti7af7c752015-08-12 15:45:19 +0200542 # and restart the reader thread
543 self._start_reader()
544 elif c in 'bB': # B -> change baudrate
545 sys.stderr.write('\n--- Baudrate: ')
546 sys.stderr.flush()
Chris Liechti269f77b2015-08-24 01:31:42 +0200547 with self.console:
548 backup = self.serial.baudrate
549 try:
550 self.serial.baudrate = int(sys.stdin.readline().strip())
551 except ValueError as e:
552 sys.stderr.write('--- ERROR setting baudrate: %s ---\n'.format(e))
553 self.serial.baudrate = backup
554 else:
555 self.dump_port_settings()
Chris Liechti7af7c752015-08-12 15:45:19 +0200556 elif c == '8': # 8 -> change to 8 bits
557 self.serial.bytesize = serial.EIGHTBITS
558 self.dump_port_settings()
559 elif c == '7': # 7 -> change to 8 bits
560 self.serial.bytesize = serial.SEVENBITS
561 self.dump_port_settings()
562 elif c in 'eE': # E -> change to even parity
563 self.serial.parity = serial.PARITY_EVEN
564 self.dump_port_settings()
565 elif c in 'oO': # O -> change to odd parity
566 self.serial.parity = serial.PARITY_ODD
567 self.dump_port_settings()
568 elif c in 'mM': # M -> change to mark parity
569 self.serial.parity = serial.PARITY_MARK
570 self.dump_port_settings()
571 elif c in 'sS': # S -> change to space parity
572 self.serial.parity = serial.PARITY_SPACE
573 self.dump_port_settings()
574 elif c in 'nN': # N -> change to no parity
575 self.serial.parity = serial.PARITY_NONE
576 self.dump_port_settings()
577 elif c == '1': # 1 -> change to 1 stop bits
578 self.serial.stopbits = serial.STOPBITS_ONE
579 self.dump_port_settings()
580 elif c == '2': # 2 -> change to 2 stop bits
581 self.serial.stopbits = serial.STOPBITS_TWO
582 self.dump_port_settings()
583 elif c == '3': # 3 -> change to 1.5 stop bits
584 self.serial.stopbits = serial.STOPBITS_ONE_POINT_FIVE
585 self.dump_port_settings()
586 elif c in 'xX': # X -> change software flow control
587 self.serial.xonxoff = (c == 'X')
588 self.dump_port_settings()
589 elif c in 'rR': # R -> change hardware flow control
590 self.serial.rtscts = (c == 'R')
591 self.dump_port_settings()
592 else:
Chris Liechti442bf512015-08-15 01:42:24 +0200593 sys.stderr.write('--- unknown menu character {} --\n'.format(key_description(c)))
594
595 def get_help_text(self):
Chris Liechti55ba7d92015-08-15 16:33:51 +0200596 # help text, starts with blank line!
Chris Liechti442bf512015-08-15 01:42:24 +0200597 return """
598--- pySerial ({version}) - miniterm - help
599---
600--- {exit:8} Exit program
601--- {menu:8} Menu escape key, followed by:
602--- Menu keys:
603--- {menu:7} Send the menu character itself to remote
604--- {exit:7} Send the exit character itself to remote
605--- {info:7} Show info
606--- {upload:7} Upload file (prompt will be shown)
Chris Liechtib3df13e2015-08-25 02:20:09 +0200607--- {repr:7} encoding
608--- {filter:7} edit filters
Chris Liechti442bf512015-08-15 01:42:24 +0200609--- Toggles:
Chris Liechtib3df13e2015-08-25 02:20:09 +0200610--- {rts:7} RTS {dtr:7} DTR {brk:7} BREAK
611--- {echo:7} echo {eol:7} EOL
Chris Liechti442bf512015-08-15 01:42:24 +0200612---
Chris Liechti55ba7d92015-08-15 16:33:51 +0200613--- Port settings ({menu} followed by the following):
Chris Liechti442bf512015-08-15 01:42:24 +0200614--- p change port
615--- 7 8 set data bits
Chris Liechtib7550bd2015-08-15 04:09:10 +0200616--- N E O S M change parity (None, Even, Odd, Space, Mark)
Chris Liechti442bf512015-08-15 01:42:24 +0200617--- 1 2 3 set stop bits (1, 2, 1.5)
618--- b change baud rate
619--- x X disable/enable software flow control
620--- r R disable/enable hardware flow control
621""".format(
622 version=getattr(serial, 'VERSION', 'unknown version'),
623 exit=key_description(self.exit_character),
624 menu=key_description(self.menu_character),
Chris Liechtib7550bd2015-08-15 04:09:10 +0200625 rts=key_description('\x12'),
626 dtr=key_description('\x04'),
627 brk=key_description('\x02'),
628 echo=key_description('\x05'),
629 info=key_description('\x09'),
630 upload=key_description('\x15'),
Chris Liechtib3df13e2015-08-25 02:20:09 +0200631 repr=key_description('\x01'),
632 filter=key_description('\x06'),
633 eol=key_description('\x0c'),
Chris Liechti442bf512015-08-15 01:42:24 +0200634 )
Chris Liechti7af7c752015-08-12 15:45:19 +0200635
636
Chris Liechtib3df13e2015-08-25 02:20:09 +0200637# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechti55ba7d92015-08-15 16:33:51 +0200638# default args can be used to override when calling main() from an other script
639# e.g to create a miniterm-my-device.py
640def main(default_port=None, default_baudrate=9600, default_rts=None, default_dtr=None):
Chris Liechtib7550bd2015-08-15 04:09:10 +0200641 import argparse
cliechti6385f2c2005-09-21 19:51:19 +0000642
Chris Liechtib7550bd2015-08-15 04:09:10 +0200643 parser = argparse.ArgumentParser(
644 description="Miniterm - A simple terminal program for the serial port.")
cliechti6385f2c2005-09-21 19:51:19 +0000645
Chris Liechti033f17c2015-08-30 21:28:04 +0200646 parser.add_argument(
647 "port",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200648 nargs='?',
649 help="serial port name",
Chris Liechti55ba7d92015-08-15 16:33:51 +0200650 default=default_port)
cliechti5370cee2013-10-13 03:08:19 +0000651
Chris Liechti033f17c2015-08-30 21:28:04 +0200652 parser.add_argument(
653 "baudrate",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200654 nargs='?',
655 type=int,
656 help="set baud rate, default: %(default)s",
Chris Liechti55ba7d92015-08-15 16:33:51 +0200657 default=default_baudrate)
cliechti6385f2c2005-09-21 19:51:19 +0000658
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200659 group = parser.add_argument_group("port settings")
cliechti53edb472009-02-06 21:18:46 +0000660
Chris Liechti033f17c2015-08-30 21:28:04 +0200661 group.add_argument(
662 "--parity",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200663 choices=['N', 'E', 'O', 'S', 'M'],
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200664 type=lambda c: c.upper(),
Chris Liechtib7550bd2015-08-15 04:09:10 +0200665 help="set parity, one of {N E O S M}, default: N",
666 default='N')
cliechti53edb472009-02-06 21:18:46 +0000667
Chris Liechti033f17c2015-08-30 21:28:04 +0200668 group.add_argument(
669 "--rtscts",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200670 action="store_true",
671 help="enable RTS/CTS flow control (default off)",
672 default=False)
cliechti53edb472009-02-06 21:18:46 +0000673
Chris Liechti033f17c2015-08-30 21:28:04 +0200674 group.add_argument(
675 "--xonxoff",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200676 action="store_true",
677 help="enable software flow control (default off)",
678 default=False)
cliechti53edb472009-02-06 21:18:46 +0000679
Chris Liechti033f17c2015-08-30 21:28:04 +0200680 group.add_argument(
681 "--rts",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200682 type=int,
683 help="set initial RTS line state (possible values: 0, 1)",
Chris Liechti55ba7d92015-08-15 16:33:51 +0200684 default=default_rts)
cliechti5370cee2013-10-13 03:08:19 +0000685
Chris Liechti033f17c2015-08-30 21:28:04 +0200686 group.add_argument(
687 "--dtr",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200688 type=int,
689 help="set initial DTR line state (possible values: 0, 1)",
Chris Liechti55ba7d92015-08-15 16:33:51 +0200690 default=default_dtr)
cliechti5370cee2013-10-13 03:08:19 +0000691
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200692 group = parser.add_argument_group("data handling")
cliechti5370cee2013-10-13 03:08:19 +0000693
Chris Liechti033f17c2015-08-30 21:28:04 +0200694 group.add_argument(
695 "-e", "--echo",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200696 action="store_true",
697 help="enable local echo (default off)",
698 default=False)
cliechti5370cee2013-10-13 03:08:19 +0000699
Chris Liechti033f17c2015-08-30 21:28:04 +0200700 group.add_argument(
701 "--encoding",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200702 dest="serial_port_encoding",
703 metavar="CODEC",
Chris Liechtia7e7b692015-08-25 21:10:28 +0200704 help="set the encoding for the serial port (e.g. hexlify, Latin1, UTF-8), default: %(default)s",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200705 default='UTF-8')
cliechti5370cee2013-10-13 03:08:19 +0000706
Chris Liechti033f17c2015-08-30 21:28:04 +0200707 group.add_argument(
708 "-f", "--filter",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200709 action="append",
710 metavar="NAME",
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200711 help="add text transformation",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200712 default=[])
Chris Liechti2b1b3552015-08-12 15:35:33 +0200713
Chris Liechti033f17c2015-08-30 21:28:04 +0200714 group.add_argument(
715 "--eol",
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200716 choices=['CR', 'LF', 'CRLF'],
717 type=lambda c: c.upper(),
718 help="end of line mode",
719 default='CRLF')
cliechti53edb472009-02-06 21:18:46 +0000720
Chris Liechti033f17c2015-08-30 21:28:04 +0200721 group.add_argument(
722 "--raw",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200723 action="store_true",
724 help="Do no apply any encodings/transformations",
725 default=False)
cliechti6385f2c2005-09-21 19:51:19 +0000726
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200727 group = parser.add_argument_group("hotkeys")
cliechtib7d746d2006-03-28 22:44:30 +0000728
Chris Liechti033f17c2015-08-30 21:28:04 +0200729 group.add_argument(
730 "--exit-char",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200731 type=int,
Chris Liechti55ba7d92015-08-15 16:33:51 +0200732 metavar='NUM',
733 help="Unicode of special character that is used to exit the application, default: %(default)s",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200734 default=0x1d # GS/CTRL+]
735 )
cliechtibf6bb7d2006-03-30 00:28:18 +0000736
Chris Liechti033f17c2015-08-30 21:28:04 +0200737 group.add_argument(
738 "--menu-char",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200739 type=int,
Chris Liechti55ba7d92015-08-15 16:33:51 +0200740 metavar='NUM',
741 help="Unicode code of special character that is used to control miniterm (menu), default: %(default)s",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200742 default=0x14 # Menu: CTRL+T
743 )
cliechti9c592b32008-06-16 22:00:14 +0000744
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200745 group = parser.add_argument_group("diagnostics")
cliechti6385f2c2005-09-21 19:51:19 +0000746
Chris Liechti033f17c2015-08-30 21:28:04 +0200747 group.add_argument(
748 "-q", "--quiet",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200749 action="store_true",
750 help="suppress non-error messages",
751 default=False)
cliechti5370cee2013-10-13 03:08:19 +0000752
Chris Liechti033f17c2015-08-30 21:28:04 +0200753 group.add_argument(
754 "--develop",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200755 action="store_true",
756 help="show Python traceback on error",
757 default=False)
cliechti5370cee2013-10-13 03:08:19 +0000758
Chris Liechtib7550bd2015-08-15 04:09:10 +0200759 args = parser.parse_args()
cliechti5370cee2013-10-13 03:08:19 +0000760
Chris Liechtib7550bd2015-08-15 04:09:10 +0200761 if args.menu_char == args.exit_char:
cliechti6c8eb2f2009-07-08 02:10:46 +0000762 parser.error('--exit-char can not be the same as --menu-char')
763
Chris Liechtib7550bd2015-08-15 04:09:10 +0200764 # no port given on command line -> ask user now
765 if args.port is None:
766 dump_port_list()
767 args.port = raw_input('Enter port name:')
cliechti53edb472009-02-06 21:18:46 +0000768
Chris Liechtib3df13e2015-08-25 02:20:09 +0200769 if args.filter:
770 if 'help' in args.filter:
771 sys.stderr.write('Available filters:\n')
Chris Liechti442bf512015-08-15 01:42:24 +0200772 sys.stderr.write('\n'.join(
Chris Liechtib3df13e2015-08-25 02:20:09 +0200773 '{:<10} = {.__doc__}'.format(k, v)
Chris Liechtib7550bd2015-08-15 04:09:10 +0200774 for k, v in sorted(TRANSFORMATIONS.items())))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200775 sys.stderr.write('\n')
776 sys.exit(1)
Chris Liechtib3df13e2015-08-25 02:20:09 +0200777 filters = args.filter
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200778 else:
Chris Liechtib3df13e2015-08-25 02:20:09 +0200779 filters = ['default']
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200780
cliechti6385f2c2005-09-21 19:51:19 +0000781 try:
Chris Liechti3b454802015-08-26 23:39:59 +0200782 serial_instance = serial.serial_for_url(
Chris Liechtib7550bd2015-08-15 04:09:10 +0200783 args.port,
784 args.baudrate,
Chris Liechti3b454802015-08-26 23:39:59 +0200785 parity=args.parity,
Chris Liechtib7550bd2015-08-15 04:09:10 +0200786 rtscts=args.rtscts,
787 xonxoff=args.xonxoff,
Chris Liechti3b454802015-08-26 23:39:59 +0200788 timeout=1,
789 do_not_open=True)
790
791 if args.dtr is not None:
792 if not args.quiet:
793 sys.stderr.write('--- forcing DTR {}\n'.format('active' if args.dtr else 'inactive'))
794 serial_instance.dtr = args.dtr
795 if args.rts is not None:
796 if not args.quiet:
797 sys.stderr.write('--- forcing RTS {}\n'.format('active' if args.rts else 'inactive'))
798 serial_instance.rts = args.rts
799
800 serial_instance.open()
Chris Liechti68340d72015-08-03 14:15:48 +0200801 except serial.SerialException as e:
Chris Liechtiaccd2012015-08-17 03:09:23 +0200802 sys.stderr.write('could not open port {}: {}\n'.format(repr(args.port), e))
Chris Liechtib7550bd2015-08-15 04:09:10 +0200803 if args.develop:
Chris Liechti91090912015-08-05 02:36:14 +0200804 raise
cliechti6385f2c2005-09-21 19:51:19 +0000805 sys.exit(1)
806
Chris Liechti3b454802015-08-26 23:39:59 +0200807 miniterm = Miniterm(
808 serial_instance,
809 echo=args.echo,
810 eol=args.eol.lower(),
811 filters=filters)
812 miniterm.exit_character = unichr(args.exit_char)
813 miniterm.menu_character = unichr(args.menu_char)
814 miniterm.raw = args.raw
815 miniterm.set_rx_encoding(args.serial_port_encoding)
816 miniterm.set_tx_encoding(args.serial_port_encoding)
817
Chris Liechtib7550bd2015-08-15 04:09:10 +0200818 if not args.quiet:
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200819 sys.stderr.write('--- Miniterm on {p.name} {p.baudrate},{p.bytesize},{p.parity},{p.stopbits} ---\n'.format(
820 p=miniterm.serial))
Chris Liechtib7550bd2015-08-15 04:09:10 +0200821 sys.stderr.write('--- Quit: {} | Menu: {} | Help: {} followed by {} ---\n'.format(
Chris Liechti442bf512015-08-15 01:42:24 +0200822 key_description(miniterm.exit_character),
823 key_description(miniterm.menu_character),
824 key_description(miniterm.menu_character),
Chris Liechtib7550bd2015-08-15 04:09:10 +0200825 key_description('\x08'),
Chris Liechti442bf512015-08-15 01:42:24 +0200826 ))
cliechti6fa76fb2009-07-08 23:53:39 +0000827
cliechti6385f2c2005-09-21 19:51:19 +0000828 miniterm.start()
cliechti258ab0a2011-03-21 23:03:45 +0000829 try:
830 miniterm.join(True)
831 except KeyboardInterrupt:
832 pass
Chris Liechtib7550bd2015-08-15 04:09:10 +0200833 if not args.quiet:
cliechtibf6bb7d2006-03-30 00:28:18 +0000834 sys.stderr.write("\n--- exit ---\n")
cliechti6385f2c2005-09-21 19:51:19 +0000835 miniterm.join()
cliechtibf6bb7d2006-03-30 00:28:18 +0000836
cliechti5370cee2013-10-13 03:08:19 +0000837# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
cliechti8b3ad392002-03-03 20:12:21 +0000838if __name__ == '__main__':
cliechti6385f2c2005-09-21 19:51:19 +0000839 main()