blob: 7814c842efc68abc61ce25bca737d3056599e8b8 [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 Liechti89eb2472015-08-08 17:06:25 +020031EXITCHARCTER = b'\x1d' # GS/CTRL+]
32MENUCHARACTER = b'\x14' # Menu: CTRL+T
cliechtia128a702004-07-21 22:13:31 +000033
cliechti096e1962012-02-20 01:52:38 +000034DEFAULT_PORT = None
35DEFAULT_BAUDRATE = 9600
36DEFAULT_RTS = None
37DEFAULT_DTR = None
38
cliechti6c8eb2f2009-07-08 02:10:46 +000039
40def key_description(character):
41 """generate a readable description for a key"""
42 ascii_code = ord(character)
43 if ascii_code < 32:
44 return 'Ctrl+%c' % (ord('@') + ascii_code)
45 else:
46 return repr(character)
47
cliechti91165532011-03-18 02:02:52 +000048
cliechti6c8eb2f2009-07-08 02:10:46 +000049# help text, starts with blank line! it's a function so that the current values
50# for the shortcut keys is used and not the value at program start
51def get_help_text():
52 return """
cliechti6963b262010-01-02 03:01:21 +000053--- pySerial (%(version)s) - miniterm - help
cliechti6fa76fb2009-07-08 23:53:39 +000054---
55--- %(exit)-8s Exit program
56--- %(menu)-8s Menu escape key, followed by:
57--- Menu keys:
cliechti258ab0a2011-03-21 23:03:45 +000058--- %(itself)-7s Send the menu character itself to remote
59--- %(exchar)-7s Send the exit character itself to remote
60--- %(info)-7s Show info
61--- %(upload)-7s Upload file (prompt will be shown)
cliechti6fa76fb2009-07-08 23:53:39 +000062--- Toggles:
cliechti258ab0a2011-03-21 23:03:45 +000063--- %(rts)-7s RTS %(echo)-7s local echo
64--- %(dtr)-7s DTR %(break)-7s BREAK
cliechti6fa76fb2009-07-08 23:53:39 +000065---
66--- Port settings (%(menu)s followed by the following):
cliechti258ab0a2011-03-21 23:03:45 +000067--- p change port
68--- 7 8 set data bits
69--- n e o s m change parity (None, Even, Odd, Space, Mark)
70--- 1 2 3 set stop bits (1, 2, 1.5)
71--- b change baud rate
72--- x X disable/enable software flow control
73--- r R disable/enable hardware flow control
cliechti6c8eb2f2009-07-08 02:10:46 +000074""" % {
cliechti8c2ea842011-03-18 01:51:46 +000075 'version': getattr(serial, 'VERSION', 'unknown version'),
cliechti6c8eb2f2009-07-08 02:10:46 +000076 'exit': key_description(EXITCHARCTER),
77 'menu': key_description(MENUCHARACTER),
Chris Liechti89eb2472015-08-08 17:06:25 +020078 'rts': key_description(b'\x12'),
Chris Liechti89eb2472015-08-08 17:06:25 +020079 'dtr': key_description(b'\x04'),
Chris Liechti89eb2472015-08-08 17:06:25 +020080 'break': key_description(b'\x02'),
81 'echo': key_description(b'\x05'),
82 'info': key_description(b'\x09'),
83 'upload': key_description(b'\x15'),
cliechti6fa76fb2009-07-08 23:53:39 +000084 'itself': key_description(MENUCHARACTER),
85 'exchar': key_description(EXITCHARCTER),
cliechti6c8eb2f2009-07-08 02:10:46 +000086}
87
cliechti393fa0e2011-08-22 00:53:36 +000088
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020089class ConsoleBase(object):
90 def __init__(self):
91 if sys.version_info >= (3, 0):
92 self.byte_output = sys.stdout.buffer
93 else:
94 self.byte_output = sys.stdout
95 self.output = sys.stdout
cliechtif467aa82013-10-13 21:36:49 +000096
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020097 def setup(self):
98 pass # Do nothing for 'nt'
cliechtif467aa82013-10-13 21:36:49 +000099
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200100 def cleanup(self):
101 pass # Do nothing for 'nt'
102
103 def getkey(self):
104 return None
105
106 def write_bytes(self, s):
107 self.byte_output.write(s)
108 self.byte_output.flush()
109
110 def write(self, s):
111 self.output.write(s)
112 self.output.flush()
113
cliechti9c592b32008-06-16 22:00:14 +0000114
cliechtifc9eb382002-03-05 01:12:29 +0000115if os.name == 'nt':
cliechti576de252002-02-28 23:54:44 +0000116 import msvcrt
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200117 import ctypes
118 class Console(ConsoleBase):
cliechti3a8bf092008-09-17 11:26:53 +0000119 def getkey(self):
cliechti91165532011-03-18 02:02:52 +0000120 while True:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200121 z = msvcrt.getwch()
122 if z == '\r':
123 return '\n'
124 elif z in '\x00\x0e': # functions keys, ignore
125 msvcrt.getwch()
cliechti9c592b32008-06-16 22:00:14 +0000126 else:
cliechti9c592b32008-06-16 22:00:14 +0000127 return z
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200128
Chris Liechti89eb2472015-08-08 17:06:25 +0200129 def write(self, s):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200130 # works, kind of.. can't print unicode
131 self.byte_output.write(s.encode(sys.stdout.encoding, 'replace'))
132 #~ sys.stdout.write(s) # fails with encoding errors
133 #~ for byte in data: # fails for python3 as it returns ints instead of b''
134 #~ for x in range(len(s)):
135 #~ byte = s[x:x+1]
136 #~ msvcrt.putwch(byte) # blocks?!? non-overlapped win io?
137
138 def write_bytes(self, data):
139 #~ for byte in data: # fails for python3 as it returns ints instead of b''
140 for x in range(len(data)):
141 byte = data[x:x+1]
142 msvcrt.putch(byte)
cliechti53edb472009-02-06 21:18:46 +0000143
cliechti576de252002-02-28 23:54:44 +0000144elif os.name == 'posix':
Chris Liechtia1d5c6d2015-08-07 14:41:24 +0200145 import atexit
146 import termios
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200147 class Console(ConsoleBase):
cliechti9c592b32008-06-16 22:00:14 +0000148 def __init__(self):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200149 super(Console, self).__init__()
cliechti9c592b32008-06-16 22:00:14 +0000150 self.fd = sys.stdin.fileno()
cliechti5370cee2013-10-13 03:08:19 +0000151 self.old = None
Chris Liechti89eb2472015-08-08 17:06:25 +0200152 atexit.register(self.cleanup)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200153 if sys.version_info < (3, 0):
154 sys.stdin = codecs.getreader(sys.stdin.encoding)(sys.stdin)
cliechti9c592b32008-06-16 22:00:14 +0000155
156 def setup(self):
157 self.old = termios.tcgetattr(self.fd)
158 new = termios.tcgetattr(self.fd)
159 new[3] = new[3] & ~termios.ICANON & ~termios.ECHO & ~termios.ISIG
160 new[6][termios.VMIN] = 1
161 new[6][termios.VTIME] = 0
162 termios.tcsetattr(self.fd, termios.TCSANOW, new)
cliechti53edb472009-02-06 21:18:46 +0000163
cliechti9c592b32008-06-16 22:00:14 +0000164 def getkey(self):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200165 return sys.stdin.read(1)
166 #~ c = os.read(self.fd, 1)
167 #~ return c
cliechti53edb472009-02-06 21:18:46 +0000168
cliechti9c592b32008-06-16 22:00:14 +0000169 def cleanup(self):
cliechti5370cee2013-10-13 03:08:19 +0000170 if self.old is not None:
171 termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old)
cliechti9c592b32008-06-16 22:00:14 +0000172
cliechti576de252002-02-28 23:54:44 +0000173else:
cliechti8c2ea842011-03-18 01:51:46 +0000174 raise NotImplementedError("Sorry no implementation for your platform (%s) available." % sys.platform)
cliechti576de252002-02-28 23:54:44 +0000175
cliechti6fa76fb2009-07-08 23:53:39 +0000176
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200177# XXX how to handle multi byte sequences like CRLF?
178# codecs.IncrementalEncoder would be a good choice
179
180class Transform(object):
181 def input(self, text):
182 """text received from serial port"""
183 return text
184
185 def output(self, text):
186 """text to be sent to serial port"""
187 return text
188
189 def echo(self, text):
190 """text to be sent but displayed on console"""
191 return text
192
193class CRLF(Transform):
194 """ENTER sends CR+LF"""
195 def input(self, text):
196 return text.replace('\r\n', '\n')
197
198 def output(self, text):
199 return text.replace('\n', '\r\n')
200
201class CR(Transform):
202 """ENTER sends CR"""
203 def input(self, text):
204 return text.replace('\r', '\n')
205
206 def output(self, text):
207 return text.replace('\n', '\r')
208
209class LF(Transform):
210 """ENTER sends LF"""
211
212
213class NoTerminal(Transform):
214 """remove typical terminal control codes from input"""
215 def input(self, text):
Chris Liechti7e9cfd42015-08-12 15:28:19 +0200216 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 +0200217
218 echo = input
219
220
221class NoControls(Transform):
222 """Remove all control codes, incl. CR+LF"""
223 def input(self, text):
224 return ''.join(t if t >= ' ' else unichr(0x2400 + ord(t)) for t in text)
225
226 echo = input
227
228
229class HexDump(Transform):
230 """Complete hex dump"""
231 def input(self, text):
232 return ''.join('{:02x} '.format(ord(t)) for t in text)
233
234 echo = input
235
236
237class Printable(Transform):
Chris Liechti7e9cfd42015-08-12 15:28:19 +0200238 """Show decimal code for all non-ASCII characters and most control codes"""
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200239 def input(self, text):
240 r = []
241 for t in text:
Chris Liechti7e9cfd42015-08-12 15:28:19 +0200242 if ' ' <= t < '\x7f' or t in '\r\n\b\t':
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200243 r.append(t)
244 else:
245 r.extend(unichr(0x2080 + ord(d) - 48) for d in '{:d}'.format(ord(t)))
246 r.append(' ')
247 return ''.join(r)
248
249 echo = input
250
251
252
253class Colorize(Transform):
254 """Apply different colors for input and echo"""
255 def __init__(self):
256 # XXX make it configurable, use colorama?
257 self.input_color = '\x1b[37m'
258 self.echo_color = '\x1b[31m'
259
260 def input(self, text):
261 return self.input_color + text
262
263 def echo(self, text):
264 return self.echo_color + text
265
266class DebugIO(Transform):
267 """Apply different colors for input and echo"""
268 def input(self, text):
269 sys.stderr.write('in: %r\n' % text)
270 return text
271
272 def echo(self, text):
273 sys.stderr.write('out: %r\n' % text)
274 return text
275
276# other ideas:
277# - add date/time for each newline
278# - insert newline after: a) timeout b) packet end character
279
280TRANSFORMATIONS = {
281 'crlf': CRLF,
282 'cr': CR,
283 'lf': LF,
284 'default': NoTerminal,
285 'nocontrol': NoControls,
286 'printable': Printable,
287 'hex': HexDump,
288 'colorize': Colorize,
289 'debug': DebugIO,
290 }
291
292
cliechti1351dde2012-04-12 16:47:47 +0000293def dump_port_list():
294 if comports:
295 sys.stderr.write('\n--- Available ports:\n')
296 for port, desc, hwid in sorted(comports()):
297 #~ sys.stderr.write('--- %-20s %s [%s]\n' % (port, desc, hwid))
298 sys.stderr.write('--- %-20s %s\n' % (port, desc))
299
300
cliechti8c2ea842011-03-18 01:51:46 +0000301class Miniterm(object):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200302 def __init__(self, port, baudrate, parity, rtscts, xonxoff, echo=False, transformations=()):
Chris Liechti89eb2472015-08-08 17:06:25 +0200303 self.console = Console()
Chris Liechtia1d5c6d2015-08-07 14:41:24 +0200304 self.serial = serial.serial_for_url(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1)
cliechti6385f2c2005-09-21 19:51:19 +0000305 self.echo = echo
cliechti6c8eb2f2009-07-08 02:10:46 +0000306 self.dtr_state = True
307 self.rts_state = True
308 self.break_state = False
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200309 self.raw = False
310 self.input_encoding = 'latin1'
311 self.input_error_handling = 'replace'
312 self.output_encoding = 'latin1'
313 self.output_error_handling = 'ignore'
314 self.transformations = [TRANSFORMATIONS[t]() for t in transformations]
315 self.transformation_names = transformations
cliechti576de252002-02-28 23:54:44 +0000316
cliechti8c2ea842011-03-18 01:51:46 +0000317 def _start_reader(self):
318 """Start reader thread"""
319 self._reader_alive = True
cliechti6fa76fb2009-07-08 23:53:39 +0000320 # start serial->console thread
cliechti6385f2c2005-09-21 19:51:19 +0000321 self.receiver_thread = threading.Thread(target=self.reader)
cliechti8c2ea842011-03-18 01:51:46 +0000322 self.receiver_thread.setDaemon(True)
cliechti6385f2c2005-09-21 19:51:19 +0000323 self.receiver_thread.start()
cliechti8c2ea842011-03-18 01:51:46 +0000324
325 def _stop_reader(self):
326 """Stop reader thread only, wait for clean exit of thread"""
327 self._reader_alive = False
328 self.receiver_thread.join()
329
330
331 def start(self):
332 self.alive = True
333 self._start_reader()
cliechti6fa76fb2009-07-08 23:53:39 +0000334 # enter console->serial loop
cliechti6385f2c2005-09-21 19:51:19 +0000335 self.transmitter_thread = threading.Thread(target=self.writer)
cliechti8c2ea842011-03-18 01:51:46 +0000336 self.transmitter_thread.setDaemon(True)
cliechti6385f2c2005-09-21 19:51:19 +0000337 self.transmitter_thread.start()
Chris Liechti89eb2472015-08-08 17:06:25 +0200338 self.console.setup()
cliechti53edb472009-02-06 21:18:46 +0000339
cliechti6385f2c2005-09-21 19:51:19 +0000340 def stop(self):
341 self.alive = False
cliechti53edb472009-02-06 21:18:46 +0000342
cliechtibf6bb7d2006-03-30 00:28:18 +0000343 def join(self, transmit_only=False):
cliechti6385f2c2005-09-21 19:51:19 +0000344 self.transmitter_thread.join()
cliechtibf6bb7d2006-03-30 00:28:18 +0000345 if not transmit_only:
346 self.receiver_thread.join()
cliechti6385f2c2005-09-21 19:51:19 +0000347
cliechti6c8eb2f2009-07-08 02:10:46 +0000348 def dump_port_settings(self):
cliechti6fa76fb2009-07-08 23:53:39 +0000349 sys.stderr.write("\n--- Settings: %s %s,%s,%s,%s\n" % (
cliechti258ab0a2011-03-21 23:03:45 +0000350 self.serial.portstr,
351 self.serial.baudrate,
352 self.serial.bytesize,
353 self.serial.parity,
354 self.serial.stopbits))
355 sys.stderr.write('--- RTS: %-8s DTR: %-8s BREAK: %-8s\n' % (
356 (self.rts_state and 'active' or 'inactive'),
357 (self.dtr_state and 'active' or 'inactive'),
358 (self.break_state and 'active' or 'inactive')))
cliechti10114572009-08-05 23:40:50 +0000359 try:
cliechti258ab0a2011-03-21 23:03:45 +0000360 sys.stderr.write('--- CTS: %-8s DSR: %-8s RI: %-8s CD: %-8s\n' % (
361 (self.serial.getCTS() and 'active' or 'inactive'),
362 (self.serial.getDSR() and 'active' or 'inactive'),
363 (self.serial.getRI() and 'active' or 'inactive'),
364 (self.serial.getCD() and 'active' or 'inactive')))
cliechti10114572009-08-05 23:40:50 +0000365 except serial.SerialException:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200366 # on RFC 2217 ports, it can happen to no modem state notification was
cliechti10114572009-08-05 23:40:50 +0000367 # yet received. ignore this error.
368 pass
cliechti258ab0a2011-03-21 23:03:45 +0000369 sys.stderr.write('--- software flow control: %s\n' % (self.serial.xonxoff and 'active' or 'inactive'))
370 sys.stderr.write('--- hardware flow control: %s\n' % (self.serial.rtscts and 'active' or 'inactive'))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200371 #~ sys.stderr.write('--- data escaping: %s linefeed: %s\n' % (
372 #~ REPR_MODES[self.repr_mode],
373 #~ LF_MODES[self.convert_outgoing]))
374 sys.stderr.write('--- serial input encoding: %s\n' % (self.input_encoding,))
375 sys.stderr.write('--- serial output encoding: %s\n' % (self.output_encoding,))
376 sys.stderr.write('--- transformations: %s\n' % ' '.join(self.transformation_names))
cliechti6c8eb2f2009-07-08 02:10:46 +0000377
cliechti6385f2c2005-09-21 19:51:19 +0000378 def reader(self):
379 """loop and copy serial->console"""
cliechti6963b262010-01-02 03:01:21 +0000380 try:
cliechti8c2ea842011-03-18 01:51:46 +0000381 while self.alive and self._reader_alive:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200382 data = self.serial.read(1) + self.serial.read(self.serial.inWaiting())
383 if data:
384 if self.raw:
385 self.console.write_bytes(data)
cliechti6963b262010-01-02 03:01:21 +0000386 else:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200387 text = codecs.decode(
388 data,
389 self.input_encoding,
390 self.input_error_handling)
391 for transformation in self.transformations:
392 text = transformation.input(text)
393 self.console.write(text)
Chris Liechti68340d72015-08-03 14:15:48 +0200394 except serial.SerialException as e:
cliechti6963b262010-01-02 03:01:21 +0000395 self.alive = False
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200396 # XXX would be nice if the writer could be interrupted at this
397 # point... to exit completely
cliechti6963b262010-01-02 03:01:21 +0000398 raise
cliechti576de252002-02-28 23:54:44 +0000399
cliechti576de252002-02-28 23:54:44 +0000400
cliechti6385f2c2005-09-21 19:51:19 +0000401 def writer(self):
cliechti8c2ea842011-03-18 01:51:46 +0000402 """\
403 Loop and copy console->serial until EXITCHARCTER character is
404 found. When MENUCHARACTER is found, interpret the next key
405 locally.
cliechti6c8eb2f2009-07-08 02:10:46 +0000406 """
407 menu_active = False
408 try:
409 while self.alive:
410 try:
Chris Liechti89eb2472015-08-08 17:06:25 +0200411 c = self.console.getkey()
cliechti6c8eb2f2009-07-08 02:10:46 +0000412 except KeyboardInterrupt:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200413 c = '\x03'
cliechti6c8eb2f2009-07-08 02:10:46 +0000414 if menu_active:
Chris Liechti7af7c752015-08-12 15:45:19 +0200415 self.handle_menu_key(c)
cliechti6c8eb2f2009-07-08 02:10:46 +0000416 menu_active = False
Chris Liechti7af7c752015-08-12 15:45:19 +0200417 elif c == MENUCHARACTER:
418 menu_active = True # next char will be for menu
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200419 elif c == EXITCHARCTER:
Chris Liechti7af7c752015-08-12 15:45:19 +0200420 self.stop() # exit app
421 break
cliechti6c8eb2f2009-07-08 02:10:46 +0000422 else:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200423 #~ if self.raw:
424 text = c
425 echo_text = text
426 for transformation in self.transformations:
427 text = transformation.output(text)
428 echo_text = transformation.echo(echo_text)
429 b = codecs.encode(
430 text,
431 self.output_encoding,
432 self.output_error_handling)
433 self.serial.write(b)
cliechti6c8eb2f2009-07-08 02:10:46 +0000434 if self.echo:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200435 self.console.write(echo_text)
cliechti6c8eb2f2009-07-08 02:10:46 +0000436 except:
437 self.alive = False
438 raise
cliechti6385f2c2005-09-21 19:51:19 +0000439
Chris Liechti7af7c752015-08-12 15:45:19 +0200440 def handle_menu_key(self, c):
441 """Implement a simple menu / settings"""
442 if c == MENUCHARACTER or c == EXITCHARCTER: # Menu character again/exit char -> send itself
443 b = codecs.encode(
444 c,
445 self.output_encoding,
446 self.output_error_handling)
447 self.serial.write(b)
448 if self.echo:
449 self.console.write(c)
450 elif c == b'\x15': # CTRL+U -> upload file
451 sys.stderr.write('\n--- File to upload: ')
452 sys.stderr.flush()
453 self.console.cleanup()
454 filename = sys.stdin.readline().rstrip('\r\n')
455 if filename:
456 try:
457 with open(filename, 'rb') as f:
458 sys.stderr.write('--- Sending file %s ---\n' % filename)
459 while True:
460 block = f.read(1024)
461 if not block:
462 break
463 self.serial.write(block)
464 # Wait for output buffer to drain.
465 self.serial.flush()
466 sys.stderr.write('.') # Progress indicator.
467 sys.stderr.write('\n--- File %s sent ---\n' % filename)
468 except IOError as e:
469 sys.stderr.write('--- ERROR opening file %s: %s ---\n' % (filename, e))
470 self.console.setup()
471 elif c in '\x08hH?': # CTRL+H, h, H, ? -> Show help
472 sys.stderr.write(get_help_text())
473 elif c == '\x12': # CTRL+R -> Toggle RTS
474 self.rts_state = not self.rts_state
475 self.serial.setRTS(self.rts_state)
476 sys.stderr.write('--- RTS %s ---\n' % (self.rts_state and 'active' or 'inactive'))
477 elif c == '\x04': # CTRL+D -> Toggle DTR
478 self.dtr_state = not self.dtr_state
479 self.serial.setDTR(self.dtr_state)
480 sys.stderr.write('--- DTR %s ---\n' % (self.dtr_state and 'active' or 'inactive'))
481 elif c == '\x02': # CTRL+B -> toggle BREAK condition
482 self.break_state = not self.break_state
483 self.serial.setBreak(self.break_state)
484 sys.stderr.write('--- BREAK %s ---\n' % (self.break_state and 'active' or 'inactive'))
485 elif c == '\x05': # CTRL+E -> toggle local echo
486 self.echo = not self.echo
487 sys.stderr.write('--- local echo %s ---\n' % (self.echo and 'active' or 'inactive'))
488 elif c == '\x09': # CTRL+I -> info
489 self.dump_port_settings()
490 #~ elif c == '\x01': # CTRL+A -> cycle escape mode
491 #~ elif c == '\x0c': # CTRL+L -> cycle linefeed mode
492 elif c in 'pP': # P -> change port
493 dump_port_list()
494 sys.stderr.write('--- Enter port name: ')
495 sys.stderr.flush()
496 self.console.cleanup()
497 try:
498 port = sys.stdin.readline().strip()
499 except KeyboardInterrupt:
500 port = None
501 self.console.setup()
502 if port and port != self.serial.port:
503 # reader thread needs to be shut down
504 self._stop_reader()
505 # save settings
506 settings = self.serial.getSettingsDict()
507 try:
508 new_serial = serial.serial_for_url(port, do_not_open=True)
509 # restore settings and open
510 new_serial.applySettingsDict(settings)
511 new_serial.open()
512 new_serial.setRTS(self.rts_state)
513 new_serial.setDTR(self.dtr_state)
514 new_serial.setBreak(self.break_state)
515 except Exception as e:
516 sys.stderr.write('--- ERROR opening new port: %s ---\n' % (e,))
517 new_serial.close()
518 else:
519 self.serial.close()
520 self.serial = new_serial
521 sys.stderr.write('--- Port changed to: %s ---\n' % (self.serial.port,))
522 # and restart the reader thread
523 self._start_reader()
524 elif c in 'bB': # B -> change baudrate
525 sys.stderr.write('\n--- Baudrate: ')
526 sys.stderr.flush()
527 self.console.cleanup()
528 backup = self.serial.baudrate
529 try:
530 self.serial.baudrate = int(sys.stdin.readline().strip())
531 except ValueError as e:
532 sys.stderr.write('--- ERROR setting baudrate: %s ---\n' % (e,))
533 self.serial.baudrate = backup
534 else:
535 self.dump_port_settings()
536 self.console.setup()
537 elif c == '8': # 8 -> change to 8 bits
538 self.serial.bytesize = serial.EIGHTBITS
539 self.dump_port_settings()
540 elif c == '7': # 7 -> change to 8 bits
541 self.serial.bytesize = serial.SEVENBITS
542 self.dump_port_settings()
543 elif c in 'eE': # E -> change to even parity
544 self.serial.parity = serial.PARITY_EVEN
545 self.dump_port_settings()
546 elif c in 'oO': # O -> change to odd parity
547 self.serial.parity = serial.PARITY_ODD
548 self.dump_port_settings()
549 elif c in 'mM': # M -> change to mark parity
550 self.serial.parity = serial.PARITY_MARK
551 self.dump_port_settings()
552 elif c in 'sS': # S -> change to space parity
553 self.serial.parity = serial.PARITY_SPACE
554 self.dump_port_settings()
555 elif c in 'nN': # N -> change to no parity
556 self.serial.parity = serial.PARITY_NONE
557 self.dump_port_settings()
558 elif c == '1': # 1 -> change to 1 stop bits
559 self.serial.stopbits = serial.STOPBITS_ONE
560 self.dump_port_settings()
561 elif c == '2': # 2 -> change to 2 stop bits
562 self.serial.stopbits = serial.STOPBITS_TWO
563 self.dump_port_settings()
564 elif c == '3': # 3 -> change to 1.5 stop bits
565 self.serial.stopbits = serial.STOPBITS_ONE_POINT_FIVE
566 self.dump_port_settings()
567 elif c in 'xX': # X -> change software flow control
568 self.serial.xonxoff = (c == 'X')
569 self.dump_port_settings()
570 elif c in 'rR': # R -> change hardware flow control
571 self.serial.rtscts = (c == 'R')
572 self.dump_port_settings()
573 else:
574 sys.stderr.write('--- unknown menu character %s --\n' % key_description(c))
575
576
577
cliechti6385f2c2005-09-21 19:51:19 +0000578def main():
579 import optparse
580
cliechti53edb472009-02-06 21:18:46 +0000581 parser = optparse.OptionParser(
582 usage = "%prog [options] [port [baudrate]]",
583 description = "Miniterm - A simple terminal program for the serial port."
584 )
cliechti6385f2c2005-09-21 19:51:19 +0000585
cliechti5370cee2013-10-13 03:08:19 +0000586 group = optparse.OptionGroup(parser, "Port settings")
587
588 group.add_option("-p", "--port",
cliechti53edb472009-02-06 21:18:46 +0000589 dest = "port",
cliechti91165532011-03-18 02:02:52 +0000590 help = "port, a number or a device name. (deprecated option, use parameter instead)",
cliechti096e1962012-02-20 01:52:38 +0000591 default = DEFAULT_PORT
cliechti53edb472009-02-06 21:18:46 +0000592 )
cliechti6385f2c2005-09-21 19:51:19 +0000593
cliechti5370cee2013-10-13 03:08:19 +0000594 group.add_option("-b", "--baud",
cliechti53edb472009-02-06 21:18:46 +0000595 dest = "baudrate",
596 action = "store",
597 type = 'int',
cliechti6fa76fb2009-07-08 23:53:39 +0000598 help = "set baud rate, default %default",
cliechti096e1962012-02-20 01:52:38 +0000599 default = DEFAULT_BAUDRATE
cliechti53edb472009-02-06 21:18:46 +0000600 )
601
cliechti5370cee2013-10-13 03:08:19 +0000602 group.add_option("--parity",
cliechti53edb472009-02-06 21:18:46 +0000603 dest = "parity",
604 action = "store",
cliechtie0af3972009-07-08 11:03:47 +0000605 help = "set parity, one of [N, E, O, S, M], default=N",
cliechti53edb472009-02-06 21:18:46 +0000606 default = 'N'
607 )
608
cliechti5370cee2013-10-13 03:08:19 +0000609 group.add_option("--rtscts",
cliechti53edb472009-02-06 21:18:46 +0000610 dest = "rtscts",
611 action = "store_true",
612 help = "enable RTS/CTS flow control (default off)",
613 default = False
614 )
615
cliechti5370cee2013-10-13 03:08:19 +0000616 group.add_option("--xonxoff",
cliechti53edb472009-02-06 21:18:46 +0000617 dest = "xonxoff",
618 action = "store_true",
619 help = "enable software flow control (default off)",
620 default = False
621 )
622
cliechti5370cee2013-10-13 03:08:19 +0000623 group.add_option("--rts",
624 dest = "rts_state",
625 action = "store",
626 type = 'int',
627 help = "set initial RTS line state (possible values: 0, 1)",
628 default = DEFAULT_RTS
629 )
630
631 group.add_option("--dtr",
632 dest = "dtr_state",
633 action = "store",
634 type = 'int',
635 help = "set initial DTR line state (possible values: 0, 1)",
636 default = DEFAULT_DTR
637 )
638
639 parser.add_option_group(group)
640
641 group = optparse.OptionGroup(parser, "Data handling")
642
643 group.add_option("-e", "--echo",
644 dest = "echo",
645 action = "store_true",
646 help = "enable local echo (default off)",
647 default = False
648 )
649
Chris Liechti2b1b3552015-08-12 15:35:33 +0200650 group.add_option("--encoding",
651 dest = "serial_port_encoding",
652 metavar="CODEC",
653 action = "store",
654 help = "Set the encoding for the serial port (default: %default)",
655 default = 'latin1'
656 )
657
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200658 group.add_option("-t", "--transformation",
659 dest = "transformations",
Chris Liechti2b1b3552015-08-12 15:35:33 +0200660 metavar="NAME",
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200661 action = "append",
662 help = "Add text transformation",
663 default = []
664 )
665
cliechti5370cee2013-10-13 03:08:19 +0000666 group.add_option("--cr",
cliechti53edb472009-02-06 21:18:46 +0000667 dest = "cr",
668 action = "store_true",
669 help = "do not send CR+LF, send CR only",
670 default = False
671 )
672
cliechti5370cee2013-10-13 03:08:19 +0000673 group.add_option("--lf",
cliechti53edb472009-02-06 21:18:46 +0000674 dest = "lf",
675 action = "store_true",
676 help = "do not send CR+LF, send LF only",
677 default = False
678 )
679
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200680 group.add_option("--raw",
681 dest = "raw",
682 action = "store_true",
683 help = "Do no apply any encodings/transformations",
684 default = False
cliechti53edb472009-02-06 21:18:46 +0000685 )
cliechti6385f2c2005-09-21 19:51:19 +0000686
cliechti5370cee2013-10-13 03:08:19 +0000687 parser.add_option_group(group)
cliechtib7d746d2006-03-28 22:44:30 +0000688
cliechti5370cee2013-10-13 03:08:19 +0000689 group = optparse.OptionGroup(parser, "Hotkeys")
cliechtibf6bb7d2006-03-30 00:28:18 +0000690
cliechti5370cee2013-10-13 03:08:19 +0000691 group.add_option("--exit-char",
cliechti53edb472009-02-06 21:18:46 +0000692 dest = "exit_char",
693 action = "store",
694 type = 'int',
695 help = "ASCII code of special character that is used to exit the application",
696 default = 0x1d
697 )
cliechti9c592b32008-06-16 22:00:14 +0000698
cliechti5370cee2013-10-13 03:08:19 +0000699 group.add_option("--menu-char",
cliechti6c8eb2f2009-07-08 02:10:46 +0000700 dest = "menu_char",
cliechti53edb472009-02-06 21:18:46 +0000701 action = "store",
702 type = 'int',
cliechtidfec0c82009-07-21 01:35:41 +0000703 help = "ASCII code of special character that is used to control miniterm (menu)",
cliechti6c8eb2f2009-07-08 02:10:46 +0000704 default = 0x14
cliechti53edb472009-02-06 21:18:46 +0000705 )
cliechti6385f2c2005-09-21 19:51:19 +0000706
cliechti5370cee2013-10-13 03:08:19 +0000707 parser.add_option_group(group)
708
709 group = optparse.OptionGroup(parser, "Diagnostics")
710
711 group.add_option("-q", "--quiet",
712 dest = "quiet",
713 action = "store_true",
714 help = "suppress non-error messages",
715 default = False
716 )
717
Chris Liechti91090912015-08-05 02:36:14 +0200718 group.add_option("", "--develop",
719 dest = "develop",
720 action = "store_true",
721 help = "show Python traceback on error",
722 default = False
723 )
724
cliechti5370cee2013-10-13 03:08:19 +0000725 parser.add_option_group(group)
726
727
cliechti6385f2c2005-09-21 19:51:19 +0000728 (options, args) = parser.parse_args()
729
cliechtie0af3972009-07-08 11:03:47 +0000730 options.parity = options.parity.upper()
731 if options.parity not in 'NEOSM':
732 parser.error("invalid parity")
733
cliechti9cf26222006-03-24 20:09:21 +0000734 if options.cr and options.lf:
cliechti53edb472009-02-06 21:18:46 +0000735 parser.error("only one of --cr or --lf can be specified")
736
cliechtic1ca0772009-08-05 12:34:04 +0000737 if options.menu_char == options.exit_char:
cliechti6c8eb2f2009-07-08 02:10:46 +0000738 parser.error('--exit-char can not be the same as --menu-char')
739
740 global EXITCHARCTER, MENUCHARACTER
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200741 EXITCHARCTER = chr(options.exit_char)
742 MENUCHARACTER = chr(options.menu_char)
cliechti9c592b32008-06-16 22:00:14 +0000743
cliechti9743e222006-04-04 21:48:56 +0000744 port = options.port
745 baudrate = options.baudrate
cliechti9cf26222006-03-24 20:09:21 +0000746 if args:
cliechti9743e222006-04-04 21:48:56 +0000747 if options.port is not None:
748 parser.error("no arguments are allowed, options only when --port is given")
749 port = args.pop(0)
750 if args:
751 try:
752 baudrate = int(args[0])
753 except ValueError:
cliechti53edb472009-02-06 21:18:46 +0000754 parser.error("baud rate must be a number, not %r" % args[0])
cliechti9743e222006-04-04 21:48:56 +0000755 args.pop(0)
756 if args:
757 parser.error("too many arguments")
758 else:
cliechti7d448562014-08-03 21:57:45 +0000759 # no port given on command line -> ask user now
cliechti1351dde2012-04-12 16:47:47 +0000760 if port is None:
761 dump_port_list()
762 port = raw_input('Enter port name:')
cliechti53edb472009-02-06 21:18:46 +0000763
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200764 if options.transformations:
765 if 'help' in options.transformations:
766 sys.stderr.write('Available Transformations:\n')
767 sys.stderr.write('\n'.join('{:<20} = {.__doc__}'.format(k,v) for k,v in sorted(TRANSFORMATIONS.items())))
768 sys.stderr.write('\n')
769 sys.exit(1)
770 transformations = options.transformations
771 else:
772 transformations = ['default']
773
cliechti9cf26222006-03-24 20:09:21 +0000774 if options.cr:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200775 transformations.append('cr')
cliechti9cf26222006-03-24 20:09:21 +0000776 elif options.lf:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200777 transformations.append('lf')
778 else:
779 transformations.append('crlf')
cliechti6385f2c2005-09-21 19:51:19 +0000780
781 try:
782 miniterm = Miniterm(
cliechti9743e222006-04-04 21:48:56 +0000783 port,
784 baudrate,
cliechti6385f2c2005-09-21 19:51:19 +0000785 options.parity,
786 rtscts=options.rtscts,
787 xonxoff=options.xonxoff,
788 echo=options.echo,
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200789 transformations=transformations,
cliechti6385f2c2005-09-21 19:51:19 +0000790 )
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200791 miniterm.raw = options.raw
Chris Liechti2b1b3552015-08-12 15:35:33 +0200792 miniterm.input_encoding = options.serial_port_encoding
793 miniterm.output_encoding = options.serial_port_encoding
Chris Liechti68340d72015-08-03 14:15:48 +0200794 except serial.SerialException as e:
cliechtieb4a14f2009-08-03 23:48:35 +0000795 sys.stderr.write("could not open port %r: %s\n" % (port, e))
Chris Liechti91090912015-08-05 02:36:14 +0200796 if options.develop:
797 raise
cliechti6385f2c2005-09-21 19:51:19 +0000798 sys.exit(1)
799
cliechtibf6bb7d2006-03-30 00:28:18 +0000800 if not options.quiet:
cliechti6fa76fb2009-07-08 23:53:39 +0000801 sys.stderr.write('--- Miniterm on %s: %d,%s,%s,%s ---\n' % (
cliechti9743e222006-04-04 21:48:56 +0000802 miniterm.serial.portstr,
803 miniterm.serial.baudrate,
804 miniterm.serial.bytesize,
805 miniterm.serial.parity,
806 miniterm.serial.stopbits,
807 ))
cliechti6c8eb2f2009-07-08 02:10:46 +0000808 sys.stderr.write('--- Quit: %s | Menu: %s | Help: %s followed by %s ---\n' % (
cliechti9c592b32008-06-16 22:00:14 +0000809 key_description(EXITCHARCTER),
cliechti6c8eb2f2009-07-08 02:10:46 +0000810 key_description(MENUCHARACTER),
811 key_description(MENUCHARACTER),
Chris Liechti89eb2472015-08-08 17:06:25 +0200812 key_description(b'\x08'),
cliechti9c592b32008-06-16 22:00:14 +0000813 ))
cliechti6fa76fb2009-07-08 23:53:39 +0000814
cliechtib7d746d2006-03-28 22:44:30 +0000815 if options.dtr_state is not None:
cliechtibf6bb7d2006-03-30 00:28:18 +0000816 if not options.quiet:
817 sys.stderr.write('--- forcing DTR %s\n' % (options.dtr_state and 'active' or 'inactive'))
cliechtib7d746d2006-03-28 22:44:30 +0000818 miniterm.serial.setDTR(options.dtr_state)
cliechti6c8eb2f2009-07-08 02:10:46 +0000819 miniterm.dtr_state = options.dtr_state
cliechtibf6bb7d2006-03-30 00:28:18 +0000820 if options.rts_state is not None:
821 if not options.quiet:
822 sys.stderr.write('--- forcing RTS %s\n' % (options.rts_state and 'active' or 'inactive'))
823 miniterm.serial.setRTS(options.rts_state)
cliechti6c8eb2f2009-07-08 02:10:46 +0000824 miniterm.rts_state = options.rts_state
cliechti53edb472009-02-06 21:18:46 +0000825
cliechti6385f2c2005-09-21 19:51:19 +0000826 miniterm.start()
cliechti258ab0a2011-03-21 23:03:45 +0000827 try:
828 miniterm.join(True)
829 except KeyboardInterrupt:
830 pass
cliechtibf6bb7d2006-03-30 00:28:18 +0000831 if not options.quiet:
832 sys.stderr.write("\n--- exit ---\n")
cliechti6385f2c2005-09-21 19:51:19 +0000833 miniterm.join()
cliechtibf6bb7d2006-03-30 00:28:18 +0000834
cliechti5370cee2013-10-13 03:08:19 +0000835# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
cliechti8b3ad392002-03-03 20:12:21 +0000836if __name__ == '__main__':
cliechti6385f2c2005-09-21 19:51:19 +0000837 main()