blob: 8b9605feee6cd9b5460e52ac24011cd9a87ddce6 [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):
46 pass # Do nothing for 'nt'
cliechtif467aa82013-10-13 21:36:49 +000047
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020048 def cleanup(self):
49 pass # Do nothing for 'nt'
50
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
77 class Console(ConsoleBase):
Chris Liechticbb00b22015-08-13 22:58:49 +020078 def __init__(self):
79 super(Console, self).__init__()
80 ctypes.windll.kernel32.SetConsoleOutputCP(65001)
81 ctypes.windll.kernel32.SetConsoleCP(65001)
82 if sys.version_info < (3, 0):
83 class Out:
84 def __init__(self):
85 self.fd = sys.stdout.fileno()
86 def flush(self):
87 pass
88 def write(self, s):
89 os.write(self.fd, s)
90 self.output = codecs.getwriter('UTF-8')(Out(), 'replace')
91 self.byte_output = Out()
92 else:
93 self.output = codecs.getwriter('UTF-8')(sys.stdout.buffer, 'replace')
94
cliechti3a8bf092008-09-17 11:26:53 +000095 def getkey(self):
cliechti91165532011-03-18 02:02:52 +000096 while True:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020097 z = msvcrt.getwch()
Chris Liechti3b454802015-08-26 23:39:59 +020098 if z == u'\r':
99 return u'\n'
100 elif z in u'\x00\x0e': # functions keys, ignore
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200101 msvcrt.getwch()
cliechti9c592b32008-06-16 22:00:14 +0000102 else:
cliechti9c592b32008-06-16 22:00:14 +0000103 return z
cliechti53edb472009-02-06 21:18:46 +0000104
cliechti576de252002-02-28 23:54:44 +0000105elif os.name == 'posix':
Chris Liechtia1d5c6d2015-08-07 14:41:24 +0200106 import atexit
107 import termios
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200108 class Console(ConsoleBase):
cliechti9c592b32008-06-16 22:00:14 +0000109 def __init__(self):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200110 super(Console, self).__init__()
cliechti9c592b32008-06-16 22:00:14 +0000111 self.fd = sys.stdin.fileno()
Chris Liechti4d989c22015-08-24 00:24:49 +0200112 self.old = termios.tcgetattr(self.fd)
Chris Liechti89eb2472015-08-08 17:06:25 +0200113 atexit.register(self.cleanup)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200114 if sys.version_info < (3, 0):
Chris Liechtia7e7b692015-08-25 21:10:28 +0200115 self.enc_stdin = codecs.getreader(sys.stdin.encoding)(sys.stdin)
116 else:
117 self.enc_stdin = sys.stdin
cliechti9c592b32008-06-16 22:00:14 +0000118
119 def setup(self):
cliechti9c592b32008-06-16 22:00:14 +0000120 new = termios.tcgetattr(self.fd)
121 new[3] = new[3] & ~termios.ICANON & ~termios.ECHO & ~termios.ISIG
122 new[6][termios.VMIN] = 1
123 new[6][termios.VTIME] = 0
124 termios.tcsetattr(self.fd, termios.TCSANOW, new)
cliechti53edb472009-02-06 21:18:46 +0000125
cliechti9c592b32008-06-16 22:00:14 +0000126 def getkey(self):
Chris Liechtia7e7b692015-08-25 21:10:28 +0200127 c = self.enc_stdin.read(1)
Chris Liechti3b454802015-08-26 23:39:59 +0200128 if c == u'\x7f':
129 c = u'\b' # map the BS key (which yields DEL) to backspace
Chris Liechti9a720852015-08-25 00:20:38 +0200130 return c
cliechti53edb472009-02-06 21:18:46 +0000131
cliechti9c592b32008-06-16 22:00:14 +0000132 def cleanup(self):
Chris Liechti4d989c22015-08-24 00:24:49 +0200133 termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old)
cliechti9c592b32008-06-16 22:00:14 +0000134
cliechti576de252002-02-28 23:54:44 +0000135else:
cliechti8c2ea842011-03-18 01:51:46 +0000136 raise NotImplementedError("Sorry no implementation for your platform (%s) available." % sys.platform)
cliechti576de252002-02-28 23:54:44 +0000137
cliechti6fa76fb2009-07-08 23:53:39 +0000138
Chris Liechti9a720852015-08-25 00:20:38 +0200139# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200140
141class Transform(object):
Chris Liechticbb00b22015-08-13 22:58:49 +0200142 """do-nothing: forward all data unchanged"""
Chris Liechtid698af72015-08-24 20:24:55 +0200143 def rx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200144 """text received from serial port"""
145 return text
146
Chris Liechtid698af72015-08-24 20:24:55 +0200147 def tx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200148 """text to be sent to serial port"""
149 return text
150
151 def echo(self, text):
152 """text to be sent but displayed on console"""
153 return text
154
Chris Liechti442bf512015-08-15 01:42:24 +0200155
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200156class CRLF(Transform):
157 """ENTER sends CR+LF"""
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200158
Chris Liechtid698af72015-08-24 20:24:55 +0200159 def tx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200160 return text.replace('\n', '\r\n')
161
Chris Liechti442bf512015-08-15 01:42:24 +0200162
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200163class CR(Transform):
164 """ENTER sends CR"""
Chris Liechtid698af72015-08-24 20:24:55 +0200165
166 def rx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200167 return text.replace('\r', '\n')
168
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')
171
Chris Liechti442bf512015-08-15 01:42:24 +0200172
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200173class LF(Transform):
174 """ENTER sends LF"""
175
176
177class NoTerminal(Transform):
178 """remove typical terminal control codes from input"""
Chris Liechti9a720852015-08-25 00:20:38 +0200179
180 REPLACEMENT_MAP = dict((x, 0x2400 + x) for x in range(32) if unichr(x) not in '\r\n\b\t')
181 REPLACEMENT_MAP.update({
182 0x7F: 0x2421, # DEL
183 0x9B: 0x2425, # CSI
184 })
185
Chris Liechtid698af72015-08-24 20:24:55 +0200186 def rx(self, text):
Chris Liechti9a720852015-08-25 00:20:38 +0200187 return text.translate(self.REPLACEMENT_MAP)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200188
Chris Liechtid698af72015-08-24 20:24:55 +0200189 echo = rx
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200190
191
Chris Liechti9a720852015-08-25 00:20:38 +0200192class NoControls(NoTerminal):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200193 """Remove all control codes, incl. CR+LF"""
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200194
Chris Liechti9a720852015-08-25 00:20:38 +0200195 REPLACEMENT_MAP = dict((x, 0x2400 + x) for x in range(32))
196 REPLACEMENT_MAP.update({
197 32: 0x2423, # visual space
198 0x7F: 0x2421, # DEL
199 0x9B: 0x2425, # CSI
200 })
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200201
202
203class Printable(Transform):
Chris Liechtid698af72015-08-24 20:24:55 +0200204 """Show decimal code for all non-ASCII characters and replace most control codes"""
Chris Liechtic0c660a2015-08-25 00:55:51 +0200205
Chris Liechtid698af72015-08-24 20:24:55 +0200206 def rx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200207 r = []
208 for t in text:
Chris Liechti7e9cfd42015-08-12 15:28:19 +0200209 if ' ' <= t < '\x7f' or t in '\r\n\b\t':
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200210 r.append(t)
Chris Liechtid698af72015-08-24 20:24:55 +0200211 elif t < ' ':
212 r.append(unichr(0x2400 + ord(t)))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200213 else:
214 r.extend(unichr(0x2080 + ord(d) - 48) for d in '{:d}'.format(ord(t)))
215 r.append(' ')
216 return ''.join(r)
217
Chris Liechtid698af72015-08-24 20:24:55 +0200218 echo = rx
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200219
220
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200221class Colorize(Transform):
Chris Liechti442bf512015-08-15 01:42:24 +0200222 """Apply different colors for received and echo"""
Chris Liechtic0c660a2015-08-25 00:55:51 +0200223
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200224 def __init__(self):
225 # XXX make it configurable, use colorama?
226 self.input_color = '\x1b[37m'
227 self.echo_color = '\x1b[31m'
228
Chris Liechtid698af72015-08-24 20:24:55 +0200229 def rx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200230 return self.input_color + text
231
232 def echo(self, text):
233 return self.echo_color + text
234
Chris Liechti442bf512015-08-15 01:42:24 +0200235
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200236class DebugIO(Transform):
Chris Liechti442bf512015-08-15 01:42:24 +0200237 """Print what is sent and received"""
Chris Liechtic0c660a2015-08-25 00:55:51 +0200238
Chris Liechtid698af72015-08-24 20:24:55 +0200239 def rx(self, text):
Chris Liechtie1384382015-08-15 17:06:05 +0200240 sys.stderr.write(' [RX:{}] '.format(repr(text)))
241 sys.stderr.flush()
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200242 return text
243
Chris Liechtid698af72015-08-24 20:24:55 +0200244 def tx(self, text):
Chris Liechtie1384382015-08-15 17:06:05 +0200245 sys.stderr.write(' [TX:{}] '.format(repr(text)))
246 sys.stderr.flush()
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200247 return text
248
Chris Liechti442bf512015-08-15 01:42:24 +0200249
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200250# other ideas:
251# - add date/time for each newline
252# - insert newline after: a) timeout b) packet end character
253
Chris Liechtib3df13e2015-08-25 02:20:09 +0200254EOL_TRANSFORMATIONS = {
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200255 'crlf': CRLF,
256 'cr': CR,
257 'lf': LF,
Chris Liechtib3df13e2015-08-25 02:20:09 +0200258 }
259
260TRANSFORMATIONS = {
Chris Liechticbb00b22015-08-13 22:58:49 +0200261 'direct': Transform, # no transformation
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200262 'default': NoTerminal,
263 'nocontrol': NoControls,
264 'printable': Printable,
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200265 'colorize': Colorize,
266 'debug': DebugIO,
267 }
268
Chris Liechti9a720852015-08-25 00:20:38 +0200269# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200270
cliechti1351dde2012-04-12 16:47:47 +0000271def dump_port_list():
272 if comports:
273 sys.stderr.write('\n--- Available ports:\n')
274 for port, desc, hwid in sorted(comports()):
275 #~ sys.stderr.write('--- %-20s %s [%s]\n' % (port, desc, hwid))
276 sys.stderr.write('--- %-20s %s\n' % (port, desc))
277
278
cliechti8c2ea842011-03-18 01:51:46 +0000279class Miniterm(object):
Chris Liechti3b454802015-08-26 23:39:59 +0200280 def __init__(self, serial_instance, echo=False, eol='crlf', filters=()):
Chris Liechti89eb2472015-08-08 17:06:25 +0200281 self.console = Console()
Chris Liechti3b454802015-08-26 23:39:59 +0200282 self.serial = serial_instance
cliechti6385f2c2005-09-21 19:51:19 +0000283 self.echo = echo
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200284 self.raw = False
Chris Liechti442bf512015-08-15 01:42:24 +0200285 self.input_encoding = 'UTF-8'
Chris Liechti442bf512015-08-15 01:42:24 +0200286 self.output_encoding = 'UTF-8'
Chris Liechtib3df13e2015-08-25 02:20:09 +0200287 self.eol = eol
288 self.filters = filters
289 self.update_transformations()
Chris Liechti442bf512015-08-15 01:42:24 +0200290 self.exit_character = 0x1d # GS/CTRL+]
291 self.menu_character = 0x14 # Menu: CTRL+T
cliechti576de252002-02-28 23:54:44 +0000292
cliechti8c2ea842011-03-18 01:51:46 +0000293 def _start_reader(self):
294 """Start reader thread"""
295 self._reader_alive = True
cliechti6fa76fb2009-07-08 23:53:39 +0000296 # start serial->console thread
Chris Liechti55ba7d92015-08-15 16:33:51 +0200297 self.receiver_thread = threading.Thread(target=self.reader, name='rx')
298 self.receiver_thread.daemon = True
cliechti6385f2c2005-09-21 19:51:19 +0000299 self.receiver_thread.start()
cliechti8c2ea842011-03-18 01:51:46 +0000300
301 def _stop_reader(self):
302 """Stop reader thread only, wait for clean exit of thread"""
303 self._reader_alive = False
304 self.receiver_thread.join()
305
306
307 def start(self):
308 self.alive = True
309 self._start_reader()
cliechti6fa76fb2009-07-08 23:53:39 +0000310 # enter console->serial loop
Chris Liechti55ba7d92015-08-15 16:33:51 +0200311 self.transmitter_thread = threading.Thread(target=self.writer, name='tx')
312 self.transmitter_thread.daemon = True
cliechti6385f2c2005-09-21 19:51:19 +0000313 self.transmitter_thread.start()
Chris Liechti89eb2472015-08-08 17:06:25 +0200314 self.console.setup()
cliechti53edb472009-02-06 21:18:46 +0000315
cliechti6385f2c2005-09-21 19:51:19 +0000316 def stop(self):
317 self.alive = False
cliechti53edb472009-02-06 21:18:46 +0000318
cliechtibf6bb7d2006-03-30 00:28:18 +0000319 def join(self, transmit_only=False):
cliechti6385f2c2005-09-21 19:51:19 +0000320 self.transmitter_thread.join()
cliechtibf6bb7d2006-03-30 00:28:18 +0000321 if not transmit_only:
322 self.receiver_thread.join()
cliechti6385f2c2005-09-21 19:51:19 +0000323
Chris Liechtib3df13e2015-08-25 02:20:09 +0200324 def update_transformations(self):
325 transformations = [EOL_TRANSFORMATIONS[self.eol]] + [TRANSFORMATIONS[f] for f in self.filters]
326 self.tx_transformations = [t() for t in transformations]
327 self.rx_transformations = list(reversed(self.tx_transformations))
328
Chris Liechtid698af72015-08-24 20:24:55 +0200329 def set_rx_encoding(self, encoding, errors='replace'):
330 self.input_encoding = encoding
331 self.rx_decoder = codecs.getincrementaldecoder(encoding)(errors)
332
333 def set_tx_encoding(self, encoding, errors='replace'):
334 self.output_encoding = encoding
335 self.tx_encoder = codecs.getincrementalencoder(encoding)(errors)
336
337
cliechti6c8eb2f2009-07-08 02:10:46 +0000338 def dump_port_settings(self):
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200339 sys.stderr.write("\n--- Settings: {p.name} {p.baudrate},{p.bytesize},{p.parity},{p.stopbits}\n".format(
340 p=self.serial))
Chris Liechti442bf512015-08-15 01:42:24 +0200341 sys.stderr.write('--- RTS: {:8} DTR: {:8} BREAK: {:8}\n'.format(
Chris Liechti3b454802015-08-26 23:39:59 +0200342 ('active' if self.serial.rts else 'inactive'),
343 ('active' if self.serial.dtr else 'inactive'),
344 ('active' if self.serial.break_condition else 'inactive')))
cliechti10114572009-08-05 23:40:50 +0000345 try:
Chris Liechti442bf512015-08-15 01:42:24 +0200346 sys.stderr.write('--- CTS: {:8} DSR: {:8} RI: {:8} CD: {:8}\n'.format(
Chris Liechti3b454802015-08-26 23:39:59 +0200347 ('active' if self.serial.cts else 'inactive'),
348 ('active' if self.serial.dsr else 'inactive'),
349 ('active' if self.serial.ri else 'inactive'),
350 ('active' if self.serial.cd else 'inactive')))
cliechti10114572009-08-05 23:40:50 +0000351 except serial.SerialException:
Chris Liechti55ba7d92015-08-15 16:33:51 +0200352 # on RFC 2217 ports, it can happen if no modem state notification was
cliechti10114572009-08-05 23:40:50 +0000353 # yet received. ignore this error.
354 pass
Chris Liechti442bf512015-08-15 01:42:24 +0200355 sys.stderr.write('--- software flow control: {}\n'.format('active' if self.serial.xonxoff else 'inactive'))
356 sys.stderr.write('--- hardware flow control: {}\n'.format('active' if self.serial.rtscts else 'inactive'))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200357 #~ sys.stderr.write('--- data escaping: %s linefeed: %s\n' % (
358 #~ REPR_MODES[self.repr_mode],
359 #~ LF_MODES[self.convert_outgoing]))
Chris Liechti442bf512015-08-15 01:42:24 +0200360 sys.stderr.write('--- serial input encoding: {}\n'.format(self.input_encoding))
361 sys.stderr.write('--- serial output encoding: {}\n'.format(self.output_encoding))
Chris Liechtib3df13e2015-08-25 02:20:09 +0200362 sys.stderr.write('--- EOL: {}\n'.format(self.eol.upper()))
363 sys.stderr.write('--- filters: {}\n'.format(' '.join(self.filters)))
cliechti6c8eb2f2009-07-08 02:10:46 +0000364
cliechti6385f2c2005-09-21 19:51:19 +0000365 def reader(self):
366 """loop and copy serial->console"""
cliechti6963b262010-01-02 03:01:21 +0000367 try:
cliechti8c2ea842011-03-18 01:51:46 +0000368 while self.alive and self._reader_alive:
Chris Liechti188cf592015-08-22 00:28:19 +0200369 # read all that is there or wait for one byte
Chris Liechti3b454802015-08-26 23:39:59 +0200370 data = self.serial.read(self.serial.in_waiting or 1)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200371 if data:
372 if self.raw:
373 self.console.write_bytes(data)
cliechti6963b262010-01-02 03:01:21 +0000374 else:
Chris Liechtid698af72015-08-24 20:24:55 +0200375 text = self.rx_decoder.decode(data)
Chris Liechtie1384382015-08-15 17:06:05 +0200376 for transformation in self.rx_transformations:
Chris Liechtid698af72015-08-24 20:24:55 +0200377 text = transformation.rx(text)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200378 self.console.write(text)
Chris Liechti68340d72015-08-03 14:15:48 +0200379 except serial.SerialException as e:
cliechti6963b262010-01-02 03:01:21 +0000380 self.alive = False
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200381 # XXX would be nice if the writer could be interrupted at this
382 # point... to exit completely
cliechti6963b262010-01-02 03:01:21 +0000383 raise
cliechti576de252002-02-28 23:54:44 +0000384
cliechti576de252002-02-28 23:54:44 +0000385
cliechti6385f2c2005-09-21 19:51:19 +0000386 def writer(self):
cliechti8c2ea842011-03-18 01:51:46 +0000387 """\
Chris Liechti442bf512015-08-15 01:42:24 +0200388 Loop and copy console->serial until self.exit_character character is
389 found. When self.menu_character is found, interpret the next key
cliechti8c2ea842011-03-18 01:51:46 +0000390 locally.
cliechti6c8eb2f2009-07-08 02:10:46 +0000391 """
392 menu_active = False
393 try:
394 while self.alive:
395 try:
Chris Liechti89eb2472015-08-08 17:06:25 +0200396 c = self.console.getkey()
cliechti6c8eb2f2009-07-08 02:10:46 +0000397 except KeyboardInterrupt:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200398 c = '\x03'
cliechti6c8eb2f2009-07-08 02:10:46 +0000399 if menu_active:
Chris Liechti7af7c752015-08-12 15:45:19 +0200400 self.handle_menu_key(c)
cliechti6c8eb2f2009-07-08 02:10:46 +0000401 menu_active = False
Chris Liechti442bf512015-08-15 01:42:24 +0200402 elif c == self.menu_character:
Chris Liechti7af7c752015-08-12 15:45:19 +0200403 menu_active = True # next char will be for menu
Chris Liechti442bf512015-08-15 01:42:24 +0200404 elif c == self.exit_character:
Chris Liechti7af7c752015-08-12 15:45:19 +0200405 self.stop() # exit app
406 break
cliechti6c8eb2f2009-07-08 02:10:46 +0000407 else:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200408 #~ if self.raw:
409 text = c
Chris Liechtie1384382015-08-15 17:06:05 +0200410 for transformation in self.tx_transformations:
Chris Liechtid698af72015-08-24 20:24:55 +0200411 text = transformation.tx(text)
Chris Liechtid698af72015-08-24 20:24:55 +0200412 self.serial.write(self.tx_encoder.encode(text))
cliechti6c8eb2f2009-07-08 02:10:46 +0000413 if self.echo:
Chris Liechti3b454802015-08-26 23:39:59 +0200414 echo_text = c
415 for transformation in self.tx_transformations:
416 echo_text = transformation.echo(echo_text)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200417 self.console.write(echo_text)
cliechti6c8eb2f2009-07-08 02:10:46 +0000418 except:
419 self.alive = False
420 raise
cliechti6385f2c2005-09-21 19:51:19 +0000421
Chris Liechti7af7c752015-08-12 15:45:19 +0200422 def handle_menu_key(self, c):
423 """Implement a simple menu / settings"""
Chris Liechti55ba7d92015-08-15 16:33:51 +0200424 if c == self.menu_character or c == self.exit_character:
425 # Menu/exit character again -> send itself
Chris Liechtid698af72015-08-24 20:24:55 +0200426 self.serial.write(self.tx_encoder.encode(c))
Chris Liechti7af7c752015-08-12 15:45:19 +0200427 if self.echo:
428 self.console.write(c)
Chris Liechtib7550bd2015-08-15 04:09:10 +0200429 elif c == '\x15': # CTRL+U -> upload file
Chris Liechti7af7c752015-08-12 15:45:19 +0200430 sys.stderr.write('\n--- File to upload: ')
431 sys.stderr.flush()
Chris Liechti269f77b2015-08-24 01:31:42 +0200432 with self.console:
433 filename = sys.stdin.readline().rstrip('\r\n')
434 if filename:
435 try:
436 with open(filename, 'rb') as f:
437 sys.stderr.write('--- Sending file {} ---\n'.format(filename))
438 while True:
439 block = f.read(1024)
440 if not block:
441 break
442 self.serial.write(block)
443 # Wait for output buffer to drain.
444 self.serial.flush()
445 sys.stderr.write('.') # Progress indicator.
446 sys.stderr.write('\n--- File {} sent ---\n'.format(filename))
447 except IOError as e:
448 sys.stderr.write('--- ERROR opening file {}: {} ---\n'.format(filename, e))
Chris Liechti7af7c752015-08-12 15:45:19 +0200449 elif c in '\x08hH?': # CTRL+H, h, H, ? -> Show help
Chris Liechti442bf512015-08-15 01:42:24 +0200450 sys.stderr.write(self.get_help_text())
Chris Liechti7af7c752015-08-12 15:45:19 +0200451 elif c == '\x12': # CTRL+R -> Toggle RTS
Chris Liechti3b454802015-08-26 23:39:59 +0200452 self.serial.rts = not self.serial.rts
453 sys.stderr.write('--- RTS {} ---\n'.format('active' if self.serial.rts else 'inactive'))
Chris Liechti7af7c752015-08-12 15:45:19 +0200454 elif c == '\x04': # CTRL+D -> Toggle DTR
Chris Liechti3b454802015-08-26 23:39:59 +0200455 self.serial.dtr = not self.serial.dtr
456 sys.stderr.write('--- DTR {} ---\n'.format('active' if self.serial.dtr else 'inactive'))
Chris Liechti7af7c752015-08-12 15:45:19 +0200457 elif c == '\x02': # CTRL+B -> toggle BREAK condition
Chris Liechti3b454802015-08-26 23:39:59 +0200458 self.serial.break_condition = not self.serial.break_condition
459 sys.stderr.write('--- BREAK {} ---\n'.format('active' if self.serial.break_condition else 'inactive'))
Chris Liechti7af7c752015-08-12 15:45:19 +0200460 elif c == '\x05': # CTRL+E -> toggle local echo
461 self.echo = not self.echo
Chris Liechti442bf512015-08-15 01:42:24 +0200462 sys.stderr.write('--- local echo {} ---\n'.format('active' if self.echo else 'inactive'))
Chris Liechtib3df13e2015-08-25 02:20:09 +0200463 elif c == '\x06': # CTRL+F -> edit filters
464 sys.stderr.write('\n--- Available Filters:\n')
465 sys.stderr.write('\n'.join(
466 '--- {:<10} = {.__doc__}'.format(k, v)
467 for k, v in sorted(TRANSFORMATIONS.items())))
468 sys.stderr.write('\n--- Enter new filter name(s) [{}]: '.format(' '.join(self.filters)))
469 with self.console:
470 new_filters = sys.stdin.readline().lower().split()
471 if new_filters:
472 for f in new_filters:
473 if f not in TRANSFORMATIONS:
474 sys.stderr.write('--- unknown filter: {}'.format(repr(f)))
475 break
476 else:
477 self.filters = new_filters
478 self.update_transformations()
479 sys.stderr.write('--- filters: {}\n'.format(' '.join(self.filters)))
480 elif c == '\x0c': # CTRL+L -> EOL mode
481 modes = list(EOL_TRANSFORMATIONS) # keys
482 eol = modes.index(self.eol) + 1
483 if eol >= len(modes):
484 eol = 0
485 self.eol = modes[eol]
486 sys.stderr.write('--- EOL: {} ---\n'.format(self.eol.upper()))
487 self.update_transformations()
488 elif c == '\x01': # CTRL+A -> set encoding
489 sys.stderr.write('\n--- Enter new encoding name [{}]: '.format(self.input_encoding))
490 with self.console:
491 new_encoding = sys.stdin.readline().strip()
492 if new_encoding:
493 try:
494 codecs.lookup(new_encoding)
495 except LookupError:
496 sys.stderr.write('--- invalid encoding name: {}\n'.format(new_encoding))
497 else:
498 self.set_rx_encoding(new_encoding)
499 self.set_tx_encoding(new_encoding)
500 sys.stderr.write('--- serial input encoding: {}\n'.format(self.input_encoding))
501 sys.stderr.write('--- serial output encoding: {}\n'.format(self.output_encoding))
Chris Liechti7af7c752015-08-12 15:45:19 +0200502 elif c == '\x09': # CTRL+I -> info
503 self.dump_port_settings()
504 #~ elif c == '\x01': # CTRL+A -> cycle escape mode
505 #~ elif c == '\x0c': # CTRL+L -> cycle linefeed mode
506 elif c in 'pP': # P -> change port
507 dump_port_list()
508 sys.stderr.write('--- Enter port name: ')
509 sys.stderr.flush()
Chris Liechti269f77b2015-08-24 01:31:42 +0200510 with self.console:
511 try:
512 port = sys.stdin.readline().strip()
513 except KeyboardInterrupt:
514 port = None
Chris Liechti7af7c752015-08-12 15:45:19 +0200515 if port and port != self.serial.port:
516 # reader thread needs to be shut down
517 self._stop_reader()
518 # save settings
519 settings = self.serial.getSettingsDict()
520 try:
521 new_serial = serial.serial_for_url(port, do_not_open=True)
522 # restore settings and open
523 new_serial.applySettingsDict(settings)
524 new_serial.open()
525 new_serial.setRTS(self.rts_state)
526 new_serial.setDTR(self.dtr_state)
527 new_serial.setBreak(self.break_state)
528 except Exception as e:
Chris Liechti442bf512015-08-15 01:42:24 +0200529 sys.stderr.write('--- ERROR opening new port: {} ---\n'.format(e))
Chris Liechti7af7c752015-08-12 15:45:19 +0200530 new_serial.close()
531 else:
532 self.serial.close()
533 self.serial = new_serial
Chris Liechti442bf512015-08-15 01:42:24 +0200534 sys.stderr.write('--- Port changed to: {} ---\n'.format(self.serial.port))
Chris Liechti7af7c752015-08-12 15:45:19 +0200535 # and restart the reader thread
536 self._start_reader()
537 elif c in 'bB': # B -> change baudrate
538 sys.stderr.write('\n--- Baudrate: ')
539 sys.stderr.flush()
Chris Liechti269f77b2015-08-24 01:31:42 +0200540 with self.console:
541 backup = self.serial.baudrate
542 try:
543 self.serial.baudrate = int(sys.stdin.readline().strip())
544 except ValueError as e:
545 sys.stderr.write('--- ERROR setting baudrate: %s ---\n'.format(e))
546 self.serial.baudrate = backup
547 else:
548 self.dump_port_settings()
Chris Liechti7af7c752015-08-12 15:45:19 +0200549 elif c == '8': # 8 -> change to 8 bits
550 self.serial.bytesize = serial.EIGHTBITS
551 self.dump_port_settings()
552 elif c == '7': # 7 -> change to 8 bits
553 self.serial.bytesize = serial.SEVENBITS
554 self.dump_port_settings()
555 elif c in 'eE': # E -> change to even parity
556 self.serial.parity = serial.PARITY_EVEN
557 self.dump_port_settings()
558 elif c in 'oO': # O -> change to odd parity
559 self.serial.parity = serial.PARITY_ODD
560 self.dump_port_settings()
561 elif c in 'mM': # M -> change to mark parity
562 self.serial.parity = serial.PARITY_MARK
563 self.dump_port_settings()
564 elif c in 'sS': # S -> change to space parity
565 self.serial.parity = serial.PARITY_SPACE
566 self.dump_port_settings()
567 elif c in 'nN': # N -> change to no parity
568 self.serial.parity = serial.PARITY_NONE
569 self.dump_port_settings()
570 elif c == '1': # 1 -> change to 1 stop bits
571 self.serial.stopbits = serial.STOPBITS_ONE
572 self.dump_port_settings()
573 elif c == '2': # 2 -> change to 2 stop bits
574 self.serial.stopbits = serial.STOPBITS_TWO
575 self.dump_port_settings()
576 elif c == '3': # 3 -> change to 1.5 stop bits
577 self.serial.stopbits = serial.STOPBITS_ONE_POINT_FIVE
578 self.dump_port_settings()
579 elif c in 'xX': # X -> change software flow control
580 self.serial.xonxoff = (c == 'X')
581 self.dump_port_settings()
582 elif c in 'rR': # R -> change hardware flow control
583 self.serial.rtscts = (c == 'R')
584 self.dump_port_settings()
585 else:
Chris Liechti442bf512015-08-15 01:42:24 +0200586 sys.stderr.write('--- unknown menu character {} --\n'.format(key_description(c)))
587
588 def get_help_text(self):
Chris Liechti55ba7d92015-08-15 16:33:51 +0200589 # help text, starts with blank line!
Chris Liechti442bf512015-08-15 01:42:24 +0200590 return """
591--- pySerial ({version}) - miniterm - help
592---
593--- {exit:8} Exit program
594--- {menu:8} Menu escape key, followed by:
595--- Menu keys:
596--- {menu:7} Send the menu character itself to remote
597--- {exit:7} Send the exit character itself to remote
598--- {info:7} Show info
599--- {upload:7} Upload file (prompt will be shown)
Chris Liechtib3df13e2015-08-25 02:20:09 +0200600--- {repr:7} encoding
601--- {filter:7} edit filters
Chris Liechti442bf512015-08-15 01:42:24 +0200602--- Toggles:
Chris Liechtib3df13e2015-08-25 02:20:09 +0200603--- {rts:7} RTS {dtr:7} DTR {brk:7} BREAK
604--- {echo:7} echo {eol:7} EOL
Chris Liechti442bf512015-08-15 01:42:24 +0200605---
Chris Liechti55ba7d92015-08-15 16:33:51 +0200606--- Port settings ({menu} followed by the following):
Chris Liechti442bf512015-08-15 01:42:24 +0200607--- p change port
608--- 7 8 set data bits
Chris Liechtib7550bd2015-08-15 04:09:10 +0200609--- N E O S M change parity (None, Even, Odd, Space, Mark)
Chris Liechti442bf512015-08-15 01:42:24 +0200610--- 1 2 3 set stop bits (1, 2, 1.5)
611--- b change baud rate
612--- x X disable/enable software flow control
613--- r R disable/enable hardware flow control
614""".format(
615 version=getattr(serial, 'VERSION', 'unknown version'),
616 exit=key_description(self.exit_character),
617 menu=key_description(self.menu_character),
Chris Liechtib7550bd2015-08-15 04:09:10 +0200618 rts=key_description('\x12'),
619 dtr=key_description('\x04'),
620 brk=key_description('\x02'),
621 echo=key_description('\x05'),
622 info=key_description('\x09'),
623 upload=key_description('\x15'),
Chris Liechtib3df13e2015-08-25 02:20:09 +0200624 repr=key_description('\x01'),
625 filter=key_description('\x06'),
626 eol=key_description('\x0c'),
Chris Liechti442bf512015-08-15 01:42:24 +0200627 )
Chris Liechti7af7c752015-08-12 15:45:19 +0200628
629
630
Chris Liechtib3df13e2015-08-25 02:20:09 +0200631# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechti55ba7d92015-08-15 16:33:51 +0200632# default args can be used to override when calling main() from an other script
633# e.g to create a miniterm-my-device.py
634def main(default_port=None, default_baudrate=9600, default_rts=None, default_dtr=None):
Chris Liechtib7550bd2015-08-15 04:09:10 +0200635 import argparse
cliechti6385f2c2005-09-21 19:51:19 +0000636
Chris Liechtib7550bd2015-08-15 04:09:10 +0200637 parser = argparse.ArgumentParser(
638 description="Miniterm - A simple terminal program for the serial port.")
cliechti6385f2c2005-09-21 19:51:19 +0000639
Chris Liechtib7550bd2015-08-15 04:09:10 +0200640 parser.add_argument("port",
641 nargs='?',
642 help="serial port name",
Chris Liechti55ba7d92015-08-15 16:33:51 +0200643 default=default_port)
cliechti5370cee2013-10-13 03:08:19 +0000644
Chris Liechtib7550bd2015-08-15 04:09:10 +0200645 parser.add_argument("baudrate",
646 nargs='?',
647 type=int,
648 help="set baud rate, default: %(default)s",
Chris Liechti55ba7d92015-08-15 16:33:51 +0200649 default=default_baudrate)
cliechti6385f2c2005-09-21 19:51:19 +0000650
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200651 group = parser.add_argument_group("port settings")
cliechti53edb472009-02-06 21:18:46 +0000652
Chris Liechtib7550bd2015-08-15 04:09:10 +0200653 group.add_argument("--parity",
654 choices=['N', 'E', 'O', 'S', 'M'],
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200655 type=lambda c: c.upper(),
Chris Liechtib7550bd2015-08-15 04:09:10 +0200656 help="set parity, one of {N E O S M}, default: N",
657 default='N')
cliechti53edb472009-02-06 21:18:46 +0000658
Chris Liechtib7550bd2015-08-15 04:09:10 +0200659 group.add_argument("--rtscts",
660 action="store_true",
661 help="enable RTS/CTS flow control (default off)",
662 default=False)
cliechti53edb472009-02-06 21:18:46 +0000663
Chris Liechtib7550bd2015-08-15 04:09:10 +0200664 group.add_argument("--xonxoff",
665 action="store_true",
666 help="enable software flow control (default off)",
667 default=False)
cliechti53edb472009-02-06 21:18:46 +0000668
Chris Liechtib7550bd2015-08-15 04:09:10 +0200669 group.add_argument("--rts",
670 type=int,
671 help="set initial RTS line state (possible values: 0, 1)",
Chris Liechti55ba7d92015-08-15 16:33:51 +0200672 default=default_rts)
cliechti5370cee2013-10-13 03:08:19 +0000673
Chris Liechtib7550bd2015-08-15 04:09:10 +0200674 group.add_argument("--dtr",
675 type=int,
676 help="set initial DTR line state (possible values: 0, 1)",
Chris Liechti55ba7d92015-08-15 16:33:51 +0200677 default=default_dtr)
cliechti5370cee2013-10-13 03:08:19 +0000678
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200679 group = parser.add_argument_group("data handling")
cliechti5370cee2013-10-13 03:08:19 +0000680
Chris Liechtib7550bd2015-08-15 04:09:10 +0200681 group.add_argument("-e", "--echo",
682 action="store_true",
683 help="enable local echo (default off)",
684 default=False)
cliechti5370cee2013-10-13 03:08:19 +0000685
Chris Liechtib7550bd2015-08-15 04:09:10 +0200686 group.add_argument("--encoding",
687 dest="serial_port_encoding",
688 metavar="CODEC",
Chris Liechtia7e7b692015-08-25 21:10:28 +0200689 help="set the encoding for the serial port (e.g. hexlify, Latin1, UTF-8), default: %(default)s",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200690 default='UTF-8')
cliechti5370cee2013-10-13 03:08:19 +0000691
Chris Liechtib3df13e2015-08-25 02:20:09 +0200692 group.add_argument("-f", "--filter",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200693 action="append",
694 metavar="NAME",
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200695 help="add text transformation",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200696 default=[])
Chris Liechti2b1b3552015-08-12 15:35:33 +0200697
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200698 group.add_argument("--eol",
699 choices=['CR', 'LF', 'CRLF'],
700 type=lambda c: c.upper(),
701 help="end of line mode",
702 default='CRLF')
cliechti53edb472009-02-06 21:18:46 +0000703
Chris Liechtib7550bd2015-08-15 04:09:10 +0200704 group.add_argument("--raw",
705 action="store_true",
706 help="Do no apply any encodings/transformations",
707 default=False)
cliechti6385f2c2005-09-21 19:51:19 +0000708
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200709 group = parser.add_argument_group("hotkeys")
cliechtib7d746d2006-03-28 22:44:30 +0000710
Chris Liechtib7550bd2015-08-15 04:09:10 +0200711 group.add_argument("--exit-char",
712 type=int,
Chris Liechti55ba7d92015-08-15 16:33:51 +0200713 metavar='NUM',
714 help="Unicode of special character that is used to exit the application, default: %(default)s",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200715 default=0x1d # GS/CTRL+]
716 )
cliechtibf6bb7d2006-03-30 00:28:18 +0000717
Chris Liechtib7550bd2015-08-15 04:09:10 +0200718 group.add_argument("--menu-char",
719 type=int,
Chris Liechti55ba7d92015-08-15 16:33:51 +0200720 metavar='NUM',
721 help="Unicode code of special character that is used to control miniterm (menu), default: %(default)s",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200722 default=0x14 # Menu: CTRL+T
723 )
cliechti9c592b32008-06-16 22:00:14 +0000724
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200725 group = parser.add_argument_group("diagnostics")
cliechti6385f2c2005-09-21 19:51:19 +0000726
Chris Liechtib7550bd2015-08-15 04:09:10 +0200727 group.add_argument("-q", "--quiet",
728 action="store_true",
729 help="suppress non-error messages",
730 default=False)
cliechti5370cee2013-10-13 03:08:19 +0000731
Chris Liechtib7550bd2015-08-15 04:09:10 +0200732 group.add_argument("--develop",
733 action="store_true",
734 help="show Python traceback on error",
735 default=False)
cliechti5370cee2013-10-13 03:08:19 +0000736
Chris Liechtib7550bd2015-08-15 04:09:10 +0200737 args = parser.parse_args()
cliechti5370cee2013-10-13 03:08:19 +0000738
Chris Liechtib7550bd2015-08-15 04:09:10 +0200739 if args.menu_char == args.exit_char:
cliechti6c8eb2f2009-07-08 02:10:46 +0000740 parser.error('--exit-char can not be the same as --menu-char')
741
cliechti9c592b32008-06-16 22:00:14 +0000742
Chris Liechtib7550bd2015-08-15 04:09:10 +0200743 # no port given on command line -> ask user now
744 if args.port is None:
745 dump_port_list()
746 args.port = raw_input('Enter port name:')
cliechti53edb472009-02-06 21:18:46 +0000747
Chris Liechtib3df13e2015-08-25 02:20:09 +0200748 if args.filter:
749 if 'help' in args.filter:
750 sys.stderr.write('Available filters:\n')
Chris Liechti442bf512015-08-15 01:42:24 +0200751 sys.stderr.write('\n'.join(
Chris Liechtib3df13e2015-08-25 02:20:09 +0200752 '{:<10} = {.__doc__}'.format(k, v)
Chris Liechtib7550bd2015-08-15 04:09:10 +0200753 for k, v in sorted(TRANSFORMATIONS.items())))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200754 sys.stderr.write('\n')
755 sys.exit(1)
Chris Liechtib3df13e2015-08-25 02:20:09 +0200756 filters = args.filter
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200757 else:
Chris Liechtib3df13e2015-08-25 02:20:09 +0200758 filters = ['default']
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200759
cliechti6385f2c2005-09-21 19:51:19 +0000760
761 try:
Chris Liechti3b454802015-08-26 23:39:59 +0200762 serial_instance = serial.serial_for_url(
Chris Liechtib7550bd2015-08-15 04:09:10 +0200763 args.port,
764 args.baudrate,
Chris Liechti3b454802015-08-26 23:39:59 +0200765 parity=args.parity,
Chris Liechtib7550bd2015-08-15 04:09:10 +0200766 rtscts=args.rtscts,
767 xonxoff=args.xonxoff,
Chris Liechti3b454802015-08-26 23:39:59 +0200768 timeout=1,
769 do_not_open=True)
770
771 if args.dtr is not None:
772 if not args.quiet:
773 sys.stderr.write('--- forcing DTR {}\n'.format('active' if args.dtr else 'inactive'))
774 serial_instance.dtr = args.dtr
775 if args.rts is not None:
776 if not args.quiet:
777 sys.stderr.write('--- forcing RTS {}\n'.format('active' if args.rts else 'inactive'))
778 serial_instance.rts = args.rts
779
780 serial_instance.open()
Chris Liechti68340d72015-08-03 14:15:48 +0200781 except serial.SerialException as e:
Chris Liechtiaccd2012015-08-17 03:09:23 +0200782 sys.stderr.write('could not open port {}: {}\n'.format(repr(args.port), e))
Chris Liechtib7550bd2015-08-15 04:09:10 +0200783 if args.develop:
Chris Liechti91090912015-08-05 02:36:14 +0200784 raise
cliechti6385f2c2005-09-21 19:51:19 +0000785 sys.exit(1)
786
Chris Liechti3b454802015-08-26 23:39:59 +0200787 miniterm = Miniterm(
788 serial_instance,
789 echo=args.echo,
790 eol=args.eol.lower(),
791 filters=filters)
792 miniterm.exit_character = unichr(args.exit_char)
793 miniterm.menu_character = unichr(args.menu_char)
794 miniterm.raw = args.raw
795 miniterm.set_rx_encoding(args.serial_port_encoding)
796 miniterm.set_tx_encoding(args.serial_port_encoding)
797
Chris Liechtib7550bd2015-08-15 04:09:10 +0200798 if not args.quiet:
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200799 sys.stderr.write('--- Miniterm on {p.name} {p.baudrate},{p.bytesize},{p.parity},{p.stopbits} ---\n'.format(
800 p=miniterm.serial))
Chris Liechtib7550bd2015-08-15 04:09:10 +0200801 sys.stderr.write('--- Quit: {} | Menu: {} | Help: {} followed by {} ---\n'.format(
Chris Liechti442bf512015-08-15 01:42:24 +0200802 key_description(miniterm.exit_character),
803 key_description(miniterm.menu_character),
804 key_description(miniterm.menu_character),
Chris Liechtib7550bd2015-08-15 04:09:10 +0200805 key_description('\x08'),
Chris Liechti442bf512015-08-15 01:42:24 +0200806 ))
cliechti6fa76fb2009-07-08 23:53:39 +0000807
cliechti6385f2c2005-09-21 19:51:19 +0000808 miniterm.start()
cliechti258ab0a2011-03-21 23:03:45 +0000809 try:
810 miniterm.join(True)
811 except KeyboardInterrupt:
812 pass
Chris Liechtib7550bd2015-08-15 04:09:10 +0200813 if not args.quiet:
cliechtibf6bb7d2006-03-30 00:28:18 +0000814 sys.stderr.write("\n--- exit ---\n")
cliechti6385f2c2005-09-21 19:51:19 +0000815 miniterm.join()
cliechtibf6bb7d2006-03-30 00:28:18 +0000816
cliechti5370cee2013-10-13 03:08:19 +0000817# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
cliechti8b3ad392002-03-03 20:12:21 +0000818if __name__ == '__main__':
cliechti6385f2c2005-09-21 19:51:19 +0000819 main()