blob: 513bb2a86e3e8c0311af5bab6bbae856bc92976d [file] [log] [blame]
cliechti576de252002-02-28 23:54:44 +00001#!/usr/bin/env python
Chris Liechtifbdd8a02015-08-09 02:37:45 +02002#
cliechtia128a702004-07-21 22:13:31 +00003# Very simple serial terminal
Chris Liechtifbdd8a02015-08-09 02:37:45 +02004#
Chris Liechti68340d72015-08-03 14:15:48 +02005# (C)2002-2015 Chris Liechti <cliechti@gmx.net>
Chris Liechtifbdd8a02015-08-09 02:37:45 +02006#
7# SPDX-License-Identifier: BSD-3-Clause
cliechtifc9eb382002-03-05 01:12:29 +00008
Chris Liechtic7a5d4c2015-08-11 23:32:20 +02009import codecs
Chris Liechtia1d5c6d2015-08-07 14:41:24 +020010import os
11import sys
12import threading
cliechti576de252002-02-28 23:54:44 +000013
Chris Liechtia1d5c6d2015-08-07 14:41:24 +020014import serial
Chris Liechti55ba7d92015-08-15 16:33:51 +020015from serial.tools.list_ports import comports
Chris Liechtia1d5c6d2015-08-07 14:41:24 +020016
Chris Liechti68340d72015-08-03 14:15:48 +020017try:
18 raw_input
19except NameError:
20 raw_input = input # in python3 it's "raw"
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020021 unichr = chr
Chris Liechti68340d72015-08-03 14:15:48 +020022
Chris Liechtic0c660a2015-08-25 00:55:51 +020023from . import hexlify_codec
24codecs.register(lambda c: hexlify_codec.getregentry() if c == 'hexlify' else None)
25
cliechti6c8eb2f2009-07-08 02:10:46 +000026
27def key_description(character):
28 """generate a readable description for a key"""
29 ascii_code = ord(character)
30 if ascii_code < 32:
31 return 'Ctrl+%c' % (ord('@') + ascii_code)
32 else:
33 return repr(character)
34
cliechti91165532011-03-18 02:02:52 +000035
Chris Liechti9a720852015-08-25 00:20:38 +020036# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020037class ConsoleBase(object):
38 def __init__(self):
39 if sys.version_info >= (3, 0):
40 self.byte_output = sys.stdout.buffer
41 else:
42 self.byte_output = sys.stdout
43 self.output = sys.stdout
cliechtif467aa82013-10-13 21:36:49 +000044
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020045 def setup(self):
Chris Liechti1df28272015-08-27 23:37:38 +020046 pass
cliechtif467aa82013-10-13 21:36:49 +000047
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020048 def cleanup(self):
Chris Liechti1df28272015-08-27 23:37:38 +020049 pass
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020050
51 def getkey(self):
52 return None
53
54 def write_bytes(self, s):
55 self.byte_output.write(s)
56 self.byte_output.flush()
57
58 def write(self, s):
59 self.output.write(s)
60 self.output.flush()
61
Chris Liechti269f77b2015-08-24 01:31:42 +020062 # - - - - - - - - - - - - - - - - - - - - - - - -
63 # context manager:
64 # switch terminal temporary to normal mode (e.g. to get user input)
65
66 def __enter__(self):
67 self.cleanup()
68 return self
69
70 def __exit__(self, *args, **kwargs):
71 self.setup()
72
cliechti9c592b32008-06-16 22:00:14 +000073
cliechtifc9eb382002-03-05 01:12:29 +000074if os.name == 'nt':
cliechti576de252002-02-28 23:54:44 +000075 import msvcrt
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020076 import ctypes
Chris Liechti9cc696b2015-08-28 00:54:22 +020077
78 class Out(object):
79 def __init__(self, fd):
80 self.fd = fd
81
82 def flush(self):
83 pass
84
85 def write(self, s):
86 os.write(self.fd, s)
87
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020088 class Console(ConsoleBase):
Chris Liechticbb00b22015-08-13 22:58:49 +020089 def __init__(self):
90 super(Console, self).__init__()
Chris Liechti1df28272015-08-27 23:37:38 +020091 self._saved_ocp = ctypes.windll.kernel32.GetConsoleOutputCP()
92 self._saved_icp = ctypes.windll.kernel32.GetConsoleCP()
Chris Liechticbb00b22015-08-13 22:58:49 +020093 ctypes.windll.kernel32.SetConsoleOutputCP(65001)
94 ctypes.windll.kernel32.SetConsoleCP(65001)
Chris Liechti9cc696b2015-08-28 00:54:22 +020095 self.output = codecs.getwriter('UTF-8')(Out(sys.stdout.fileno()), 'replace')
96 # the change of the code page is not propagated to Python, manually fix it
97 sys.stderr = codecs.getwriter('UTF-8')(Out(sys.stderr.fileno()), 'replace')
98 sys.stdout = self.output
Chris Liechticbb00b22015-08-13 22:58:49 +020099
Chris Liechti1df28272015-08-27 23:37:38 +0200100 def __del__(self):
101 ctypes.windll.kernel32.SetConsoleOutputCP(self._saved_ocp)
102 ctypes.windll.kernel32.SetConsoleCP(self._saved_icp)
103
cliechti3a8bf092008-09-17 11:26:53 +0000104 def getkey(self):
cliechti91165532011-03-18 02:02:52 +0000105 while True:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200106 z = msvcrt.getwch()
Chris Liechti3b454802015-08-26 23:39:59 +0200107 if z == u'\r':
108 return u'\n'
109 elif z in u'\x00\x0e': # functions keys, ignore
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200110 msvcrt.getwch()
cliechti9c592b32008-06-16 22:00:14 +0000111 else:
cliechti9c592b32008-06-16 22:00:14 +0000112 return z
cliechti53edb472009-02-06 21:18:46 +0000113
cliechti576de252002-02-28 23:54:44 +0000114elif os.name == 'posix':
Chris Liechtia1d5c6d2015-08-07 14:41:24 +0200115 import atexit
116 import termios
Chris Liechti9cc696b2015-08-28 00:54:22 +0200117
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200118 class Console(ConsoleBase):
cliechti9c592b32008-06-16 22:00:14 +0000119 def __init__(self):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200120 super(Console, self).__init__()
cliechti9c592b32008-06-16 22:00:14 +0000121 self.fd = sys.stdin.fileno()
Chris Liechti4d989c22015-08-24 00:24:49 +0200122 self.old = termios.tcgetattr(self.fd)
Chris Liechti89eb2472015-08-08 17:06:25 +0200123 atexit.register(self.cleanup)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200124 if sys.version_info < (3, 0):
Chris Liechtia7e7b692015-08-25 21:10:28 +0200125 self.enc_stdin = codecs.getreader(sys.stdin.encoding)(sys.stdin)
126 else:
127 self.enc_stdin = sys.stdin
cliechti9c592b32008-06-16 22:00:14 +0000128
129 def setup(self):
cliechti9c592b32008-06-16 22:00:14 +0000130 new = termios.tcgetattr(self.fd)
131 new[3] = new[3] & ~termios.ICANON & ~termios.ECHO & ~termios.ISIG
132 new[6][termios.VMIN] = 1
133 new[6][termios.VTIME] = 0
134 termios.tcsetattr(self.fd, termios.TCSANOW, new)
cliechti53edb472009-02-06 21:18:46 +0000135
cliechti9c592b32008-06-16 22:00:14 +0000136 def getkey(self):
Chris Liechtia7e7b692015-08-25 21:10:28 +0200137 c = self.enc_stdin.read(1)
Chris Liechti3b454802015-08-26 23:39:59 +0200138 if c == u'\x7f':
139 c = u'\b' # map the BS key (which yields DEL) to backspace
Chris Liechti9a720852015-08-25 00:20:38 +0200140 return c
cliechti53edb472009-02-06 21:18:46 +0000141
cliechti9c592b32008-06-16 22:00:14 +0000142 def cleanup(self):
Chris Liechti4d989c22015-08-24 00:24:49 +0200143 termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old)
cliechti9c592b32008-06-16 22:00:14 +0000144
cliechti576de252002-02-28 23:54:44 +0000145else:
cliechti8c2ea842011-03-18 01:51:46 +0000146 raise NotImplementedError("Sorry no implementation for your platform (%s) available." % sys.platform)
cliechti576de252002-02-28 23:54:44 +0000147
cliechti6fa76fb2009-07-08 23:53:39 +0000148
Chris Liechti9a720852015-08-25 00:20:38 +0200149# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200150
151class Transform(object):
Chris Liechticbb00b22015-08-13 22:58:49 +0200152 """do-nothing: forward all data unchanged"""
Chris Liechtid698af72015-08-24 20:24:55 +0200153 def rx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200154 """text received from serial port"""
155 return text
156
Chris Liechtid698af72015-08-24 20:24:55 +0200157 def tx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200158 """text to be sent to serial port"""
159 return text
160
161 def echo(self, text):
162 """text to be sent but displayed on console"""
163 return text
164
Chris Liechti442bf512015-08-15 01:42:24 +0200165
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200166class CRLF(Transform):
167 """ENTER sends CR+LF"""
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200168
Chris Liechtid698af72015-08-24 20:24:55 +0200169 def tx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200170 return text.replace('\n', '\r\n')
171
Chris Liechti442bf512015-08-15 01:42:24 +0200172
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200173class CR(Transform):
174 """ENTER sends CR"""
Chris Liechtid698af72015-08-24 20:24:55 +0200175
176 def rx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200177 return text.replace('\r', '\n')
178
Chris Liechtid698af72015-08-24 20:24:55 +0200179 def tx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200180 return text.replace('\n', '\r')
181
Chris Liechti442bf512015-08-15 01:42:24 +0200182
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200183class LF(Transform):
184 """ENTER sends LF"""
185
186
187class NoTerminal(Transform):
188 """remove typical terminal control codes from input"""
Chris Liechti9a720852015-08-25 00:20:38 +0200189
190 REPLACEMENT_MAP = dict((x, 0x2400 + x) for x in range(32) if unichr(x) not in '\r\n\b\t')
191 REPLACEMENT_MAP.update({
192 0x7F: 0x2421, # DEL
193 0x9B: 0x2425, # CSI
194 })
195
Chris Liechtid698af72015-08-24 20:24:55 +0200196 def rx(self, text):
Chris Liechti9a720852015-08-25 00:20:38 +0200197 return text.translate(self.REPLACEMENT_MAP)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200198
Chris Liechtid698af72015-08-24 20:24:55 +0200199 echo = rx
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200200
201
Chris Liechti9a720852015-08-25 00:20:38 +0200202class NoControls(NoTerminal):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200203 """Remove all control codes, incl. CR+LF"""
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200204
Chris Liechti9a720852015-08-25 00:20:38 +0200205 REPLACEMENT_MAP = dict((x, 0x2400 + x) for x in range(32))
206 REPLACEMENT_MAP.update({
207 32: 0x2423, # visual space
208 0x7F: 0x2421, # DEL
209 0x9B: 0x2425, # CSI
210 })
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200211
212
213class Printable(Transform):
Chris Liechtid698af72015-08-24 20:24:55 +0200214 """Show decimal code for all non-ASCII characters and replace most control codes"""
Chris Liechtic0c660a2015-08-25 00:55:51 +0200215
Chris Liechtid698af72015-08-24 20:24:55 +0200216 def rx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200217 r = []
218 for t in text:
Chris Liechti7e9cfd42015-08-12 15:28:19 +0200219 if ' ' <= t < '\x7f' or t in '\r\n\b\t':
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200220 r.append(t)
Chris Liechtid698af72015-08-24 20:24:55 +0200221 elif t < ' ':
222 r.append(unichr(0x2400 + ord(t)))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200223 else:
224 r.extend(unichr(0x2080 + ord(d) - 48) for d in '{:d}'.format(ord(t)))
225 r.append(' ')
226 return ''.join(r)
227
Chris Liechtid698af72015-08-24 20:24:55 +0200228 echo = rx
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200229
230
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200231class Colorize(Transform):
Chris Liechti442bf512015-08-15 01:42:24 +0200232 """Apply different colors for received and echo"""
Chris Liechtic0c660a2015-08-25 00:55:51 +0200233
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200234 def __init__(self):
235 # XXX make it configurable, use colorama?
236 self.input_color = '\x1b[37m'
237 self.echo_color = '\x1b[31m'
238
Chris Liechtid698af72015-08-24 20:24:55 +0200239 def rx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200240 return self.input_color + text
241
242 def echo(self, text):
243 return self.echo_color + text
244
Chris Liechti442bf512015-08-15 01:42:24 +0200245
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200246class DebugIO(Transform):
Chris Liechti442bf512015-08-15 01:42:24 +0200247 """Print what is sent and received"""
Chris Liechtic0c660a2015-08-25 00:55:51 +0200248
Chris Liechtid698af72015-08-24 20:24:55 +0200249 def rx(self, text):
Chris Liechtie1384382015-08-15 17:06:05 +0200250 sys.stderr.write(' [RX:{}] '.format(repr(text)))
251 sys.stderr.flush()
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200252 return text
253
Chris Liechtid698af72015-08-24 20:24:55 +0200254 def tx(self, text):
Chris Liechtie1384382015-08-15 17:06:05 +0200255 sys.stderr.write(' [TX:{}] '.format(repr(text)))
256 sys.stderr.flush()
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200257 return text
258
Chris Liechti442bf512015-08-15 01:42:24 +0200259
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200260# other ideas:
261# - add date/time for each newline
262# - insert newline after: a) timeout b) packet end character
263
Chris Liechtib3df13e2015-08-25 02:20:09 +0200264EOL_TRANSFORMATIONS = {
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200265 'crlf': CRLF,
266 'cr': CR,
267 'lf': LF,
Chris Liechtib3df13e2015-08-25 02:20:09 +0200268 }
269
270TRANSFORMATIONS = {
Chris Liechticbb00b22015-08-13 22:58:49 +0200271 'direct': Transform, # no transformation
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200272 'default': NoTerminal,
273 'nocontrol': NoControls,
274 'printable': Printable,
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200275 'colorize': Colorize,
276 'debug': DebugIO,
277 }
278
Chris Liechti9a720852015-08-25 00:20:38 +0200279# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200280
cliechti1351dde2012-04-12 16:47:47 +0000281def dump_port_list():
282 if comports:
283 sys.stderr.write('\n--- Available ports:\n')
284 for port, desc, hwid in sorted(comports()):
285 #~ sys.stderr.write('--- %-20s %s [%s]\n' % (port, desc, hwid))
286 sys.stderr.write('--- %-20s %s\n' % (port, desc))
287
288
cliechti8c2ea842011-03-18 01:51:46 +0000289class Miniterm(object):
Chris Liechti3b454802015-08-26 23:39:59 +0200290 def __init__(self, serial_instance, echo=False, eol='crlf', filters=()):
Chris Liechti89eb2472015-08-08 17:06:25 +0200291 self.console = Console()
Chris Liechti3b454802015-08-26 23:39:59 +0200292 self.serial = serial_instance
cliechti6385f2c2005-09-21 19:51:19 +0000293 self.echo = echo
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200294 self.raw = False
Chris Liechti442bf512015-08-15 01:42:24 +0200295 self.input_encoding = 'UTF-8'
Chris Liechti442bf512015-08-15 01:42:24 +0200296 self.output_encoding = 'UTF-8'
Chris Liechtib3df13e2015-08-25 02:20:09 +0200297 self.eol = eol
298 self.filters = filters
299 self.update_transformations()
Chris Liechti442bf512015-08-15 01:42:24 +0200300 self.exit_character = 0x1d # GS/CTRL+]
301 self.menu_character = 0x14 # Menu: CTRL+T
cliechti576de252002-02-28 23:54:44 +0000302
cliechti8c2ea842011-03-18 01:51:46 +0000303 def _start_reader(self):
304 """Start reader thread"""
305 self._reader_alive = True
cliechti6fa76fb2009-07-08 23:53:39 +0000306 # start serial->console thread
Chris Liechti55ba7d92015-08-15 16:33:51 +0200307 self.receiver_thread = threading.Thread(target=self.reader, name='rx')
308 self.receiver_thread.daemon = True
cliechti6385f2c2005-09-21 19:51:19 +0000309 self.receiver_thread.start()
cliechti8c2ea842011-03-18 01:51:46 +0000310
311 def _stop_reader(self):
312 """Stop reader thread only, wait for clean exit of thread"""
313 self._reader_alive = False
314 self.receiver_thread.join()
315
316
317 def start(self):
318 self.alive = True
319 self._start_reader()
cliechti6fa76fb2009-07-08 23:53:39 +0000320 # enter console->serial loop
Chris Liechti55ba7d92015-08-15 16:33:51 +0200321 self.transmitter_thread = threading.Thread(target=self.writer, name='tx')
322 self.transmitter_thread.daemon = True
cliechti6385f2c2005-09-21 19:51:19 +0000323 self.transmitter_thread.start()
Chris Liechti89eb2472015-08-08 17:06:25 +0200324 self.console.setup()
cliechti53edb472009-02-06 21:18:46 +0000325
cliechti6385f2c2005-09-21 19:51:19 +0000326 def stop(self):
327 self.alive = False
cliechti53edb472009-02-06 21:18:46 +0000328
cliechtibf6bb7d2006-03-30 00:28:18 +0000329 def join(self, transmit_only=False):
cliechti6385f2c2005-09-21 19:51:19 +0000330 self.transmitter_thread.join()
cliechtibf6bb7d2006-03-30 00:28:18 +0000331 if not transmit_only:
332 self.receiver_thread.join()
cliechti6385f2c2005-09-21 19:51:19 +0000333
Chris Liechtib3df13e2015-08-25 02:20:09 +0200334 def update_transformations(self):
335 transformations = [EOL_TRANSFORMATIONS[self.eol]] + [TRANSFORMATIONS[f] for f in self.filters]
336 self.tx_transformations = [t() for t in transformations]
337 self.rx_transformations = list(reversed(self.tx_transformations))
338
Chris Liechtid698af72015-08-24 20:24:55 +0200339 def set_rx_encoding(self, encoding, errors='replace'):
340 self.input_encoding = encoding
341 self.rx_decoder = codecs.getincrementaldecoder(encoding)(errors)
342
343 def set_tx_encoding(self, encoding, errors='replace'):
344 self.output_encoding = encoding
345 self.tx_encoder = codecs.getincrementalencoder(encoding)(errors)
346
347
cliechti6c8eb2f2009-07-08 02:10:46 +0000348 def dump_port_settings(self):
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200349 sys.stderr.write("\n--- Settings: {p.name} {p.baudrate},{p.bytesize},{p.parity},{p.stopbits}\n".format(
350 p=self.serial))
Chris Liechti442bf512015-08-15 01:42:24 +0200351 sys.stderr.write('--- RTS: {:8} DTR: {:8} BREAK: {:8}\n'.format(
Chris Liechti3b454802015-08-26 23:39:59 +0200352 ('active' if self.serial.rts else 'inactive'),
353 ('active' if self.serial.dtr else 'inactive'),
354 ('active' if self.serial.break_condition else 'inactive')))
cliechti10114572009-08-05 23:40:50 +0000355 try:
Chris Liechti442bf512015-08-15 01:42:24 +0200356 sys.stderr.write('--- CTS: {:8} DSR: {:8} RI: {:8} CD: {:8}\n'.format(
Chris Liechti3b454802015-08-26 23:39:59 +0200357 ('active' if self.serial.cts else 'inactive'),
358 ('active' if self.serial.dsr else 'inactive'),
359 ('active' if self.serial.ri else 'inactive'),
360 ('active' if self.serial.cd else 'inactive')))
cliechti10114572009-08-05 23:40:50 +0000361 except serial.SerialException:
Chris Liechti55ba7d92015-08-15 16:33:51 +0200362 # on RFC 2217 ports, it can happen if no modem state notification was
cliechti10114572009-08-05 23:40:50 +0000363 # yet received. ignore this error.
364 pass
Chris Liechti442bf512015-08-15 01:42:24 +0200365 sys.stderr.write('--- software flow control: {}\n'.format('active' if self.serial.xonxoff else 'inactive'))
366 sys.stderr.write('--- hardware flow control: {}\n'.format('active' if self.serial.rtscts else 'inactive'))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200367 #~ sys.stderr.write('--- data escaping: %s linefeed: %s\n' % (
368 #~ REPR_MODES[self.repr_mode],
369 #~ LF_MODES[self.convert_outgoing]))
Chris Liechti442bf512015-08-15 01:42:24 +0200370 sys.stderr.write('--- serial input encoding: {}\n'.format(self.input_encoding))
371 sys.stderr.write('--- serial output encoding: {}\n'.format(self.output_encoding))
Chris Liechtib3df13e2015-08-25 02:20:09 +0200372 sys.stderr.write('--- EOL: {}\n'.format(self.eol.upper()))
373 sys.stderr.write('--- filters: {}\n'.format(' '.join(self.filters)))
cliechti6c8eb2f2009-07-08 02:10:46 +0000374
cliechti6385f2c2005-09-21 19:51:19 +0000375 def reader(self):
376 """loop and copy serial->console"""
cliechti6963b262010-01-02 03:01:21 +0000377 try:
cliechti8c2ea842011-03-18 01:51:46 +0000378 while self.alive and self._reader_alive:
Chris Liechti188cf592015-08-22 00:28:19 +0200379 # read all that is there or wait for one byte
Chris Liechti3b454802015-08-26 23:39:59 +0200380 data = self.serial.read(self.serial.in_waiting or 1)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200381 if data:
382 if self.raw:
383 self.console.write_bytes(data)
cliechti6963b262010-01-02 03:01:21 +0000384 else:
Chris Liechtid698af72015-08-24 20:24:55 +0200385 text = self.rx_decoder.decode(data)
Chris Liechtie1384382015-08-15 17:06:05 +0200386 for transformation in self.rx_transformations:
Chris Liechtid698af72015-08-24 20:24:55 +0200387 text = transformation.rx(text)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200388 self.console.write(text)
Chris Liechti68340d72015-08-03 14:15:48 +0200389 except serial.SerialException as e:
cliechti6963b262010-01-02 03:01:21 +0000390 self.alive = False
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200391 # XXX would be nice if the writer could be interrupted at this
392 # point... to exit completely
cliechti6963b262010-01-02 03:01:21 +0000393 raise
cliechti576de252002-02-28 23:54:44 +0000394
cliechti576de252002-02-28 23:54:44 +0000395
cliechti6385f2c2005-09-21 19:51:19 +0000396 def writer(self):
cliechti8c2ea842011-03-18 01:51:46 +0000397 """\
Chris Liechti442bf512015-08-15 01:42:24 +0200398 Loop and copy console->serial until self.exit_character character is
399 found. When self.menu_character is found, interpret the next key
cliechti8c2ea842011-03-18 01:51:46 +0000400 locally.
cliechti6c8eb2f2009-07-08 02:10:46 +0000401 """
402 menu_active = False
403 try:
404 while self.alive:
405 try:
Chris Liechti89eb2472015-08-08 17:06:25 +0200406 c = self.console.getkey()
cliechti6c8eb2f2009-07-08 02:10:46 +0000407 except KeyboardInterrupt:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200408 c = '\x03'
cliechti6c8eb2f2009-07-08 02:10:46 +0000409 if menu_active:
Chris Liechti7af7c752015-08-12 15:45:19 +0200410 self.handle_menu_key(c)
cliechti6c8eb2f2009-07-08 02:10:46 +0000411 menu_active = False
Chris Liechti442bf512015-08-15 01:42:24 +0200412 elif c == self.menu_character:
Chris Liechti7af7c752015-08-12 15:45:19 +0200413 menu_active = True # next char will be for menu
Chris Liechti442bf512015-08-15 01:42:24 +0200414 elif c == self.exit_character:
Chris Liechti7af7c752015-08-12 15:45:19 +0200415 self.stop() # exit app
416 break
cliechti6c8eb2f2009-07-08 02:10:46 +0000417 else:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200418 #~ if self.raw:
419 text = c
Chris Liechtie1384382015-08-15 17:06:05 +0200420 for transformation in self.tx_transformations:
Chris Liechtid698af72015-08-24 20:24:55 +0200421 text = transformation.tx(text)
Chris Liechtid698af72015-08-24 20:24:55 +0200422 self.serial.write(self.tx_encoder.encode(text))
cliechti6c8eb2f2009-07-08 02:10:46 +0000423 if self.echo:
Chris Liechti3b454802015-08-26 23:39:59 +0200424 echo_text = c
425 for transformation in self.tx_transformations:
426 echo_text = transformation.echo(echo_text)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200427 self.console.write(echo_text)
cliechti6c8eb2f2009-07-08 02:10:46 +0000428 except:
429 self.alive = False
430 raise
cliechti6385f2c2005-09-21 19:51:19 +0000431
Chris Liechti7af7c752015-08-12 15:45:19 +0200432 def handle_menu_key(self, c):
433 """Implement a simple menu / settings"""
Chris Liechti55ba7d92015-08-15 16:33:51 +0200434 if c == self.menu_character or c == self.exit_character:
435 # Menu/exit character again -> send itself
Chris Liechtid698af72015-08-24 20:24:55 +0200436 self.serial.write(self.tx_encoder.encode(c))
Chris Liechti7af7c752015-08-12 15:45:19 +0200437 if self.echo:
438 self.console.write(c)
Chris Liechtib7550bd2015-08-15 04:09:10 +0200439 elif c == '\x15': # CTRL+U -> upload file
Chris Liechti7af7c752015-08-12 15:45:19 +0200440 sys.stderr.write('\n--- File to upload: ')
441 sys.stderr.flush()
Chris Liechti269f77b2015-08-24 01:31:42 +0200442 with self.console:
443 filename = sys.stdin.readline().rstrip('\r\n')
444 if filename:
445 try:
446 with open(filename, 'rb') as f:
447 sys.stderr.write('--- Sending file {} ---\n'.format(filename))
448 while True:
449 block = f.read(1024)
450 if not block:
451 break
452 self.serial.write(block)
453 # Wait for output buffer to drain.
454 self.serial.flush()
455 sys.stderr.write('.') # Progress indicator.
456 sys.stderr.write('\n--- File {} sent ---\n'.format(filename))
457 except IOError as e:
458 sys.stderr.write('--- ERROR opening file {}: {} ---\n'.format(filename, e))
Chris Liechti7af7c752015-08-12 15:45:19 +0200459 elif c in '\x08hH?': # CTRL+H, h, H, ? -> Show help
Chris Liechti442bf512015-08-15 01:42:24 +0200460 sys.stderr.write(self.get_help_text())
Chris Liechti7af7c752015-08-12 15:45:19 +0200461 elif c == '\x12': # CTRL+R -> Toggle RTS
Chris Liechti3b454802015-08-26 23:39:59 +0200462 self.serial.rts = not self.serial.rts
463 sys.stderr.write('--- RTS {} ---\n'.format('active' if self.serial.rts else 'inactive'))
Chris Liechti7af7c752015-08-12 15:45:19 +0200464 elif c == '\x04': # CTRL+D -> Toggle DTR
Chris Liechti3b454802015-08-26 23:39:59 +0200465 self.serial.dtr = not self.serial.dtr
466 sys.stderr.write('--- DTR {} ---\n'.format('active' if self.serial.dtr else 'inactive'))
Chris Liechti7af7c752015-08-12 15:45:19 +0200467 elif c == '\x02': # CTRL+B -> toggle BREAK condition
Chris Liechti3b454802015-08-26 23:39:59 +0200468 self.serial.break_condition = not self.serial.break_condition
469 sys.stderr.write('--- BREAK {} ---\n'.format('active' if self.serial.break_condition else 'inactive'))
Chris Liechti7af7c752015-08-12 15:45:19 +0200470 elif c == '\x05': # CTRL+E -> toggle local echo
471 self.echo = not self.echo
Chris Liechti442bf512015-08-15 01:42:24 +0200472 sys.stderr.write('--- local echo {} ---\n'.format('active' if self.echo else 'inactive'))
Chris Liechtib3df13e2015-08-25 02:20:09 +0200473 elif c == '\x06': # CTRL+F -> edit filters
474 sys.stderr.write('\n--- Available Filters:\n')
475 sys.stderr.write('\n'.join(
476 '--- {:<10} = {.__doc__}'.format(k, v)
477 for k, v in sorted(TRANSFORMATIONS.items())))
478 sys.stderr.write('\n--- Enter new filter name(s) [{}]: '.format(' '.join(self.filters)))
479 with self.console:
480 new_filters = sys.stdin.readline().lower().split()
481 if new_filters:
482 for f in new_filters:
483 if f not in TRANSFORMATIONS:
484 sys.stderr.write('--- unknown filter: {}'.format(repr(f)))
485 break
486 else:
487 self.filters = new_filters
488 self.update_transformations()
489 sys.stderr.write('--- filters: {}\n'.format(' '.join(self.filters)))
490 elif c == '\x0c': # CTRL+L -> EOL mode
491 modes = list(EOL_TRANSFORMATIONS) # keys
492 eol = modes.index(self.eol) + 1
493 if eol >= len(modes):
494 eol = 0
495 self.eol = modes[eol]
496 sys.stderr.write('--- EOL: {} ---\n'.format(self.eol.upper()))
497 self.update_transformations()
498 elif c == '\x01': # CTRL+A -> set encoding
499 sys.stderr.write('\n--- Enter new encoding name [{}]: '.format(self.input_encoding))
500 with self.console:
501 new_encoding = sys.stdin.readline().strip()
502 if new_encoding:
503 try:
504 codecs.lookup(new_encoding)
505 except LookupError:
506 sys.stderr.write('--- invalid encoding name: {}\n'.format(new_encoding))
507 else:
508 self.set_rx_encoding(new_encoding)
509 self.set_tx_encoding(new_encoding)
510 sys.stderr.write('--- serial input encoding: {}\n'.format(self.input_encoding))
511 sys.stderr.write('--- serial output encoding: {}\n'.format(self.output_encoding))
Chris Liechti7af7c752015-08-12 15:45:19 +0200512 elif c == '\x09': # CTRL+I -> info
513 self.dump_port_settings()
514 #~ elif c == '\x01': # CTRL+A -> cycle escape mode
515 #~ elif c == '\x0c': # CTRL+L -> cycle linefeed mode
516 elif c in 'pP': # P -> change port
517 dump_port_list()
518 sys.stderr.write('--- Enter port name: ')
519 sys.stderr.flush()
Chris Liechti269f77b2015-08-24 01:31:42 +0200520 with self.console:
521 try:
522 port = sys.stdin.readline().strip()
523 except KeyboardInterrupt:
524 port = None
Chris Liechti7af7c752015-08-12 15:45:19 +0200525 if port and port != self.serial.port:
526 # reader thread needs to be shut down
527 self._stop_reader()
528 # save settings
529 settings = self.serial.getSettingsDict()
530 try:
531 new_serial = serial.serial_for_url(port, do_not_open=True)
532 # restore settings and open
533 new_serial.applySettingsDict(settings)
534 new_serial.open()
535 new_serial.setRTS(self.rts_state)
536 new_serial.setDTR(self.dtr_state)
537 new_serial.setBreak(self.break_state)
538 except Exception as e:
Chris Liechti442bf512015-08-15 01:42:24 +0200539 sys.stderr.write('--- ERROR opening new port: {} ---\n'.format(e))
Chris Liechti7af7c752015-08-12 15:45:19 +0200540 new_serial.close()
541 else:
542 self.serial.close()
543 self.serial = new_serial
Chris Liechti442bf512015-08-15 01:42:24 +0200544 sys.stderr.write('--- Port changed to: {} ---\n'.format(self.serial.port))
Chris Liechti7af7c752015-08-12 15:45:19 +0200545 # and restart the reader thread
546 self._start_reader()
547 elif c in 'bB': # B -> change baudrate
548 sys.stderr.write('\n--- Baudrate: ')
549 sys.stderr.flush()
Chris Liechti269f77b2015-08-24 01:31:42 +0200550 with self.console:
551 backup = self.serial.baudrate
552 try:
553 self.serial.baudrate = int(sys.stdin.readline().strip())
554 except ValueError as e:
555 sys.stderr.write('--- ERROR setting baudrate: %s ---\n'.format(e))
556 self.serial.baudrate = backup
557 else:
558 self.dump_port_settings()
Chris Liechti7af7c752015-08-12 15:45:19 +0200559 elif c == '8': # 8 -> change to 8 bits
560 self.serial.bytesize = serial.EIGHTBITS
561 self.dump_port_settings()
562 elif c == '7': # 7 -> change to 8 bits
563 self.serial.bytesize = serial.SEVENBITS
564 self.dump_port_settings()
565 elif c in 'eE': # E -> change to even parity
566 self.serial.parity = serial.PARITY_EVEN
567 self.dump_port_settings()
568 elif c in 'oO': # O -> change to odd parity
569 self.serial.parity = serial.PARITY_ODD
570 self.dump_port_settings()
571 elif c in 'mM': # M -> change to mark parity
572 self.serial.parity = serial.PARITY_MARK
573 self.dump_port_settings()
574 elif c in 'sS': # S -> change to space parity
575 self.serial.parity = serial.PARITY_SPACE
576 self.dump_port_settings()
577 elif c in 'nN': # N -> change to no parity
578 self.serial.parity = serial.PARITY_NONE
579 self.dump_port_settings()
580 elif c == '1': # 1 -> change to 1 stop bits
581 self.serial.stopbits = serial.STOPBITS_ONE
582 self.dump_port_settings()
583 elif c == '2': # 2 -> change to 2 stop bits
584 self.serial.stopbits = serial.STOPBITS_TWO
585 self.dump_port_settings()
586 elif c == '3': # 3 -> change to 1.5 stop bits
587 self.serial.stopbits = serial.STOPBITS_ONE_POINT_FIVE
588 self.dump_port_settings()
589 elif c in 'xX': # X -> change software flow control
590 self.serial.xonxoff = (c == 'X')
591 self.dump_port_settings()
592 elif c in 'rR': # R -> change hardware flow control
593 self.serial.rtscts = (c == 'R')
594 self.dump_port_settings()
595 else:
Chris Liechti442bf512015-08-15 01:42:24 +0200596 sys.stderr.write('--- unknown menu character {} --\n'.format(key_description(c)))
597
598 def get_help_text(self):
Chris Liechti55ba7d92015-08-15 16:33:51 +0200599 # help text, starts with blank line!
Chris Liechti442bf512015-08-15 01:42:24 +0200600 return """
601--- pySerial ({version}) - miniterm - help
602---
603--- {exit:8} Exit program
604--- {menu:8} Menu escape key, followed by:
605--- Menu keys:
606--- {menu:7} Send the menu character itself to remote
607--- {exit:7} Send the exit character itself to remote
608--- {info:7} Show info
609--- {upload:7} Upload file (prompt will be shown)
Chris Liechtib3df13e2015-08-25 02:20:09 +0200610--- {repr:7} encoding
611--- {filter:7} edit filters
Chris Liechti442bf512015-08-15 01:42:24 +0200612--- Toggles:
Chris Liechtib3df13e2015-08-25 02:20:09 +0200613--- {rts:7} RTS {dtr:7} DTR {brk:7} BREAK
614--- {echo:7} echo {eol:7} EOL
Chris Liechti442bf512015-08-15 01:42:24 +0200615---
Chris Liechti55ba7d92015-08-15 16:33:51 +0200616--- Port settings ({menu} followed by the following):
Chris Liechti442bf512015-08-15 01:42:24 +0200617--- p change port
618--- 7 8 set data bits
Chris Liechtib7550bd2015-08-15 04:09:10 +0200619--- N E O S M change parity (None, Even, Odd, Space, Mark)
Chris Liechti442bf512015-08-15 01:42:24 +0200620--- 1 2 3 set stop bits (1, 2, 1.5)
621--- b change baud rate
622--- x X disable/enable software flow control
623--- r R disable/enable hardware flow control
624""".format(
625 version=getattr(serial, 'VERSION', 'unknown version'),
626 exit=key_description(self.exit_character),
627 menu=key_description(self.menu_character),
Chris Liechtib7550bd2015-08-15 04:09:10 +0200628 rts=key_description('\x12'),
629 dtr=key_description('\x04'),
630 brk=key_description('\x02'),
631 echo=key_description('\x05'),
632 info=key_description('\x09'),
633 upload=key_description('\x15'),
Chris Liechtib3df13e2015-08-25 02:20:09 +0200634 repr=key_description('\x01'),
635 filter=key_description('\x06'),
636 eol=key_description('\x0c'),
Chris Liechti442bf512015-08-15 01:42:24 +0200637 )
Chris Liechti7af7c752015-08-12 15:45:19 +0200638
639
640
Chris Liechtib3df13e2015-08-25 02:20:09 +0200641# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Chris Liechti55ba7d92015-08-15 16:33:51 +0200642# default args can be used to override when calling main() from an other script
643# e.g to create a miniterm-my-device.py
644def main(default_port=None, default_baudrate=9600, default_rts=None, default_dtr=None):
Chris Liechtib7550bd2015-08-15 04:09:10 +0200645 import argparse
cliechti6385f2c2005-09-21 19:51:19 +0000646
Chris Liechtib7550bd2015-08-15 04:09:10 +0200647 parser = argparse.ArgumentParser(
648 description="Miniterm - A simple terminal program for the serial port.")
cliechti6385f2c2005-09-21 19:51:19 +0000649
Chris Liechtib7550bd2015-08-15 04:09:10 +0200650 parser.add_argument("port",
651 nargs='?',
652 help="serial port name",
Chris Liechti55ba7d92015-08-15 16:33:51 +0200653 default=default_port)
cliechti5370cee2013-10-13 03:08:19 +0000654
Chris Liechtib7550bd2015-08-15 04:09:10 +0200655 parser.add_argument("baudrate",
656 nargs='?',
657 type=int,
658 help="set baud rate, default: %(default)s",
Chris Liechti55ba7d92015-08-15 16:33:51 +0200659 default=default_baudrate)
cliechti6385f2c2005-09-21 19:51:19 +0000660
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200661 group = parser.add_argument_group("port settings")
cliechti53edb472009-02-06 21:18:46 +0000662
Chris Liechtib7550bd2015-08-15 04:09:10 +0200663 group.add_argument("--parity",
664 choices=['N', 'E', 'O', 'S', 'M'],
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200665 type=lambda c: c.upper(),
Chris Liechtib7550bd2015-08-15 04:09:10 +0200666 help="set parity, one of {N E O S M}, default: N",
667 default='N')
cliechti53edb472009-02-06 21:18:46 +0000668
Chris Liechtib7550bd2015-08-15 04:09:10 +0200669 group.add_argument("--rtscts",
670 action="store_true",
671 help="enable RTS/CTS 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("--xonxoff",
675 action="store_true",
676 help="enable software flow control (default off)",
677 default=False)
cliechti53edb472009-02-06 21:18:46 +0000678
Chris Liechtib7550bd2015-08-15 04:09:10 +0200679 group.add_argument("--rts",
680 type=int,
681 help="set initial RTS line state (possible values: 0, 1)",
Chris Liechti55ba7d92015-08-15 16:33:51 +0200682 default=default_rts)
cliechti5370cee2013-10-13 03:08:19 +0000683
Chris Liechtib7550bd2015-08-15 04:09:10 +0200684 group.add_argument("--dtr",
685 type=int,
686 help="set initial DTR line state (possible values: 0, 1)",
Chris Liechti55ba7d92015-08-15 16:33:51 +0200687 default=default_dtr)
cliechti5370cee2013-10-13 03:08:19 +0000688
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200689 group = parser.add_argument_group("data handling")
cliechti5370cee2013-10-13 03:08:19 +0000690
Chris Liechtib7550bd2015-08-15 04:09:10 +0200691 group.add_argument("-e", "--echo",
692 action="store_true",
693 help="enable local echo (default off)",
694 default=False)
cliechti5370cee2013-10-13 03:08:19 +0000695
Chris Liechtib7550bd2015-08-15 04:09:10 +0200696 group.add_argument("--encoding",
697 dest="serial_port_encoding",
698 metavar="CODEC",
Chris Liechtia7e7b692015-08-25 21:10:28 +0200699 help="set the encoding for the serial port (e.g. hexlify, Latin1, UTF-8), default: %(default)s",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200700 default='UTF-8')
cliechti5370cee2013-10-13 03:08:19 +0000701
Chris Liechtib3df13e2015-08-25 02:20:09 +0200702 group.add_argument("-f", "--filter",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200703 action="append",
704 metavar="NAME",
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200705 help="add text transformation",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200706 default=[])
Chris Liechti2b1b3552015-08-12 15:35:33 +0200707
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200708 group.add_argument("--eol",
709 choices=['CR', 'LF', 'CRLF'],
710 type=lambda c: c.upper(),
711 help="end of line mode",
712 default='CRLF')
cliechti53edb472009-02-06 21:18:46 +0000713
Chris Liechtib7550bd2015-08-15 04:09:10 +0200714 group.add_argument("--raw",
715 action="store_true",
716 help="Do no apply any encodings/transformations",
717 default=False)
cliechti6385f2c2005-09-21 19:51:19 +0000718
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200719 group = parser.add_argument_group("hotkeys")
cliechtib7d746d2006-03-28 22:44:30 +0000720
Chris Liechtib7550bd2015-08-15 04:09:10 +0200721 group.add_argument("--exit-char",
722 type=int,
Chris Liechti55ba7d92015-08-15 16:33:51 +0200723 metavar='NUM',
724 help="Unicode of special character that is used to exit the application, default: %(default)s",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200725 default=0x1d # GS/CTRL+]
726 )
cliechtibf6bb7d2006-03-30 00:28:18 +0000727
Chris Liechtib7550bd2015-08-15 04:09:10 +0200728 group.add_argument("--menu-char",
729 type=int,
Chris Liechti55ba7d92015-08-15 16:33:51 +0200730 metavar='NUM',
731 help="Unicode code of special character that is used to control miniterm (menu), default: %(default)s",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200732 default=0x14 # Menu: CTRL+T
733 )
cliechti9c592b32008-06-16 22:00:14 +0000734
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200735 group = parser.add_argument_group("diagnostics")
cliechti6385f2c2005-09-21 19:51:19 +0000736
Chris Liechtib7550bd2015-08-15 04:09:10 +0200737 group.add_argument("-q", "--quiet",
738 action="store_true",
739 help="suppress non-error messages",
740 default=False)
cliechti5370cee2013-10-13 03:08:19 +0000741
Chris Liechtib7550bd2015-08-15 04:09:10 +0200742 group.add_argument("--develop",
743 action="store_true",
744 help="show Python traceback on error",
745 default=False)
cliechti5370cee2013-10-13 03:08:19 +0000746
Chris Liechtib7550bd2015-08-15 04:09:10 +0200747 args = parser.parse_args()
cliechti5370cee2013-10-13 03:08:19 +0000748
Chris Liechtib7550bd2015-08-15 04:09:10 +0200749 if args.menu_char == args.exit_char:
cliechti6c8eb2f2009-07-08 02:10:46 +0000750 parser.error('--exit-char can not be the same as --menu-char')
751
cliechti9c592b32008-06-16 22:00:14 +0000752
Chris Liechtib7550bd2015-08-15 04:09:10 +0200753 # no port given on command line -> ask user now
754 if args.port is None:
755 dump_port_list()
756 args.port = raw_input('Enter port name:')
cliechti53edb472009-02-06 21:18:46 +0000757
Chris Liechtib3df13e2015-08-25 02:20:09 +0200758 if args.filter:
759 if 'help' in args.filter:
760 sys.stderr.write('Available filters:\n')
Chris Liechti442bf512015-08-15 01:42:24 +0200761 sys.stderr.write('\n'.join(
Chris Liechtib3df13e2015-08-25 02:20:09 +0200762 '{:<10} = {.__doc__}'.format(k, v)
Chris Liechtib7550bd2015-08-15 04:09:10 +0200763 for k, v in sorted(TRANSFORMATIONS.items())))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200764 sys.stderr.write('\n')
765 sys.exit(1)
Chris Liechtib3df13e2015-08-25 02:20:09 +0200766 filters = args.filter
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200767 else:
Chris Liechtib3df13e2015-08-25 02:20:09 +0200768 filters = ['default']
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200769
cliechti6385f2c2005-09-21 19:51:19 +0000770
771 try:
Chris Liechti3b454802015-08-26 23:39:59 +0200772 serial_instance = serial.serial_for_url(
Chris Liechtib7550bd2015-08-15 04:09:10 +0200773 args.port,
774 args.baudrate,
Chris Liechti3b454802015-08-26 23:39:59 +0200775 parity=args.parity,
Chris Liechtib7550bd2015-08-15 04:09:10 +0200776 rtscts=args.rtscts,
777 xonxoff=args.xonxoff,
Chris Liechti3b454802015-08-26 23:39:59 +0200778 timeout=1,
779 do_not_open=True)
780
781 if args.dtr is not None:
782 if not args.quiet:
783 sys.stderr.write('--- forcing DTR {}\n'.format('active' if args.dtr else 'inactive'))
784 serial_instance.dtr = args.dtr
785 if args.rts is not None:
786 if not args.quiet:
787 sys.stderr.write('--- forcing RTS {}\n'.format('active' if args.rts else 'inactive'))
788 serial_instance.rts = args.rts
789
790 serial_instance.open()
Chris Liechti68340d72015-08-03 14:15:48 +0200791 except serial.SerialException as e:
Chris Liechtiaccd2012015-08-17 03:09:23 +0200792 sys.stderr.write('could not open port {}: {}\n'.format(repr(args.port), e))
Chris Liechtib7550bd2015-08-15 04:09:10 +0200793 if args.develop:
Chris Liechti91090912015-08-05 02:36:14 +0200794 raise
cliechti6385f2c2005-09-21 19:51:19 +0000795 sys.exit(1)
796
Chris Liechti3b454802015-08-26 23:39:59 +0200797 miniterm = Miniterm(
798 serial_instance,
799 echo=args.echo,
800 eol=args.eol.lower(),
801 filters=filters)
802 miniterm.exit_character = unichr(args.exit_char)
803 miniterm.menu_character = unichr(args.menu_char)
804 miniterm.raw = args.raw
805 miniterm.set_rx_encoding(args.serial_port_encoding)
806 miniterm.set_tx_encoding(args.serial_port_encoding)
807
Chris Liechtib7550bd2015-08-15 04:09:10 +0200808 if not args.quiet:
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200809 sys.stderr.write('--- Miniterm on {p.name} {p.baudrate},{p.bytesize},{p.parity},{p.stopbits} ---\n'.format(
810 p=miniterm.serial))
Chris Liechtib7550bd2015-08-15 04:09:10 +0200811 sys.stderr.write('--- Quit: {} | Menu: {} | Help: {} followed by {} ---\n'.format(
Chris Liechti442bf512015-08-15 01:42:24 +0200812 key_description(miniterm.exit_character),
813 key_description(miniterm.menu_character),
814 key_description(miniterm.menu_character),
Chris Liechtib7550bd2015-08-15 04:09:10 +0200815 key_description('\x08'),
Chris Liechti442bf512015-08-15 01:42:24 +0200816 ))
cliechti6fa76fb2009-07-08 23:53:39 +0000817
cliechti6385f2c2005-09-21 19:51:19 +0000818 miniterm.start()
cliechti258ab0a2011-03-21 23:03:45 +0000819 try:
820 miniterm.join(True)
821 except KeyboardInterrupt:
822 pass
Chris Liechtib7550bd2015-08-15 04:09:10 +0200823 if not args.quiet:
cliechtibf6bb7d2006-03-30 00:28:18 +0000824 sys.stderr.write("\n--- exit ---\n")
cliechti6385f2c2005-09-21 19:51:19 +0000825 miniterm.join()
cliechtibf6bb7d2006-03-30 00:28:18 +0000826
cliechti5370cee2013-10-13 03:08:19 +0000827# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
cliechti8b3ad392002-03-03 20:12:21 +0000828if __name__ == '__main__':
cliechti6385f2c2005-09-21 19:51:19 +0000829 main()