blob: 59086ba6fe2aaa311e594f28ed7c98c255082ec7 [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):
115 sys.stdin = codecs.getreader(sys.stdin.encoding)(sys.stdin)
cliechti9c592b32008-06-16 22:00:14 +0000116
117 def setup(self):
cliechti9c592b32008-06-16 22:00:14 +0000118 new = termios.tcgetattr(self.fd)
119 new[3] = new[3] & ~termios.ICANON & ~termios.ECHO & ~termios.ISIG
120 new[6][termios.VMIN] = 1
121 new[6][termios.VTIME] = 0
122 termios.tcsetattr(self.fd, termios.TCSANOW, new)
cliechti53edb472009-02-06 21:18:46 +0000123
cliechti9c592b32008-06-16 22:00:14 +0000124 def getkey(self):
Chris Liechti9a720852015-08-25 00:20:38 +0200125 c = sys.stdin.read(1)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200126 #~ c = os.read(self.fd, 1)
Chris Liechti9a720852015-08-25 00:20:38 +0200127 if c == '\x7f':
128 c = '\b' # map the BS key (which yields DEL) to backspace
129 return c
cliechti53edb472009-02-06 21:18:46 +0000130
cliechti9c592b32008-06-16 22:00:14 +0000131 def cleanup(self):
Chris Liechti4d989c22015-08-24 00:24:49 +0200132 termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old)
cliechti9c592b32008-06-16 22:00:14 +0000133
cliechti576de252002-02-28 23:54:44 +0000134else:
cliechti8c2ea842011-03-18 01:51:46 +0000135 raise NotImplementedError("Sorry no implementation for your platform (%s) available." % sys.platform)
cliechti576de252002-02-28 23:54:44 +0000136
cliechti6fa76fb2009-07-08 23:53:39 +0000137
Chris Liechti9a720852015-08-25 00:20:38 +0200138# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200139
140class Transform(object):
Chris Liechticbb00b22015-08-13 22:58:49 +0200141 """do-nothing: forward all data unchanged"""
Chris Liechtid698af72015-08-24 20:24:55 +0200142 def rx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200143 """text received from serial port"""
144 return text
145
Chris Liechtid698af72015-08-24 20:24:55 +0200146 def tx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200147 """text to be sent to serial port"""
148 return text
149
150 def echo(self, text):
151 """text to be sent but displayed on console"""
152 return text
153
Chris Liechti442bf512015-08-15 01:42:24 +0200154
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200155class CRLF(Transform):
156 """ENTER sends CR+LF"""
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200157
Chris Liechtid698af72015-08-24 20:24:55 +0200158 def tx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200159 return text.replace('\n', '\r\n')
160
Chris Liechti442bf512015-08-15 01:42:24 +0200161
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200162class CR(Transform):
163 """ENTER sends CR"""
Chris Liechtid698af72015-08-24 20:24:55 +0200164
165 def rx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200166 return text.replace('\r', '\n')
167
Chris Liechtid698af72015-08-24 20:24:55 +0200168 def tx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200169 return text.replace('\n', '\r')
170
Chris Liechti442bf512015-08-15 01:42:24 +0200171
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200172class LF(Transform):
173 """ENTER sends LF"""
174
175
176class NoTerminal(Transform):
177 """remove typical terminal control codes from input"""
Chris Liechti9a720852015-08-25 00:20:38 +0200178
179 REPLACEMENT_MAP = dict((x, 0x2400 + x) for x in range(32) if unichr(x) not in '\r\n\b\t')
180 REPLACEMENT_MAP.update({
181 0x7F: 0x2421, # DEL
182 0x9B: 0x2425, # CSI
183 })
184
Chris Liechtid698af72015-08-24 20:24:55 +0200185 def rx(self, text):
Chris Liechti9a720852015-08-25 00:20:38 +0200186 return text.translate(self.REPLACEMENT_MAP)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200187
Chris Liechtid698af72015-08-24 20:24:55 +0200188 echo = rx
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200189
190
Chris Liechti9a720852015-08-25 00:20:38 +0200191class NoControls(NoTerminal):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200192 """Remove all control codes, incl. CR+LF"""
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200193
Chris Liechti9a720852015-08-25 00:20:38 +0200194 REPLACEMENT_MAP = dict((x, 0x2400 + x) for x in range(32))
195 REPLACEMENT_MAP.update({
196 32: 0x2423, # visual space
197 0x7F: 0x2421, # DEL
198 0x9B: 0x2425, # CSI
199 })
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200200
201
202class Printable(Transform):
Chris Liechtid698af72015-08-24 20:24:55 +0200203 """Show decimal code for all non-ASCII characters and replace most control codes"""
Chris Liechtic0c660a2015-08-25 00:55:51 +0200204
Chris Liechtid698af72015-08-24 20:24:55 +0200205 def rx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200206 r = []
207 for t in text:
Chris Liechti7e9cfd42015-08-12 15:28:19 +0200208 if ' ' <= t < '\x7f' or t in '\r\n\b\t':
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200209 r.append(t)
Chris Liechtid698af72015-08-24 20:24:55 +0200210 elif t < ' ':
211 r.append(unichr(0x2400 + ord(t)))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200212 else:
213 r.extend(unichr(0x2080 + ord(d) - 48) for d in '{:d}'.format(ord(t)))
214 r.append(' ')
215 return ''.join(r)
216
Chris Liechtid698af72015-08-24 20:24:55 +0200217 echo = rx
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200218
219
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200220class Colorize(Transform):
Chris Liechti442bf512015-08-15 01:42:24 +0200221 """Apply different colors for received and echo"""
Chris Liechtic0c660a2015-08-25 00:55:51 +0200222
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200223 def __init__(self):
224 # XXX make it configurable, use colorama?
225 self.input_color = '\x1b[37m'
226 self.echo_color = '\x1b[31m'
227
Chris Liechtid698af72015-08-24 20:24:55 +0200228 def rx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200229 return self.input_color + text
230
231 def echo(self, text):
232 return self.echo_color + text
233
Chris Liechti442bf512015-08-15 01:42:24 +0200234
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200235class DebugIO(Transform):
Chris Liechti442bf512015-08-15 01:42:24 +0200236 """Print what is sent and received"""
Chris Liechtic0c660a2015-08-25 00:55:51 +0200237
Chris Liechtid698af72015-08-24 20:24:55 +0200238 def rx(self, text):
Chris Liechtie1384382015-08-15 17:06:05 +0200239 sys.stderr.write(' [RX:{}] '.format(repr(text)))
240 sys.stderr.flush()
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200241 return text
242
Chris Liechtid698af72015-08-24 20:24:55 +0200243 def tx(self, text):
Chris Liechtie1384382015-08-15 17:06:05 +0200244 sys.stderr.write(' [TX:{}] '.format(repr(text)))
245 sys.stderr.flush()
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200246 return text
247
Chris Liechti442bf512015-08-15 01:42:24 +0200248
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200249# other ideas:
250# - add date/time for each newline
251# - insert newline after: a) timeout b) packet end character
252
Chris Liechtib3df13e2015-08-25 02:20:09 +0200253EOL_TRANSFORMATIONS = {
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200254 'crlf': CRLF,
255 'cr': CR,
256 'lf': LF,
Chris Liechtib3df13e2015-08-25 02:20:09 +0200257 }
258
259TRANSFORMATIONS = {
Chris Liechticbb00b22015-08-13 22:58:49 +0200260 'direct': Transform, # no transformation
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200261 'default': NoTerminal,
262 'nocontrol': NoControls,
263 'printable': Printable,
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200264 'colorize': Colorize,
265 'debug': DebugIO,
266 }
267
Chris Liechti9a720852015-08-25 00:20:38 +0200268# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200269
cliechti1351dde2012-04-12 16:47:47 +0000270def dump_port_list():
271 if comports:
272 sys.stderr.write('\n--- Available ports:\n')
273 for port, desc, hwid in sorted(comports()):
274 #~ sys.stderr.write('--- %-20s %s [%s]\n' % (port, desc, hwid))
275 sys.stderr.write('--- %-20s %s\n' % (port, desc))
276
277
cliechti8c2ea842011-03-18 01:51:46 +0000278class Miniterm(object):
Chris Liechtib3df13e2015-08-25 02:20:09 +0200279 def __init__(self, port, baudrate, parity, rtscts, xonxoff, echo=False, eol='crlf', filters=()):
Chris Liechti89eb2472015-08-08 17:06:25 +0200280 self.console = Console()
Chris Liechtia1d5c6d2015-08-07 14:41:24 +0200281 self.serial = serial.serial_for_url(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1)
cliechti6385f2c2005-09-21 19:51:19 +0000282 self.echo = echo
cliechti6c8eb2f2009-07-08 02:10:46 +0000283 self.dtr_state = True
284 self.rts_state = True
285 self.break_state = False
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200286 self.raw = False
Chris Liechti442bf512015-08-15 01:42:24 +0200287 self.input_encoding = 'UTF-8'
Chris Liechti442bf512015-08-15 01:42:24 +0200288 self.output_encoding = 'UTF-8'
Chris Liechtib3df13e2015-08-25 02:20:09 +0200289 self.eol = eol
290 self.filters = filters
291 self.update_transformations()
Chris Liechti442bf512015-08-15 01:42:24 +0200292 self.exit_character = 0x1d # GS/CTRL+]
293 self.menu_character = 0x14 # Menu: CTRL+T
cliechti576de252002-02-28 23:54:44 +0000294
cliechti8c2ea842011-03-18 01:51:46 +0000295 def _start_reader(self):
296 """Start reader thread"""
297 self._reader_alive = True
cliechti6fa76fb2009-07-08 23:53:39 +0000298 # start serial->console thread
Chris Liechti55ba7d92015-08-15 16:33:51 +0200299 self.receiver_thread = threading.Thread(target=self.reader, name='rx')
300 self.receiver_thread.daemon = True
cliechti6385f2c2005-09-21 19:51:19 +0000301 self.receiver_thread.start()
cliechti8c2ea842011-03-18 01:51:46 +0000302
303 def _stop_reader(self):
304 """Stop reader thread only, wait for clean exit of thread"""
305 self._reader_alive = False
306 self.receiver_thread.join()
307
308
309 def start(self):
310 self.alive = True
311 self._start_reader()
cliechti6fa76fb2009-07-08 23:53:39 +0000312 # enter console->serial loop
Chris Liechti55ba7d92015-08-15 16:33:51 +0200313 self.transmitter_thread = threading.Thread(target=self.writer, name='tx')
314 self.transmitter_thread.daemon = True
cliechti6385f2c2005-09-21 19:51:19 +0000315 self.transmitter_thread.start()
Chris Liechti89eb2472015-08-08 17:06:25 +0200316 self.console.setup()
cliechti53edb472009-02-06 21:18:46 +0000317
cliechti6385f2c2005-09-21 19:51:19 +0000318 def stop(self):
319 self.alive = False
cliechti53edb472009-02-06 21:18:46 +0000320
cliechtibf6bb7d2006-03-30 00:28:18 +0000321 def join(self, transmit_only=False):
cliechti6385f2c2005-09-21 19:51:19 +0000322 self.transmitter_thread.join()
cliechtibf6bb7d2006-03-30 00:28:18 +0000323 if not transmit_only:
324 self.receiver_thread.join()
cliechti6385f2c2005-09-21 19:51:19 +0000325
Chris Liechtib3df13e2015-08-25 02:20:09 +0200326 def update_transformations(self):
327 transformations = [EOL_TRANSFORMATIONS[self.eol]] + [TRANSFORMATIONS[f] for f in self.filters]
328 self.tx_transformations = [t() for t in transformations]
329 self.rx_transformations = list(reversed(self.tx_transformations))
330
Chris Liechtid698af72015-08-24 20:24:55 +0200331 def set_rx_encoding(self, encoding, errors='replace'):
332 self.input_encoding = encoding
333 self.rx_decoder = codecs.getincrementaldecoder(encoding)(errors)
334
335 def set_tx_encoding(self, encoding, errors='replace'):
336 self.output_encoding = encoding
337 self.tx_encoder = codecs.getincrementalencoder(encoding)(errors)
338
339
cliechti6c8eb2f2009-07-08 02:10:46 +0000340 def dump_port_settings(self):
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200341 sys.stderr.write("\n--- Settings: {p.name} {p.baudrate},{p.bytesize},{p.parity},{p.stopbits}\n".format(
342 p=self.serial))
Chris Liechti442bf512015-08-15 01:42:24 +0200343 sys.stderr.write('--- RTS: {:8} DTR: {:8} BREAK: {:8}\n'.format(
344 ('active' if self.rts_state else 'inactive'),
345 ('active' if self.dtr_state else 'inactive'),
346 ('active' if self.break_state else 'inactive')))
cliechti10114572009-08-05 23:40:50 +0000347 try:
Chris Liechti442bf512015-08-15 01:42:24 +0200348 sys.stderr.write('--- CTS: {:8} DSR: {:8} RI: {:8} CD: {:8}\n'.format(
349 ('active' if self.serial.getCTS() else 'inactive'),
350 ('active' if self.serial.getDSR() else 'inactive'),
351 ('active' if self.serial.getRI() else 'inactive'),
352 ('active' if self.serial.getCD() else 'inactive')))
cliechti10114572009-08-05 23:40:50 +0000353 except serial.SerialException:
Chris Liechti55ba7d92015-08-15 16:33:51 +0200354 # on RFC 2217 ports, it can happen if no modem state notification was
cliechti10114572009-08-05 23:40:50 +0000355 # yet received. ignore this error.
356 pass
Chris Liechti442bf512015-08-15 01:42:24 +0200357 sys.stderr.write('--- software flow control: {}\n'.format('active' if self.serial.xonxoff else 'inactive'))
358 sys.stderr.write('--- hardware flow control: {}\n'.format('active' if self.serial.rtscts else 'inactive'))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200359 #~ sys.stderr.write('--- data escaping: %s linefeed: %s\n' % (
360 #~ REPR_MODES[self.repr_mode],
361 #~ LF_MODES[self.convert_outgoing]))
Chris Liechti442bf512015-08-15 01:42:24 +0200362 sys.stderr.write('--- serial input encoding: {}\n'.format(self.input_encoding))
363 sys.stderr.write('--- serial output encoding: {}\n'.format(self.output_encoding))
Chris Liechtib3df13e2015-08-25 02:20:09 +0200364 sys.stderr.write('--- EOL: {}\n'.format(self.eol.upper()))
365 sys.stderr.write('--- filters: {}\n'.format(' '.join(self.filters)))
cliechti6c8eb2f2009-07-08 02:10:46 +0000366
cliechti6385f2c2005-09-21 19:51:19 +0000367 def reader(self):
368 """loop and copy serial->console"""
cliechti6963b262010-01-02 03:01:21 +0000369 try:
cliechti8c2ea842011-03-18 01:51:46 +0000370 while self.alive and self._reader_alive:
Chris Liechti188cf592015-08-22 00:28:19 +0200371 # read all that is there or wait for one byte
372 data = self.serial.read(self.serial.inWaiting() or 1)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200373 if data:
374 if self.raw:
375 self.console.write_bytes(data)
cliechti6963b262010-01-02 03:01:21 +0000376 else:
Chris Liechtid698af72015-08-24 20:24:55 +0200377 text = self.rx_decoder.decode(data)
Chris Liechtie1384382015-08-15 17:06:05 +0200378 for transformation in self.rx_transformations:
Chris Liechtid698af72015-08-24 20:24:55 +0200379 text = transformation.rx(text)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200380 self.console.write(text)
Chris Liechti68340d72015-08-03 14:15:48 +0200381 except serial.SerialException as e:
cliechti6963b262010-01-02 03:01:21 +0000382 self.alive = False
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200383 # XXX would be nice if the writer could be interrupted at this
384 # point... to exit completely
cliechti6963b262010-01-02 03:01:21 +0000385 raise
cliechti576de252002-02-28 23:54:44 +0000386
cliechti576de252002-02-28 23:54:44 +0000387
cliechti6385f2c2005-09-21 19:51:19 +0000388 def writer(self):
cliechti8c2ea842011-03-18 01:51:46 +0000389 """\
Chris Liechti442bf512015-08-15 01:42:24 +0200390 Loop and copy console->serial until self.exit_character character is
391 found. When self.menu_character is found, interpret the next key
cliechti8c2ea842011-03-18 01:51:46 +0000392 locally.
cliechti6c8eb2f2009-07-08 02:10:46 +0000393 """
394 menu_active = False
395 try:
396 while self.alive:
397 try:
Chris Liechti89eb2472015-08-08 17:06:25 +0200398 c = self.console.getkey()
cliechti6c8eb2f2009-07-08 02:10:46 +0000399 except KeyboardInterrupt:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200400 c = '\x03'
cliechti6c8eb2f2009-07-08 02:10:46 +0000401 if menu_active:
Chris Liechti7af7c752015-08-12 15:45:19 +0200402 self.handle_menu_key(c)
cliechti6c8eb2f2009-07-08 02:10:46 +0000403 menu_active = False
Chris Liechti442bf512015-08-15 01:42:24 +0200404 elif c == self.menu_character:
Chris Liechti7af7c752015-08-12 15:45:19 +0200405 menu_active = True # next char will be for menu
Chris Liechti442bf512015-08-15 01:42:24 +0200406 elif c == self.exit_character:
Chris Liechti7af7c752015-08-12 15:45:19 +0200407 self.stop() # exit app
408 break
cliechti6c8eb2f2009-07-08 02:10:46 +0000409 else:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200410 #~ if self.raw:
411 text = c
412 echo_text = text
Chris Liechtie1384382015-08-15 17:06:05 +0200413 for transformation in self.tx_transformations:
Chris Liechtid698af72015-08-24 20:24:55 +0200414 text = transformation.tx(text)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200415 echo_text = transformation.echo(echo_text)
Chris Liechtid698af72015-08-24 20:24:55 +0200416 self.serial.write(self.tx_encoder.encode(text))
cliechti6c8eb2f2009-07-08 02:10:46 +0000417 if self.echo:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200418 self.console.write(echo_text)
cliechti6c8eb2f2009-07-08 02:10:46 +0000419 except:
420 self.alive = False
421 raise
cliechti6385f2c2005-09-21 19:51:19 +0000422
Chris Liechti7af7c752015-08-12 15:45:19 +0200423 def handle_menu_key(self, c):
424 """Implement a simple menu / settings"""
Chris Liechti55ba7d92015-08-15 16:33:51 +0200425 if c == self.menu_character or c == self.exit_character:
426 # Menu/exit character again -> send itself
Chris Liechtid698af72015-08-24 20:24:55 +0200427 self.serial.write(self.tx_encoder.encode(c))
Chris Liechti7af7c752015-08-12 15:45:19 +0200428 if self.echo:
429 self.console.write(c)
Chris Liechtib7550bd2015-08-15 04:09:10 +0200430 elif c == '\x15': # CTRL+U -> upload file
Chris Liechti7af7c752015-08-12 15:45:19 +0200431 sys.stderr.write('\n--- File to upload: ')
432 sys.stderr.flush()
Chris Liechti269f77b2015-08-24 01:31:42 +0200433 with self.console:
434 filename = sys.stdin.readline().rstrip('\r\n')
435 if filename:
436 try:
437 with open(filename, 'rb') as f:
438 sys.stderr.write('--- Sending file {} ---\n'.format(filename))
439 while True:
440 block = f.read(1024)
441 if not block:
442 break
443 self.serial.write(block)
444 # Wait for output buffer to drain.
445 self.serial.flush()
446 sys.stderr.write('.') # Progress indicator.
447 sys.stderr.write('\n--- File {} sent ---\n'.format(filename))
448 except IOError as e:
449 sys.stderr.write('--- ERROR opening file {}: {} ---\n'.format(filename, e))
Chris Liechti7af7c752015-08-12 15:45:19 +0200450 elif c in '\x08hH?': # CTRL+H, h, H, ? -> Show help
Chris Liechti442bf512015-08-15 01:42:24 +0200451 sys.stderr.write(self.get_help_text())
Chris Liechti7af7c752015-08-12 15:45:19 +0200452 elif c == '\x12': # CTRL+R -> Toggle RTS
453 self.rts_state = not self.rts_state
454 self.serial.setRTS(self.rts_state)
Chris Liechti442bf512015-08-15 01:42:24 +0200455 sys.stderr.write('--- RTS {} ---\n'.format('active' if self.rts_state else 'inactive'))
Chris Liechti7af7c752015-08-12 15:45:19 +0200456 elif c == '\x04': # CTRL+D -> Toggle DTR
457 self.dtr_state = not self.dtr_state
458 self.serial.setDTR(self.dtr_state)
Chris Liechti442bf512015-08-15 01:42:24 +0200459 sys.stderr.write('--- DTR {} ---\n'.format('active' if self.dtr_state else 'inactive'))
Chris Liechti7af7c752015-08-12 15:45:19 +0200460 elif c == '\x02': # CTRL+B -> toggle BREAK condition
461 self.break_state = not self.break_state
462 self.serial.setBreak(self.break_state)
Chris Liechti442bf512015-08-15 01:42:24 +0200463 sys.stderr.write('--- BREAK {} ---\n'.format('active' if self.break_state else 'inactive'))
Chris Liechti7af7c752015-08-12 15:45:19 +0200464 elif c == '\x05': # CTRL+E -> toggle local echo
465 self.echo = not self.echo
Chris Liechti442bf512015-08-15 01:42:24 +0200466 sys.stderr.write('--- local echo {} ---\n'.format('active' if self.echo else 'inactive'))
Chris Liechtib3df13e2015-08-25 02:20:09 +0200467 elif c == '\x06': # CTRL+F -> edit filters
468 sys.stderr.write('\n--- Available Filters:\n')
469 sys.stderr.write('\n'.join(
470 '--- {:<10} = {.__doc__}'.format(k, v)
471 for k, v in sorted(TRANSFORMATIONS.items())))
472 sys.stderr.write('\n--- Enter new filter name(s) [{}]: '.format(' '.join(self.filters)))
473 with self.console:
474 new_filters = sys.stdin.readline().lower().split()
475 if new_filters:
476 for f in new_filters:
477 if f not in TRANSFORMATIONS:
478 sys.stderr.write('--- unknown filter: {}'.format(repr(f)))
479 break
480 else:
481 self.filters = new_filters
482 self.update_transformations()
483 sys.stderr.write('--- filters: {}\n'.format(' '.join(self.filters)))
484 elif c == '\x0c': # CTRL+L -> EOL mode
485 modes = list(EOL_TRANSFORMATIONS) # keys
486 eol = modes.index(self.eol) + 1
487 if eol >= len(modes):
488 eol = 0
489 self.eol = modes[eol]
490 sys.stderr.write('--- EOL: {} ---\n'.format(self.eol.upper()))
491 self.update_transformations()
492 elif c == '\x01': # CTRL+A -> set encoding
493 sys.stderr.write('\n--- Enter new encoding name [{}]: '.format(self.input_encoding))
494 with self.console:
495 new_encoding = sys.stdin.readline().strip()
496 if new_encoding:
497 try:
498 codecs.lookup(new_encoding)
499 except LookupError:
500 sys.stderr.write('--- invalid encoding name: {}\n'.format(new_encoding))
501 else:
502 self.set_rx_encoding(new_encoding)
503 self.set_tx_encoding(new_encoding)
504 sys.stderr.write('--- serial input encoding: {}\n'.format(self.input_encoding))
505 sys.stderr.write('--- serial output encoding: {}\n'.format(self.output_encoding))
Chris Liechti7af7c752015-08-12 15:45:19 +0200506 elif c == '\x09': # CTRL+I -> info
507 self.dump_port_settings()
508 #~ elif c == '\x01': # CTRL+A -> cycle escape mode
509 #~ elif c == '\x0c': # CTRL+L -> cycle linefeed mode
510 elif c in 'pP': # P -> change port
511 dump_port_list()
512 sys.stderr.write('--- Enter port name: ')
513 sys.stderr.flush()
Chris Liechti269f77b2015-08-24 01:31:42 +0200514 with self.console:
515 try:
516 port = sys.stdin.readline().strip()
517 except KeyboardInterrupt:
518 port = None
Chris Liechti7af7c752015-08-12 15:45:19 +0200519 if port and port != self.serial.port:
520 # reader thread needs to be shut down
521 self._stop_reader()
522 # save settings
523 settings = self.serial.getSettingsDict()
524 try:
525 new_serial = serial.serial_for_url(port, do_not_open=True)
526 # restore settings and open
527 new_serial.applySettingsDict(settings)
528 new_serial.open()
529 new_serial.setRTS(self.rts_state)
530 new_serial.setDTR(self.dtr_state)
531 new_serial.setBreak(self.break_state)
532 except Exception as e:
Chris Liechti442bf512015-08-15 01:42:24 +0200533 sys.stderr.write('--- ERROR opening new port: {} ---\n'.format(e))
Chris Liechti7af7c752015-08-12 15:45:19 +0200534 new_serial.close()
535 else:
536 self.serial.close()
537 self.serial = new_serial
Chris Liechti442bf512015-08-15 01:42:24 +0200538 sys.stderr.write('--- Port changed to: {} ---\n'.format(self.serial.port))
Chris Liechti7af7c752015-08-12 15:45:19 +0200539 # and restart the reader thread
540 self._start_reader()
541 elif c in 'bB': # B -> change baudrate
542 sys.stderr.write('\n--- Baudrate: ')
543 sys.stderr.flush()
Chris Liechti269f77b2015-08-24 01:31:42 +0200544 with self.console:
545 backup = self.serial.baudrate
546 try:
547 self.serial.baudrate = int(sys.stdin.readline().strip())
548 except ValueError as e:
549 sys.stderr.write('--- ERROR setting baudrate: %s ---\n'.format(e))
550 self.serial.baudrate = backup
551 else:
552 self.dump_port_settings()
Chris Liechti7af7c752015-08-12 15:45:19 +0200553 elif c == '8': # 8 -> change to 8 bits
554 self.serial.bytesize = serial.EIGHTBITS
555 self.dump_port_settings()
556 elif c == '7': # 7 -> change to 8 bits
557 self.serial.bytesize = serial.SEVENBITS
558 self.dump_port_settings()
559 elif c in 'eE': # E -> change to even parity
560 self.serial.parity = serial.PARITY_EVEN
561 self.dump_port_settings()
562 elif c in 'oO': # O -> change to odd parity
563 self.serial.parity = serial.PARITY_ODD
564 self.dump_port_settings()
565 elif c in 'mM': # M -> change to mark parity
566 self.serial.parity = serial.PARITY_MARK
567 self.dump_port_settings()
568 elif c in 'sS': # S -> change to space parity
569 self.serial.parity = serial.PARITY_SPACE
570 self.dump_port_settings()
571 elif c in 'nN': # N -> change to no parity
572 self.serial.parity = serial.PARITY_NONE
573 self.dump_port_settings()
574 elif c == '1': # 1 -> change to 1 stop bits
575 self.serial.stopbits = serial.STOPBITS_ONE
576 self.dump_port_settings()
577 elif c == '2': # 2 -> change to 2 stop bits
578 self.serial.stopbits = serial.STOPBITS_TWO
579 self.dump_port_settings()
580 elif c == '3': # 3 -> change to 1.5 stop bits
581 self.serial.stopbits = serial.STOPBITS_ONE_POINT_FIVE
582 self.dump_port_settings()
583 elif c in 'xX': # X -> change software flow control
584 self.serial.xonxoff = (c == 'X')
585 self.dump_port_settings()
586 elif c in 'rR': # R -> change hardware flow control
587 self.serial.rtscts = (c == 'R')
588 self.dump_port_settings()
589 else:
Chris Liechti442bf512015-08-15 01:42:24 +0200590 sys.stderr.write('--- unknown menu character {} --\n'.format(key_description(c)))
591
592 def get_help_text(self):
Chris Liechti55ba7d92015-08-15 16:33:51 +0200593 # help text, starts with blank line!
Chris Liechti442bf512015-08-15 01:42:24 +0200594 return """
595--- pySerial ({version}) - miniterm - help
596---
597--- {exit:8} Exit program
598--- {menu:8} Menu escape key, followed by:
599--- Menu keys:
600--- {menu:7} Send the menu character itself to remote
601--- {exit:7} Send the exit character itself to remote
602--- {info:7} Show info
603--- {upload:7} Upload file (prompt will be shown)
Chris Liechtib3df13e2015-08-25 02:20:09 +0200604--- {repr:7} encoding
605--- {filter:7} edit filters
Chris Liechti442bf512015-08-15 01:42:24 +0200606--- Toggles:
Chris Liechtib3df13e2015-08-25 02:20:09 +0200607--- {rts:7} RTS {dtr:7} DTR {brk:7} BREAK
608--- {echo:7} echo {eol:7} EOL
Chris Liechti442bf512015-08-15 01:42:24 +0200609---
Chris Liechti55ba7d92015-08-15 16:33:51 +0200610--- Port settings ({menu} followed by the following):
Chris Liechti442bf512015-08-15 01:42:24 +0200611--- p change port
612--- 7 8 set data bits
Chris Liechtib7550bd2015-08-15 04:09:10 +0200613--- N E O S M change parity (None, Even, Odd, Space, Mark)
Chris Liechti442bf512015-08-15 01:42:24 +0200614--- 1 2 3 set stop bits (1, 2, 1.5)
615--- b change baud rate
616--- x X disable/enable software flow control
617--- r R disable/enable hardware flow control
618""".format(
619 version=getattr(serial, 'VERSION', 'unknown version'),
620 exit=key_description(self.exit_character),
621 menu=key_description(self.menu_character),
Chris Liechtib7550bd2015-08-15 04:09:10 +0200622 rts=key_description('\x12'),
623 dtr=key_description('\x04'),
624 brk=key_description('\x02'),
625 echo=key_description('\x05'),
626 info=key_description('\x09'),
627 upload=key_description('\x15'),
Chris Liechtib3df13e2015-08-25 02:20:09 +0200628 repr=key_description('\x01'),
629 filter=key_description('\x06'),
630 eol=key_description('\x0c'),
Chris Liechti442bf512015-08-15 01:42:24 +0200631 )
Chris Liechti7af7c752015-08-12 15:45:19 +0200632
633
634
Chris Liechtib3df13e2015-08-25 02:20:09 +0200635# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechti55ba7d92015-08-15 16:33:51 +0200636# default args can be used to override when calling main() from an other script
637# e.g to create a miniterm-my-device.py
638def main(default_port=None, default_baudrate=9600, default_rts=None, default_dtr=None):
Chris Liechtib7550bd2015-08-15 04:09:10 +0200639 import argparse
cliechti6385f2c2005-09-21 19:51:19 +0000640
Chris Liechtib7550bd2015-08-15 04:09:10 +0200641 parser = argparse.ArgumentParser(
642 description="Miniterm - A simple terminal program for the serial port.")
cliechti6385f2c2005-09-21 19:51:19 +0000643
Chris Liechtib7550bd2015-08-15 04:09:10 +0200644 parser.add_argument("port",
645 nargs='?',
646 help="serial port name",
Chris Liechti55ba7d92015-08-15 16:33:51 +0200647 default=default_port)
cliechti5370cee2013-10-13 03:08:19 +0000648
Chris Liechtib7550bd2015-08-15 04:09:10 +0200649 parser.add_argument("baudrate",
650 nargs='?',
651 type=int,
652 help="set baud rate, default: %(default)s",
Chris Liechti55ba7d92015-08-15 16:33:51 +0200653 default=default_baudrate)
cliechti6385f2c2005-09-21 19:51:19 +0000654
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200655 group = parser.add_argument_group("port settings")
cliechti53edb472009-02-06 21:18:46 +0000656
Chris Liechtib7550bd2015-08-15 04:09:10 +0200657 group.add_argument("--parity",
658 choices=['N', 'E', 'O', 'S', 'M'],
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200659 type=lambda c: c.upper(),
Chris Liechtib7550bd2015-08-15 04:09:10 +0200660 help="set parity, one of {N E O S M}, default: N",
661 default='N')
cliechti53edb472009-02-06 21:18:46 +0000662
Chris Liechtib7550bd2015-08-15 04:09:10 +0200663 group.add_argument("--rtscts",
664 action="store_true",
665 help="enable RTS/CTS flow control (default off)",
666 default=False)
cliechti53edb472009-02-06 21:18:46 +0000667
Chris Liechtib7550bd2015-08-15 04:09:10 +0200668 group.add_argument("--xonxoff",
669 action="store_true",
670 help="enable software flow control (default off)",
671 default=False)
cliechti53edb472009-02-06 21:18:46 +0000672
Chris Liechtib7550bd2015-08-15 04:09:10 +0200673 group.add_argument("--rts",
674 type=int,
675 help="set initial RTS line state (possible values: 0, 1)",
Chris Liechti55ba7d92015-08-15 16:33:51 +0200676 default=default_rts)
cliechti5370cee2013-10-13 03:08:19 +0000677
Chris Liechtib7550bd2015-08-15 04:09:10 +0200678 group.add_argument("--dtr",
679 type=int,
680 help="set initial DTR line state (possible values: 0, 1)",
Chris Liechti55ba7d92015-08-15 16:33:51 +0200681 default=default_dtr)
cliechti5370cee2013-10-13 03:08:19 +0000682
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200683 group = parser.add_argument_group("data handling")
cliechti5370cee2013-10-13 03:08:19 +0000684
Chris Liechtib7550bd2015-08-15 04:09:10 +0200685 group.add_argument("-e", "--echo",
686 action="store_true",
687 help="enable local echo (default off)",
688 default=False)
cliechti5370cee2013-10-13 03:08:19 +0000689
Chris Liechtib7550bd2015-08-15 04:09:10 +0200690 group.add_argument("--encoding",
691 dest="serial_port_encoding",
692 metavar="CODEC",
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200693 help="set the encoding for the serial port, default: %(default)s",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200694 default='UTF-8')
cliechti5370cee2013-10-13 03:08:19 +0000695
Chris Liechtib3df13e2015-08-25 02:20:09 +0200696 group.add_argument("-f", "--filter",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200697 action="append",
698 metavar="NAME",
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200699 help="add text transformation",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200700 default=[])
Chris Liechti2b1b3552015-08-12 15:35:33 +0200701
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200702 group.add_argument("--eol",
703 choices=['CR', 'LF', 'CRLF'],
704 type=lambda c: c.upper(),
705 help="end of line mode",
706 default='CRLF')
cliechti53edb472009-02-06 21:18:46 +0000707
Chris Liechtib7550bd2015-08-15 04:09:10 +0200708 group.add_argument("--raw",
709 action="store_true",
710 help="Do no apply any encodings/transformations",
711 default=False)
cliechti6385f2c2005-09-21 19:51:19 +0000712
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200713 group = parser.add_argument_group("hotkeys")
cliechtib7d746d2006-03-28 22:44:30 +0000714
Chris Liechtib7550bd2015-08-15 04:09:10 +0200715 group.add_argument("--exit-char",
716 type=int,
Chris Liechti55ba7d92015-08-15 16:33:51 +0200717 metavar='NUM',
718 help="Unicode of special character that is used to exit the application, default: %(default)s",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200719 default=0x1d # GS/CTRL+]
720 )
cliechtibf6bb7d2006-03-30 00:28:18 +0000721
Chris Liechtib7550bd2015-08-15 04:09:10 +0200722 group.add_argument("--menu-char",
723 type=int,
Chris Liechti55ba7d92015-08-15 16:33:51 +0200724 metavar='NUM',
725 help="Unicode code of special character that is used to control miniterm (menu), default: %(default)s",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200726 default=0x14 # Menu: CTRL+T
727 )
cliechti9c592b32008-06-16 22:00:14 +0000728
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200729 group = parser.add_argument_group("diagnostics")
cliechti6385f2c2005-09-21 19:51:19 +0000730
Chris Liechtib7550bd2015-08-15 04:09:10 +0200731 group.add_argument("-q", "--quiet",
732 action="store_true",
733 help="suppress non-error messages",
734 default=False)
cliechti5370cee2013-10-13 03:08:19 +0000735
Chris Liechtib7550bd2015-08-15 04:09:10 +0200736 group.add_argument("--develop",
737 action="store_true",
738 help="show Python traceback on error",
739 default=False)
cliechti5370cee2013-10-13 03:08:19 +0000740
Chris Liechtib7550bd2015-08-15 04:09:10 +0200741 args = parser.parse_args()
cliechti5370cee2013-10-13 03:08:19 +0000742
Chris Liechtib7550bd2015-08-15 04:09:10 +0200743 if args.menu_char == args.exit_char:
cliechti6c8eb2f2009-07-08 02:10:46 +0000744 parser.error('--exit-char can not be the same as --menu-char')
745
cliechti9c592b32008-06-16 22:00:14 +0000746
Chris Liechtib7550bd2015-08-15 04:09:10 +0200747 # no port given on command line -> ask user now
748 if args.port is None:
749 dump_port_list()
750 args.port = raw_input('Enter port name:')
cliechti53edb472009-02-06 21:18:46 +0000751
Chris Liechtib3df13e2015-08-25 02:20:09 +0200752 if args.filter:
753 if 'help' in args.filter:
754 sys.stderr.write('Available filters:\n')
Chris Liechti442bf512015-08-15 01:42:24 +0200755 sys.stderr.write('\n'.join(
Chris Liechtib3df13e2015-08-25 02:20:09 +0200756 '{:<10} = {.__doc__}'.format(k, v)
Chris Liechtib7550bd2015-08-15 04:09:10 +0200757 for k, v in sorted(TRANSFORMATIONS.items())))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200758 sys.stderr.write('\n')
759 sys.exit(1)
Chris Liechtib3df13e2015-08-25 02:20:09 +0200760 filters = args.filter
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200761 else:
Chris Liechtib3df13e2015-08-25 02:20:09 +0200762 filters = ['default']
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200763
cliechti6385f2c2005-09-21 19:51:19 +0000764
765 try:
766 miniterm = Miniterm(
Chris Liechtib7550bd2015-08-15 04:09:10 +0200767 args.port,
768 args.baudrate,
769 args.parity,
770 rtscts=args.rtscts,
771 xonxoff=args.xonxoff,
772 echo=args.echo,
Chris Liechtib3df13e2015-08-25 02:20:09 +0200773 eol=args.eol.lower(),
774 filters=filters,
Chris Liechti442bf512015-08-15 01:42:24 +0200775 )
Chris Liechtib7550bd2015-08-15 04:09:10 +0200776 miniterm.exit_character = unichr(args.exit_char)
777 miniterm.menu_character = unichr(args.menu_char)
778 miniterm.raw = args.raw
Chris Liechtid698af72015-08-24 20:24:55 +0200779 miniterm.set_rx_encoding(args.serial_port_encoding)
780 miniterm.set_tx_encoding(args.serial_port_encoding)
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 Liechtib7550bd2015-08-15 04:09:10 +0200787 if not args.quiet:
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200788 sys.stderr.write('--- Miniterm on {p.name} {p.baudrate},{p.bytesize},{p.parity},{p.stopbits} ---\n'.format(
789 p=miniterm.serial))
Chris Liechtib7550bd2015-08-15 04:09:10 +0200790 sys.stderr.write('--- Quit: {} | Menu: {} | Help: {} followed by {} ---\n'.format(
Chris Liechti442bf512015-08-15 01:42:24 +0200791 key_description(miniterm.exit_character),
792 key_description(miniterm.menu_character),
793 key_description(miniterm.menu_character),
Chris Liechtib7550bd2015-08-15 04:09:10 +0200794 key_description('\x08'),
Chris Liechti442bf512015-08-15 01:42:24 +0200795 ))
cliechti6fa76fb2009-07-08 23:53:39 +0000796
Chris Liechtib7550bd2015-08-15 04:09:10 +0200797 if args.dtr is not None:
798 if not args.quiet:
799 sys.stderr.write('--- forcing DTR {}\n'.format('active' if args.dtr else 'inactive'))
800 miniterm.serial.setDTR(args.dtr)
801 miniterm.dtr_state = args.dtr
802 if args.rts is not None:
803 if not args.quiet:
804 sys.stderr.write('--- forcing RTS {}\n'.format('active' if args.rts else 'inactive'))
805 miniterm.serial.setRTS(args.rts)
806 miniterm.rts_state = args.rts
cliechti53edb472009-02-06 21:18:46 +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()