blob: 6ed4df090ac9dd01c25eb7313e98b82c8a50d71d [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 Liechtia1d5c6d2015-08-07 14:41:24 +020013import os
14import sys
15import threading
cliechti21e2c842012-02-21 16:40:27 +000016try:
17 from serial.tools.list_ports import comports
18except ImportError:
19 comports = None
cliechti576de252002-02-28 23:54:44 +000020
Chris Liechtia1d5c6d2015-08-07 14:41:24 +020021import serial
22
23
Chris Liechti68340d72015-08-03 14:15:48 +020024try:
25 raw_input
26except NameError:
27 raw_input = input # in python3 it's "raw"
28
Chris Liechti89eb2472015-08-08 17:06:25 +020029EXITCHARCTER = b'\x1d' # GS/CTRL+]
30MENUCHARACTER = b'\x14' # Menu: CTRL+T
cliechtia128a702004-07-21 22:13:31 +000031
cliechti096e1962012-02-20 01:52:38 +000032DEFAULT_PORT = None
33DEFAULT_BAUDRATE = 9600
34DEFAULT_RTS = None
35DEFAULT_DTR = None
36
cliechti6c8eb2f2009-07-08 02:10:46 +000037
38def key_description(character):
39 """generate a readable description for a key"""
40 ascii_code = ord(character)
41 if ascii_code < 32:
42 return 'Ctrl+%c' % (ord('@') + ascii_code)
43 else:
44 return repr(character)
45
cliechti91165532011-03-18 02:02:52 +000046
cliechti6c8eb2f2009-07-08 02:10:46 +000047# help text, starts with blank line! it's a function so that the current values
48# for the shortcut keys is used and not the value at program start
49def get_help_text():
50 return """
cliechti6963b262010-01-02 03:01:21 +000051--- pySerial (%(version)s) - miniterm - help
cliechti6fa76fb2009-07-08 23:53:39 +000052---
53--- %(exit)-8s Exit program
54--- %(menu)-8s Menu escape key, followed by:
55--- Menu keys:
cliechti258ab0a2011-03-21 23:03:45 +000056--- %(itself)-7s Send the menu character itself to remote
57--- %(exchar)-7s Send the exit character itself to remote
58--- %(info)-7s Show info
59--- %(upload)-7s Upload file (prompt will be shown)
cliechti6fa76fb2009-07-08 23:53:39 +000060--- Toggles:
cliechti258ab0a2011-03-21 23:03:45 +000061--- %(rts)-7s RTS %(echo)-7s local echo
62--- %(dtr)-7s DTR %(break)-7s BREAK
63--- %(lfm)-7s line feed %(repr)-7s Cycle repr mode
cliechti6fa76fb2009-07-08 23:53:39 +000064---
65--- Port settings (%(menu)s followed by the following):
cliechti258ab0a2011-03-21 23:03:45 +000066--- p change port
67--- 7 8 set data bits
68--- n e o s m change parity (None, Even, Odd, Space, Mark)
69--- 1 2 3 set stop bits (1, 2, 1.5)
70--- b change baud rate
71--- x X disable/enable software flow control
72--- r R disable/enable hardware flow control
cliechti6c8eb2f2009-07-08 02:10:46 +000073""" % {
cliechti8c2ea842011-03-18 01:51:46 +000074 'version': getattr(serial, 'VERSION', 'unknown version'),
cliechti6c8eb2f2009-07-08 02:10:46 +000075 'exit': key_description(EXITCHARCTER),
76 'menu': key_description(MENUCHARACTER),
Chris Liechti89eb2472015-08-08 17:06:25 +020077 'rts': key_description(b'\x12'),
78 'repr': key_description(b'\x01'),
79 'dtr': key_description(b'\x04'),
80 'lfm': key_description(b'\x0c'),
81 'break': key_description(b'\x02'),
82 'echo': key_description(b'\x05'),
83 'info': key_description(b'\x09'),
84 'upload': key_description(b'\x15'),
cliechti6fa76fb2009-07-08 23:53:39 +000085 'itself': key_description(MENUCHARACTER),
86 'exchar': key_description(EXITCHARCTER),
cliechti6c8eb2f2009-07-08 02:10:46 +000087}
88
cliechti393fa0e2011-08-22 00:53:36 +000089
Chris Liechti89eb2472015-08-08 17:06:25 +020090LF = b'\n'
91CR = b'\r'
92CRLF = b'\r\n'
cliechtif467aa82013-10-13 21:36:49 +000093
Chris Liechti89eb2472015-08-08 17:06:25 +020094X00 = b'\x00'
95X0E = b'\x0e'
cliechtif467aa82013-10-13 21:36:49 +000096
cliechti6c8eb2f2009-07-08 02:10:46 +000097# first choose a platform dependant way to read single characters from the console
cliechti9c592b32008-06-16 22:00:14 +000098global console
99
cliechtifc9eb382002-03-05 01:12:29 +0000100if os.name == 'nt':
cliechti576de252002-02-28 23:54:44 +0000101 import msvcrt
cliechti91165532011-03-18 02:02:52 +0000102 class Console(object):
cliechti9c592b32008-06-16 22:00:14 +0000103 def __init__(self):
Chris Liechti89eb2472015-08-08 17:06:25 +0200104 if sys.version_info >= (3, 0):
105 self.output = sys.stdout.buffer
106 else:
107 self.output = sys.stdout
cliechti576de252002-02-28 23:54:44 +0000108
cliechti9c592b32008-06-16 22:00:14 +0000109 def setup(self):
110 pass # Do nothing for 'nt'
111
112 def cleanup(self):
113 pass # Do nothing for 'nt'
114
cliechti3a8bf092008-09-17 11:26:53 +0000115 def getkey(self):
cliechti91165532011-03-18 02:02:52 +0000116 while True:
cliechti9c592b32008-06-16 22:00:14 +0000117 z = msvcrt.getch()
cliechtif467aa82013-10-13 21:36:49 +0000118 if z == X00 or z == X0E: # functions keys, ignore
cliechti9c592b32008-06-16 22:00:14 +0000119 msvcrt.getch()
120 else:
cliechtif467aa82013-10-13 21:36:49 +0000121 if z == CR:
122 return LF
cliechti9c592b32008-06-16 22:00:14 +0000123 return z
cliechti53edb472009-02-06 21:18:46 +0000124
Chris Liechti89eb2472015-08-08 17:06:25 +0200125 def write(self, s):
126 sys.output.write(s)
127 sys.output.flush()
cliechti53edb472009-02-06 21:18:46 +0000128
cliechti576de252002-02-28 23:54:44 +0000129elif os.name == 'posix':
Chris Liechtia1d5c6d2015-08-07 14:41:24 +0200130 import atexit
131 import termios
cliechti91165532011-03-18 02:02:52 +0000132 class Console(object):
cliechti9c592b32008-06-16 22:00:14 +0000133 def __init__(self):
134 self.fd = sys.stdin.fileno()
cliechti5370cee2013-10-13 03:08:19 +0000135 self.old = None
Chris Liechti89eb2472015-08-08 17:06:25 +0200136 if sys.version_info >= (3, 0):
137 self.output = sys.stdout.buffer
138 else:
139 self.output = sys.stdout
140 atexit.register(self.cleanup)
cliechti9c592b32008-06-16 22:00:14 +0000141
142 def setup(self):
143 self.old = termios.tcgetattr(self.fd)
144 new = termios.tcgetattr(self.fd)
145 new[3] = new[3] & ~termios.ICANON & ~termios.ECHO & ~termios.ISIG
146 new[6][termios.VMIN] = 1
147 new[6][termios.VTIME] = 0
148 termios.tcsetattr(self.fd, termios.TCSANOW, new)
cliechti53edb472009-02-06 21:18:46 +0000149
cliechti9c592b32008-06-16 22:00:14 +0000150 def getkey(self):
151 c = os.read(self.fd, 1)
152 return c
cliechti53edb472009-02-06 21:18:46 +0000153
cliechti9c592b32008-06-16 22:00:14 +0000154 def cleanup(self):
cliechti5370cee2013-10-13 03:08:19 +0000155 if self.old is not None:
156 termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old)
cliechti9c592b32008-06-16 22:00:14 +0000157
Chris Liechti89eb2472015-08-08 17:06:25 +0200158 def write(self, s):
159 self.output.write(s)
160 self.output.flush()
cliechti576de252002-02-28 23:54:44 +0000161
162else:
cliechti8c2ea842011-03-18 01:51:46 +0000163 raise NotImplementedError("Sorry no implementation for your platform (%s) available." % sys.platform)
cliechti576de252002-02-28 23:54:44 +0000164
cliechti6fa76fb2009-07-08 23:53:39 +0000165
cliechti1351dde2012-04-12 16:47:47 +0000166def dump_port_list():
167 if comports:
168 sys.stderr.write('\n--- Available ports:\n')
169 for port, desc, hwid in sorted(comports()):
170 #~ sys.stderr.write('--- %-20s %s [%s]\n' % (port, desc, hwid))
171 sys.stderr.write('--- %-20s %s\n' % (port, desc))
172
173
cliechtia128a702004-07-21 22:13:31 +0000174CONVERT_CRLF = 2
175CONVERT_CR = 1
176CONVERT_LF = 0
cliechtif467aa82013-10-13 21:36:49 +0000177NEWLINE_CONVERISON_MAP = (LF, CR, CRLF)
cliechti6fa76fb2009-07-08 23:53:39 +0000178LF_MODES = ('LF', 'CR', 'CR/LF')
179
180REPR_MODES = ('raw', 'some control', 'all control', 'hex')
cliechti576de252002-02-28 23:54:44 +0000181
cliechti8c2ea842011-03-18 01:51:46 +0000182class Miniterm(object):
cliechti9743e222006-04-04 21:48:56 +0000183 def __init__(self, port, baudrate, parity, rtscts, xonxoff, echo=False, convert_outgoing=CONVERT_CRLF, repr_mode=0):
Chris Liechti89eb2472015-08-08 17:06:25 +0200184 self.console = Console()
Chris Liechtia1d5c6d2015-08-07 14:41:24 +0200185 self.serial = serial.serial_for_url(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1)
cliechti6385f2c2005-09-21 19:51:19 +0000186 self.echo = echo
187 self.repr_mode = repr_mode
188 self.convert_outgoing = convert_outgoing
cliechtibf6bb7d2006-03-30 00:28:18 +0000189 self.newline = NEWLINE_CONVERISON_MAP[self.convert_outgoing]
cliechti6c8eb2f2009-07-08 02:10:46 +0000190 self.dtr_state = True
191 self.rts_state = True
192 self.break_state = False
cliechti576de252002-02-28 23:54:44 +0000193
cliechti8c2ea842011-03-18 01:51:46 +0000194 def _start_reader(self):
195 """Start reader thread"""
196 self._reader_alive = True
cliechti6fa76fb2009-07-08 23:53:39 +0000197 # start serial->console thread
cliechti6385f2c2005-09-21 19:51:19 +0000198 self.receiver_thread = threading.Thread(target=self.reader)
cliechti8c2ea842011-03-18 01:51:46 +0000199 self.receiver_thread.setDaemon(True)
cliechti6385f2c2005-09-21 19:51:19 +0000200 self.receiver_thread.start()
cliechti8c2ea842011-03-18 01:51:46 +0000201
202 def _stop_reader(self):
203 """Stop reader thread only, wait for clean exit of thread"""
204 self._reader_alive = False
205 self.receiver_thread.join()
206
207
208 def start(self):
209 self.alive = True
210 self._start_reader()
cliechti6fa76fb2009-07-08 23:53:39 +0000211 # enter console->serial loop
cliechti6385f2c2005-09-21 19:51:19 +0000212 self.transmitter_thread = threading.Thread(target=self.writer)
cliechti8c2ea842011-03-18 01:51:46 +0000213 self.transmitter_thread.setDaemon(True)
cliechti6385f2c2005-09-21 19:51:19 +0000214 self.transmitter_thread.start()
Chris Liechti89eb2472015-08-08 17:06:25 +0200215 self.console.setup()
cliechti53edb472009-02-06 21:18:46 +0000216
cliechti6385f2c2005-09-21 19:51:19 +0000217 def stop(self):
218 self.alive = False
cliechti53edb472009-02-06 21:18:46 +0000219
cliechtibf6bb7d2006-03-30 00:28:18 +0000220 def join(self, transmit_only=False):
cliechti6385f2c2005-09-21 19:51:19 +0000221 self.transmitter_thread.join()
cliechtibf6bb7d2006-03-30 00:28:18 +0000222 if not transmit_only:
223 self.receiver_thread.join()
cliechti6385f2c2005-09-21 19:51:19 +0000224
cliechti6c8eb2f2009-07-08 02:10:46 +0000225 def dump_port_settings(self):
cliechti6fa76fb2009-07-08 23:53:39 +0000226 sys.stderr.write("\n--- Settings: %s %s,%s,%s,%s\n" % (
cliechti258ab0a2011-03-21 23:03:45 +0000227 self.serial.portstr,
228 self.serial.baudrate,
229 self.serial.bytesize,
230 self.serial.parity,
231 self.serial.stopbits))
232 sys.stderr.write('--- RTS: %-8s DTR: %-8s BREAK: %-8s\n' % (
233 (self.rts_state and 'active' or 'inactive'),
234 (self.dtr_state and 'active' or 'inactive'),
235 (self.break_state and 'active' or 'inactive')))
cliechti10114572009-08-05 23:40:50 +0000236 try:
cliechti258ab0a2011-03-21 23:03:45 +0000237 sys.stderr.write('--- CTS: %-8s DSR: %-8s RI: %-8s CD: %-8s\n' % (
238 (self.serial.getCTS() and 'active' or 'inactive'),
239 (self.serial.getDSR() and 'active' or 'inactive'),
240 (self.serial.getRI() and 'active' or 'inactive'),
241 (self.serial.getCD() and 'active' or 'inactive')))
cliechti10114572009-08-05 23:40:50 +0000242 except serial.SerialException:
243 # on RFC 2217 ports it can happen to no modem state notification was
244 # yet received. ignore this error.
245 pass
cliechti258ab0a2011-03-21 23:03:45 +0000246 sys.stderr.write('--- software flow control: %s\n' % (self.serial.xonxoff and 'active' or 'inactive'))
247 sys.stderr.write('--- hardware flow control: %s\n' % (self.serial.rtscts and 'active' or 'inactive'))
248 sys.stderr.write('--- data escaping: %s linefeed: %s\n' % (
249 REPR_MODES[self.repr_mode],
250 LF_MODES[self.convert_outgoing]))
cliechti6c8eb2f2009-07-08 02:10:46 +0000251
cliechti6385f2c2005-09-21 19:51:19 +0000252 def reader(self):
253 """loop and copy serial->console"""
cliechti6963b262010-01-02 03:01:21 +0000254 try:
cliechti8c2ea842011-03-18 01:51:46 +0000255 while self.alive and self._reader_alive:
Chris Liechti89eb2472015-08-08 17:06:25 +0200256 data = self.serial.read(1)
cliechti53edb472009-02-06 21:18:46 +0000257
cliechti6963b262010-01-02 03:01:21 +0000258 if self.repr_mode == 0:
259 # direct output, just have to care about newline setting
Chris Liechti89eb2472015-08-08 17:06:25 +0200260 if data == b'\r' and self.convert_outgoing == CONVERT_CR:
261 self.console.write(b'\n')
cliechti6963b262010-01-02 03:01:21 +0000262 else:
Chris Liechti89eb2472015-08-08 17:06:25 +0200263 self.console.write(data)
cliechti6963b262010-01-02 03:01:21 +0000264 elif self.repr_mode == 1:
265 # escape non-printable, let pass newlines
266 if self.convert_outgoing == CONVERT_CRLF and data in '\r\n':
Chris Liechti89eb2472015-08-08 17:06:25 +0200267 if data == b'\n':
268 self.console.write(b'\n')
269 elif data == b'\r':
cliechti6963b262010-01-02 03:01:21 +0000270 pass
Chris Liechti89eb2472015-08-08 17:06:25 +0200271 elif data == b'\n' and self.convert_outgoing == CONVERT_LF:
272 self.console.write(b'\n')
273 elif data == b'\r' and self.convert_outgoing == CONVERT_CR:
274 self.console.write(b'\n')
cliechti6963b262010-01-02 03:01:21 +0000275 else:
Chris Liechti89eb2472015-08-08 17:06:25 +0200276 self.console.write(repr(data)[1:-1])
cliechti6963b262010-01-02 03:01:21 +0000277 elif self.repr_mode == 2:
278 # escape all non-printable, including newline
Chris Liechti89eb2472015-08-08 17:06:25 +0200279 self.console.write(repr(data)[1:-1])
cliechti6963b262010-01-02 03:01:21 +0000280 elif self.repr_mode == 3:
281 # escape everything (hexdump)
cliechti393fa0e2011-08-22 00:53:36 +0000282 for c in data:
Chris Liechti89eb2472015-08-08 17:06:25 +0200283 self.console.write(b"%s " % c.encode('hex'))
Chris Liechti68340d72015-08-03 14:15:48 +0200284 except serial.SerialException as e:
cliechti6963b262010-01-02 03:01:21 +0000285 self.alive = False
286 # would be nice if the console reader could be interruptted at this
287 # point...
288 raise
cliechti576de252002-02-28 23:54:44 +0000289
cliechti576de252002-02-28 23:54:44 +0000290
cliechti6385f2c2005-09-21 19:51:19 +0000291 def writer(self):
cliechti8c2ea842011-03-18 01:51:46 +0000292 """\
293 Loop and copy console->serial until EXITCHARCTER character is
294 found. When MENUCHARACTER is found, interpret the next key
295 locally.
cliechti6c8eb2f2009-07-08 02:10:46 +0000296 """
297 menu_active = False
298 try:
299 while self.alive:
300 try:
Chris Liechti89eb2472015-08-08 17:06:25 +0200301 c = self.console.getkey()
cliechti6c8eb2f2009-07-08 02:10:46 +0000302 except KeyboardInterrupt:
Chris Liechti89eb2472015-08-08 17:06:25 +0200303 c = b'\x03'
cliechti6c8eb2f2009-07-08 02:10:46 +0000304 if menu_active:
305 if c == MENUCHARACTER or c == EXITCHARCTER: # Menu character again/exit char -> send itself
cliechti393fa0e2011-08-22 00:53:36 +0000306 self.serial.write(b) # send character
cliechti6c8eb2f2009-07-08 02:10:46 +0000307 if self.echo:
Chris Liechti89eb2472015-08-08 17:06:25 +0200308 self.console.write(c)
309 elif c == b'\x15': # CTRL+U -> upload file
cliechti6fa76fb2009-07-08 23:53:39 +0000310 sys.stderr.write('\n--- File to upload: ')
cliechti6c8eb2f2009-07-08 02:10:46 +0000311 sys.stderr.flush()
Chris Liechti89eb2472015-08-08 17:06:25 +0200312 self.console.cleanup()
cliechti6c8eb2f2009-07-08 02:10:46 +0000313 filename = sys.stdin.readline().rstrip('\r\n')
314 if filename:
315 try:
Chris Liechti89eb2472015-08-08 17:06:25 +0200316 with open(filename, 'rb') as f:
317 sys.stderr.write('--- Sending file %s ---\n' % filename)
318 while True:
319 block = f.read(1024)
320 if not block:
321 break
322 self.serial.write(block)
323 # Wait for output buffer to drain.
324 self.serial.flush()
325 sys.stderr.write('.') # Progress indicator.
cliechti6fa76fb2009-07-08 23:53:39 +0000326 sys.stderr.write('\n--- File %s sent ---\n' % filename)
Chris Liechti68340d72015-08-03 14:15:48 +0200327 except IOError as e:
cliechti6fa76fb2009-07-08 23:53:39 +0000328 sys.stderr.write('--- ERROR opening file %s: %s ---\n' % (filename, e))
Chris Liechti89eb2472015-08-08 17:06:25 +0200329 self.console.setup()
330 elif c in b'\x08hH?': # CTRL+H, h, H, ? -> Show help
cliechti6c8eb2f2009-07-08 02:10:46 +0000331 sys.stderr.write(get_help_text())
Chris Liechti89eb2472015-08-08 17:06:25 +0200332 elif c == b'\x12': # CTRL+R -> Toggle RTS
cliechti6c8eb2f2009-07-08 02:10:46 +0000333 self.rts_state = not self.rts_state
334 self.serial.setRTS(self.rts_state)
cliechti6fa76fb2009-07-08 23:53:39 +0000335 sys.stderr.write('--- RTS %s ---\n' % (self.rts_state and 'active' or 'inactive'))
Chris Liechti89eb2472015-08-08 17:06:25 +0200336 elif c == b'\x04': # CTRL+D -> Toggle DTR
cliechti6c8eb2f2009-07-08 02:10:46 +0000337 self.dtr_state = not self.dtr_state
338 self.serial.setDTR(self.dtr_state)
cliechti6fa76fb2009-07-08 23:53:39 +0000339 sys.stderr.write('--- DTR %s ---\n' % (self.dtr_state and 'active' or 'inactive'))
Chris Liechti89eb2472015-08-08 17:06:25 +0200340 elif c == b'\x02': # CTRL+B -> toggle BREAK condition
cliechti6c8eb2f2009-07-08 02:10:46 +0000341 self.break_state = not self.break_state
342 self.serial.setBreak(self.break_state)
cliechti6fa76fb2009-07-08 23:53:39 +0000343 sys.stderr.write('--- BREAK %s ---\n' % (self.break_state and 'active' or 'inactive'))
Chris Liechti89eb2472015-08-08 17:06:25 +0200344 elif c == b'\x05': # CTRL+E -> toggle local echo
cliechtie0af3972009-07-08 11:03:47 +0000345 self.echo = not self.echo
cliechti6fa76fb2009-07-08 23:53:39 +0000346 sys.stderr.write('--- local echo %s ---\n' % (self.echo and 'active' or 'inactive'))
Chris Liechti89eb2472015-08-08 17:06:25 +0200347 elif c == b'\x09': # CTRL+I -> info
cliechti6c8eb2f2009-07-08 02:10:46 +0000348 self.dump_port_settings()
Chris Liechti89eb2472015-08-08 17:06:25 +0200349 elif c == b'\x01': # CTRL+A -> cycle escape mode
cliechti6fa76fb2009-07-08 23:53:39 +0000350 self.repr_mode += 1
351 if self.repr_mode > 3:
352 self.repr_mode = 0
353 sys.stderr.write('--- escape data: %s ---\n' % (
354 REPR_MODES[self.repr_mode],
355 ))
Chris Liechti89eb2472015-08-08 17:06:25 +0200356 elif c == b'\x0c': # CTRL+L -> cycle linefeed mode
cliechti6fa76fb2009-07-08 23:53:39 +0000357 self.convert_outgoing += 1
358 if self.convert_outgoing > 2:
359 self.convert_outgoing = 0
360 self.newline = NEWLINE_CONVERISON_MAP[self.convert_outgoing]
361 sys.stderr.write('--- line feed %s ---\n' % (
362 LF_MODES[self.convert_outgoing],
363 ))
Chris Liechti89eb2472015-08-08 17:06:25 +0200364 elif c in b'pP': # P -> change port
cliechti1351dde2012-04-12 16:47:47 +0000365 dump_port_list()
cliechti21e2c842012-02-21 16:40:27 +0000366 sys.stderr.write('--- Enter port name: ')
cliechti8c2ea842011-03-18 01:51:46 +0000367 sys.stderr.flush()
Chris Liechti89eb2472015-08-08 17:06:25 +0200368 self.console.cleanup()
cliechti258ab0a2011-03-21 23:03:45 +0000369 try:
370 port = sys.stdin.readline().strip()
371 except KeyboardInterrupt:
372 port = None
Chris Liechti89eb2472015-08-08 17:06:25 +0200373 self.console.setup()
cliechti258ab0a2011-03-21 23:03:45 +0000374 if port and port != self.serial.port:
cliechti8c2ea842011-03-18 01:51:46 +0000375 # reader thread needs to be shut down
376 self._stop_reader()
377 # save settings
378 settings = self.serial.getSettingsDict()
cliechti8c2ea842011-03-18 01:51:46 +0000379 try:
cliechti258ab0a2011-03-21 23:03:45 +0000380 try:
381 new_serial = serial.serial_for_url(port, do_not_open=True)
382 except AttributeError:
383 # happens when the installed pyserial is older than 2.5. use the
384 # Serial class directly then.
385 new_serial = serial.Serial()
386 new_serial.port = port
387 # restore settings and open
388 new_serial.applySettingsDict(settings)
389 new_serial.open()
390 new_serial.setRTS(self.rts_state)
391 new_serial.setDTR(self.dtr_state)
392 new_serial.setBreak(self.break_state)
Chris Liechti68340d72015-08-03 14:15:48 +0200393 except Exception as e:
cliechti258ab0a2011-03-21 23:03:45 +0000394 sys.stderr.write('--- ERROR opening new port: %s ---\n' % (e,))
395 new_serial.close()
396 else:
397 self.serial.close()
398 self.serial = new_serial
399 sys.stderr.write('--- Port changed to: %s ---\n' % (self.serial.port,))
cliechti91165532011-03-18 02:02:52 +0000400 # and restart the reader thread
cliechti8c2ea842011-03-18 01:51:46 +0000401 self._start_reader()
Chris Liechti89eb2472015-08-08 17:06:25 +0200402 elif c in b'bB': # B -> change baudrate
cliechti6fa76fb2009-07-08 23:53:39 +0000403 sys.stderr.write('\n--- Baudrate: ')
cliechti6c8eb2f2009-07-08 02:10:46 +0000404 sys.stderr.flush()
Chris Liechti89eb2472015-08-08 17:06:25 +0200405 self.console.cleanup()
cliechti6c8eb2f2009-07-08 02:10:46 +0000406 backup = self.serial.baudrate
407 try:
408 self.serial.baudrate = int(sys.stdin.readline().strip())
Chris Liechti68340d72015-08-03 14:15:48 +0200409 except ValueError as e:
cliechti6fa76fb2009-07-08 23:53:39 +0000410 sys.stderr.write('--- ERROR setting baudrate: %s ---\n' % (e,))
cliechti6c8eb2f2009-07-08 02:10:46 +0000411 self.serial.baudrate = backup
cliechti6fa76fb2009-07-08 23:53:39 +0000412 else:
413 self.dump_port_settings()
Chris Liechti89eb2472015-08-08 17:06:25 +0200414 self.console.setup()
415 elif c == b'8': # 8 -> change to 8 bits
cliechti6c8eb2f2009-07-08 02:10:46 +0000416 self.serial.bytesize = serial.EIGHTBITS
417 self.dump_port_settings()
Chris Liechti89eb2472015-08-08 17:06:25 +0200418 elif c == b'7': # 7 -> change to 8 bits
cliechti6c8eb2f2009-07-08 02:10:46 +0000419 self.serial.bytesize = serial.SEVENBITS
420 self.dump_port_settings()
Chris Liechti89eb2472015-08-08 17:06:25 +0200421 elif c in b'eE': # E -> change to even parity
cliechti6c8eb2f2009-07-08 02:10:46 +0000422 self.serial.parity = serial.PARITY_EVEN
423 self.dump_port_settings()
Chris Liechti89eb2472015-08-08 17:06:25 +0200424 elif c in b'oO': # O -> change to odd parity
cliechti6c8eb2f2009-07-08 02:10:46 +0000425 self.serial.parity = serial.PARITY_ODD
426 self.dump_port_settings()
Chris Liechti89eb2472015-08-08 17:06:25 +0200427 elif c in b'mM': # M -> change to mark parity
cliechti6c8eb2f2009-07-08 02:10:46 +0000428 self.serial.parity = serial.PARITY_MARK
429 self.dump_port_settings()
Chris Liechti89eb2472015-08-08 17:06:25 +0200430 elif c in b'sS': # S -> change to space parity
cliechti6c8eb2f2009-07-08 02:10:46 +0000431 self.serial.parity = serial.PARITY_SPACE
432 self.dump_port_settings()
Chris Liechti89eb2472015-08-08 17:06:25 +0200433 elif c in b'nN': # N -> change to no parity
cliechti6c8eb2f2009-07-08 02:10:46 +0000434 self.serial.parity = serial.PARITY_NONE
435 self.dump_port_settings()
Chris Liechti89eb2472015-08-08 17:06:25 +0200436 elif c == b'1': # 1 -> change to 1 stop bits
cliechti6c8eb2f2009-07-08 02:10:46 +0000437 self.serial.stopbits = serial.STOPBITS_ONE
438 self.dump_port_settings()
Chris Liechti89eb2472015-08-08 17:06:25 +0200439 elif c == b'2': # 2 -> change to 2 stop bits
cliechti6c8eb2f2009-07-08 02:10:46 +0000440 self.serial.stopbits = serial.STOPBITS_TWO
441 self.dump_port_settings()
Chris Liechti89eb2472015-08-08 17:06:25 +0200442 elif c == b'3': # 3 -> change to 1.5 stop bits
cliechti6c8eb2f2009-07-08 02:10:46 +0000443 self.serial.stopbits = serial.STOPBITS_ONE_POINT_FIVE
444 self.dump_port_settings()
Chris Liechti89eb2472015-08-08 17:06:25 +0200445 elif c in b'xX': # X -> change software flow control
446 self.serial.xonxoff = (c == b'X')
cliechti6c8eb2f2009-07-08 02:10:46 +0000447 self.dump_port_settings()
Chris Liechti89eb2472015-08-08 17:06:25 +0200448 elif c in b'rR': # R -> change hardware flow control
449 self.serial.rtscts = (c == b'R')
cliechti6c8eb2f2009-07-08 02:10:46 +0000450 self.dump_port_settings()
451 else:
cliechti6fa76fb2009-07-08 23:53:39 +0000452 sys.stderr.write('--- unknown menu character %s --\n' % key_description(c))
cliechti6c8eb2f2009-07-08 02:10:46 +0000453 menu_active = False
454 elif c == MENUCHARACTER: # next char will be for menu
455 menu_active = True
456 elif c == EXITCHARCTER:
457 self.stop()
458 break # exit app
Chris Liechti89eb2472015-08-08 17:06:25 +0200459 elif c == b'\n':
cliechti6c8eb2f2009-07-08 02:10:46 +0000460 self.serial.write(self.newline) # send newline character(s)
461 if self.echo:
Chris Liechti89eb2472015-08-08 17:06:25 +0200462 sys.console.write(c) # local echo is a real newline in any case
cliechti6c8eb2f2009-07-08 02:10:46 +0000463 else:
Chris Liechtifc7ed922015-08-09 17:35:25 +0200464 self.serial.write(c) # send byte
cliechti6c8eb2f2009-07-08 02:10:46 +0000465 if self.echo:
Chris Liechti89eb2472015-08-08 17:06:25 +0200466 self.console.write(c)
cliechti6c8eb2f2009-07-08 02:10:46 +0000467 except:
468 self.alive = False
469 raise
cliechti6385f2c2005-09-21 19:51:19 +0000470
471def main():
472 import optparse
473
cliechti53edb472009-02-06 21:18:46 +0000474 parser = optparse.OptionParser(
475 usage = "%prog [options] [port [baudrate]]",
476 description = "Miniterm - A simple terminal program for the serial port."
477 )
cliechti6385f2c2005-09-21 19:51:19 +0000478
cliechti5370cee2013-10-13 03:08:19 +0000479 group = optparse.OptionGroup(parser, "Port settings")
480
481 group.add_option("-p", "--port",
cliechti53edb472009-02-06 21:18:46 +0000482 dest = "port",
cliechti91165532011-03-18 02:02:52 +0000483 help = "port, a number or a device name. (deprecated option, use parameter instead)",
cliechti096e1962012-02-20 01:52:38 +0000484 default = DEFAULT_PORT
cliechti53edb472009-02-06 21:18:46 +0000485 )
cliechti6385f2c2005-09-21 19:51:19 +0000486
cliechti5370cee2013-10-13 03:08:19 +0000487 group.add_option("-b", "--baud",
cliechti53edb472009-02-06 21:18:46 +0000488 dest = "baudrate",
489 action = "store",
490 type = 'int',
cliechti6fa76fb2009-07-08 23:53:39 +0000491 help = "set baud rate, default %default",
cliechti096e1962012-02-20 01:52:38 +0000492 default = DEFAULT_BAUDRATE
cliechti53edb472009-02-06 21:18:46 +0000493 )
494
cliechti5370cee2013-10-13 03:08:19 +0000495 group.add_option("--parity",
cliechti53edb472009-02-06 21:18:46 +0000496 dest = "parity",
497 action = "store",
cliechtie0af3972009-07-08 11:03:47 +0000498 help = "set parity, one of [N, E, O, S, M], default=N",
cliechti53edb472009-02-06 21:18:46 +0000499 default = 'N'
500 )
501
cliechti5370cee2013-10-13 03:08:19 +0000502 group.add_option("--rtscts",
cliechti53edb472009-02-06 21:18:46 +0000503 dest = "rtscts",
504 action = "store_true",
505 help = "enable RTS/CTS flow control (default off)",
506 default = False
507 )
508
cliechti5370cee2013-10-13 03:08:19 +0000509 group.add_option("--xonxoff",
cliechti53edb472009-02-06 21:18:46 +0000510 dest = "xonxoff",
511 action = "store_true",
512 help = "enable software flow control (default off)",
513 default = False
514 )
515
cliechti5370cee2013-10-13 03:08:19 +0000516 group.add_option("--rts",
517 dest = "rts_state",
518 action = "store",
519 type = 'int',
520 help = "set initial RTS line state (possible values: 0, 1)",
521 default = DEFAULT_RTS
522 )
523
524 group.add_option("--dtr",
525 dest = "dtr_state",
526 action = "store",
527 type = 'int',
528 help = "set initial DTR line state (possible values: 0, 1)",
529 default = DEFAULT_DTR
530 )
531
532 parser.add_option_group(group)
533
534 group = optparse.OptionGroup(parser, "Data handling")
535
536 group.add_option("-e", "--echo",
537 dest = "echo",
538 action = "store_true",
539 help = "enable local echo (default off)",
540 default = False
541 )
542
543 group.add_option("--cr",
cliechti53edb472009-02-06 21:18:46 +0000544 dest = "cr",
545 action = "store_true",
546 help = "do not send CR+LF, send CR only",
547 default = False
548 )
549
cliechti5370cee2013-10-13 03:08:19 +0000550 group.add_option("--lf",
cliechti53edb472009-02-06 21:18:46 +0000551 dest = "lf",
552 action = "store_true",
553 help = "do not send CR+LF, send LF only",
554 default = False
555 )
556
cliechti5370cee2013-10-13 03:08:19 +0000557 group.add_option("-D", "--debug",
cliechti53edb472009-02-06 21:18:46 +0000558 dest = "repr_mode",
559 action = "count",
560 help = """debug received data (escape non-printable chars)
cliechti9743e222006-04-04 21:48:56 +0000561--debug can be given multiple times:
5620: just print what is received
cliechti53edb472009-02-06 21:18:46 +00005631: escape non-printable characters, do newlines as unusual
cliechti9743e222006-04-04 21:48:56 +00005642: escape non-printable characters, newlines too
cliechti53edb472009-02-06 21:18:46 +00005653: hex dump everything""",
566 default = 0
567 )
cliechti6385f2c2005-09-21 19:51:19 +0000568
cliechti5370cee2013-10-13 03:08:19 +0000569 parser.add_option_group(group)
cliechtib7d746d2006-03-28 22:44:30 +0000570
cliechtib7d746d2006-03-28 22:44:30 +0000571
cliechti5370cee2013-10-13 03:08:19 +0000572 group = optparse.OptionGroup(parser, "Hotkeys")
cliechtibf6bb7d2006-03-30 00:28:18 +0000573
cliechti5370cee2013-10-13 03:08:19 +0000574 group.add_option("--exit-char",
cliechti53edb472009-02-06 21:18:46 +0000575 dest = "exit_char",
576 action = "store",
577 type = 'int',
578 help = "ASCII code of special character that is used to exit the application",
579 default = 0x1d
580 )
cliechti9c592b32008-06-16 22:00:14 +0000581
cliechti5370cee2013-10-13 03:08:19 +0000582 group.add_option("--menu-char",
cliechti6c8eb2f2009-07-08 02:10:46 +0000583 dest = "menu_char",
cliechti53edb472009-02-06 21:18:46 +0000584 action = "store",
585 type = 'int',
cliechtidfec0c82009-07-21 01:35:41 +0000586 help = "ASCII code of special character that is used to control miniterm (menu)",
cliechti6c8eb2f2009-07-08 02:10:46 +0000587 default = 0x14
cliechti53edb472009-02-06 21:18:46 +0000588 )
cliechti6385f2c2005-09-21 19:51:19 +0000589
cliechti5370cee2013-10-13 03:08:19 +0000590 parser.add_option_group(group)
591
592 group = optparse.OptionGroup(parser, "Diagnostics")
593
594 group.add_option("-q", "--quiet",
595 dest = "quiet",
596 action = "store_true",
597 help = "suppress non-error messages",
598 default = False
599 )
600
Chris Liechti91090912015-08-05 02:36:14 +0200601 group.add_option("", "--develop",
602 dest = "develop",
603 action = "store_true",
604 help = "show Python traceback on error",
605 default = False
606 )
607
608
609
cliechti5370cee2013-10-13 03:08:19 +0000610 parser.add_option_group(group)
611
612
cliechti6385f2c2005-09-21 19:51:19 +0000613 (options, args) = parser.parse_args()
614
cliechtie0af3972009-07-08 11:03:47 +0000615 options.parity = options.parity.upper()
616 if options.parity not in 'NEOSM':
617 parser.error("invalid parity")
618
cliechti9cf26222006-03-24 20:09:21 +0000619 if options.cr and options.lf:
cliechti53edb472009-02-06 21:18:46 +0000620 parser.error("only one of --cr or --lf can be specified")
621
cliechtic1ca0772009-08-05 12:34:04 +0000622 if options.menu_char == options.exit_char:
cliechti6c8eb2f2009-07-08 02:10:46 +0000623 parser.error('--exit-char can not be the same as --menu-char')
624
625 global EXITCHARCTER, MENUCHARACTER
Chris Liechti89eb2472015-08-08 17:06:25 +0200626 EXITCHARCTER = serial.to_bytes([options.exit_char])
627 MENUCHARACTER = serial.to_bytes([options.menu_char])
cliechti9c592b32008-06-16 22:00:14 +0000628
cliechti9743e222006-04-04 21:48:56 +0000629 port = options.port
630 baudrate = options.baudrate
cliechti9cf26222006-03-24 20:09:21 +0000631 if args:
cliechti9743e222006-04-04 21:48:56 +0000632 if options.port is not None:
633 parser.error("no arguments are allowed, options only when --port is given")
634 port = args.pop(0)
635 if args:
636 try:
637 baudrate = int(args[0])
638 except ValueError:
cliechti53edb472009-02-06 21:18:46 +0000639 parser.error("baud rate must be a number, not %r" % args[0])
cliechti9743e222006-04-04 21:48:56 +0000640 args.pop(0)
641 if args:
642 parser.error("too many arguments")
643 else:
cliechti7d448562014-08-03 21:57:45 +0000644 # no port given on command line -> ask user now
cliechti1351dde2012-04-12 16:47:47 +0000645 if port is None:
646 dump_port_list()
647 port = raw_input('Enter port name:')
cliechti53edb472009-02-06 21:18:46 +0000648
cliechti6385f2c2005-09-21 19:51:19 +0000649 convert_outgoing = CONVERT_CRLF
cliechti9cf26222006-03-24 20:09:21 +0000650 if options.cr:
cliechti6385f2c2005-09-21 19:51:19 +0000651 convert_outgoing = CONVERT_CR
cliechti9cf26222006-03-24 20:09:21 +0000652 elif options.lf:
cliechti6385f2c2005-09-21 19:51:19 +0000653 convert_outgoing = CONVERT_LF
654
655 try:
656 miniterm = Miniterm(
cliechti9743e222006-04-04 21:48:56 +0000657 port,
658 baudrate,
cliechti6385f2c2005-09-21 19:51:19 +0000659 options.parity,
660 rtscts=options.rtscts,
661 xonxoff=options.xonxoff,
662 echo=options.echo,
663 convert_outgoing=convert_outgoing,
664 repr_mode=options.repr_mode,
665 )
Chris Liechti68340d72015-08-03 14:15:48 +0200666 except serial.SerialException as e:
cliechtieb4a14f2009-08-03 23:48:35 +0000667 sys.stderr.write("could not open port %r: %s\n" % (port, e))
Chris Liechti91090912015-08-05 02:36:14 +0200668 if options.develop:
669 raise
cliechti6385f2c2005-09-21 19:51:19 +0000670 sys.exit(1)
671
cliechtibf6bb7d2006-03-30 00:28:18 +0000672 if not options.quiet:
cliechti6fa76fb2009-07-08 23:53:39 +0000673 sys.stderr.write('--- Miniterm on %s: %d,%s,%s,%s ---\n' % (
cliechti9743e222006-04-04 21:48:56 +0000674 miniterm.serial.portstr,
675 miniterm.serial.baudrate,
676 miniterm.serial.bytesize,
677 miniterm.serial.parity,
678 miniterm.serial.stopbits,
679 ))
cliechti6c8eb2f2009-07-08 02:10:46 +0000680 sys.stderr.write('--- Quit: %s | Menu: %s | Help: %s followed by %s ---\n' % (
cliechti9c592b32008-06-16 22:00:14 +0000681 key_description(EXITCHARCTER),
cliechti6c8eb2f2009-07-08 02:10:46 +0000682 key_description(MENUCHARACTER),
683 key_description(MENUCHARACTER),
Chris Liechti89eb2472015-08-08 17:06:25 +0200684 key_description(b'\x08'),
cliechti9c592b32008-06-16 22:00:14 +0000685 ))
cliechti6fa76fb2009-07-08 23:53:39 +0000686
cliechtib7d746d2006-03-28 22:44:30 +0000687 if options.dtr_state is not None:
cliechtibf6bb7d2006-03-30 00:28:18 +0000688 if not options.quiet:
689 sys.stderr.write('--- forcing DTR %s\n' % (options.dtr_state and 'active' or 'inactive'))
cliechtib7d746d2006-03-28 22:44:30 +0000690 miniterm.serial.setDTR(options.dtr_state)
cliechti6c8eb2f2009-07-08 02:10:46 +0000691 miniterm.dtr_state = options.dtr_state
cliechtibf6bb7d2006-03-30 00:28:18 +0000692 if options.rts_state is not None:
693 if not options.quiet:
694 sys.stderr.write('--- forcing RTS %s\n' % (options.rts_state and 'active' or 'inactive'))
695 miniterm.serial.setRTS(options.rts_state)
cliechti6c8eb2f2009-07-08 02:10:46 +0000696 miniterm.rts_state = options.rts_state
cliechti53edb472009-02-06 21:18:46 +0000697
cliechti6385f2c2005-09-21 19:51:19 +0000698 miniterm.start()
cliechti258ab0a2011-03-21 23:03:45 +0000699 try:
700 miniterm.join(True)
701 except KeyboardInterrupt:
702 pass
cliechtibf6bb7d2006-03-30 00:28:18 +0000703 if not options.quiet:
704 sys.stderr.write("\n--- exit ---\n")
cliechti6385f2c2005-09-21 19:51:19 +0000705 miniterm.join()
cliechti5370cee2013-10-13 03:08:19 +0000706 #~ console.cleanup()
cliechtibf6bb7d2006-03-30 00:28:18 +0000707
cliechti5370cee2013-10-13 03:08:19 +0000708# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
cliechti8b3ad392002-03-03 20:12:21 +0000709if __name__ == '__main__':
cliechti6385f2c2005-09-21 19:51:19 +0000710 main()