blob: d82c4088cac227802a45dee24c4c8bad4106f31a [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
cliechti6c8eb2f2009-07-08 02:10:46 +000023
24def key_description(character):
25 """generate a readable description for a key"""
26 ascii_code = ord(character)
27 if ascii_code < 32:
28 return 'Ctrl+%c' % (ord('@') + ascii_code)
29 else:
30 return repr(character)
31
cliechti91165532011-03-18 02:02:52 +000032
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020033class ConsoleBase(object):
34 def __init__(self):
35 if sys.version_info >= (3, 0):
36 self.byte_output = sys.stdout.buffer
37 else:
38 self.byte_output = sys.stdout
39 self.output = sys.stdout
cliechtif467aa82013-10-13 21:36:49 +000040
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020041 def setup(self):
42 pass # Do nothing for 'nt'
cliechtif467aa82013-10-13 21:36:49 +000043
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020044 def cleanup(self):
45 pass # Do nothing for 'nt'
46
47 def getkey(self):
48 return None
49
50 def write_bytes(self, s):
51 self.byte_output.write(s)
52 self.byte_output.flush()
53
54 def write(self, s):
55 self.output.write(s)
56 self.output.flush()
57
Chris Liechti269f77b2015-08-24 01:31:42 +020058 # - - - - - - - - - - - - - - - - - - - - - - - -
59 # context manager:
60 # switch terminal temporary to normal mode (e.g. to get user input)
61
62 def __enter__(self):
63 self.cleanup()
64 return self
65
66 def __exit__(self, *args, **kwargs):
67 self.setup()
68
cliechti9c592b32008-06-16 22:00:14 +000069
cliechtifc9eb382002-03-05 01:12:29 +000070if os.name == 'nt':
cliechti576de252002-02-28 23:54:44 +000071 import msvcrt
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020072 import ctypes
73 class Console(ConsoleBase):
Chris Liechticbb00b22015-08-13 22:58:49 +020074 def __init__(self):
75 super(Console, self).__init__()
76 ctypes.windll.kernel32.SetConsoleOutputCP(65001)
77 ctypes.windll.kernel32.SetConsoleCP(65001)
78 if sys.version_info < (3, 0):
79 class Out:
80 def __init__(self):
81 self.fd = sys.stdout.fileno()
82 def flush(self):
83 pass
84 def write(self, s):
85 os.write(self.fd, s)
86 self.output = codecs.getwriter('UTF-8')(Out(), 'replace')
87 self.byte_output = Out()
88 else:
89 self.output = codecs.getwriter('UTF-8')(sys.stdout.buffer, 'replace')
90
cliechti3a8bf092008-09-17 11:26:53 +000091 def getkey(self):
cliechti91165532011-03-18 02:02:52 +000092 while True:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020093 z = msvcrt.getwch()
94 if z == '\r':
95 return '\n'
96 elif z in '\x00\x0e': # functions keys, ignore
97 msvcrt.getwch()
cliechti9c592b32008-06-16 22:00:14 +000098 else:
cliechti9c592b32008-06-16 22:00:14 +000099 return z
cliechti53edb472009-02-06 21:18:46 +0000100
cliechti576de252002-02-28 23:54:44 +0000101elif os.name == 'posix':
Chris Liechtia1d5c6d2015-08-07 14:41:24 +0200102 import atexit
103 import termios
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200104 class Console(ConsoleBase):
cliechti9c592b32008-06-16 22:00:14 +0000105 def __init__(self):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200106 super(Console, self).__init__()
cliechti9c592b32008-06-16 22:00:14 +0000107 self.fd = sys.stdin.fileno()
Chris Liechti4d989c22015-08-24 00:24:49 +0200108 self.old = termios.tcgetattr(self.fd)
Chris Liechti89eb2472015-08-08 17:06:25 +0200109 atexit.register(self.cleanup)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200110 if sys.version_info < (3, 0):
111 sys.stdin = codecs.getreader(sys.stdin.encoding)(sys.stdin)
cliechti9c592b32008-06-16 22:00:14 +0000112
113 def setup(self):
cliechti9c592b32008-06-16 22:00:14 +0000114 new = termios.tcgetattr(self.fd)
115 new[3] = new[3] & ~termios.ICANON & ~termios.ECHO & ~termios.ISIG
116 new[6][termios.VMIN] = 1
117 new[6][termios.VTIME] = 0
118 termios.tcsetattr(self.fd, termios.TCSANOW, new)
cliechti53edb472009-02-06 21:18:46 +0000119
cliechti9c592b32008-06-16 22:00:14 +0000120 def getkey(self):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200121 return sys.stdin.read(1)
122 #~ c = os.read(self.fd, 1)
123 #~ return c
cliechti53edb472009-02-06 21:18:46 +0000124
cliechti9c592b32008-06-16 22:00:14 +0000125 def cleanup(self):
Chris Liechti4d989c22015-08-24 00:24:49 +0200126 termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old)
cliechti9c592b32008-06-16 22:00:14 +0000127
cliechti576de252002-02-28 23:54:44 +0000128else:
cliechti8c2ea842011-03-18 01:51:46 +0000129 raise NotImplementedError("Sorry no implementation for your platform (%s) available." % sys.platform)
cliechti576de252002-02-28 23:54:44 +0000130
cliechti6fa76fb2009-07-08 23:53:39 +0000131
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200132
133class Transform(object):
Chris Liechticbb00b22015-08-13 22:58:49 +0200134 """do-nothing: forward all data unchanged"""
Chris Liechtid698af72015-08-24 20:24:55 +0200135 def rx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200136 """text received from serial port"""
137 return text
138
Chris Liechtid698af72015-08-24 20:24:55 +0200139 def tx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200140 """text to be sent to serial port"""
141 return text
142
143 def echo(self, text):
144 """text to be sent but displayed on console"""
145 return text
146
Chris Liechti442bf512015-08-15 01:42:24 +0200147
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200148class CRLF(Transform):
149 """ENTER sends CR+LF"""
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200150
Chris Liechtid698af72015-08-24 20:24:55 +0200151 def tx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200152 return text.replace('\n', '\r\n')
153
Chris Liechti442bf512015-08-15 01:42:24 +0200154
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200155class CR(Transform):
156 """ENTER sends CR"""
Chris Liechtid698af72015-08-24 20:24:55 +0200157
158 def rx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200159 return text.replace('\r', '\n')
160
Chris Liechtid698af72015-08-24 20:24:55 +0200161 def tx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200162 return text.replace('\n', '\r')
163
Chris Liechti442bf512015-08-15 01:42:24 +0200164
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200165class LF(Transform):
166 """ENTER sends LF"""
167
168
169class NoTerminal(Transform):
170 """remove typical terminal control codes from input"""
Chris Liechtid698af72015-08-24 20:24:55 +0200171 def rx(self, text):
Chris Liechti7e9cfd42015-08-12 15:28:19 +0200172 return ''.join(t if t >= ' ' or t in '\r\n\b\t' else unichr(0x2400 + ord(t)) for t in text)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200173
Chris Liechtid698af72015-08-24 20:24:55 +0200174 echo = rx
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200175
176
177class NoControls(Transform):
178 """Remove all control codes, incl. CR+LF"""
Chris Liechtid698af72015-08-24 20:24:55 +0200179 def rx(self, text):
180 return ''.join(t if t >= ' ' else unichr(0x2400 + ord(t)) for t in text).replace(' ', '\u2423')
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200181
Chris Liechtid698af72015-08-24 20:24:55 +0200182 echo = rx
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200183
184
185class Printable(Transform):
Chris Liechtid698af72015-08-24 20:24:55 +0200186 """Show decimal code for all non-ASCII characters and replace most control codes"""
187 def rx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200188 r = []
189 for t in text:
Chris Liechti7e9cfd42015-08-12 15:28:19 +0200190 if ' ' <= t < '\x7f' or t in '\r\n\b\t':
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200191 r.append(t)
Chris Liechtid698af72015-08-24 20:24:55 +0200192 elif t < ' ':
193 r.append(unichr(0x2400 + ord(t)))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200194 else:
195 r.extend(unichr(0x2080 + ord(d) - 48) for d in '{:d}'.format(ord(t)))
196 r.append(' ')
197 return ''.join(r)
198
Chris Liechtid698af72015-08-24 20:24:55 +0200199 echo = rx
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200200
201
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200202class Colorize(Transform):
Chris Liechti442bf512015-08-15 01:42:24 +0200203 """Apply different colors for received and echo"""
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200204 def __init__(self):
205 # XXX make it configurable, use colorama?
206 self.input_color = '\x1b[37m'
207 self.echo_color = '\x1b[31m'
208
Chris Liechtid698af72015-08-24 20:24:55 +0200209 def rx(self, text):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200210 return self.input_color + text
211
212 def echo(self, text):
213 return self.echo_color + text
214
Chris Liechti442bf512015-08-15 01:42:24 +0200215
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200216class DebugIO(Transform):
Chris Liechti442bf512015-08-15 01:42:24 +0200217 """Print what is sent and received"""
Chris Liechtid698af72015-08-24 20:24:55 +0200218 def rx(self, text):
Chris Liechtie1384382015-08-15 17:06:05 +0200219 sys.stderr.write(' [RX:{}] '.format(repr(text)))
220 sys.stderr.flush()
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200221 return text
222
Chris Liechtid698af72015-08-24 20:24:55 +0200223 def tx(self, text):
Chris Liechtie1384382015-08-15 17:06:05 +0200224 sys.stderr.write(' [TX:{}] '.format(repr(text)))
225 sys.stderr.flush()
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200226 return text
227
Chris Liechti442bf512015-08-15 01:42:24 +0200228
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200229# other ideas:
230# - add date/time for each newline
231# - insert newline after: a) timeout b) packet end character
232
233TRANSFORMATIONS = {
234 'crlf': CRLF,
235 'cr': CR,
236 'lf': LF,
Chris Liechticbb00b22015-08-13 22:58:49 +0200237 'direct': Transform, # no transformation
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200238 'default': NoTerminal,
239 'nocontrol': NoControls,
240 'printable': Printable,
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200241 'colorize': Colorize,
242 'debug': DebugIO,
243 }
244
245
cliechti1351dde2012-04-12 16:47:47 +0000246def dump_port_list():
247 if comports:
248 sys.stderr.write('\n--- Available ports:\n')
249 for port, desc, hwid in sorted(comports()):
250 #~ sys.stderr.write('--- %-20s %s [%s]\n' % (port, desc, hwid))
251 sys.stderr.write('--- %-20s %s\n' % (port, desc))
252
253
cliechti8c2ea842011-03-18 01:51:46 +0000254class Miniterm(object):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200255 def __init__(self, port, baudrate, parity, rtscts, xonxoff, echo=False, transformations=()):
Chris Liechti89eb2472015-08-08 17:06:25 +0200256 self.console = Console()
Chris Liechtia1d5c6d2015-08-07 14:41:24 +0200257 self.serial = serial.serial_for_url(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1)
cliechti6385f2c2005-09-21 19:51:19 +0000258 self.echo = echo
cliechti6c8eb2f2009-07-08 02:10:46 +0000259 self.dtr_state = True
260 self.rts_state = True
261 self.break_state = False
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200262 self.raw = False
Chris Liechti442bf512015-08-15 01:42:24 +0200263 self.input_encoding = 'UTF-8'
Chris Liechti442bf512015-08-15 01:42:24 +0200264 self.output_encoding = 'UTF-8'
Chris Liechtie1384382015-08-15 17:06:05 +0200265 self.tx_transformations = [TRANSFORMATIONS[t]() for t in transformations]
266 self.rx_transformations = list(reversed(self.tx_transformations))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200267 self.transformation_names = transformations
Chris Liechti442bf512015-08-15 01:42:24 +0200268 self.exit_character = 0x1d # GS/CTRL+]
269 self.menu_character = 0x14 # Menu: CTRL+T
cliechti576de252002-02-28 23:54:44 +0000270
cliechti8c2ea842011-03-18 01:51:46 +0000271 def _start_reader(self):
272 """Start reader thread"""
273 self._reader_alive = True
cliechti6fa76fb2009-07-08 23:53:39 +0000274 # start serial->console thread
Chris Liechti55ba7d92015-08-15 16:33:51 +0200275 self.receiver_thread = threading.Thread(target=self.reader, name='rx')
276 self.receiver_thread.daemon = True
cliechti6385f2c2005-09-21 19:51:19 +0000277 self.receiver_thread.start()
cliechti8c2ea842011-03-18 01:51:46 +0000278
279 def _stop_reader(self):
280 """Stop reader thread only, wait for clean exit of thread"""
281 self._reader_alive = False
282 self.receiver_thread.join()
283
284
285 def start(self):
286 self.alive = True
287 self._start_reader()
cliechti6fa76fb2009-07-08 23:53:39 +0000288 # enter console->serial loop
Chris Liechti55ba7d92015-08-15 16:33:51 +0200289 self.transmitter_thread = threading.Thread(target=self.writer, name='tx')
290 self.transmitter_thread.daemon = True
cliechti6385f2c2005-09-21 19:51:19 +0000291 self.transmitter_thread.start()
Chris Liechti89eb2472015-08-08 17:06:25 +0200292 self.console.setup()
cliechti53edb472009-02-06 21:18:46 +0000293
cliechti6385f2c2005-09-21 19:51:19 +0000294 def stop(self):
295 self.alive = False
cliechti53edb472009-02-06 21:18:46 +0000296
cliechtibf6bb7d2006-03-30 00:28:18 +0000297 def join(self, transmit_only=False):
cliechti6385f2c2005-09-21 19:51:19 +0000298 self.transmitter_thread.join()
cliechtibf6bb7d2006-03-30 00:28:18 +0000299 if not transmit_only:
300 self.receiver_thread.join()
cliechti6385f2c2005-09-21 19:51:19 +0000301
Chris Liechtid698af72015-08-24 20:24:55 +0200302 def set_rx_encoding(self, encoding, errors='replace'):
303 self.input_encoding = encoding
304 self.rx_decoder = codecs.getincrementaldecoder(encoding)(errors)
305
306 def set_tx_encoding(self, encoding, errors='replace'):
307 self.output_encoding = encoding
308 self.tx_encoder = codecs.getincrementalencoder(encoding)(errors)
309
310
cliechti6c8eb2f2009-07-08 02:10:46 +0000311 def dump_port_settings(self):
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200312 sys.stderr.write("\n--- Settings: {p.name} {p.baudrate},{p.bytesize},{p.parity},{p.stopbits}\n".format(
313 p=self.serial))
Chris Liechti442bf512015-08-15 01:42:24 +0200314 sys.stderr.write('--- RTS: {:8} DTR: {:8} BREAK: {:8}\n'.format(
315 ('active' if self.rts_state else 'inactive'),
316 ('active' if self.dtr_state else 'inactive'),
317 ('active' if self.break_state else 'inactive')))
cliechti10114572009-08-05 23:40:50 +0000318 try:
Chris Liechti442bf512015-08-15 01:42:24 +0200319 sys.stderr.write('--- CTS: {:8} DSR: {:8} RI: {:8} CD: {:8}\n'.format(
320 ('active' if self.serial.getCTS() else 'inactive'),
321 ('active' if self.serial.getDSR() else 'inactive'),
322 ('active' if self.serial.getRI() else 'inactive'),
323 ('active' if self.serial.getCD() else 'inactive')))
cliechti10114572009-08-05 23:40:50 +0000324 except serial.SerialException:
Chris Liechti55ba7d92015-08-15 16:33:51 +0200325 # on RFC 2217 ports, it can happen if no modem state notification was
cliechti10114572009-08-05 23:40:50 +0000326 # yet received. ignore this error.
327 pass
Chris Liechti442bf512015-08-15 01:42:24 +0200328 sys.stderr.write('--- software flow control: {}\n'.format('active' if self.serial.xonxoff else 'inactive'))
329 sys.stderr.write('--- hardware flow control: {}\n'.format('active' if self.serial.rtscts else 'inactive'))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200330 #~ sys.stderr.write('--- data escaping: %s linefeed: %s\n' % (
331 #~ REPR_MODES[self.repr_mode],
332 #~ LF_MODES[self.convert_outgoing]))
Chris Liechti442bf512015-08-15 01:42:24 +0200333 sys.stderr.write('--- serial input encoding: {}\n'.format(self.input_encoding))
334 sys.stderr.write('--- serial output encoding: {}\n'.format(self.output_encoding))
335 sys.stderr.write('--- transformations: {}\n'.format(' '.join(self.transformation_names)))
cliechti6c8eb2f2009-07-08 02:10:46 +0000336
cliechti6385f2c2005-09-21 19:51:19 +0000337 def reader(self):
338 """loop and copy serial->console"""
cliechti6963b262010-01-02 03:01:21 +0000339 try:
cliechti8c2ea842011-03-18 01:51:46 +0000340 while self.alive and self._reader_alive:
Chris Liechti188cf592015-08-22 00:28:19 +0200341 # read all that is there or wait for one byte
342 data = self.serial.read(self.serial.inWaiting() or 1)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200343 if data:
344 if self.raw:
345 self.console.write_bytes(data)
cliechti6963b262010-01-02 03:01:21 +0000346 else:
Chris Liechtid698af72015-08-24 20:24:55 +0200347 text = self.rx_decoder.decode(data)
Chris Liechtie1384382015-08-15 17:06:05 +0200348 for transformation in self.rx_transformations:
Chris Liechtid698af72015-08-24 20:24:55 +0200349 text = transformation.rx(text)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200350 self.console.write(text)
Chris Liechti68340d72015-08-03 14:15:48 +0200351 except serial.SerialException as e:
cliechti6963b262010-01-02 03:01:21 +0000352 self.alive = False
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200353 # XXX would be nice if the writer could be interrupted at this
354 # point... to exit completely
cliechti6963b262010-01-02 03:01:21 +0000355 raise
cliechti576de252002-02-28 23:54:44 +0000356
cliechti576de252002-02-28 23:54:44 +0000357
cliechti6385f2c2005-09-21 19:51:19 +0000358 def writer(self):
cliechti8c2ea842011-03-18 01:51:46 +0000359 """\
Chris Liechti442bf512015-08-15 01:42:24 +0200360 Loop and copy console->serial until self.exit_character character is
361 found. When self.menu_character is found, interpret the next key
cliechti8c2ea842011-03-18 01:51:46 +0000362 locally.
cliechti6c8eb2f2009-07-08 02:10:46 +0000363 """
364 menu_active = False
365 try:
366 while self.alive:
367 try:
Chris Liechti89eb2472015-08-08 17:06:25 +0200368 c = self.console.getkey()
cliechti6c8eb2f2009-07-08 02:10:46 +0000369 except KeyboardInterrupt:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200370 c = '\x03'
cliechti6c8eb2f2009-07-08 02:10:46 +0000371 if menu_active:
Chris Liechti7af7c752015-08-12 15:45:19 +0200372 self.handle_menu_key(c)
cliechti6c8eb2f2009-07-08 02:10:46 +0000373 menu_active = False
Chris Liechti442bf512015-08-15 01:42:24 +0200374 elif c == self.menu_character:
Chris Liechti7af7c752015-08-12 15:45:19 +0200375 menu_active = True # next char will be for menu
Chris Liechti442bf512015-08-15 01:42:24 +0200376 elif c == self.exit_character:
Chris Liechti7af7c752015-08-12 15:45:19 +0200377 self.stop() # exit app
378 break
cliechti6c8eb2f2009-07-08 02:10:46 +0000379 else:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200380 #~ if self.raw:
381 text = c
382 echo_text = text
Chris Liechtie1384382015-08-15 17:06:05 +0200383 for transformation in self.tx_transformations:
Chris Liechtid698af72015-08-24 20:24:55 +0200384 text = transformation.tx(text)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200385 echo_text = transformation.echo(echo_text)
Chris Liechtid698af72015-08-24 20:24:55 +0200386 self.serial.write(self.tx_encoder.encode(text))
cliechti6c8eb2f2009-07-08 02:10:46 +0000387 if self.echo:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200388 self.console.write(echo_text)
cliechti6c8eb2f2009-07-08 02:10:46 +0000389 except:
390 self.alive = False
391 raise
cliechti6385f2c2005-09-21 19:51:19 +0000392
Chris Liechti7af7c752015-08-12 15:45:19 +0200393 def handle_menu_key(self, c):
394 """Implement a simple menu / settings"""
Chris Liechti55ba7d92015-08-15 16:33:51 +0200395 if c == self.menu_character or c == self.exit_character:
396 # Menu/exit character again -> send itself
Chris Liechtid698af72015-08-24 20:24:55 +0200397 self.serial.write(self.tx_encoder.encode(c))
Chris Liechti7af7c752015-08-12 15:45:19 +0200398 if self.echo:
399 self.console.write(c)
Chris Liechtib7550bd2015-08-15 04:09:10 +0200400 elif c == '\x15': # CTRL+U -> upload file
Chris Liechti7af7c752015-08-12 15:45:19 +0200401 sys.stderr.write('\n--- File to upload: ')
402 sys.stderr.flush()
Chris Liechti269f77b2015-08-24 01:31:42 +0200403 with self.console:
404 filename = sys.stdin.readline().rstrip('\r\n')
405 if filename:
406 try:
407 with open(filename, 'rb') as f:
408 sys.stderr.write('--- Sending file {} ---\n'.format(filename))
409 while True:
410 block = f.read(1024)
411 if not block:
412 break
413 self.serial.write(block)
414 # Wait for output buffer to drain.
415 self.serial.flush()
416 sys.stderr.write('.') # Progress indicator.
417 sys.stderr.write('\n--- File {} sent ---\n'.format(filename))
418 except IOError as e:
419 sys.stderr.write('--- ERROR opening file {}: {} ---\n'.format(filename, e))
Chris Liechti7af7c752015-08-12 15:45:19 +0200420 elif c in '\x08hH?': # CTRL+H, h, H, ? -> Show help
Chris Liechti442bf512015-08-15 01:42:24 +0200421 sys.stderr.write(self.get_help_text())
Chris Liechti7af7c752015-08-12 15:45:19 +0200422 elif c == '\x12': # CTRL+R -> Toggle RTS
423 self.rts_state = not self.rts_state
424 self.serial.setRTS(self.rts_state)
Chris Liechti442bf512015-08-15 01:42:24 +0200425 sys.stderr.write('--- RTS {} ---\n'.format('active' if self.rts_state else 'inactive'))
Chris Liechti7af7c752015-08-12 15:45:19 +0200426 elif c == '\x04': # CTRL+D -> Toggle DTR
427 self.dtr_state = not self.dtr_state
428 self.serial.setDTR(self.dtr_state)
Chris Liechti442bf512015-08-15 01:42:24 +0200429 sys.stderr.write('--- DTR {} ---\n'.format('active' if self.dtr_state else 'inactive'))
Chris Liechti7af7c752015-08-12 15:45:19 +0200430 elif c == '\x02': # CTRL+B -> toggle BREAK condition
431 self.break_state = not self.break_state
432 self.serial.setBreak(self.break_state)
Chris Liechti442bf512015-08-15 01:42:24 +0200433 sys.stderr.write('--- BREAK {} ---\n'.format('active' if self.break_state else 'inactive'))
Chris Liechti7af7c752015-08-12 15:45:19 +0200434 elif c == '\x05': # CTRL+E -> toggle local echo
435 self.echo = not self.echo
Chris Liechti442bf512015-08-15 01:42:24 +0200436 sys.stderr.write('--- local echo {} ---\n'.format('active' if self.echo else 'inactive'))
Chris Liechti7af7c752015-08-12 15:45:19 +0200437 elif c == '\x09': # CTRL+I -> info
438 self.dump_port_settings()
439 #~ elif c == '\x01': # CTRL+A -> cycle escape mode
440 #~ elif c == '\x0c': # CTRL+L -> cycle linefeed mode
441 elif c in 'pP': # P -> change port
442 dump_port_list()
443 sys.stderr.write('--- Enter port name: ')
444 sys.stderr.flush()
Chris Liechti269f77b2015-08-24 01:31:42 +0200445 with self.console:
446 try:
447 port = sys.stdin.readline().strip()
448 except KeyboardInterrupt:
449 port = None
Chris Liechti7af7c752015-08-12 15:45:19 +0200450 if port and port != self.serial.port:
451 # reader thread needs to be shut down
452 self._stop_reader()
453 # save settings
454 settings = self.serial.getSettingsDict()
455 try:
456 new_serial = serial.serial_for_url(port, do_not_open=True)
457 # restore settings and open
458 new_serial.applySettingsDict(settings)
459 new_serial.open()
460 new_serial.setRTS(self.rts_state)
461 new_serial.setDTR(self.dtr_state)
462 new_serial.setBreak(self.break_state)
463 except Exception as e:
Chris Liechti442bf512015-08-15 01:42:24 +0200464 sys.stderr.write('--- ERROR opening new port: {} ---\n'.format(e))
Chris Liechti7af7c752015-08-12 15:45:19 +0200465 new_serial.close()
466 else:
467 self.serial.close()
468 self.serial = new_serial
Chris Liechti442bf512015-08-15 01:42:24 +0200469 sys.stderr.write('--- Port changed to: {} ---\n'.format(self.serial.port))
Chris Liechti7af7c752015-08-12 15:45:19 +0200470 # and restart the reader thread
471 self._start_reader()
472 elif c in 'bB': # B -> change baudrate
473 sys.stderr.write('\n--- Baudrate: ')
474 sys.stderr.flush()
Chris Liechti269f77b2015-08-24 01:31:42 +0200475 with self.console:
476 backup = self.serial.baudrate
477 try:
478 self.serial.baudrate = int(sys.stdin.readline().strip())
479 except ValueError as e:
480 sys.stderr.write('--- ERROR setting baudrate: %s ---\n'.format(e))
481 self.serial.baudrate = backup
482 else:
483 self.dump_port_settings()
Chris Liechti7af7c752015-08-12 15:45:19 +0200484 elif c == '8': # 8 -> change to 8 bits
485 self.serial.bytesize = serial.EIGHTBITS
486 self.dump_port_settings()
487 elif c == '7': # 7 -> change to 8 bits
488 self.serial.bytesize = serial.SEVENBITS
489 self.dump_port_settings()
490 elif c in 'eE': # E -> change to even parity
491 self.serial.parity = serial.PARITY_EVEN
492 self.dump_port_settings()
493 elif c in 'oO': # O -> change to odd parity
494 self.serial.parity = serial.PARITY_ODD
495 self.dump_port_settings()
496 elif c in 'mM': # M -> change to mark parity
497 self.serial.parity = serial.PARITY_MARK
498 self.dump_port_settings()
499 elif c in 'sS': # S -> change to space parity
500 self.serial.parity = serial.PARITY_SPACE
501 self.dump_port_settings()
502 elif c in 'nN': # N -> change to no parity
503 self.serial.parity = serial.PARITY_NONE
504 self.dump_port_settings()
505 elif c == '1': # 1 -> change to 1 stop bits
506 self.serial.stopbits = serial.STOPBITS_ONE
507 self.dump_port_settings()
508 elif c == '2': # 2 -> change to 2 stop bits
509 self.serial.stopbits = serial.STOPBITS_TWO
510 self.dump_port_settings()
511 elif c == '3': # 3 -> change to 1.5 stop bits
512 self.serial.stopbits = serial.STOPBITS_ONE_POINT_FIVE
513 self.dump_port_settings()
514 elif c in 'xX': # X -> change software flow control
515 self.serial.xonxoff = (c == 'X')
516 self.dump_port_settings()
517 elif c in 'rR': # R -> change hardware flow control
518 self.serial.rtscts = (c == 'R')
519 self.dump_port_settings()
520 else:
Chris Liechti442bf512015-08-15 01:42:24 +0200521 sys.stderr.write('--- unknown menu character {} --\n'.format(key_description(c)))
522
523 def get_help_text(self):
Chris Liechti55ba7d92015-08-15 16:33:51 +0200524 # help text, starts with blank line!
Chris Liechti442bf512015-08-15 01:42:24 +0200525 return """
526--- pySerial ({version}) - miniterm - help
527---
528--- {exit:8} Exit program
529--- {menu:8} Menu escape key, followed by:
530--- Menu keys:
531--- {menu:7} Send the menu character itself to remote
532--- {exit:7} Send the exit character itself to remote
533--- {info:7} Show info
534--- {upload:7} Upload file (prompt will be shown)
535--- Toggles:
536--- {rts:7} RTS {echo:7} local echo
537--- {dtr:7} DTR {brk:7} BREAK
538---
Chris Liechti55ba7d92015-08-15 16:33:51 +0200539--- Port settings ({menu} followed by the following):
Chris Liechti442bf512015-08-15 01:42:24 +0200540--- p change port
541--- 7 8 set data bits
Chris Liechtib7550bd2015-08-15 04:09:10 +0200542--- N E O S M change parity (None, Even, Odd, Space, Mark)
Chris Liechti442bf512015-08-15 01:42:24 +0200543--- 1 2 3 set stop bits (1, 2, 1.5)
544--- b change baud rate
545--- x X disable/enable software flow control
546--- r R disable/enable hardware flow control
547""".format(
548 version=getattr(serial, 'VERSION', 'unknown version'),
549 exit=key_description(self.exit_character),
550 menu=key_description(self.menu_character),
Chris Liechtib7550bd2015-08-15 04:09:10 +0200551 rts=key_description('\x12'),
552 dtr=key_description('\x04'),
553 brk=key_description('\x02'),
554 echo=key_description('\x05'),
555 info=key_description('\x09'),
556 upload=key_description('\x15'),
Chris Liechti442bf512015-08-15 01:42:24 +0200557 )
Chris Liechti7af7c752015-08-12 15:45:19 +0200558
559
560
Chris Liechti55ba7d92015-08-15 16:33:51 +0200561# default args can be used to override when calling main() from an other script
562# e.g to create a miniterm-my-device.py
563def main(default_port=None, default_baudrate=9600, default_rts=None, default_dtr=None):
Chris Liechtib7550bd2015-08-15 04:09:10 +0200564 import argparse
cliechti6385f2c2005-09-21 19:51:19 +0000565
Chris Liechtib7550bd2015-08-15 04:09:10 +0200566 parser = argparse.ArgumentParser(
567 description="Miniterm - A simple terminal program for the serial port.")
cliechti6385f2c2005-09-21 19:51:19 +0000568
Chris Liechtib7550bd2015-08-15 04:09:10 +0200569 parser.add_argument("port",
570 nargs='?',
571 help="serial port name",
Chris Liechti55ba7d92015-08-15 16:33:51 +0200572 default=default_port)
cliechti5370cee2013-10-13 03:08:19 +0000573
Chris Liechtib7550bd2015-08-15 04:09:10 +0200574 parser.add_argument("baudrate",
575 nargs='?',
576 type=int,
577 help="set baud rate, default: %(default)s",
Chris Liechti55ba7d92015-08-15 16:33:51 +0200578 default=default_baudrate)
cliechti6385f2c2005-09-21 19:51:19 +0000579
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200580 group = parser.add_argument_group("port settings")
cliechti53edb472009-02-06 21:18:46 +0000581
Chris Liechtib7550bd2015-08-15 04:09:10 +0200582 group.add_argument("--parity",
583 choices=['N', 'E', 'O', 'S', 'M'],
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200584 type=lambda c: c.upper(),
Chris Liechtib7550bd2015-08-15 04:09:10 +0200585 help="set parity, one of {N E O S M}, default: N",
586 default='N')
cliechti53edb472009-02-06 21:18:46 +0000587
Chris Liechtib7550bd2015-08-15 04:09:10 +0200588 group.add_argument("--rtscts",
589 action="store_true",
590 help="enable RTS/CTS flow control (default off)",
591 default=False)
cliechti53edb472009-02-06 21:18:46 +0000592
Chris Liechtib7550bd2015-08-15 04:09:10 +0200593 group.add_argument("--xonxoff",
594 action="store_true",
595 help="enable software flow control (default off)",
596 default=False)
cliechti53edb472009-02-06 21:18:46 +0000597
Chris Liechtib7550bd2015-08-15 04:09:10 +0200598 group.add_argument("--rts",
599 type=int,
600 help="set initial RTS line state (possible values: 0, 1)",
Chris Liechti55ba7d92015-08-15 16:33:51 +0200601 default=default_rts)
cliechti5370cee2013-10-13 03:08:19 +0000602
Chris Liechtib7550bd2015-08-15 04:09:10 +0200603 group.add_argument("--dtr",
604 type=int,
605 help="set initial DTR line state (possible values: 0, 1)",
Chris Liechti55ba7d92015-08-15 16:33:51 +0200606 default=default_dtr)
cliechti5370cee2013-10-13 03:08:19 +0000607
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200608 group = parser.add_argument_group("data handling")
cliechti5370cee2013-10-13 03:08:19 +0000609
Chris Liechtib7550bd2015-08-15 04:09:10 +0200610 group.add_argument("-e", "--echo",
611 action="store_true",
612 help="enable local echo (default off)",
613 default=False)
cliechti5370cee2013-10-13 03:08:19 +0000614
Chris Liechtib7550bd2015-08-15 04:09:10 +0200615 group.add_argument("--encoding",
616 dest="serial_port_encoding",
617 metavar="CODEC",
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200618 help="set the encoding for the serial port, default: %(default)s",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200619 default='UTF-8')
cliechti5370cee2013-10-13 03:08:19 +0000620
Chris Liechtib7550bd2015-08-15 04:09:10 +0200621 group.add_argument("-t", "--transformation",
622 dest="transformations",
623 action="append",
624 metavar="NAME",
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200625 help="add text transformation",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200626 default=[])
Chris Liechti2b1b3552015-08-12 15:35:33 +0200627
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200628 group.add_argument("--eol",
629 choices=['CR', 'LF', 'CRLF'],
630 type=lambda c: c.upper(),
631 help="end of line mode",
632 default='CRLF')
cliechti53edb472009-02-06 21:18:46 +0000633
Chris Liechtib7550bd2015-08-15 04:09:10 +0200634 group.add_argument("--raw",
635 action="store_true",
636 help="Do no apply any encodings/transformations",
637 default=False)
cliechti6385f2c2005-09-21 19:51:19 +0000638
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200639 group = parser.add_argument_group("hotkeys")
cliechtib7d746d2006-03-28 22:44:30 +0000640
Chris Liechtib7550bd2015-08-15 04:09:10 +0200641 group.add_argument("--exit-char",
642 type=int,
Chris Liechti55ba7d92015-08-15 16:33:51 +0200643 metavar='NUM',
644 help="Unicode of special character that is used to exit the application, default: %(default)s",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200645 default=0x1d # GS/CTRL+]
646 )
cliechtibf6bb7d2006-03-30 00:28:18 +0000647
Chris Liechtib7550bd2015-08-15 04:09:10 +0200648 group.add_argument("--menu-char",
649 type=int,
Chris Liechti55ba7d92015-08-15 16:33:51 +0200650 metavar='NUM',
651 help="Unicode code of special character that is used to control miniterm (menu), default: %(default)s",
Chris Liechtib7550bd2015-08-15 04:09:10 +0200652 default=0x14 # Menu: CTRL+T
653 )
cliechti9c592b32008-06-16 22:00:14 +0000654
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200655 group = parser.add_argument_group("diagnostics")
cliechti6385f2c2005-09-21 19:51:19 +0000656
Chris Liechtib7550bd2015-08-15 04:09:10 +0200657 group.add_argument("-q", "--quiet",
658 action="store_true",
659 help="suppress non-error messages",
660 default=False)
cliechti5370cee2013-10-13 03:08:19 +0000661
Chris Liechtib7550bd2015-08-15 04:09:10 +0200662 group.add_argument("--develop",
663 action="store_true",
664 help="show Python traceback on error",
665 default=False)
cliechti5370cee2013-10-13 03:08:19 +0000666
Chris Liechtib7550bd2015-08-15 04:09:10 +0200667 args = parser.parse_args()
cliechti5370cee2013-10-13 03:08:19 +0000668
Chris Liechtib7550bd2015-08-15 04:09:10 +0200669 if args.menu_char == args.exit_char:
cliechti6c8eb2f2009-07-08 02:10:46 +0000670 parser.error('--exit-char can not be the same as --menu-char')
671
cliechti9c592b32008-06-16 22:00:14 +0000672
Chris Liechtib7550bd2015-08-15 04:09:10 +0200673 # no port given on command line -> ask user now
674 if args.port is None:
675 dump_port_list()
676 args.port = raw_input('Enter port name:')
cliechti53edb472009-02-06 21:18:46 +0000677
Chris Liechtib7550bd2015-08-15 04:09:10 +0200678 if args.transformations:
679 if 'help' in args.transformations:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200680 sys.stderr.write('Available Transformations:\n')
Chris Liechti442bf512015-08-15 01:42:24 +0200681 sys.stderr.write('\n'.join(
Chris Liechtib7550bd2015-08-15 04:09:10 +0200682 '{:<20} = {.__doc__}'.format(k, v)
683 for k, v in sorted(TRANSFORMATIONS.items())))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200684 sys.stderr.write('\n')
685 sys.exit(1)
Chris Liechtib7550bd2015-08-15 04:09:10 +0200686 transformations = args.transformations
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200687 else:
688 transformations = ['default']
689
Chris Liechtie1384382015-08-15 17:06:05 +0200690 transformations.insert(0, args.eol.lower())
cliechti6385f2c2005-09-21 19:51:19 +0000691
692 try:
693 miniterm = Miniterm(
Chris Liechtib7550bd2015-08-15 04:09:10 +0200694 args.port,
695 args.baudrate,
696 args.parity,
697 rtscts=args.rtscts,
698 xonxoff=args.xonxoff,
699 echo=args.echo,
Chris Liechti442bf512015-08-15 01:42:24 +0200700 transformations=transformations,
701 )
Chris Liechtib7550bd2015-08-15 04:09:10 +0200702 miniterm.exit_character = unichr(args.exit_char)
703 miniterm.menu_character = unichr(args.menu_char)
704 miniterm.raw = args.raw
Chris Liechtid698af72015-08-24 20:24:55 +0200705 miniterm.set_rx_encoding(args.serial_port_encoding)
706 miniterm.set_tx_encoding(args.serial_port_encoding)
Chris Liechti68340d72015-08-03 14:15:48 +0200707 except serial.SerialException as e:
Chris Liechtiaccd2012015-08-17 03:09:23 +0200708 sys.stderr.write('could not open port {}: {}\n'.format(repr(args.port), e))
Chris Liechtib7550bd2015-08-15 04:09:10 +0200709 if args.develop:
Chris Liechti91090912015-08-05 02:36:14 +0200710 raise
cliechti6385f2c2005-09-21 19:51:19 +0000711 sys.exit(1)
712
Chris Liechtib7550bd2015-08-15 04:09:10 +0200713 if not args.quiet:
Chris Liechti1f7ac6c2015-08-15 15:16:37 +0200714 sys.stderr.write('--- Miniterm on {p.name} {p.baudrate},{p.bytesize},{p.parity},{p.stopbits} ---\n'.format(
715 p=miniterm.serial))
Chris Liechtib7550bd2015-08-15 04:09:10 +0200716 sys.stderr.write('--- Quit: {} | Menu: {} | Help: {} followed by {} ---\n'.format(
Chris Liechti442bf512015-08-15 01:42:24 +0200717 key_description(miniterm.exit_character),
718 key_description(miniterm.menu_character),
719 key_description(miniterm.menu_character),
Chris Liechtib7550bd2015-08-15 04:09:10 +0200720 key_description('\x08'),
Chris Liechti442bf512015-08-15 01:42:24 +0200721 ))
cliechti6fa76fb2009-07-08 23:53:39 +0000722
Chris Liechtib7550bd2015-08-15 04:09:10 +0200723 if args.dtr is not None:
724 if not args.quiet:
725 sys.stderr.write('--- forcing DTR {}\n'.format('active' if args.dtr else 'inactive'))
726 miniterm.serial.setDTR(args.dtr)
727 miniterm.dtr_state = args.dtr
728 if args.rts is not None:
729 if not args.quiet:
730 sys.stderr.write('--- forcing RTS {}\n'.format('active' if args.rts else 'inactive'))
731 miniterm.serial.setRTS(args.rts)
732 miniterm.rts_state = args.rts
cliechti53edb472009-02-06 21:18:46 +0000733
cliechti6385f2c2005-09-21 19:51:19 +0000734 miniterm.start()
cliechti258ab0a2011-03-21 23:03:45 +0000735 try:
736 miniterm.join(True)
737 except KeyboardInterrupt:
738 pass
Chris Liechtib7550bd2015-08-15 04:09:10 +0200739 if not args.quiet:
cliechtibf6bb7d2006-03-30 00:28:18 +0000740 sys.stderr.write("\n--- exit ---\n")
cliechti6385f2c2005-09-21 19:51:19 +0000741 miniterm.join()
cliechtibf6bb7d2006-03-30 00:28:18 +0000742
cliechti5370cee2013-10-13 03:08:19 +0000743# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
cliechti8b3ad392002-03-03 20:12:21 +0000744if __name__ == '__main__':
cliechti6385f2c2005-09-21 19:51:19 +0000745 main()