blob: e9fe2f9e365f0b43e1026b7a9c0fd34da253f7c3 [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()
98 if z == '\r':
99 return '\n'
100 elif z in '\x00\x0e': # functions keys, ignore
101 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 Liechti9a720852015-08-25 00:20:38 +0200128 if c == '\x7f':
129 c = '\b' # map the BS key (which yields DEL) to backspace
130 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 Liechtib3df13e2015-08-25 02:20:09 +0200280 def __init__(self, port, baudrate, parity, rtscts, xonxoff, echo=False, eol='crlf', filters=()):
Chris Liechti89eb2472015-08-08 17:06:25 +0200281 self.console = Console()
Chris Liechtia1d5c6d2015-08-07 14:41:24 +0200282 self.serial = serial.serial_for_url(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1)
cliechti6385f2c2005-09-21 19:51:19 +0000283 self.echo = echo
cliechti6c8eb2f2009-07-08 02:10:46 +0000284 self.dtr_state = True
285 self.rts_state = True
286 self.break_state = False
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200287 self.raw = False
Chris Liechti442bf512015-08-15 01:42:24 +0200288 self.input_encoding = 'UTF-8'
Chris Liechti442bf512015-08-15 01:42:24 +0200289 self.output_encoding = 'UTF-8'
Chris Liechtib3df13e2015-08-25 02:20:09 +0200290 self.eol = eol
291 self.filters = filters
292 self.update_transformations()
Chris Liechti442bf512015-08-15 01:42:24 +0200293 self.exit_character = 0x1d # GS/CTRL+]
294 self.menu_character = 0x14 # Menu: CTRL+T
cliechti576de252002-02-28 23:54:44 +0000295
cliechti8c2ea842011-03-18 01:51:46 +0000296 def _start_reader(self):
297 """Start reader thread"""
298 self._reader_alive = True
cliechti6fa76fb2009-07-08 23:53:39 +0000299 # start serial->console thread
Chris Liechti55ba7d92015-08-15 16:33:51 +0200300 self.receiver_thread = threading.Thread(target=self.reader, name='rx')
301 self.receiver_thread.daemon = True
cliechti6385f2c2005-09-21 19:51:19 +0000302 self.receiver_thread.start()
cliechti8c2ea842011-03-18 01:51:46 +0000303
304 def _stop_reader(self):
305 """Stop reader thread only, wait for clean exit of thread"""
306 self._reader_alive = False
307 self.receiver_thread.join()
308
309
310 def start(self):
311 self.alive = True
312 self._start_reader()
cliechti6fa76fb2009-07-08 23:53:39 +0000313 # enter console->serial loop
Chris Liechti55ba7d92015-08-15 16:33:51 +0200314 self.transmitter_thread = threading.Thread(target=self.writer, name='tx')
315 self.transmitter_thread.daemon = True
cliechti6385f2c2005-09-21 19:51:19 +0000316 self.transmitter_thread.start()
Chris Liechti89eb2472015-08-08 17:06:25 +0200317 self.console.setup()
cliechti53edb472009-02-06 21:18:46 +0000318
cliechti6385f2c2005-09-21 19:51:19 +0000319 def stop(self):
320 self.alive = False
cliechti53edb472009-02-06 21:18:46 +0000321
cliechtibf6bb7d2006-03-30 00:28:18 +0000322 def join(self, transmit_only=False):
cliechti6385f2c2005-09-21 19:51:19 +0000323 self.transmitter_thread.join()
cliechtibf6bb7d2006-03-30 00:28:18 +0000324 if not transmit_only:
325 self.receiver_thread.join()
cliechti6385f2c2005-09-21 19:51:19 +0000326
Chris Liechtib3df13e2015-08-25 02:20:09 +0200327 def update_transformations(self):
328 transformations = [EOL_TRANSFORMATIONS[self.eol]] + [TRANSFORMATIONS[f] for f in self.filters]
329 self.tx_transformations = [t() for t in transformations]
330 self.rx_transformations = list(reversed(self.tx_transformations))
331
Chris Liechtid698af72015-08-24 20:24:55 +0200332 def set_rx_encoding(self, encoding, errors='replace'):
333 self.input_encoding = encoding
334 self.rx_decoder = codecs.getincrementaldecoder(encoding)(errors)
335
336 def set_tx_encoding(self, encoding, errors='replace'):
337 self.output_encoding = encoding
338 self.tx_encoder = codecs.getincrementalencoder(encoding)(errors)
339
340
cliechti6c8eb2f2009-07-08 02:10:46 +0000341 def dump_port_settings(self):
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200342 sys.stderr.write("\n--- Settings: {p.name} {p.baudrate},{p.bytesize},{p.parity},{p.stopbits}\n".format(
343 p=self.serial))
Chris Liechti442bf512015-08-15 01:42:24 +0200344 sys.stderr.write('--- RTS: {:8} DTR: {:8} BREAK: {:8}\n'.format(
345 ('active' if self.rts_state else 'inactive'),
346 ('active' if self.dtr_state else 'inactive'),
347 ('active' if self.break_state else 'inactive')))
cliechti10114572009-08-05 23:40:50 +0000348 try:
Chris Liechti442bf512015-08-15 01:42:24 +0200349 sys.stderr.write('--- CTS: {:8} DSR: {:8} RI: {:8} CD: {:8}\n'.format(
350 ('active' if self.serial.getCTS() else 'inactive'),
351 ('active' if self.serial.getDSR() else 'inactive'),
352 ('active' if self.serial.getRI() else 'inactive'),
353 ('active' if self.serial.getCD() else 'inactive')))
cliechti10114572009-08-05 23:40:50 +0000354 except serial.SerialException:
Chris Liechti55ba7d92015-08-15 16:33:51 +0200355 # on RFC 2217 ports, it can happen if no modem state notification was
cliechti10114572009-08-05 23:40:50 +0000356 # yet received. ignore this error.
357 pass
Chris Liechti442bf512015-08-15 01:42:24 +0200358 sys.stderr.write('--- software flow control: {}\n'.format('active' if self.serial.xonxoff else 'inactive'))
359 sys.stderr.write('--- hardware flow control: {}\n'.format('active' if self.serial.rtscts else 'inactive'))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200360 #~ sys.stderr.write('--- data escaping: %s linefeed: %s\n' % (
361 #~ REPR_MODES[self.repr_mode],
362 #~ LF_MODES[self.convert_outgoing]))
Chris Liechti442bf512015-08-15 01:42:24 +0200363 sys.stderr.write('--- serial input encoding: {}\n'.format(self.input_encoding))
364 sys.stderr.write('--- serial output encoding: {}\n'.format(self.output_encoding))
Chris Liechtib3df13e2015-08-25 02:20:09 +0200365 sys.stderr.write('--- EOL: {}\n'.format(self.eol.upper()))
366 sys.stderr.write('--- filters: {}\n'.format(' '.join(self.filters)))
cliechti6c8eb2f2009-07-08 02:10:46 +0000367
cliechti6385f2c2005-09-21 19:51:19 +0000368 def reader(self):
369 """loop and copy serial->console"""
cliechti6963b262010-01-02 03:01:21 +0000370 try:
cliechti8c2ea842011-03-18 01:51:46 +0000371 while self.alive and self._reader_alive:
Chris Liechti188cf592015-08-22 00:28:19 +0200372 # read all that is there or wait for one byte
373 data = self.serial.read(self.serial.inWaiting() or 1)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200374 if data:
375 if self.raw:
376 self.console.write_bytes(data)
cliechti6963b262010-01-02 03:01:21 +0000377 else:
Chris Liechtid698af72015-08-24 20:24:55 +0200378 text = self.rx_decoder.decode(data)
Chris Liechtie1384382015-08-15 17:06:05 +0200379 for transformation in self.rx_transformations:
Chris Liechtid698af72015-08-24 20:24:55 +0200380 text = transformation.rx(text)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200381 self.console.write(text)
Chris Liechti68340d72015-08-03 14:15:48 +0200382 except serial.SerialException as e:
cliechti6963b262010-01-02 03:01:21 +0000383 self.alive = False
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200384 # XXX would be nice if the writer could be interrupted at this
385 # point... to exit completely
cliechti6963b262010-01-02 03:01:21 +0000386 raise
cliechti576de252002-02-28 23:54:44 +0000387
cliechti576de252002-02-28 23:54:44 +0000388
cliechti6385f2c2005-09-21 19:51:19 +0000389 def writer(self):
cliechti8c2ea842011-03-18 01:51:46 +0000390 """\
Chris Liechti442bf512015-08-15 01:42:24 +0200391 Loop and copy console->serial until self.exit_character character is
392 found. When self.menu_character is found, interpret the next key
cliechti8c2ea842011-03-18 01:51:46 +0000393 locally.
cliechti6c8eb2f2009-07-08 02:10:46 +0000394 """
395 menu_active = False
396 try:
397 while self.alive:
398 try:
Chris Liechti89eb2472015-08-08 17:06:25 +0200399 c = self.console.getkey()
cliechti6c8eb2f2009-07-08 02:10:46 +0000400 except KeyboardInterrupt:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200401 c = '\x03'
cliechti6c8eb2f2009-07-08 02:10:46 +0000402 if menu_active:
Chris Liechti7af7c752015-08-12 15:45:19 +0200403 self.handle_menu_key(c)
cliechti6c8eb2f2009-07-08 02:10:46 +0000404 menu_active = False
Chris Liechti442bf512015-08-15 01:42:24 +0200405 elif c == self.menu_character:
Chris Liechti7af7c752015-08-12 15:45:19 +0200406 menu_active = True # next char will be for menu
Chris Liechti442bf512015-08-15 01:42:24 +0200407 elif c == self.exit_character:
Chris Liechti7af7c752015-08-12 15:45:19 +0200408 self.stop() # exit app
409 break
cliechti6c8eb2f2009-07-08 02:10:46 +0000410 else:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200411 #~ if self.raw:
412 text = c
413 echo_text = text
Chris Liechtie1384382015-08-15 17:06:05 +0200414 for transformation in self.tx_transformations:
Chris Liechtid698af72015-08-24 20:24:55 +0200415 text = transformation.tx(text)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200416 echo_text = transformation.echo(echo_text)
Chris Liechtid698af72015-08-24 20:24:55 +0200417 self.serial.write(self.tx_encoder.encode(text))
cliechti6c8eb2f2009-07-08 02:10:46 +0000418 if self.echo:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200419 self.console.write(echo_text)
cliechti6c8eb2f2009-07-08 02:10:46 +0000420 except:
421 self.alive = False
422 raise
cliechti6385f2c2005-09-21 19:51:19 +0000423
Chris Liechti7af7c752015-08-12 15:45:19 +0200424 def handle_menu_key(self, c):
425 """Implement a simple menu / settings"""
Chris Liechti55ba7d92015-08-15 16:33:51 +0200426 if c == self.menu_character or c == self.exit_character:
427 # Menu/exit character again -> send itself
Chris Liechtid698af72015-08-24 20:24:55 +0200428 self.serial.write(self.tx_encoder.encode(c))
Chris Liechti7af7c752015-08-12 15:45:19 +0200429 if self.echo:
430 self.console.write(c)
Chris Liechtib7550bd2015-08-15 04:09:10 +0200431 elif c == '\x15': # CTRL+U -> upload file
Chris Liechti7af7c752015-08-12 15:45:19 +0200432 sys.stderr.write('\n--- File to upload: ')
433 sys.stderr.flush()
Chris Liechti269f77b2015-08-24 01:31:42 +0200434 with self.console:
435 filename = sys.stdin.readline().rstrip('\r\n')
436 if filename:
437 try:
438 with open(filename, 'rb') as f:
439 sys.stderr.write('--- Sending file {} ---\n'.format(filename))
440 while True:
441 block = f.read(1024)
442 if not block:
443 break
444 self.serial.write(block)
445 # Wait for output buffer to drain.
446 self.serial.flush()
447 sys.stderr.write('.') # Progress indicator.
448 sys.stderr.write('\n--- File {} sent ---\n'.format(filename))
449 except IOError as e:
450 sys.stderr.write('--- ERROR opening file {}: {} ---\n'.format(filename, e))
Chris Liechti7af7c752015-08-12 15:45:19 +0200451 elif c in '\x08hH?': # CTRL+H, h, H, ? -> Show help
Chris Liechti442bf512015-08-15 01:42:24 +0200452 sys.stderr.write(self.get_help_text())
Chris Liechti7af7c752015-08-12 15:45:19 +0200453 elif c == '\x12': # CTRL+R -> Toggle RTS
454 self.rts_state = not self.rts_state
455 self.serial.setRTS(self.rts_state)
Chris Liechti442bf512015-08-15 01:42:24 +0200456 sys.stderr.write('--- RTS {} ---\n'.format('active' if self.rts_state else 'inactive'))
Chris Liechti7af7c752015-08-12 15:45:19 +0200457 elif c == '\x04': # CTRL+D -> Toggle DTR
458 self.dtr_state = not self.dtr_state
459 self.serial.setDTR(self.dtr_state)
Chris Liechti442bf512015-08-15 01:42:24 +0200460 sys.stderr.write('--- DTR {} ---\n'.format('active' if self.dtr_state else 'inactive'))
Chris Liechti7af7c752015-08-12 15:45:19 +0200461 elif c == '\x02': # CTRL+B -> toggle BREAK condition
462 self.break_state = not self.break_state
463 self.serial.setBreak(self.break_state)
Chris Liechti442bf512015-08-15 01:42:24 +0200464 sys.stderr.write('--- BREAK {} ---\n'.format('active' if self.break_state else 'inactive'))
Chris Liechti7af7c752015-08-12 15:45:19 +0200465 elif c == '\x05': # CTRL+E -> toggle local echo
466 self.echo = not self.echo
Chris Liechti442bf512015-08-15 01:42:24 +0200467 sys.stderr.write('--- local echo {} ---\n'.format('active' if self.echo else 'inactive'))
Chris Liechtib3df13e2015-08-25 02:20:09 +0200468 elif c == '\x06': # CTRL+F -> edit filters
469 sys.stderr.write('\n--- Available Filters:\n')
470 sys.stderr.write('\n'.join(
471 '--- {:<10} = {.__doc__}'.format(k, v)
472 for k, v in sorted(TRANSFORMATIONS.items())))
473 sys.stderr.write('\n--- Enter new filter name(s) [{}]: '.format(' '.join(self.filters)))
474 with self.console:
475 new_filters = sys.stdin.readline().lower().split()
476 if new_filters:
477 for f in new_filters:
478 if f not in TRANSFORMATIONS:
479 sys.stderr.write('--- unknown filter: {}'.format(repr(f)))
480 break
481 else:
482 self.filters = new_filters
483 self.update_transformations()
484 sys.stderr.write('--- filters: {}\n'.format(' '.join(self.filters)))
485 elif c == '\x0c': # CTRL+L -> EOL mode
486 modes = list(EOL_TRANSFORMATIONS) # keys
487 eol = modes.index(self.eol) + 1
488 if eol >= len(modes):
489 eol = 0
490 self.eol = modes[eol]
491 sys.stderr.write('--- EOL: {} ---\n'.format(self.eol.upper()))
492 self.update_transformations()
493 elif c == '\x01': # CTRL+A -> set encoding
494 sys.stderr.write('\n--- Enter new encoding name [{}]: '.format(self.input_encoding))
495 with self.console:
496 new_encoding = sys.stdin.readline().strip()
497 if new_encoding:
498 try:
499 codecs.lookup(new_encoding)
500 except LookupError:
501 sys.stderr.write('--- invalid encoding name: {}\n'.format(new_encoding))
502 else:
503 self.set_rx_encoding(new_encoding)
504 self.set_tx_encoding(new_encoding)
505 sys.stderr.write('--- serial input encoding: {}\n'.format(self.input_encoding))
506 sys.stderr.write('--- serial output encoding: {}\n'.format(self.output_encoding))
Chris Liechti7af7c752015-08-12 15:45:19 +0200507 elif c == '\x09': # CTRL+I -> info
508 self.dump_port_settings()
509 #~ elif c == '\x01': # CTRL+A -> cycle escape mode
510 #~ elif c == '\x0c': # CTRL+L -> cycle linefeed mode
511 elif c in 'pP': # P -> change port
512 dump_port_list()
513 sys.stderr.write('--- Enter port name: ')
514 sys.stderr.flush()
Chris Liechti269f77b2015-08-24 01:31:42 +0200515 with self.console:
516 try:
517 port = sys.stdin.readline().strip()
518 except KeyboardInterrupt:
519 port = None
Chris Liechti7af7c752015-08-12 15:45:19 +0200520 if port and port != self.serial.port:
521 # reader thread needs to be shut down
522 self._stop_reader()
523 # save settings
524 settings = self.serial.getSettingsDict()
525 try:
526 new_serial = serial.serial_for_url(port, do_not_open=True)
527 # restore settings and open
528 new_serial.applySettingsDict(settings)
529 new_serial.open()
530 new_serial.setRTS(self.rts_state)
531 new_serial.setDTR(self.dtr_state)
532 new_serial.setBreak(self.break_state)
533 except Exception as e:
Chris Liechti442bf512015-08-15 01:42:24 +0200534 sys.stderr.write('--- ERROR opening new port: {} ---\n'.format(e))
Chris Liechti7af7c752015-08-12 15:45:19 +0200535 new_serial.close()
536 else:
537 self.serial.close()
538 self.serial = new_serial
Chris Liechti442bf512015-08-15 01:42:24 +0200539 sys.stderr.write('--- Port changed to: {} ---\n'.format(self.serial.port))
Chris Liechti7af7c752015-08-12 15:45:19 +0200540 # and restart the reader thread
541 self._start_reader()
542 elif c in 'bB': # B -> change baudrate
543 sys.stderr.write('\n--- Baudrate: ')
544 sys.stderr.flush()
Chris Liechti269f77b2015-08-24 01:31:42 +0200545 with self.console:
546 backup = self.serial.baudrate
547 try:
548 self.serial.baudrate = int(sys.stdin.readline().strip())
549 except ValueError as e:
550 sys.stderr.write('--- ERROR setting baudrate: %s ---\n'.format(e))
551 self.serial.baudrate = backup
552 else:
553 self.dump_port_settings()
Chris Liechti7af7c752015-08-12 15:45:19 +0200554 elif c == '8': # 8 -> change to 8 bits
555 self.serial.bytesize = serial.EIGHTBITS
556 self.dump_port_settings()
557 elif c == '7': # 7 -> change to 8 bits
558 self.serial.bytesize = serial.SEVENBITS
559 self.dump_port_settings()
560 elif c in 'eE': # E -> change to even parity
561 self.serial.parity = serial.PARITY_EVEN
562 self.dump_port_settings()
563 elif c in 'oO': # O -> change to odd parity
564 self.serial.parity = serial.PARITY_ODD
565 self.dump_port_settings()
566 elif c in 'mM': # M -> change to mark parity
567 self.serial.parity = serial.PARITY_MARK
568 self.dump_port_settings()
569 elif c in 'sS': # S -> change to space parity
570 self.serial.parity = serial.PARITY_SPACE
571 self.dump_port_settings()
572 elif c in 'nN': # N -> change to no parity
573 self.serial.parity = serial.PARITY_NONE
574 self.dump_port_settings()
575 elif c == '1': # 1 -> change to 1 stop bits
576 self.serial.stopbits = serial.STOPBITS_ONE
577 self.dump_port_settings()
578 elif c == '2': # 2 -> change to 2 stop bits
579 self.serial.stopbits = serial.STOPBITS_TWO
580 self.dump_port_settings()
581 elif c == '3': # 3 -> change to 1.5 stop bits
582 self.serial.stopbits = serial.STOPBITS_ONE_POINT_FIVE
583 self.dump_port_settings()
584 elif c in 'xX': # X -> change software flow control
585 self.serial.xonxoff = (c == 'X')
586 self.dump_port_settings()
587 elif c in 'rR': # R -> change hardware flow control
588 self.serial.rtscts = (c == 'R')
589 self.dump_port_settings()
590 else:
Chris Liechti442bf512015-08-15 01:42:24 +0200591 sys.stderr.write('--- unknown menu character {} --\n'.format(key_description(c)))
592
593 def get_help_text(self):
Chris Liechti55ba7d92015-08-15 16:33:51 +0200594 # help text, starts with blank line!
Chris Liechti442bf512015-08-15 01:42:24 +0200595 return """
596--- pySerial ({version}) - miniterm - help
597---
598--- {exit:8} Exit program
599--- {menu:8} Menu escape key, followed by:
600--- Menu keys:
601--- {menu:7} Send the menu character itself to remote
602--- {exit:7} Send the exit character itself to remote
603--- {info:7} Show info
604--- {upload:7} Upload file (prompt will be shown)
Chris Liechtib3df13e2015-08-25 02:20:09 +0200605--- {repr:7} encoding
606--- {filter:7} edit filters
Chris Liechti442bf512015-08-15 01:42:24 +0200607--- Toggles:
Chris Liechtib3df13e2015-08-25 02:20:09 +0200608--- {rts:7} RTS {dtr:7} DTR {brk:7} BREAK
609--- {echo:7} echo {eol:7} EOL
Chris Liechti442bf512015-08-15 01:42:24 +0200610---
Chris Liechti55ba7d92015-08-15 16:33:51 +0200611--- Port settings ({menu} followed by the following):
Chris Liechti442bf512015-08-15 01:42:24 +0200612--- p change port
613--- 7 8 set data bits
Chris Liechtib7550bd2015-08-15 04:09:10 +0200614--- N E O S M change parity (None, Even, Odd, Space, Mark)
Chris Liechti442bf512015-08-15 01:42:24 +0200615--- 1 2 3 set stop bits (1, 2, 1.5)
616--- b change baud rate
617--- x X disable/enable software flow control
618--- r R disable/enable hardware flow control
619""".format(
620 version=getattr(serial, 'VERSION', 'unknown version'),
621 exit=key_description(self.exit_character),
622 menu=key_description(self.menu_character),
Chris Liechtib7550bd2015-08-15 04:09:10 +0200623 rts=key_description('\x12'),
624 dtr=key_description('\x04'),
625 brk=key_description('\x02'),
626 echo=key_description('\x05'),
627 info=key_description('\x09'),
628 upload=key_description('\x15'),
Chris Liechtib3df13e2015-08-25 02:20:09 +0200629 repr=key_description('\x01'),
630 filter=key_description('\x06'),
631 eol=key_description('\x0c'),
Chris Liechti442bf512015-08-15 01:42:24 +0200632 )
Chris Liechti7af7c752015-08-12 15:45:19 +0200633
634
635
Chris Liechtib3df13e2015-08-25 02:20:09 +0200636# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechti55ba7d92015-08-15 16:33:51 +0200637# default args can be used to override when calling main() from an other script
638# e.g to create a miniterm-my-device.py
639def main(default_port=None, default_baudrate=9600, default_rts=None, default_dtr=None):
Chris Liechtib7550bd2015-08-15 04:09:10 +0200640 import argparse
cliechti6385f2c2005-09-21 19:51:19 +0000641
Chris Liechtib7550bd2015-08-15 04:09:10 +0200642 parser = argparse.ArgumentParser(
643 description="Miniterm - A simple terminal program for the serial port.")
cliechti6385f2c2005-09-21 19:51:19 +0000644
Chris Liechtib7550bd2015-08-15 04:09:10 +0200645 parser.add_argument("port",
646 nargs='?',
647 help="serial port name",
Chris Liechti55ba7d92015-08-15 16:33:51 +0200648 default=default_port)
cliechti5370cee2013-10-13 03:08:19 +0000649
Chris Liechtib7550bd2015-08-15 04:09:10 +0200650 parser.add_argument("baudrate",
651 nargs='?',
652 type=int,
653 help="set baud rate, default: %(default)s",
Chris Liechti55ba7d92015-08-15 16:33:51 +0200654 default=default_baudrate)
cliechti6385f2c2005-09-21 19:51:19 +0000655
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200656 group = parser.add_argument_group("port settings")
cliechti53edb472009-02-06 21:18:46 +0000657
Chris Liechtib7550bd2015-08-15 04:09:10 +0200658 group.add_argument("--parity",
659 choices=['N', 'E', 'O', 'S', 'M'],
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200660 type=lambda c: c.upper(),
Chris Liechtib7550bd2015-08-15 04:09:10 +0200661 help="set parity, one of {N E O S M}, default: N",
662 default='N')
cliechti53edb472009-02-06 21:18:46 +0000663
Chris Liechtib7550bd2015-08-15 04:09:10 +0200664 group.add_argument("--rtscts",
665 action="store_true",
666 help="enable RTS/CTS 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("--xonxoff",
670 action="store_true",
671 help="enable software flow control (default off)",
672 default=False)
cliechti53edb472009-02-06 21:18:46 +0000673
Chris Liechtib7550bd2015-08-15 04:09:10 +0200674 group.add_argument("--rts",
675 type=int,
676 help="set initial RTS line state (possible values: 0, 1)",
Chris Liechti55ba7d92015-08-15 16:33:51 +0200677 default=default_rts)
cliechti5370cee2013-10-13 03:08:19 +0000678
Chris Liechtib7550bd2015-08-15 04:09:10 +0200679 group.add_argument("--dtr",
680 type=int,
681 help="set initial DTR line state (possible values: 0, 1)",
Chris Liechti55ba7d92015-08-15 16:33:51 +0200682 default=default_dtr)
cliechti5370cee2013-10-13 03:08:19 +0000683
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200684 group = parser.add_argument_group("data handling")
cliechti5370cee2013-10-13 03:08:19 +0000685
Chris Liechtib7550bd2015-08-15 04:09:10 +0200686 group.add_argument("-e", "--echo",
687 action="store_true",
688 help="enable local echo (default off)",
689 default=False)
cliechti5370cee2013-10-13 03:08:19 +0000690
Chris Liechtib7550bd2015-08-15 04:09:10 +0200691 group.add_argument("--encoding",
692 dest="serial_port_encoding",
693 metavar="CODEC",
Chris Liechtia7e7b692015-08-25 21:10:28 +0200694 help="set the encoding for the serial port (e.g. hexlify, Latin1, UTF-8), default: %(default)s",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200695 default='UTF-8')
cliechti5370cee2013-10-13 03:08:19 +0000696
Chris Liechtib3df13e2015-08-25 02:20:09 +0200697 group.add_argument("-f", "--filter",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200698 action="append",
699 metavar="NAME",
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200700 help="add text transformation",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200701 default=[])
Chris Liechti2b1b3552015-08-12 15:35:33 +0200702
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200703 group.add_argument("--eol",
704 choices=['CR', 'LF', 'CRLF'],
705 type=lambda c: c.upper(),
706 help="end of line mode",
707 default='CRLF')
cliechti53edb472009-02-06 21:18:46 +0000708
Chris Liechtib7550bd2015-08-15 04:09:10 +0200709 group.add_argument("--raw",
710 action="store_true",
711 help="Do no apply any encodings/transformations",
712 default=False)
cliechti6385f2c2005-09-21 19:51:19 +0000713
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200714 group = parser.add_argument_group("hotkeys")
cliechtib7d746d2006-03-28 22:44:30 +0000715
Chris Liechtib7550bd2015-08-15 04:09:10 +0200716 group.add_argument("--exit-char",
717 type=int,
Chris Liechti55ba7d92015-08-15 16:33:51 +0200718 metavar='NUM',
719 help="Unicode of special character that is used to exit the application, default: %(default)s",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200720 default=0x1d # GS/CTRL+]
721 )
cliechtibf6bb7d2006-03-30 00:28:18 +0000722
Chris Liechtib7550bd2015-08-15 04:09:10 +0200723 group.add_argument("--menu-char",
724 type=int,
Chris Liechti55ba7d92015-08-15 16:33:51 +0200725 metavar='NUM',
726 help="Unicode code of special character that is used to control miniterm (menu), default: %(default)s",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200727 default=0x14 # Menu: CTRL+T
728 )
cliechti9c592b32008-06-16 22:00:14 +0000729
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200730 group = parser.add_argument_group("diagnostics")
cliechti6385f2c2005-09-21 19:51:19 +0000731
Chris Liechtib7550bd2015-08-15 04:09:10 +0200732 group.add_argument("-q", "--quiet",
733 action="store_true",
734 help="suppress non-error messages",
735 default=False)
cliechti5370cee2013-10-13 03:08:19 +0000736
Chris Liechtib7550bd2015-08-15 04:09:10 +0200737 group.add_argument("--develop",
738 action="store_true",
739 help="show Python traceback on error",
740 default=False)
cliechti5370cee2013-10-13 03:08:19 +0000741
Chris Liechtib7550bd2015-08-15 04:09:10 +0200742 args = parser.parse_args()
cliechti5370cee2013-10-13 03:08:19 +0000743
Chris Liechtib7550bd2015-08-15 04:09:10 +0200744 if args.menu_char == args.exit_char:
cliechti6c8eb2f2009-07-08 02:10:46 +0000745 parser.error('--exit-char can not be the same as --menu-char')
746
cliechti9c592b32008-06-16 22:00:14 +0000747
Chris Liechtib7550bd2015-08-15 04:09:10 +0200748 # no port given on command line -> ask user now
749 if args.port is None:
750 dump_port_list()
751 args.port = raw_input('Enter port name:')
cliechti53edb472009-02-06 21:18:46 +0000752
Chris Liechtib3df13e2015-08-25 02:20:09 +0200753 if args.filter:
754 if 'help' in args.filter:
755 sys.stderr.write('Available filters:\n')
Chris Liechti442bf512015-08-15 01:42:24 +0200756 sys.stderr.write('\n'.join(
Chris Liechtib3df13e2015-08-25 02:20:09 +0200757 '{:<10} = {.__doc__}'.format(k, v)
Chris Liechtib7550bd2015-08-15 04:09:10 +0200758 for k, v in sorted(TRANSFORMATIONS.items())))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200759 sys.stderr.write('\n')
760 sys.exit(1)
Chris Liechtib3df13e2015-08-25 02:20:09 +0200761 filters = args.filter
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200762 else:
Chris Liechtib3df13e2015-08-25 02:20:09 +0200763 filters = ['default']
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200764
cliechti6385f2c2005-09-21 19:51:19 +0000765
766 try:
767 miniterm = Miniterm(
Chris Liechtib7550bd2015-08-15 04:09:10 +0200768 args.port,
769 args.baudrate,
770 args.parity,
771 rtscts=args.rtscts,
772 xonxoff=args.xonxoff,
773 echo=args.echo,
Chris Liechtib3df13e2015-08-25 02:20:09 +0200774 eol=args.eol.lower(),
775 filters=filters,
Chris Liechti442bf512015-08-15 01:42:24 +0200776 )
Chris Liechtib7550bd2015-08-15 04:09:10 +0200777 miniterm.exit_character = unichr(args.exit_char)
778 miniterm.menu_character = unichr(args.menu_char)
779 miniterm.raw = args.raw
Chris Liechtid698af72015-08-24 20:24:55 +0200780 miniterm.set_rx_encoding(args.serial_port_encoding)
781 miniterm.set_tx_encoding(args.serial_port_encoding)
Chris Liechti68340d72015-08-03 14:15:48 +0200782 except serial.SerialException as e:
Chris Liechtiaccd2012015-08-17 03:09:23 +0200783 sys.stderr.write('could not open port {}: {}\n'.format(repr(args.port), e))
Chris Liechtib7550bd2015-08-15 04:09:10 +0200784 if args.develop:
Chris Liechti91090912015-08-05 02:36:14 +0200785 raise
cliechti6385f2c2005-09-21 19:51:19 +0000786 sys.exit(1)
787
Chris Liechtib7550bd2015-08-15 04:09:10 +0200788 if not args.quiet:
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200789 sys.stderr.write('--- Miniterm on {p.name} {p.baudrate},{p.bytesize},{p.parity},{p.stopbits} ---\n'.format(
790 p=miniterm.serial))
Chris Liechtib7550bd2015-08-15 04:09:10 +0200791 sys.stderr.write('--- Quit: {} | Menu: {} | Help: {} followed by {} ---\n'.format(
Chris Liechti442bf512015-08-15 01:42:24 +0200792 key_description(miniterm.exit_character),
793 key_description(miniterm.menu_character),
794 key_description(miniterm.menu_character),
Chris Liechtib7550bd2015-08-15 04:09:10 +0200795 key_description('\x08'),
Chris Liechti442bf512015-08-15 01:42:24 +0200796 ))
cliechti6fa76fb2009-07-08 23:53:39 +0000797
Chris Liechtib7550bd2015-08-15 04:09:10 +0200798 if args.dtr is not None:
799 if not args.quiet:
800 sys.stderr.write('--- forcing DTR {}\n'.format('active' if args.dtr else 'inactive'))
801 miniterm.serial.setDTR(args.dtr)
802 miniterm.dtr_state = args.dtr
803 if args.rts is not None:
804 if not args.quiet:
805 sys.stderr.write('--- forcing RTS {}\n'.format('active' if args.rts else 'inactive'))
806 miniterm.serial.setRTS(args.rts)
807 miniterm.rts_state = args.rts
cliechti53edb472009-02-06 21:18:46 +0000808
cliechti6385f2c2005-09-21 19:51:19 +0000809 miniterm.start()
cliechti258ab0a2011-03-21 23:03:45 +0000810 try:
811 miniterm.join(True)
812 except KeyboardInterrupt:
813 pass
Chris Liechtib7550bd2015-08-15 04:09:10 +0200814 if not args.quiet:
cliechtibf6bb7d2006-03-30 00:28:18 +0000815 sys.stderr.write("\n--- exit ---\n")
cliechti6385f2c2005-09-21 19:51:19 +0000816 miniterm.join()
cliechtibf6bb7d2006-03-30 00:28:18 +0000817
cliechti5370cee2013-10-13 03:08:19 +0000818# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
cliechti8b3ad392002-03-03 20:12:21 +0000819if __name__ == '__main__':
cliechti6385f2c2005-09-21 19:51:19 +0000820 main()