blob: 6807153df5709cb44133a0bb9746e767f2e87f6d [file] [log] [blame]
cliechti576de252002-02-28 23:54:44 +00001#!/usr/bin/env python
Chris Liechtifbdd8a02015-08-09 02:37:45 +02002#
cliechtia128a702004-07-21 22:13:31 +00003# Very simple serial terminal
Chris Liechtifbdd8a02015-08-09 02:37:45 +02004#
Chris Liechti68340d72015-08-03 14:15:48 +02005# (C)2002-2015 Chris Liechti <cliechti@gmx.net>
Chris Liechtifbdd8a02015-08-09 02:37:45 +02006#
7# SPDX-License-Identifier: BSD-3-Clause
cliechtifc9eb382002-03-05 01:12:29 +00008
Chris Liechtic7a5d4c2015-08-11 23:32:20 +02009import codecs
Chris Liechtia1d5c6d2015-08-07 14:41:24 +020010import os
11import sys
12import threading
cliechti576de252002-02-28 23:54:44 +000013
Chris Liechtia1d5c6d2015-08-07 14:41:24 +020014import serial
Chris Liechti55ba7d92015-08-15 16:33:51 +020015from serial.tools.list_ports import comports
Chris Liechtia1d5c6d2015-08-07 14:41:24 +020016
Chris Liechti68340d72015-08-03 14:15:48 +020017try:
18 raw_input
19except NameError:
20 raw_input = input # in python3 it's "raw"
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020021 unichr = chr
Chris Liechti68340d72015-08-03 14:15:48 +020022
Chris Liechtic0c660a2015-08-25 00:55:51 +020023from . import hexlify_codec
24codecs.register(lambda c: hexlify_codec.getregentry() if c == 'hexlify' else None)
25
cliechti6c8eb2f2009-07-08 02:10:46 +000026
27def key_description(character):
28 """generate a readable description for a key"""
29 ascii_code = ord(character)
30 if ascii_code < 32:
31 return 'Ctrl+%c' % (ord('@') + ascii_code)
32 else:
33 return repr(character)
34
cliechti91165532011-03-18 02:02:52 +000035
Chris Liechti9a720852015-08-25 00:20:38 +020036# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020037class ConsoleBase(object):
38 def __init__(self):
39 if sys.version_info >= (3, 0):
40 self.byte_output = sys.stdout.buffer
41 else:
42 self.byte_output = sys.stdout
43 self.output = sys.stdout
cliechtif467aa82013-10-13 21:36:49 +000044
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020045 def setup(self):
Chris Liechti1df28272015-08-27 23:37:38 +020046 pass
cliechtif467aa82013-10-13 21:36:49 +000047
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020048 def cleanup(self):
Chris Liechti1df28272015-08-27 23:37:38 +020049 pass
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020050
51 def getkey(self):
52 return None
53
54 def write_bytes(self, s):
55 self.byte_output.write(s)
56 self.byte_output.flush()
57
58 def write(self, s):
59 self.output.write(s)
60 self.output.flush()
61
Chris Liechti269f77b2015-08-24 01:31:42 +020062 # - - - - - - - - - - - - - - - - - - - - - - - -
63 # context manager:
64 # switch terminal temporary to normal mode (e.g. to get user input)
65
66 def __enter__(self):
67 self.cleanup()
68 return self
69
70 def __exit__(self, *args, **kwargs):
71 self.setup()
72
cliechti9c592b32008-06-16 22:00:14 +000073
cliechtifc9eb382002-03-05 01:12:29 +000074if os.name == 'nt':
cliechti576de252002-02-28 23:54:44 +000075 import msvcrt
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020076 import ctypes
77 class Console(ConsoleBase):
Chris Liechticbb00b22015-08-13 22:58:49 +020078 def __init__(self):
79 super(Console, self).__init__()
Chris Liechti1df28272015-08-27 23:37:38 +020080 self._saved_ocp = ctypes.windll.kernel32.GetConsoleOutputCP()
81 self._saved_icp = ctypes.windll.kernel32.GetConsoleCP()
Chris Liechticbb00b22015-08-13 22:58:49 +020082 ctypes.windll.kernel32.SetConsoleOutputCP(65001)
83 ctypes.windll.kernel32.SetConsoleCP(65001)
84 if sys.version_info < (3, 0):
85 class Out:
86 def __init__(self):
87 self.fd = sys.stdout.fileno()
88 def flush(self):
89 pass
90 def write(self, s):
91 os.write(self.fd, s)
92 self.output = codecs.getwriter('UTF-8')(Out(), 'replace')
93 self.byte_output = Out()
94 else:
95 self.output = codecs.getwriter('UTF-8')(sys.stdout.buffer, 'replace')
96
Chris Liechti1df28272015-08-27 23:37:38 +020097 def __del__(self):
98 ctypes.windll.kernel32.SetConsoleOutputCP(self._saved_ocp)
99 ctypes.windll.kernel32.SetConsoleCP(self._saved_icp)
100
cliechti3a8bf092008-09-17 11:26:53 +0000101 def getkey(self):
cliechti91165532011-03-18 02:02:52 +0000102 while True:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200103 z = msvcrt.getwch()
Chris Liechti3b454802015-08-26 23:39:59 +0200104 if z == u'\r':
105 return u'\n'
106 elif z in u'\x00\x0e': # functions keys, ignore
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200107 msvcrt.getwch()
cliechti9c592b32008-06-16 22:00:14 +0000108 else:
cliechti9c592b32008-06-16 22:00:14 +0000109 return z
cliechti53edb472009-02-06 21:18:46 +0000110
cliechti576de252002-02-28 23:54:44 +0000111elif os.name == 'posix':
Chris Liechtia1d5c6d2015-08-07 14:41:24 +0200112 import atexit
113 import termios
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200114 class Console(ConsoleBase):
cliechti9c592b32008-06-16 22:00:14 +0000115 def __init__(self):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200116 super(Console, self).__init__()
cliechti9c592b32008-06-16 22:00:14 +0000117 self.fd = sys.stdin.fileno()
Chris Liechti4d989c22015-08-24 00:24:49 +0200118 self.old = termios.tcgetattr(self.fd)
Chris Liechti89eb2472015-08-08 17:06:25 +0200119 atexit.register(self.cleanup)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200120 if sys.version_info < (3, 0):
Chris Liechtia7e7b692015-08-25 21:10:28 +0200121 self.enc_stdin = codecs.getreader(sys.stdin.encoding)(sys.stdin)
122 else:
123 self.enc_stdin = sys.stdin
cliechti9c592b32008-06-16 22:00:14 +0000124
125 def setup(self):
cliechti9c592b32008-06-16 22:00:14 +0000126 new = termios.tcgetattr(self.fd)
127 new[3] = new[3] & ~termios.ICANON & ~termios.ECHO & ~termios.ISIG
128 new[6][termios.VMIN] = 1
129 new[6][termios.VTIME] = 0
130 termios.tcsetattr(self.fd, termios.TCSANOW, new)
cliechti53edb472009-02-06 21:18:46 +0000131
cliechti9c592b32008-06-16 22:00:14 +0000132 def getkey(self):
Chris Liechtia7e7b692015-08-25 21:10:28 +0200133 c = self.enc_stdin.read(1)
Chris Liechti3b454802015-08-26 23:39:59 +0200134 if c == u'\x7f':
135 c = u'\b' # map the BS key (which yields DEL) to backspace
Chris Liechti9a720852015-08-25 00:20:38 +0200136 return c
cliechti53edb472009-02-06 21:18:46 +0000137
cliechti9c592b32008-06-16 22:00:14 +0000138 def cleanup(self):
Chris Liechti4d989c22015-08-24 00:24:49 +0200139 termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old)
cliechti9c592b32008-06-16 22:00:14 +0000140
cliechti576de252002-02-28 23:54:44 +0000141else:
cliechti8c2ea842011-03-18 01:51:46 +0000142 raise NotImplementedError("Sorry no implementation for your platform (%s) available." % sys.platform)
cliechti576de252002-02-28 23:54:44 +0000143
cliechti6fa76fb2009-07-08 23:53:39 +0000144
Chris Liechti9a720852015-08-25 00:20:38 +0200145# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200146
147class Transform(object):
Chris Liechticbb00b22015-08-13 22:58:49 +0200148 """do-nothing: forward all data unchanged"""
Chris Liechtid698af72015-08-24 20:24:55 +0200149 def rx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200150 """text received from serial port"""
151 return text
152
Chris Liechtid698af72015-08-24 20:24:55 +0200153 def tx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200154 """text to be sent to serial port"""
155 return text
156
157 def echo(self, text):
158 """text to be sent but displayed on console"""
159 return text
160
Chris Liechti442bf512015-08-15 01:42:24 +0200161
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200162class CRLF(Transform):
163 """ENTER sends CR+LF"""
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200164
Chris Liechtid698af72015-08-24 20:24:55 +0200165 def tx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200166 return text.replace('\n', '\r\n')
167
Chris Liechti442bf512015-08-15 01:42:24 +0200168
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200169class CR(Transform):
170 """ENTER sends CR"""
Chris Liechtid698af72015-08-24 20:24:55 +0200171
172 def rx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200173 return text.replace('\r', '\n')
174
Chris Liechtid698af72015-08-24 20:24:55 +0200175 def tx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200176 return text.replace('\n', '\r')
177
Chris Liechti442bf512015-08-15 01:42:24 +0200178
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200179class LF(Transform):
180 """ENTER sends LF"""
181
182
183class NoTerminal(Transform):
184 """remove typical terminal control codes from input"""
Chris Liechti9a720852015-08-25 00:20:38 +0200185
186 REPLACEMENT_MAP = dict((x, 0x2400 + x) for x in range(32) if unichr(x) not in '\r\n\b\t')
187 REPLACEMENT_MAP.update({
188 0x7F: 0x2421, # DEL
189 0x9B: 0x2425, # CSI
190 })
191
Chris Liechtid698af72015-08-24 20:24:55 +0200192 def rx(self, text):
Chris Liechti9a720852015-08-25 00:20:38 +0200193 return text.translate(self.REPLACEMENT_MAP)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200194
Chris Liechtid698af72015-08-24 20:24:55 +0200195 echo = rx
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200196
197
Chris Liechti9a720852015-08-25 00:20:38 +0200198class NoControls(NoTerminal):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200199 """Remove all control codes, incl. CR+LF"""
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200200
Chris Liechti9a720852015-08-25 00:20:38 +0200201 REPLACEMENT_MAP = dict((x, 0x2400 + x) for x in range(32))
202 REPLACEMENT_MAP.update({
203 32: 0x2423, # visual space
204 0x7F: 0x2421, # DEL
205 0x9B: 0x2425, # CSI
206 })
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200207
208
209class Printable(Transform):
Chris Liechtid698af72015-08-24 20:24:55 +0200210 """Show decimal code for all non-ASCII characters and replace most control codes"""
Chris Liechtic0c660a2015-08-25 00:55:51 +0200211
Chris Liechtid698af72015-08-24 20:24:55 +0200212 def rx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200213 r = []
214 for t in text:
Chris Liechti7e9cfd42015-08-12 15:28:19 +0200215 if ' ' <= t < '\x7f' or t in '\r\n\b\t':
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200216 r.append(t)
Chris Liechtid698af72015-08-24 20:24:55 +0200217 elif t < ' ':
218 r.append(unichr(0x2400 + ord(t)))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200219 else:
220 r.extend(unichr(0x2080 + ord(d) - 48) for d in '{:d}'.format(ord(t)))
221 r.append(' ')
222 return ''.join(r)
223
Chris Liechtid698af72015-08-24 20:24:55 +0200224 echo = rx
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200225
226
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200227class Colorize(Transform):
Chris Liechti442bf512015-08-15 01:42:24 +0200228 """Apply different colors for received and echo"""
Chris Liechtic0c660a2015-08-25 00:55:51 +0200229
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200230 def __init__(self):
231 # XXX make it configurable, use colorama?
232 self.input_color = '\x1b[37m'
233 self.echo_color = '\x1b[31m'
234
Chris Liechtid698af72015-08-24 20:24:55 +0200235 def rx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200236 return self.input_color + text
237
238 def echo(self, text):
239 return self.echo_color + text
240
Chris Liechti442bf512015-08-15 01:42:24 +0200241
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200242class DebugIO(Transform):
Chris Liechti442bf512015-08-15 01:42:24 +0200243 """Print what is sent and received"""
Chris Liechtic0c660a2015-08-25 00:55:51 +0200244
Chris Liechtid698af72015-08-24 20:24:55 +0200245 def rx(self, text):
Chris Liechtie1384382015-08-15 17:06:05 +0200246 sys.stderr.write(' [RX:{}] '.format(repr(text)))
247 sys.stderr.flush()
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200248 return text
249
Chris Liechtid698af72015-08-24 20:24:55 +0200250 def tx(self, text):
Chris Liechtie1384382015-08-15 17:06:05 +0200251 sys.stderr.write(' [TX:{}] '.format(repr(text)))
252 sys.stderr.flush()
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200253 return text
254
Chris Liechti442bf512015-08-15 01:42:24 +0200255
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200256# other ideas:
257# - add date/time for each newline
258# - insert newline after: a) timeout b) packet end character
259
Chris Liechtib3df13e2015-08-25 02:20:09 +0200260EOL_TRANSFORMATIONS = {
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200261 'crlf': CRLF,
262 'cr': CR,
263 'lf': LF,
Chris Liechtib3df13e2015-08-25 02:20:09 +0200264 }
265
266TRANSFORMATIONS = {
Chris Liechticbb00b22015-08-13 22:58:49 +0200267 'direct': Transform, # no transformation
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200268 'default': NoTerminal,
269 'nocontrol': NoControls,
270 'printable': Printable,
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200271 'colorize': Colorize,
272 'debug': DebugIO,
273 }
274
Chris Liechti9a720852015-08-25 00:20:38 +0200275# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200276
cliechti1351dde2012-04-12 16:47:47 +0000277def dump_port_list():
278 if comports:
279 sys.stderr.write('\n--- Available ports:\n')
280 for port, desc, hwid in sorted(comports()):
281 #~ sys.stderr.write('--- %-20s %s [%s]\n' % (port, desc, hwid))
282 sys.stderr.write('--- %-20s %s\n' % (port, desc))
283
284
cliechti8c2ea842011-03-18 01:51:46 +0000285class Miniterm(object):
Chris Liechti3b454802015-08-26 23:39:59 +0200286 def __init__(self, serial_instance, echo=False, eol='crlf', filters=()):
Chris Liechti89eb2472015-08-08 17:06:25 +0200287 self.console = Console()
Chris Liechti3b454802015-08-26 23:39:59 +0200288 self.serial = serial_instance
cliechti6385f2c2005-09-21 19:51:19 +0000289 self.echo = echo
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200290 self.raw = False
Chris Liechti442bf512015-08-15 01:42:24 +0200291 self.input_encoding = 'UTF-8'
Chris Liechti442bf512015-08-15 01:42:24 +0200292 self.output_encoding = 'UTF-8'
Chris Liechtib3df13e2015-08-25 02:20:09 +0200293 self.eol = eol
294 self.filters = filters
295 self.update_transformations()
Chris Liechti442bf512015-08-15 01:42:24 +0200296 self.exit_character = 0x1d # GS/CTRL+]
297 self.menu_character = 0x14 # Menu: CTRL+T
cliechti576de252002-02-28 23:54:44 +0000298
cliechti8c2ea842011-03-18 01:51:46 +0000299 def _start_reader(self):
300 """Start reader thread"""
301 self._reader_alive = True
cliechti6fa76fb2009-07-08 23:53:39 +0000302 # start serial->console thread
Chris Liechti55ba7d92015-08-15 16:33:51 +0200303 self.receiver_thread = threading.Thread(target=self.reader, name='rx')
304 self.receiver_thread.daemon = True
cliechti6385f2c2005-09-21 19:51:19 +0000305 self.receiver_thread.start()
cliechti8c2ea842011-03-18 01:51:46 +0000306
307 def _stop_reader(self):
308 """Stop reader thread only, wait for clean exit of thread"""
309 self._reader_alive = False
310 self.receiver_thread.join()
311
312
313 def start(self):
314 self.alive = True
315 self._start_reader()
cliechti6fa76fb2009-07-08 23:53:39 +0000316 # enter console->serial loop
Chris Liechti55ba7d92015-08-15 16:33:51 +0200317 self.transmitter_thread = threading.Thread(target=self.writer, name='tx')
318 self.transmitter_thread.daemon = True
cliechti6385f2c2005-09-21 19:51:19 +0000319 self.transmitter_thread.start()
Chris Liechti89eb2472015-08-08 17:06:25 +0200320 self.console.setup()
cliechti53edb472009-02-06 21:18:46 +0000321
cliechti6385f2c2005-09-21 19:51:19 +0000322 def stop(self):
323 self.alive = False
cliechti53edb472009-02-06 21:18:46 +0000324
cliechtibf6bb7d2006-03-30 00:28:18 +0000325 def join(self, transmit_only=False):
cliechti6385f2c2005-09-21 19:51:19 +0000326 self.transmitter_thread.join()
cliechtibf6bb7d2006-03-30 00:28:18 +0000327 if not transmit_only:
328 self.receiver_thread.join()
cliechti6385f2c2005-09-21 19:51:19 +0000329
Chris Liechtib3df13e2015-08-25 02:20:09 +0200330 def update_transformations(self):
331 transformations = [EOL_TRANSFORMATIONS[self.eol]] + [TRANSFORMATIONS[f] for f in self.filters]
332 self.tx_transformations = [t() for t in transformations]
333 self.rx_transformations = list(reversed(self.tx_transformations))
334
Chris Liechtid698af72015-08-24 20:24:55 +0200335 def set_rx_encoding(self, encoding, errors='replace'):
336 self.input_encoding = encoding
337 self.rx_decoder = codecs.getincrementaldecoder(encoding)(errors)
338
339 def set_tx_encoding(self, encoding, errors='replace'):
340 self.output_encoding = encoding
341 self.tx_encoder = codecs.getincrementalencoder(encoding)(errors)
342
343
cliechti6c8eb2f2009-07-08 02:10:46 +0000344 def dump_port_settings(self):
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200345 sys.stderr.write("\n--- Settings: {p.name} {p.baudrate},{p.bytesize},{p.parity},{p.stopbits}\n".format(
346 p=self.serial))
Chris Liechti442bf512015-08-15 01:42:24 +0200347 sys.stderr.write('--- RTS: {:8} DTR: {:8} BREAK: {:8}\n'.format(
Chris Liechti3b454802015-08-26 23:39:59 +0200348 ('active' if self.serial.rts else 'inactive'),
349 ('active' if self.serial.dtr else 'inactive'),
350 ('active' if self.serial.break_condition else 'inactive')))
cliechti10114572009-08-05 23:40:50 +0000351 try:
Chris Liechti442bf512015-08-15 01:42:24 +0200352 sys.stderr.write('--- CTS: {:8} DSR: {:8} RI: {:8} CD: {:8}\n'.format(
Chris Liechti3b454802015-08-26 23:39:59 +0200353 ('active' if self.serial.cts else 'inactive'),
354 ('active' if self.serial.dsr else 'inactive'),
355 ('active' if self.serial.ri else 'inactive'),
356 ('active' if self.serial.cd else 'inactive')))
cliechti10114572009-08-05 23:40:50 +0000357 except serial.SerialException:
Chris Liechti55ba7d92015-08-15 16:33:51 +0200358 # on RFC 2217 ports, it can happen if no modem state notification was
cliechti10114572009-08-05 23:40:50 +0000359 # yet received. ignore this error.
360 pass
Chris Liechti442bf512015-08-15 01:42:24 +0200361 sys.stderr.write('--- software flow control: {}\n'.format('active' if self.serial.xonxoff else 'inactive'))
362 sys.stderr.write('--- hardware flow control: {}\n'.format('active' if self.serial.rtscts else 'inactive'))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200363 #~ sys.stderr.write('--- data escaping: %s linefeed: %s\n' % (
364 #~ REPR_MODES[self.repr_mode],
365 #~ LF_MODES[self.convert_outgoing]))
Chris Liechti442bf512015-08-15 01:42:24 +0200366 sys.stderr.write('--- serial input encoding: {}\n'.format(self.input_encoding))
367 sys.stderr.write('--- serial output encoding: {}\n'.format(self.output_encoding))
Chris Liechtib3df13e2015-08-25 02:20:09 +0200368 sys.stderr.write('--- EOL: {}\n'.format(self.eol.upper()))
369 sys.stderr.write('--- filters: {}\n'.format(' '.join(self.filters)))
cliechti6c8eb2f2009-07-08 02:10:46 +0000370
cliechti6385f2c2005-09-21 19:51:19 +0000371 def reader(self):
372 """loop and copy serial->console"""
cliechti6963b262010-01-02 03:01:21 +0000373 try:
cliechti8c2ea842011-03-18 01:51:46 +0000374 while self.alive and self._reader_alive:
Chris Liechti188cf592015-08-22 00:28:19 +0200375 # read all that is there or wait for one byte
Chris Liechti3b454802015-08-26 23:39:59 +0200376 data = self.serial.read(self.serial.in_waiting or 1)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200377 if data:
378 if self.raw:
379 self.console.write_bytes(data)
cliechti6963b262010-01-02 03:01:21 +0000380 else:
Chris Liechtid698af72015-08-24 20:24:55 +0200381 text = self.rx_decoder.decode(data)
Chris Liechtie1384382015-08-15 17:06:05 +0200382 for transformation in self.rx_transformations:
Chris Liechtid698af72015-08-24 20:24:55 +0200383 text = transformation.rx(text)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200384 self.console.write(text)
Chris Liechti68340d72015-08-03 14:15:48 +0200385 except serial.SerialException as e:
cliechti6963b262010-01-02 03:01:21 +0000386 self.alive = False
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200387 # XXX would be nice if the writer could be interrupted at this
388 # point... to exit completely
cliechti6963b262010-01-02 03:01:21 +0000389 raise
cliechti576de252002-02-28 23:54:44 +0000390
cliechti576de252002-02-28 23:54:44 +0000391
cliechti6385f2c2005-09-21 19:51:19 +0000392 def writer(self):
cliechti8c2ea842011-03-18 01:51:46 +0000393 """\
Chris Liechti442bf512015-08-15 01:42:24 +0200394 Loop and copy console->serial until self.exit_character character is
395 found. When self.menu_character is found, interpret the next key
cliechti8c2ea842011-03-18 01:51:46 +0000396 locally.
cliechti6c8eb2f2009-07-08 02:10:46 +0000397 """
398 menu_active = False
399 try:
400 while self.alive:
401 try:
Chris Liechti89eb2472015-08-08 17:06:25 +0200402 c = self.console.getkey()
cliechti6c8eb2f2009-07-08 02:10:46 +0000403 except KeyboardInterrupt:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200404 c = '\x03'
cliechti6c8eb2f2009-07-08 02:10:46 +0000405 if menu_active:
Chris Liechti7af7c752015-08-12 15:45:19 +0200406 self.handle_menu_key(c)
cliechti6c8eb2f2009-07-08 02:10:46 +0000407 menu_active = False
Chris Liechti442bf512015-08-15 01:42:24 +0200408 elif c == self.menu_character:
Chris Liechti7af7c752015-08-12 15:45:19 +0200409 menu_active = True # next char will be for menu
Chris Liechti442bf512015-08-15 01:42:24 +0200410 elif c == self.exit_character:
Chris Liechti7af7c752015-08-12 15:45:19 +0200411 self.stop() # exit app
412 break
cliechti6c8eb2f2009-07-08 02:10:46 +0000413 else:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200414 #~ if self.raw:
415 text = c
Chris Liechtie1384382015-08-15 17:06:05 +0200416 for transformation in self.tx_transformations:
Chris Liechtid698af72015-08-24 20:24:55 +0200417 text = transformation.tx(text)
Chris Liechtid698af72015-08-24 20:24:55 +0200418 self.serial.write(self.tx_encoder.encode(text))
cliechti6c8eb2f2009-07-08 02:10:46 +0000419 if self.echo:
Chris Liechti3b454802015-08-26 23:39:59 +0200420 echo_text = c
421 for transformation in self.tx_transformations:
422 echo_text = transformation.echo(echo_text)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200423 self.console.write(echo_text)
cliechti6c8eb2f2009-07-08 02:10:46 +0000424 except:
425 self.alive = False
426 raise
cliechti6385f2c2005-09-21 19:51:19 +0000427
Chris Liechti7af7c752015-08-12 15:45:19 +0200428 def handle_menu_key(self, c):
429 """Implement a simple menu / settings"""
Chris Liechti55ba7d92015-08-15 16:33:51 +0200430 if c == self.menu_character or c == self.exit_character:
431 # Menu/exit character again -> send itself
Chris Liechtid698af72015-08-24 20:24:55 +0200432 self.serial.write(self.tx_encoder.encode(c))
Chris Liechti7af7c752015-08-12 15:45:19 +0200433 if self.echo:
434 self.console.write(c)
Chris Liechtib7550bd2015-08-15 04:09:10 +0200435 elif c == '\x15': # CTRL+U -> upload file
Chris Liechti7af7c752015-08-12 15:45:19 +0200436 sys.stderr.write('\n--- File to upload: ')
437 sys.stderr.flush()
Chris Liechti269f77b2015-08-24 01:31:42 +0200438 with self.console:
439 filename = sys.stdin.readline().rstrip('\r\n')
440 if filename:
441 try:
442 with open(filename, 'rb') as f:
443 sys.stderr.write('--- Sending file {} ---\n'.format(filename))
444 while True:
445 block = f.read(1024)
446 if not block:
447 break
448 self.serial.write(block)
449 # Wait for output buffer to drain.
450 self.serial.flush()
451 sys.stderr.write('.') # Progress indicator.
452 sys.stderr.write('\n--- File {} sent ---\n'.format(filename))
453 except IOError as e:
454 sys.stderr.write('--- ERROR opening file {}: {} ---\n'.format(filename, e))
Chris Liechti7af7c752015-08-12 15:45:19 +0200455 elif c in '\x08hH?': # CTRL+H, h, H, ? -> Show help
Chris Liechti442bf512015-08-15 01:42:24 +0200456 sys.stderr.write(self.get_help_text())
Chris Liechti7af7c752015-08-12 15:45:19 +0200457 elif c == '\x12': # CTRL+R -> Toggle RTS
Chris Liechti3b454802015-08-26 23:39:59 +0200458 self.serial.rts = not self.serial.rts
459 sys.stderr.write('--- RTS {} ---\n'.format('active' if self.serial.rts else 'inactive'))
Chris Liechti7af7c752015-08-12 15:45:19 +0200460 elif c == '\x04': # CTRL+D -> Toggle DTR
Chris Liechti3b454802015-08-26 23:39:59 +0200461 self.serial.dtr = not self.serial.dtr
462 sys.stderr.write('--- DTR {} ---\n'.format('active' if self.serial.dtr else 'inactive'))
Chris Liechti7af7c752015-08-12 15:45:19 +0200463 elif c == '\x02': # CTRL+B -> toggle BREAK condition
Chris Liechti3b454802015-08-26 23:39:59 +0200464 self.serial.break_condition = not self.serial.break_condition
465 sys.stderr.write('--- BREAK {} ---\n'.format('active' if self.serial.break_condition else 'inactive'))
Chris Liechti7af7c752015-08-12 15:45:19 +0200466 elif c == '\x05': # CTRL+E -> toggle local echo
467 self.echo = not self.echo
Chris Liechti442bf512015-08-15 01:42:24 +0200468 sys.stderr.write('--- local echo {} ---\n'.format('active' if self.echo else 'inactive'))
Chris Liechtib3df13e2015-08-25 02:20:09 +0200469 elif c == '\x06': # CTRL+F -> edit filters
470 sys.stderr.write('\n--- Available Filters:\n')
471 sys.stderr.write('\n'.join(
472 '--- {:<10} = {.__doc__}'.format(k, v)
473 for k, v in sorted(TRANSFORMATIONS.items())))
474 sys.stderr.write('\n--- Enter new filter name(s) [{}]: '.format(' '.join(self.filters)))
475 with self.console:
476 new_filters = sys.stdin.readline().lower().split()
477 if new_filters:
478 for f in new_filters:
479 if f not in TRANSFORMATIONS:
480 sys.stderr.write('--- unknown filter: {}'.format(repr(f)))
481 break
482 else:
483 self.filters = new_filters
484 self.update_transformations()
485 sys.stderr.write('--- filters: {}\n'.format(' '.join(self.filters)))
486 elif c == '\x0c': # CTRL+L -> EOL mode
487 modes = list(EOL_TRANSFORMATIONS) # keys
488 eol = modes.index(self.eol) + 1
489 if eol >= len(modes):
490 eol = 0
491 self.eol = modes[eol]
492 sys.stderr.write('--- EOL: {} ---\n'.format(self.eol.upper()))
493 self.update_transformations()
494 elif c == '\x01': # CTRL+A -> set encoding
495 sys.stderr.write('\n--- Enter new encoding name [{}]: '.format(self.input_encoding))
496 with self.console:
497 new_encoding = sys.stdin.readline().strip()
498 if new_encoding:
499 try:
500 codecs.lookup(new_encoding)
501 except LookupError:
502 sys.stderr.write('--- invalid encoding name: {}\n'.format(new_encoding))
503 else:
504 self.set_rx_encoding(new_encoding)
505 self.set_tx_encoding(new_encoding)
506 sys.stderr.write('--- serial input encoding: {}\n'.format(self.input_encoding))
507 sys.stderr.write('--- serial output encoding: {}\n'.format(self.output_encoding))
Chris Liechti7af7c752015-08-12 15:45:19 +0200508 elif c == '\x09': # CTRL+I -> info
509 self.dump_port_settings()
510 #~ elif c == '\x01': # CTRL+A -> cycle escape mode
511 #~ elif c == '\x0c': # CTRL+L -> cycle linefeed mode
512 elif c in 'pP': # P -> change port
513 dump_port_list()
514 sys.stderr.write('--- Enter port name: ')
515 sys.stderr.flush()
Chris Liechti269f77b2015-08-24 01:31:42 +0200516 with self.console:
517 try:
518 port = sys.stdin.readline().strip()
519 except KeyboardInterrupt:
520 port = None
Chris Liechti7af7c752015-08-12 15:45:19 +0200521 if port and port != self.serial.port:
522 # reader thread needs to be shut down
523 self._stop_reader()
524 # save settings
525 settings = self.serial.getSettingsDict()
526 try:
527 new_serial = serial.serial_for_url(port, do_not_open=True)
528 # restore settings and open
529 new_serial.applySettingsDict(settings)
530 new_serial.open()
531 new_serial.setRTS(self.rts_state)
532 new_serial.setDTR(self.dtr_state)
533 new_serial.setBreak(self.break_state)
534 except Exception as e:
Chris Liechti442bf512015-08-15 01:42:24 +0200535 sys.stderr.write('--- ERROR opening new port: {} ---\n'.format(e))
Chris Liechti7af7c752015-08-12 15:45:19 +0200536 new_serial.close()
537 else:
538 self.serial.close()
539 self.serial = new_serial
Chris Liechti442bf512015-08-15 01:42:24 +0200540 sys.stderr.write('--- Port changed to: {} ---\n'.format(self.serial.port))
Chris Liechti7af7c752015-08-12 15:45:19 +0200541 # and restart the reader thread
542 self._start_reader()
543 elif c in 'bB': # B -> change baudrate
544 sys.stderr.write('\n--- Baudrate: ')
545 sys.stderr.flush()
Chris Liechti269f77b2015-08-24 01:31:42 +0200546 with self.console:
547 backup = self.serial.baudrate
548 try:
549 self.serial.baudrate = int(sys.stdin.readline().strip())
550 except ValueError as e:
551 sys.stderr.write('--- ERROR setting baudrate: %s ---\n'.format(e))
552 self.serial.baudrate = backup
553 else:
554 self.dump_port_settings()
Chris Liechti7af7c752015-08-12 15:45:19 +0200555 elif c == '8': # 8 -> change to 8 bits
556 self.serial.bytesize = serial.EIGHTBITS
557 self.dump_port_settings()
558 elif c == '7': # 7 -> change to 8 bits
559 self.serial.bytesize = serial.SEVENBITS
560 self.dump_port_settings()
561 elif c in 'eE': # E -> change to even parity
562 self.serial.parity = serial.PARITY_EVEN
563 self.dump_port_settings()
564 elif c in 'oO': # O -> change to odd parity
565 self.serial.parity = serial.PARITY_ODD
566 self.dump_port_settings()
567 elif c in 'mM': # M -> change to mark parity
568 self.serial.parity = serial.PARITY_MARK
569 self.dump_port_settings()
570 elif c in 'sS': # S -> change to space parity
571 self.serial.parity = serial.PARITY_SPACE
572 self.dump_port_settings()
573 elif c in 'nN': # N -> change to no parity
574 self.serial.parity = serial.PARITY_NONE
575 self.dump_port_settings()
576 elif c == '1': # 1 -> change to 1 stop bits
577 self.serial.stopbits = serial.STOPBITS_ONE
578 self.dump_port_settings()
579 elif c == '2': # 2 -> change to 2 stop bits
580 self.serial.stopbits = serial.STOPBITS_TWO
581 self.dump_port_settings()
582 elif c == '3': # 3 -> change to 1.5 stop bits
583 self.serial.stopbits = serial.STOPBITS_ONE_POINT_FIVE
584 self.dump_port_settings()
585 elif c in 'xX': # X -> change software flow control
586 self.serial.xonxoff = (c == 'X')
587 self.dump_port_settings()
588 elif c in 'rR': # R -> change hardware flow control
589 self.serial.rtscts = (c == 'R')
590 self.dump_port_settings()
591 else:
Chris Liechti442bf512015-08-15 01:42:24 +0200592 sys.stderr.write('--- unknown menu character {} --\n'.format(key_description(c)))
593
594 def get_help_text(self):
Chris Liechti55ba7d92015-08-15 16:33:51 +0200595 # help text, starts with blank line!
Chris Liechti442bf512015-08-15 01:42:24 +0200596 return """
597--- pySerial ({version}) - miniterm - help
598---
599--- {exit:8} Exit program
600--- {menu:8} Menu escape key, followed by:
601--- Menu keys:
602--- {menu:7} Send the menu character itself to remote
603--- {exit:7} Send the exit character itself to remote
604--- {info:7} Show info
605--- {upload:7} Upload file (prompt will be shown)
Chris Liechtib3df13e2015-08-25 02:20:09 +0200606--- {repr:7} encoding
607--- {filter:7} edit filters
Chris Liechti442bf512015-08-15 01:42:24 +0200608--- Toggles:
Chris Liechtib3df13e2015-08-25 02:20:09 +0200609--- {rts:7} RTS {dtr:7} DTR {brk:7} BREAK
610--- {echo:7} echo {eol:7} EOL
Chris Liechti442bf512015-08-15 01:42:24 +0200611---
Chris Liechti55ba7d92015-08-15 16:33:51 +0200612--- Port settings ({menu} followed by the following):
Chris Liechti442bf512015-08-15 01:42:24 +0200613--- p change port
614--- 7 8 set data bits
Chris Liechtib7550bd2015-08-15 04:09:10 +0200615--- N E O S M change parity (None, Even, Odd, Space, Mark)
Chris Liechti442bf512015-08-15 01:42:24 +0200616--- 1 2 3 set stop bits (1, 2, 1.5)
617--- b change baud rate
618--- x X disable/enable software flow control
619--- r R disable/enable hardware flow control
620""".format(
621 version=getattr(serial, 'VERSION', 'unknown version'),
622 exit=key_description(self.exit_character),
623 menu=key_description(self.menu_character),
Chris Liechtib7550bd2015-08-15 04:09:10 +0200624 rts=key_description('\x12'),
625 dtr=key_description('\x04'),
626 brk=key_description('\x02'),
627 echo=key_description('\x05'),
628 info=key_description('\x09'),
629 upload=key_description('\x15'),
Chris Liechtib3df13e2015-08-25 02:20:09 +0200630 repr=key_description('\x01'),
631 filter=key_description('\x06'),
632 eol=key_description('\x0c'),
Chris Liechti442bf512015-08-15 01:42:24 +0200633 )
Chris Liechti7af7c752015-08-12 15:45:19 +0200634
635
636
Chris Liechtib3df13e2015-08-25 02:20:09 +0200637# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechti55ba7d92015-08-15 16:33:51 +0200638# default args can be used to override when calling main() from an other script
639# e.g to create a miniterm-my-device.py
640def main(default_port=None, default_baudrate=9600, default_rts=None, default_dtr=None):
Chris Liechtib7550bd2015-08-15 04:09:10 +0200641 import argparse
cliechti6385f2c2005-09-21 19:51:19 +0000642
Chris Liechtib7550bd2015-08-15 04:09:10 +0200643 parser = argparse.ArgumentParser(
644 description="Miniterm - A simple terminal program for the serial port.")
cliechti6385f2c2005-09-21 19:51:19 +0000645
Chris Liechtib7550bd2015-08-15 04:09:10 +0200646 parser.add_argument("port",
647 nargs='?',
648 help="serial port name",
Chris Liechti55ba7d92015-08-15 16:33:51 +0200649 default=default_port)
cliechti5370cee2013-10-13 03:08:19 +0000650
Chris Liechtib7550bd2015-08-15 04:09:10 +0200651 parser.add_argument("baudrate",
652 nargs='?',
653 type=int,
654 help="set baud rate, default: %(default)s",
Chris Liechti55ba7d92015-08-15 16:33:51 +0200655 default=default_baudrate)
cliechti6385f2c2005-09-21 19:51:19 +0000656
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200657 group = parser.add_argument_group("port settings")
cliechti53edb472009-02-06 21:18:46 +0000658
Chris Liechtib7550bd2015-08-15 04:09:10 +0200659 group.add_argument("--parity",
660 choices=['N', 'E', 'O', 'S', 'M'],
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200661 type=lambda c: c.upper(),
Chris Liechtib7550bd2015-08-15 04:09:10 +0200662 help="set parity, one of {N E O S M}, default: N",
663 default='N')
cliechti53edb472009-02-06 21:18:46 +0000664
Chris Liechtib7550bd2015-08-15 04:09:10 +0200665 group.add_argument("--rtscts",
666 action="store_true",
667 help="enable RTS/CTS flow control (default off)",
668 default=False)
cliechti53edb472009-02-06 21:18:46 +0000669
Chris Liechtib7550bd2015-08-15 04:09:10 +0200670 group.add_argument("--xonxoff",
671 action="store_true",
672 help="enable software flow control (default off)",
673 default=False)
cliechti53edb472009-02-06 21:18:46 +0000674
Chris Liechtib7550bd2015-08-15 04:09:10 +0200675 group.add_argument("--rts",
676 type=int,
677 help="set initial RTS line state (possible values: 0, 1)",
Chris Liechti55ba7d92015-08-15 16:33:51 +0200678 default=default_rts)
cliechti5370cee2013-10-13 03:08:19 +0000679
Chris Liechtib7550bd2015-08-15 04:09:10 +0200680 group.add_argument("--dtr",
681 type=int,
682 help="set initial DTR line state (possible values: 0, 1)",
Chris Liechti55ba7d92015-08-15 16:33:51 +0200683 default=default_dtr)
cliechti5370cee2013-10-13 03:08:19 +0000684
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200685 group = parser.add_argument_group("data handling")
cliechti5370cee2013-10-13 03:08:19 +0000686
Chris Liechtib7550bd2015-08-15 04:09:10 +0200687 group.add_argument("-e", "--echo",
688 action="store_true",
689 help="enable local echo (default off)",
690 default=False)
cliechti5370cee2013-10-13 03:08:19 +0000691
Chris Liechtib7550bd2015-08-15 04:09:10 +0200692 group.add_argument("--encoding",
693 dest="serial_port_encoding",
694 metavar="CODEC",
Chris Liechtia7e7b692015-08-25 21:10:28 +0200695 help="set the encoding for the serial port (e.g. hexlify, Latin1, UTF-8), default: %(default)s",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200696 default='UTF-8')
cliechti5370cee2013-10-13 03:08:19 +0000697
Chris Liechtib3df13e2015-08-25 02:20:09 +0200698 group.add_argument("-f", "--filter",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200699 action="append",
700 metavar="NAME",
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200701 help="add text transformation",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200702 default=[])
Chris Liechti2b1b3552015-08-12 15:35:33 +0200703
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200704 group.add_argument("--eol",
705 choices=['CR', 'LF', 'CRLF'],
706 type=lambda c: c.upper(),
707 help="end of line mode",
708 default='CRLF')
cliechti53edb472009-02-06 21:18:46 +0000709
Chris Liechtib7550bd2015-08-15 04:09:10 +0200710 group.add_argument("--raw",
711 action="store_true",
712 help="Do no apply any encodings/transformations",
713 default=False)
cliechti6385f2c2005-09-21 19:51:19 +0000714
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200715 group = parser.add_argument_group("hotkeys")
cliechtib7d746d2006-03-28 22:44:30 +0000716
Chris Liechtib7550bd2015-08-15 04:09:10 +0200717 group.add_argument("--exit-char",
718 type=int,
Chris Liechti55ba7d92015-08-15 16:33:51 +0200719 metavar='NUM',
720 help="Unicode of special character that is used to exit the application, default: %(default)s",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200721 default=0x1d # GS/CTRL+]
722 )
cliechtibf6bb7d2006-03-30 00:28:18 +0000723
Chris Liechtib7550bd2015-08-15 04:09:10 +0200724 group.add_argument("--menu-char",
725 type=int,
Chris Liechti55ba7d92015-08-15 16:33:51 +0200726 metavar='NUM',
727 help="Unicode code of special character that is used to control miniterm (menu), default: %(default)s",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200728 default=0x14 # Menu: CTRL+T
729 )
cliechti9c592b32008-06-16 22:00:14 +0000730
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200731 group = parser.add_argument_group("diagnostics")
cliechti6385f2c2005-09-21 19:51:19 +0000732
Chris Liechtib7550bd2015-08-15 04:09:10 +0200733 group.add_argument("-q", "--quiet",
734 action="store_true",
735 help="suppress non-error messages",
736 default=False)
cliechti5370cee2013-10-13 03:08:19 +0000737
Chris Liechtib7550bd2015-08-15 04:09:10 +0200738 group.add_argument("--develop",
739 action="store_true",
740 help="show Python traceback on error",
741 default=False)
cliechti5370cee2013-10-13 03:08:19 +0000742
Chris Liechtib7550bd2015-08-15 04:09:10 +0200743 args = parser.parse_args()
cliechti5370cee2013-10-13 03:08:19 +0000744
Chris Liechtib7550bd2015-08-15 04:09:10 +0200745 if args.menu_char == args.exit_char:
cliechti6c8eb2f2009-07-08 02:10:46 +0000746 parser.error('--exit-char can not be the same as --menu-char')
747
cliechti9c592b32008-06-16 22:00:14 +0000748
Chris Liechtib7550bd2015-08-15 04:09:10 +0200749 # no port given on command line -> ask user now
750 if args.port is None:
751 dump_port_list()
752 args.port = raw_input('Enter port name:')
cliechti53edb472009-02-06 21:18:46 +0000753
Chris Liechtib3df13e2015-08-25 02:20:09 +0200754 if args.filter:
755 if 'help' in args.filter:
756 sys.stderr.write('Available filters:\n')
Chris Liechti442bf512015-08-15 01:42:24 +0200757 sys.stderr.write('\n'.join(
Chris Liechtib3df13e2015-08-25 02:20:09 +0200758 '{:<10} = {.__doc__}'.format(k, v)
Chris Liechtib7550bd2015-08-15 04:09:10 +0200759 for k, v in sorted(TRANSFORMATIONS.items())))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200760 sys.stderr.write('\n')
761 sys.exit(1)
Chris Liechtib3df13e2015-08-25 02:20:09 +0200762 filters = args.filter
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200763 else:
Chris Liechtib3df13e2015-08-25 02:20:09 +0200764 filters = ['default']
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200765
cliechti6385f2c2005-09-21 19:51:19 +0000766
767 try:
Chris Liechti3b454802015-08-26 23:39:59 +0200768 serial_instance = serial.serial_for_url(
Chris Liechtib7550bd2015-08-15 04:09:10 +0200769 args.port,
770 args.baudrate,
Chris Liechti3b454802015-08-26 23:39:59 +0200771 parity=args.parity,
Chris Liechtib7550bd2015-08-15 04:09:10 +0200772 rtscts=args.rtscts,
773 xonxoff=args.xonxoff,
Chris Liechti3b454802015-08-26 23:39:59 +0200774 timeout=1,
775 do_not_open=True)
776
777 if args.dtr is not None:
778 if not args.quiet:
779 sys.stderr.write('--- forcing DTR {}\n'.format('active' if args.dtr else 'inactive'))
780 serial_instance.dtr = args.dtr
781 if args.rts is not None:
782 if not args.quiet:
783 sys.stderr.write('--- forcing RTS {}\n'.format('active' if args.rts else 'inactive'))
784 serial_instance.rts = args.rts
785
786 serial_instance.open()
Chris Liechti68340d72015-08-03 14:15:48 +0200787 except serial.SerialException as e:
Chris Liechtiaccd2012015-08-17 03:09:23 +0200788 sys.stderr.write('could not open port {}: {}\n'.format(repr(args.port), e))
Chris Liechtib7550bd2015-08-15 04:09:10 +0200789 if args.develop:
Chris Liechti91090912015-08-05 02:36:14 +0200790 raise
cliechti6385f2c2005-09-21 19:51:19 +0000791 sys.exit(1)
792
Chris Liechti3b454802015-08-26 23:39:59 +0200793 miniterm = Miniterm(
794 serial_instance,
795 echo=args.echo,
796 eol=args.eol.lower(),
797 filters=filters)
798 miniterm.exit_character = unichr(args.exit_char)
799 miniterm.menu_character = unichr(args.menu_char)
800 miniterm.raw = args.raw
801 miniterm.set_rx_encoding(args.serial_port_encoding)
802 miniterm.set_tx_encoding(args.serial_port_encoding)
803
Chris Liechtib7550bd2015-08-15 04:09:10 +0200804 if not args.quiet:
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200805 sys.stderr.write('--- Miniterm on {p.name} {p.baudrate},{p.bytesize},{p.parity},{p.stopbits} ---\n'.format(
806 p=miniterm.serial))
Chris Liechtib7550bd2015-08-15 04:09:10 +0200807 sys.stderr.write('--- Quit: {} | Menu: {} | Help: {} followed by {} ---\n'.format(
Chris Liechti442bf512015-08-15 01:42:24 +0200808 key_description(miniterm.exit_character),
809 key_description(miniterm.menu_character),
810 key_description(miniterm.menu_character),
Chris Liechtib7550bd2015-08-15 04:09:10 +0200811 key_description('\x08'),
Chris Liechti442bf512015-08-15 01:42:24 +0200812 ))
cliechti6fa76fb2009-07-08 23:53:39 +0000813
cliechti6385f2c2005-09-21 19:51:19 +0000814 miniterm.start()
cliechti258ab0a2011-03-21 23:03:45 +0000815 try:
816 miniterm.join(True)
817 except KeyboardInterrupt:
818 pass
Chris Liechtib7550bd2015-08-15 04:09:10 +0200819 if not args.quiet:
cliechtibf6bb7d2006-03-30 00:28:18 +0000820 sys.stderr.write("\n--- exit ---\n")
cliechti6385f2c2005-09-21 19:51:19 +0000821 miniterm.join()
cliechtibf6bb7d2006-03-30 00:28:18 +0000822
cliechti5370cee2013-10-13 03:08:19 +0000823# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
cliechti8b3ad392002-03-03 20:12:21 +0000824if __name__ == '__main__':
cliechti6385f2c2005-09-21 19:51:19 +0000825 main()