blob: 792ca915ba5494fb089ea9a0c606e549b4c7f28a [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
cliechtia128a702004-07-21 22:13:31 +00009# Input characters are sent directly (only LF -> CR/LF/CRLF translation is
Chris Liechti89eb2472015-08-08 17:06:25 +020010# done), received characters are displayed as is (or escaped through pythons
cliechtia128a702004-07-21 22:13:31 +000011# repr, useful for debug purposes)
cliechti576de252002-02-28 23:54:44 +000012
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020013import codecs
Chris Liechtia1d5c6d2015-08-07 14:41:24 +020014import os
15import sys
16import threading
cliechti21e2c842012-02-21 16:40:27 +000017try:
18 from serial.tools.list_ports import comports
19except ImportError:
20 comports = None
cliechti576de252002-02-28 23:54:44 +000021
Chris Liechtia1d5c6d2015-08-07 14:41:24 +020022import serial
23
24
Chris Liechti68340d72015-08-03 14:15:48 +020025try:
26 raw_input
27except NameError:
28 raw_input = input # in python3 it's "raw"
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020029 unichr = chr
Chris Liechti68340d72015-08-03 14:15:48 +020030
Chris Liechti442bf512015-08-15 01:42:24 +020031# globals: can be used to override then call .main() to customize from an other
32# script
cliechti096e1962012-02-20 01:52:38 +000033DEFAULT_PORT = None
34DEFAULT_BAUDRATE = 9600
35DEFAULT_RTS = None
36DEFAULT_DTR = None
37
cliechti6c8eb2f2009-07-08 02:10:46 +000038
39def key_description(character):
40 """generate a readable description for a key"""
41 ascii_code = ord(character)
42 if ascii_code < 32:
43 return 'Ctrl+%c' % (ord('@') + ascii_code)
44 else:
45 return repr(character)
46
cliechti91165532011-03-18 02:02:52 +000047
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020048class ConsoleBase(object):
49 def __init__(self):
50 if sys.version_info >= (3, 0):
51 self.byte_output = sys.stdout.buffer
52 else:
53 self.byte_output = sys.stdout
54 self.output = sys.stdout
cliechtif467aa82013-10-13 21:36:49 +000055
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020056 def setup(self):
57 pass # Do nothing for 'nt'
cliechtif467aa82013-10-13 21:36:49 +000058
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020059 def cleanup(self):
60 pass # Do nothing for 'nt'
61
62 def getkey(self):
63 return None
64
65 def write_bytes(self, s):
66 self.byte_output.write(s)
67 self.byte_output.flush()
68
69 def write(self, s):
70 self.output.write(s)
71 self.output.flush()
72
cliechti9c592b32008-06-16 22:00:14 +000073
cliechtifc9eb382002-03-05 01:12:29 +000074if os.name == 'nt':
cliechti576de252002-02-28 23:54:44 +000075 import msvcrt
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020076 import ctypes
77 class Console(ConsoleBase):
Chris Liechticbb00b22015-08-13 22:58:49 +020078 def __init__(self):
79 super(Console, self).__init__()
80 ctypes.windll.kernel32.SetConsoleOutputCP(65001)
81 ctypes.windll.kernel32.SetConsoleCP(65001)
82 if sys.version_info < (3, 0):
83 class Out:
84 def __init__(self):
85 self.fd = sys.stdout.fileno()
86 def flush(self):
87 pass
88 def write(self, s):
89 os.write(self.fd, s)
90 self.output = codecs.getwriter('UTF-8')(Out(), 'replace')
91 self.byte_output = Out()
92 else:
93 self.output = codecs.getwriter('UTF-8')(sys.stdout.buffer, 'replace')
94
cliechti3a8bf092008-09-17 11:26:53 +000095 def getkey(self):
cliechti91165532011-03-18 02:02:52 +000096 while True:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020097 z = msvcrt.getwch()
98 if z == '\r':
99 return '\n'
100 elif z in '\x00\x0e': # functions keys, ignore
101 msvcrt.getwch()
cliechti9c592b32008-06-16 22:00:14 +0000102 else:
cliechti9c592b32008-06-16 22:00:14 +0000103 return z
cliechti53edb472009-02-06 21:18:46 +0000104
cliechti576de252002-02-28 23:54:44 +0000105elif os.name == 'posix':
Chris Liechtia1d5c6d2015-08-07 14:41:24 +0200106 import atexit
107 import termios
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200108 class Console(ConsoleBase):
cliechti9c592b32008-06-16 22:00:14 +0000109 def __init__(self):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200110 super(Console, self).__init__()
cliechti9c592b32008-06-16 22:00:14 +0000111 self.fd = sys.stdin.fileno()
cliechti5370cee2013-10-13 03:08:19 +0000112 self.old = None
Chris Liechti89eb2472015-08-08 17:06:25 +0200113 atexit.register(self.cleanup)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200114 if sys.version_info < (3, 0):
115 sys.stdin = codecs.getreader(sys.stdin.encoding)(sys.stdin)
cliechti9c592b32008-06-16 22:00:14 +0000116
117 def setup(self):
118 self.old = termios.tcgetattr(self.fd)
119 new = termios.tcgetattr(self.fd)
120 new[3] = new[3] & ~termios.ICANON & ~termios.ECHO & ~termios.ISIG
121 new[6][termios.VMIN] = 1
122 new[6][termios.VTIME] = 0
123 termios.tcsetattr(self.fd, termios.TCSANOW, new)
cliechti53edb472009-02-06 21:18:46 +0000124
cliechti9c592b32008-06-16 22:00:14 +0000125 def getkey(self):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200126 return sys.stdin.read(1)
127 #~ c = os.read(self.fd, 1)
128 #~ return c
cliechti53edb472009-02-06 21:18:46 +0000129
cliechti9c592b32008-06-16 22:00:14 +0000130 def cleanup(self):
cliechti5370cee2013-10-13 03:08:19 +0000131 if self.old is not None:
132 termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old)
cliechti9c592b32008-06-16 22:00:14 +0000133
cliechti576de252002-02-28 23:54:44 +0000134else:
cliechti8c2ea842011-03-18 01:51:46 +0000135 raise NotImplementedError("Sorry no implementation for your platform (%s) available." % sys.platform)
cliechti576de252002-02-28 23:54:44 +0000136
cliechti6fa76fb2009-07-08 23:53:39 +0000137
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200138# XXX how to handle multi byte sequences like CRLF?
139# codecs.IncrementalEncoder would be a good choice
140
141class Transform(object):
Chris Liechticbb00b22015-08-13 22:58:49 +0200142 """do-nothing: forward all data unchanged"""
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200143 def input(self, text):
144 """text received from serial port"""
145 return text
146
147 def output(self, text):
148 """text to be sent to serial port"""
149 return text
150
151 def echo(self, text):
152 """text to be sent but displayed on console"""
153 return text
154
Chris Liechti442bf512015-08-15 01:42:24 +0200155
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200156class CRLF(Transform):
157 """ENTER sends CR+LF"""
158 def input(self, text):
159 return text.replace('\r\n', '\n')
160
161 def output(self, text):
162 return text.replace('\n', '\r\n')
163
Chris Liechti442bf512015-08-15 01:42:24 +0200164
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200165class CR(Transform):
166 """ENTER sends CR"""
167 def input(self, text):
168 return text.replace('\r', '\n')
169
170 def output(self, text):
171 return text.replace('\n', '\r')
172
Chris Liechti442bf512015-08-15 01:42:24 +0200173
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200174class LF(Transform):
175 """ENTER sends LF"""
176
177
178class NoTerminal(Transform):
179 """remove typical terminal control codes from input"""
180 def input(self, text):
Chris Liechti7e9cfd42015-08-12 15:28:19 +0200181 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 +0200182
183 echo = input
184
185
186class NoControls(Transform):
187 """Remove all control codes, incl. CR+LF"""
188 def input(self, text):
189 return ''.join(t if t >= ' ' else unichr(0x2400 + ord(t)) for t in text)
190
191 echo = input
192
193
194class HexDump(Transform):
195 """Complete hex dump"""
196 def input(self, text):
197 return ''.join('{:02x} '.format(ord(t)) for t in text)
198
199 echo = input
200
201
202class Printable(Transform):
Chris Liechti7e9cfd42015-08-12 15:28:19 +0200203 """Show decimal code for all non-ASCII characters and most control codes"""
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200204 def input(self, text):
205 r = []
206 for t in text:
Chris Liechti7e9cfd42015-08-12 15:28:19 +0200207 if ' ' <= t < '\x7f' or t in '\r\n\b\t':
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200208 r.append(t)
209 else:
210 r.extend(unichr(0x2080 + ord(d) - 48) for d in '{:d}'.format(ord(t)))
211 r.append(' ')
212 return ''.join(r)
213
214 echo = input
215
216
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200217class Colorize(Transform):
Chris Liechti442bf512015-08-15 01:42:24 +0200218 """Apply different colors for received and echo"""
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200219 def __init__(self):
220 # XXX make it configurable, use colorama?
221 self.input_color = '\x1b[37m'
222 self.echo_color = '\x1b[31m'
223
224 def input(self, text):
225 return self.input_color + text
226
227 def echo(self, text):
228 return self.echo_color + text
229
Chris Liechti442bf512015-08-15 01:42:24 +0200230
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200231class DebugIO(Transform):
Chris Liechti442bf512015-08-15 01:42:24 +0200232 """Print what is sent and received"""
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200233 def input(self, text):
Chris Liechti442bf512015-08-15 01:42:24 +0200234 sys.stderr.write('rx: {} (0x{:X})\n'.format(repr(text), ord(text[0:1])))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200235 return text
236
Chris Liechti442bf512015-08-15 01:42:24 +0200237 def output(self, text):
238 sys.stderr.write('tx: {} (0x{:X})\n'.format(repr(text), ord(text[0:1])))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200239 return text
240
Chris Liechti442bf512015-08-15 01:42:24 +0200241
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200242# other ideas:
243# - add date/time for each newline
244# - insert newline after: a) timeout b) packet end character
245
246TRANSFORMATIONS = {
247 'crlf': CRLF,
248 'cr': CR,
249 'lf': LF,
Chris Liechticbb00b22015-08-13 22:58:49 +0200250 'direct': Transform, # no transformation
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200251 'default': NoTerminal,
252 'nocontrol': NoControls,
253 'printable': Printable,
254 'hex': HexDump,
255 'colorize': Colorize,
256 'debug': DebugIO,
257 }
258
259
cliechti1351dde2012-04-12 16:47:47 +0000260def dump_port_list():
261 if comports:
262 sys.stderr.write('\n--- Available ports:\n')
263 for port, desc, hwid in sorted(comports()):
264 #~ sys.stderr.write('--- %-20s %s [%s]\n' % (port, desc, hwid))
265 sys.stderr.write('--- %-20s %s\n' % (port, desc))
266
267
cliechti8c2ea842011-03-18 01:51:46 +0000268class Miniterm(object):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200269 def __init__(self, port, baudrate, parity, rtscts, xonxoff, echo=False, transformations=()):
Chris Liechti89eb2472015-08-08 17:06:25 +0200270 self.console = Console()
Chris Liechtia1d5c6d2015-08-07 14:41:24 +0200271 self.serial = serial.serial_for_url(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1)
cliechti6385f2c2005-09-21 19:51:19 +0000272 self.echo = echo
cliechti6c8eb2f2009-07-08 02:10:46 +0000273 self.dtr_state = True
274 self.rts_state = True
275 self.break_state = False
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200276 self.raw = False
Chris Liechti442bf512015-08-15 01:42:24 +0200277 self.input_encoding = 'UTF-8'
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200278 self.input_error_handling = 'replace'
Chris Liechti442bf512015-08-15 01:42:24 +0200279 self.output_encoding = 'UTF-8'
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200280 self.output_error_handling = 'ignore'
281 self.transformations = [TRANSFORMATIONS[t]() for t in transformations]
282 self.transformation_names = transformations
Chris Liechti442bf512015-08-15 01:42:24 +0200283 self.exit_character = 0x1d # GS/CTRL+]
284 self.menu_character = 0x14 # Menu: CTRL+T
cliechti576de252002-02-28 23:54:44 +0000285
cliechti8c2ea842011-03-18 01:51:46 +0000286 def _start_reader(self):
287 """Start reader thread"""
288 self._reader_alive = True
cliechti6fa76fb2009-07-08 23:53:39 +0000289 # start serial->console thread
cliechti6385f2c2005-09-21 19:51:19 +0000290 self.receiver_thread = threading.Thread(target=self.reader)
cliechti8c2ea842011-03-18 01:51:46 +0000291 self.receiver_thread.setDaemon(True)
cliechti6385f2c2005-09-21 19:51:19 +0000292 self.receiver_thread.start()
cliechti8c2ea842011-03-18 01:51:46 +0000293
294 def _stop_reader(self):
295 """Stop reader thread only, wait for clean exit of thread"""
296 self._reader_alive = False
297 self.receiver_thread.join()
298
299
300 def start(self):
301 self.alive = True
302 self._start_reader()
cliechti6fa76fb2009-07-08 23:53:39 +0000303 # enter console->serial loop
cliechti6385f2c2005-09-21 19:51:19 +0000304 self.transmitter_thread = threading.Thread(target=self.writer)
cliechti8c2ea842011-03-18 01:51:46 +0000305 self.transmitter_thread.setDaemon(True)
cliechti6385f2c2005-09-21 19:51:19 +0000306 self.transmitter_thread.start()
Chris Liechti89eb2472015-08-08 17:06:25 +0200307 self.console.setup()
cliechti53edb472009-02-06 21:18:46 +0000308
cliechti6385f2c2005-09-21 19:51:19 +0000309 def stop(self):
310 self.alive = False
cliechti53edb472009-02-06 21:18:46 +0000311
cliechtibf6bb7d2006-03-30 00:28:18 +0000312 def join(self, transmit_only=False):
cliechti6385f2c2005-09-21 19:51:19 +0000313 self.transmitter_thread.join()
cliechtibf6bb7d2006-03-30 00:28:18 +0000314 if not transmit_only:
315 self.receiver_thread.join()
cliechti6385f2c2005-09-21 19:51:19 +0000316
cliechti6c8eb2f2009-07-08 02:10:46 +0000317 def dump_port_settings(self):
Chris Liechti442bf512015-08-15 01:42:24 +0200318 sys.stderr.write("\n--- Settings: {} {},{},{},{}\n".format(
cliechti258ab0a2011-03-21 23:03:45 +0000319 self.serial.portstr,
320 self.serial.baudrate,
321 self.serial.bytesize,
322 self.serial.parity,
323 self.serial.stopbits))
Chris Liechti442bf512015-08-15 01:42:24 +0200324 sys.stderr.write('--- RTS: {:8} DTR: {:8} BREAK: {:8}\n'.format(
325 ('active' if self.rts_state else 'inactive'),
326 ('active' if self.dtr_state else 'inactive'),
327 ('active' if self.break_state else 'inactive')))
cliechti10114572009-08-05 23:40:50 +0000328 try:
Chris Liechti442bf512015-08-15 01:42:24 +0200329 sys.stderr.write('--- CTS: {:8} DSR: {:8} RI: {:8} CD: {:8}\n'.format(
330 ('active' if self.serial.getCTS() else 'inactive'),
331 ('active' if self.serial.getDSR() else 'inactive'),
332 ('active' if self.serial.getRI() else 'inactive'),
333 ('active' if self.serial.getCD() else 'inactive')))
cliechti10114572009-08-05 23:40:50 +0000334 except serial.SerialException:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200335 # on RFC 2217 ports, it can happen to no modem state notification was
cliechti10114572009-08-05 23:40:50 +0000336 # yet received. ignore this error.
337 pass
Chris Liechti442bf512015-08-15 01:42:24 +0200338 sys.stderr.write('--- software flow control: {}\n'.format('active' if self.serial.xonxoff else 'inactive'))
339 sys.stderr.write('--- hardware flow control: {}\n'.format('active' if self.serial.rtscts else 'inactive'))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200340 #~ sys.stderr.write('--- data escaping: %s linefeed: %s\n' % (
341 #~ REPR_MODES[self.repr_mode],
342 #~ LF_MODES[self.convert_outgoing]))
Chris Liechti442bf512015-08-15 01:42:24 +0200343 sys.stderr.write('--- serial input encoding: {}\n'.format(self.input_encoding))
344 sys.stderr.write('--- serial output encoding: {}\n'.format(self.output_encoding))
345 sys.stderr.write('--- transformations: {}\n'.format(' '.join(self.transformation_names)))
cliechti6c8eb2f2009-07-08 02:10:46 +0000346
cliechti6385f2c2005-09-21 19:51:19 +0000347 def reader(self):
348 """loop and copy serial->console"""
cliechti6963b262010-01-02 03:01:21 +0000349 try:
cliechti8c2ea842011-03-18 01:51:46 +0000350 while self.alive and self._reader_alive:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200351 data = self.serial.read(1) + self.serial.read(self.serial.inWaiting())
352 if data:
353 if self.raw:
354 self.console.write_bytes(data)
cliechti6963b262010-01-02 03:01:21 +0000355 else:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200356 text = codecs.decode(
357 data,
358 self.input_encoding,
359 self.input_error_handling)
360 for transformation in self.transformations:
361 text = transformation.input(text)
362 self.console.write(text)
Chris Liechti68340d72015-08-03 14:15:48 +0200363 except serial.SerialException as e:
cliechti6963b262010-01-02 03:01:21 +0000364 self.alive = False
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200365 # XXX would be nice if the writer could be interrupted at this
366 # point... to exit completely
cliechti6963b262010-01-02 03:01:21 +0000367 raise
cliechti576de252002-02-28 23:54:44 +0000368
cliechti576de252002-02-28 23:54:44 +0000369
cliechti6385f2c2005-09-21 19:51:19 +0000370 def writer(self):
cliechti8c2ea842011-03-18 01:51:46 +0000371 """\
Chris Liechti442bf512015-08-15 01:42:24 +0200372 Loop and copy console->serial until self.exit_character character is
373 found. When self.menu_character is found, interpret the next key
cliechti8c2ea842011-03-18 01:51:46 +0000374 locally.
cliechti6c8eb2f2009-07-08 02:10:46 +0000375 """
376 menu_active = False
377 try:
378 while self.alive:
379 try:
Chris Liechti89eb2472015-08-08 17:06:25 +0200380 c = self.console.getkey()
cliechti6c8eb2f2009-07-08 02:10:46 +0000381 except KeyboardInterrupt:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200382 c = '\x03'
cliechti6c8eb2f2009-07-08 02:10:46 +0000383 if menu_active:
Chris Liechti7af7c752015-08-12 15:45:19 +0200384 self.handle_menu_key(c)
cliechti6c8eb2f2009-07-08 02:10:46 +0000385 menu_active = False
Chris Liechti442bf512015-08-15 01:42:24 +0200386 elif c == self.menu_character:
Chris Liechti7af7c752015-08-12 15:45:19 +0200387 menu_active = True # next char will be for menu
Chris Liechti442bf512015-08-15 01:42:24 +0200388 elif c == self.exit_character:
Chris Liechti7af7c752015-08-12 15:45:19 +0200389 self.stop() # exit app
390 break
cliechti6c8eb2f2009-07-08 02:10:46 +0000391 else:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200392 #~ if self.raw:
393 text = c
394 echo_text = text
395 for transformation in self.transformations:
396 text = transformation.output(text)
397 echo_text = transformation.echo(echo_text)
398 b = codecs.encode(
399 text,
400 self.output_encoding,
401 self.output_error_handling)
402 self.serial.write(b)
cliechti6c8eb2f2009-07-08 02:10:46 +0000403 if self.echo:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200404 self.console.write(echo_text)
cliechti6c8eb2f2009-07-08 02:10:46 +0000405 except:
406 self.alive = False
407 raise
cliechti6385f2c2005-09-21 19:51:19 +0000408
Chris Liechti7af7c752015-08-12 15:45:19 +0200409 def handle_menu_key(self, c):
410 """Implement a simple menu / settings"""
Chris Liechti442bf512015-08-15 01:42:24 +0200411 if c == self.menu_character or c == self.exit_character: # Menu character again/exit char -> send itself
Chris Liechti7af7c752015-08-12 15:45:19 +0200412 b = codecs.encode(
413 c,
414 self.output_encoding,
415 self.output_error_handling)
416 self.serial.write(b)
417 if self.echo:
418 self.console.write(c)
Chris Liechtib7550bd2015-08-15 04:09:10 +0200419 elif c == '\x15': # CTRL+U -> upload file
Chris Liechti7af7c752015-08-12 15:45:19 +0200420 sys.stderr.write('\n--- File to upload: ')
421 sys.stderr.flush()
422 self.console.cleanup()
423 filename = sys.stdin.readline().rstrip('\r\n')
424 if filename:
425 try:
426 with open(filename, 'rb') as f:
Chris Liechti442bf512015-08-15 01:42:24 +0200427 sys.stderr.write('--- Sending file {} ---\n'.format(filename))
Chris Liechti7af7c752015-08-12 15:45:19 +0200428 while True:
429 block = f.read(1024)
430 if not block:
431 break
432 self.serial.write(block)
433 # Wait for output buffer to drain.
434 self.serial.flush()
435 sys.stderr.write('.') # Progress indicator.
Chris Liechti442bf512015-08-15 01:42:24 +0200436 sys.stderr.write('\n--- File {} sent ---\n'.format(filename))
Chris Liechti7af7c752015-08-12 15:45:19 +0200437 except IOError as e:
Chris Liechti442bf512015-08-15 01:42:24 +0200438 sys.stderr.write('--- ERROR opening file {}: {} ---\n'.format(filename, e))
Chris Liechti7af7c752015-08-12 15:45:19 +0200439 self.console.setup()
440 elif c in '\x08hH?': # CTRL+H, h, H, ? -> Show help
Chris Liechti442bf512015-08-15 01:42:24 +0200441 sys.stderr.write(self.get_help_text())
Chris Liechti7af7c752015-08-12 15:45:19 +0200442 elif c == '\x12': # CTRL+R -> Toggle RTS
443 self.rts_state = not self.rts_state
444 self.serial.setRTS(self.rts_state)
Chris Liechti442bf512015-08-15 01:42:24 +0200445 sys.stderr.write('--- RTS {} ---\n'.format('active' if self.rts_state else 'inactive'))
Chris Liechti7af7c752015-08-12 15:45:19 +0200446 elif c == '\x04': # CTRL+D -> Toggle DTR
447 self.dtr_state = not self.dtr_state
448 self.serial.setDTR(self.dtr_state)
Chris Liechti442bf512015-08-15 01:42:24 +0200449 sys.stderr.write('--- DTR {} ---\n'.format('active' if self.dtr_state else 'inactive'))
Chris Liechti7af7c752015-08-12 15:45:19 +0200450 elif c == '\x02': # CTRL+B -> toggle BREAK condition
451 self.break_state = not self.break_state
452 self.serial.setBreak(self.break_state)
Chris Liechti442bf512015-08-15 01:42:24 +0200453 sys.stderr.write('--- BREAK {} ---\n'.format('active' if self.break_state else 'inactive'))
Chris Liechti7af7c752015-08-12 15:45:19 +0200454 elif c == '\x05': # CTRL+E -> toggle local echo
455 self.echo = not self.echo
Chris Liechti442bf512015-08-15 01:42:24 +0200456 sys.stderr.write('--- local echo {} ---\n'.format('active' if self.echo else 'inactive'))
Chris Liechti7af7c752015-08-12 15:45:19 +0200457 elif c == '\x09': # CTRL+I -> info
458 self.dump_port_settings()
459 #~ elif c == '\x01': # CTRL+A -> cycle escape mode
460 #~ elif c == '\x0c': # CTRL+L -> cycle linefeed mode
461 elif c in 'pP': # P -> change port
462 dump_port_list()
463 sys.stderr.write('--- Enter port name: ')
464 sys.stderr.flush()
465 self.console.cleanup()
466 try:
467 port = sys.stdin.readline().strip()
468 except KeyboardInterrupt:
469 port = None
470 self.console.setup()
471 if port and port != self.serial.port:
472 # reader thread needs to be shut down
473 self._stop_reader()
474 # save settings
475 settings = self.serial.getSettingsDict()
476 try:
477 new_serial = serial.serial_for_url(port, do_not_open=True)
478 # restore settings and open
479 new_serial.applySettingsDict(settings)
480 new_serial.open()
481 new_serial.setRTS(self.rts_state)
482 new_serial.setDTR(self.dtr_state)
483 new_serial.setBreak(self.break_state)
484 except Exception as e:
Chris Liechti442bf512015-08-15 01:42:24 +0200485 sys.stderr.write('--- ERROR opening new port: {} ---\n'.format(e))
Chris Liechti7af7c752015-08-12 15:45:19 +0200486 new_serial.close()
487 else:
488 self.serial.close()
489 self.serial = new_serial
Chris Liechti442bf512015-08-15 01:42:24 +0200490 sys.stderr.write('--- Port changed to: {} ---\n'.format(self.serial.port))
Chris Liechti7af7c752015-08-12 15:45:19 +0200491 # and restart the reader thread
492 self._start_reader()
493 elif c in 'bB': # B -> change baudrate
494 sys.stderr.write('\n--- Baudrate: ')
495 sys.stderr.flush()
496 self.console.cleanup()
497 backup = self.serial.baudrate
498 try:
499 self.serial.baudrate = int(sys.stdin.readline().strip())
500 except ValueError as e:
Chris Liechti442bf512015-08-15 01:42:24 +0200501 sys.stderr.write('--- ERROR setting baudrate: %s ---\n'.format(e))
Chris Liechti7af7c752015-08-12 15:45:19 +0200502 self.serial.baudrate = backup
503 else:
504 self.dump_port_settings()
505 self.console.setup()
506 elif c == '8': # 8 -> change to 8 bits
507 self.serial.bytesize = serial.EIGHTBITS
508 self.dump_port_settings()
509 elif c == '7': # 7 -> change to 8 bits
510 self.serial.bytesize = serial.SEVENBITS
511 self.dump_port_settings()
512 elif c in 'eE': # E -> change to even parity
513 self.serial.parity = serial.PARITY_EVEN
514 self.dump_port_settings()
515 elif c in 'oO': # O -> change to odd parity
516 self.serial.parity = serial.PARITY_ODD
517 self.dump_port_settings()
518 elif c in 'mM': # M -> change to mark parity
519 self.serial.parity = serial.PARITY_MARK
520 self.dump_port_settings()
521 elif c in 'sS': # S -> change to space parity
522 self.serial.parity = serial.PARITY_SPACE
523 self.dump_port_settings()
524 elif c in 'nN': # N -> change to no parity
525 self.serial.parity = serial.PARITY_NONE
526 self.dump_port_settings()
527 elif c == '1': # 1 -> change to 1 stop bits
528 self.serial.stopbits = serial.STOPBITS_ONE
529 self.dump_port_settings()
530 elif c == '2': # 2 -> change to 2 stop bits
531 self.serial.stopbits = serial.STOPBITS_TWO
532 self.dump_port_settings()
533 elif c == '3': # 3 -> change to 1.5 stop bits
534 self.serial.stopbits = serial.STOPBITS_ONE_POINT_FIVE
535 self.dump_port_settings()
536 elif c in 'xX': # X -> change software flow control
537 self.serial.xonxoff = (c == 'X')
538 self.dump_port_settings()
539 elif c in 'rR': # R -> change hardware flow control
540 self.serial.rtscts = (c == 'R')
541 self.dump_port_settings()
542 else:
Chris Liechti442bf512015-08-15 01:42:24 +0200543 sys.stderr.write('--- unknown menu character {} --\n'.format(key_description(c)))
544
545 def get_help_text(self):
546 # help text, starts with blank line! it's a function so that the current values
547 # for the shortcut keys is used and not the value at program start
548 return """
549--- pySerial ({version}) - miniterm - help
550---
551--- {exit:8} Exit program
552--- {menu:8} Menu escape key, followed by:
553--- Menu keys:
554--- {menu:7} Send the menu character itself to remote
555--- {exit:7} Send the exit character itself to remote
556--- {info:7} Show info
557--- {upload:7} Upload file (prompt will be shown)
558--- Toggles:
559--- {rts:7} RTS {echo:7} local echo
560--- {dtr:7} DTR {brk:7} BREAK
561---
562--- Port settings {menu} followed by the following):
563--- p change port
564--- 7 8 set data bits
Chris Liechtib7550bd2015-08-15 04:09:10 +0200565--- N E O S M change parity (None, Even, Odd, Space, Mark)
Chris Liechti442bf512015-08-15 01:42:24 +0200566--- 1 2 3 set stop bits (1, 2, 1.5)
567--- b change baud rate
568--- x X disable/enable software flow control
569--- r R disable/enable hardware flow control
570""".format(
571 version=getattr(serial, 'VERSION', 'unknown version'),
572 exit=key_description(self.exit_character),
573 menu=key_description(self.menu_character),
Chris Liechtib7550bd2015-08-15 04:09:10 +0200574 rts=key_description('\x12'),
575 dtr=key_description('\x04'),
576 brk=key_description('\x02'),
577 echo=key_description('\x05'),
578 info=key_description('\x09'),
579 upload=key_description('\x15'),
Chris Liechti442bf512015-08-15 01:42:24 +0200580 )
Chris Liechti7af7c752015-08-12 15:45:19 +0200581
582
583
cliechti6385f2c2005-09-21 19:51:19 +0000584def main():
Chris Liechtib7550bd2015-08-15 04:09:10 +0200585 import argparse
cliechti6385f2c2005-09-21 19:51:19 +0000586
Chris Liechtib7550bd2015-08-15 04:09:10 +0200587 parser = argparse.ArgumentParser(
588 description="Miniterm - A simple terminal program for the serial port.")
cliechti6385f2c2005-09-21 19:51:19 +0000589
Chris Liechtib7550bd2015-08-15 04:09:10 +0200590 parser.add_argument("port",
591 nargs='?',
592 help="serial port name",
593 default=DEFAULT_PORT)
cliechti5370cee2013-10-13 03:08:19 +0000594
Chris Liechtib7550bd2015-08-15 04:09:10 +0200595 parser.add_argument("baudrate",
596 nargs='?',
597 type=int,
598 help="set baud rate, default: %(default)s",
599 default=DEFAULT_BAUDRATE)
cliechti6385f2c2005-09-21 19:51:19 +0000600
Chris Liechtib7550bd2015-08-15 04:09:10 +0200601 group = parser.add_argument_group("Port settings")
cliechti53edb472009-02-06 21:18:46 +0000602
Chris Liechtib7550bd2015-08-15 04:09:10 +0200603 group.add_argument("--parity",
604 choices=['N', 'E', 'O', 'S', 'M'],
605 help="set parity, one of {N E O S M}, default: N",
606 default='N')
cliechti53edb472009-02-06 21:18:46 +0000607
Chris Liechtib7550bd2015-08-15 04:09:10 +0200608 group.add_argument("--rtscts",
609 action="store_true",
610 help="enable RTS/CTS flow control (default off)",
611 default=False)
cliechti53edb472009-02-06 21:18:46 +0000612
Chris Liechtib7550bd2015-08-15 04:09:10 +0200613 group.add_argument("--xonxoff",
614 action="store_true",
615 help="enable software flow control (default off)",
616 default=False)
cliechti53edb472009-02-06 21:18:46 +0000617
Chris Liechtib7550bd2015-08-15 04:09:10 +0200618 group.add_argument("--rts",
619 type=int,
620 help="set initial RTS line state (possible values: 0, 1)",
621 default=DEFAULT_RTS)
cliechti5370cee2013-10-13 03:08:19 +0000622
Chris Liechtib7550bd2015-08-15 04:09:10 +0200623 group.add_argument("--dtr",
624 type=int,
625 help="set initial DTR line state (possible values: 0, 1)",
626 default=DEFAULT_DTR)
cliechti5370cee2013-10-13 03:08:19 +0000627
Chris Liechtib7550bd2015-08-15 04:09:10 +0200628 group = parser.add_argument_group("Data handling")
cliechti5370cee2013-10-13 03:08:19 +0000629
Chris Liechtib7550bd2015-08-15 04:09:10 +0200630 group.add_argument("-e", "--echo",
631 action="store_true",
632 help="enable local echo (default off)",
633 default=False)
cliechti5370cee2013-10-13 03:08:19 +0000634
Chris Liechtib7550bd2015-08-15 04:09:10 +0200635 group.add_argument("--encoding",
636 dest="serial_port_encoding",
637 metavar="CODEC",
638 help="Set the encoding for the serial port (default: %(default)s",
639 default='UTF-8')
cliechti5370cee2013-10-13 03:08:19 +0000640
Chris Liechtib7550bd2015-08-15 04:09:10 +0200641 group.add_argument("-t", "--transformation",
642 dest="transformations",
643 action="append",
644 metavar="NAME",
645 help="Add text transformation",
646 default=[])
Chris Liechti2b1b3552015-08-12 15:35:33 +0200647
Chris Liechtib7550bd2015-08-15 04:09:10 +0200648 eol_group = group.add_mutually_exclusive_group()
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200649
Chris Liechtib7550bd2015-08-15 04:09:10 +0200650 eol_group.add_argument("--cr",
651 action="store_true",
652 help="do not send CR+LF, send CR only",
653 default=False)
cliechti53edb472009-02-06 21:18:46 +0000654
Chris Liechtib7550bd2015-08-15 04:09:10 +0200655 eol_group.add_argument("--lf",
656 action="store_true",
657 help="do not send CR+LF, send LF only",
658 default=False)
cliechti53edb472009-02-06 21:18:46 +0000659
Chris Liechtib7550bd2015-08-15 04:09:10 +0200660 group.add_argument("--raw",
661 action="store_true",
662 help="Do no apply any encodings/transformations",
663 default=False)
cliechti6385f2c2005-09-21 19:51:19 +0000664
Chris Liechtib7550bd2015-08-15 04:09:10 +0200665 group = parser.add_argument_group("Hotkeys")
cliechtib7d746d2006-03-28 22:44:30 +0000666
Chris Liechtib7550bd2015-08-15 04:09:10 +0200667 group.add_argument("--exit-char",
668 type=int,
669 help="Unicode of special character that is used to exit the application",
670 default=0x1d # GS/CTRL+]
671 )
cliechtibf6bb7d2006-03-30 00:28:18 +0000672
Chris Liechtib7550bd2015-08-15 04:09:10 +0200673 group.add_argument("--menu-char",
674 type=int,
675 help="Unicode code of special character that is used to control miniterm (menu)",
676 default=0x14 # Menu: CTRL+T
677 )
cliechti9c592b32008-06-16 22:00:14 +0000678
Chris Liechtib7550bd2015-08-15 04:09:10 +0200679 group = parser.add_argument_group("Diagnostics")
cliechti6385f2c2005-09-21 19:51:19 +0000680
Chris Liechtib7550bd2015-08-15 04:09:10 +0200681 group.add_argument("-q", "--quiet",
682 action="store_true",
683 help="suppress non-error messages",
684 default=False)
cliechti5370cee2013-10-13 03:08:19 +0000685
Chris Liechtib7550bd2015-08-15 04:09:10 +0200686 group.add_argument("--develop",
687 action="store_true",
688 help="show Python traceback on error",
689 default=False)
cliechti5370cee2013-10-13 03:08:19 +0000690
Chris Liechtib7550bd2015-08-15 04:09:10 +0200691 args = parser.parse_args()
cliechti5370cee2013-10-13 03:08:19 +0000692
Chris Liechtib7550bd2015-08-15 04:09:10 +0200693 if args.menu_char == args.exit_char:
cliechti6c8eb2f2009-07-08 02:10:46 +0000694 parser.error('--exit-char can not be the same as --menu-char')
695
cliechti9c592b32008-06-16 22:00:14 +0000696
Chris Liechtib7550bd2015-08-15 04:09:10 +0200697 # no port given on command line -> ask user now
698 if args.port is None:
699 dump_port_list()
700 args.port = raw_input('Enter port name:')
cliechti53edb472009-02-06 21:18:46 +0000701
Chris Liechtib7550bd2015-08-15 04:09:10 +0200702 if args.transformations:
703 if 'help' in args.transformations:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200704 sys.stderr.write('Available Transformations:\n')
Chris Liechti442bf512015-08-15 01:42:24 +0200705 sys.stderr.write('\n'.join(
Chris Liechtib7550bd2015-08-15 04:09:10 +0200706 '{:<20} = {.__doc__}'.format(k, v)
707 for k, v in sorted(TRANSFORMATIONS.items())))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200708 sys.stderr.write('\n')
709 sys.exit(1)
Chris Liechtib7550bd2015-08-15 04:09:10 +0200710 transformations = args.transformations
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200711 else:
712 transformations = ['default']
713
Chris Liechtib7550bd2015-08-15 04:09:10 +0200714 if args.cr:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200715 transformations.append('cr')
Chris Liechtib7550bd2015-08-15 04:09:10 +0200716 elif args.lf:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200717 transformations.append('lf')
718 else:
719 transformations.append('crlf')
cliechti6385f2c2005-09-21 19:51:19 +0000720
721 try:
722 miniterm = Miniterm(
Chris Liechtib7550bd2015-08-15 04:09:10 +0200723 args.port,
724 args.baudrate,
725 args.parity,
726 rtscts=args.rtscts,
727 xonxoff=args.xonxoff,
728 echo=args.echo,
Chris Liechti442bf512015-08-15 01:42:24 +0200729 transformations=transformations,
730 )
Chris Liechtib7550bd2015-08-15 04:09:10 +0200731 miniterm.exit_character = unichr(args.exit_char)
732 miniterm.menu_character = unichr(args.menu_char)
733 miniterm.raw = args.raw
734 miniterm.input_encoding = args.serial_port_encoding
735 miniterm.output_encoding = args.serial_port_encoding
Chris Liechti68340d72015-08-03 14:15:48 +0200736 except serial.SerialException as e:
Chris Liechti442bf512015-08-15 01:42:24 +0200737 sys.stderr.write('could not open port {}: {}\n'.format(repr(port), e))
Chris Liechtib7550bd2015-08-15 04:09:10 +0200738 if args.develop:
Chris Liechti91090912015-08-05 02:36:14 +0200739 raise
cliechti6385f2c2005-09-21 19:51:19 +0000740 sys.exit(1)
741
Chris Liechtib7550bd2015-08-15 04:09:10 +0200742 if not args.quiet:
Chris Liechti442bf512015-08-15 01:42:24 +0200743 sys.stderr.write('--- Miniterm on {}: {},{},{},{} ---\n'.format(
744 miniterm.serial.portstr,
745 miniterm.serial.baudrate,
746 miniterm.serial.bytesize,
747 miniterm.serial.parity,
748 miniterm.serial.stopbits,
749 ))
Chris Liechtib7550bd2015-08-15 04:09:10 +0200750 sys.stderr.write('--- Quit: {} | Menu: {} | Help: {} followed by {} ---\n'.format(
Chris Liechti442bf512015-08-15 01:42:24 +0200751 key_description(miniterm.exit_character),
752 key_description(miniterm.menu_character),
753 key_description(miniterm.menu_character),
Chris Liechtib7550bd2015-08-15 04:09:10 +0200754 key_description('\x08'),
Chris Liechti442bf512015-08-15 01:42:24 +0200755 ))
cliechti6fa76fb2009-07-08 23:53:39 +0000756
Chris Liechtib7550bd2015-08-15 04:09:10 +0200757 if args.dtr is not None:
758 if not args.quiet:
759 sys.stderr.write('--- forcing DTR {}\n'.format('active' if args.dtr else 'inactive'))
760 miniterm.serial.setDTR(args.dtr)
761 miniterm.dtr_state = args.dtr
762 if args.rts is not None:
763 if not args.quiet:
764 sys.stderr.write('--- forcing RTS {}\n'.format('active' if args.rts else 'inactive'))
765 miniterm.serial.setRTS(args.rts)
766 miniterm.rts_state = args.rts
cliechti53edb472009-02-06 21:18:46 +0000767
cliechti6385f2c2005-09-21 19:51:19 +0000768 miniterm.start()
cliechti258ab0a2011-03-21 23:03:45 +0000769 try:
770 miniterm.join(True)
771 except KeyboardInterrupt:
772 pass
Chris Liechtib7550bd2015-08-15 04:09:10 +0200773 if not args.quiet:
cliechtibf6bb7d2006-03-30 00:28:18 +0000774 sys.stderr.write("\n--- exit ---\n")
cliechti6385f2c2005-09-21 19:51:19 +0000775 miniterm.join()
cliechtibf6bb7d2006-03-30 00:28:18 +0000776
cliechti5370cee2013-10-13 03:08:19 +0000777# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
cliechti8b3ad392002-03-03 20:12:21 +0000778if __name__ == '__main__':
cliechti6385f2c2005-09-21 19:51:19 +0000779 main()