blob: 85cc75ab8eef2a3b234bc66538834b799f98ffa3 [file] [log] [blame]
cliechti576de252002-02-28 23:54:44 +00001#!/usr/bin/env python
cliechtia128a702004-07-21 22:13:31 +00002# Very simple serial terminal
Chris Liechti68340d72015-08-03 14:15:48 +02003# (C)2002-2015 Chris Liechti <cliechti@gmx.net>
cliechtifc9eb382002-03-05 01:12:29 +00004
cliechtia128a702004-07-21 22:13:31 +00005# Input characters are sent directly (only LF -> CR/LF/CRLF translation is
Chris Liechti89eb2472015-08-08 17:06:25 +02006# done), received characters are displayed as is (or escaped through pythons
cliechtia128a702004-07-21 22:13:31 +00007# repr, useful for debug purposes)
cliechti576de252002-02-28 23:54:44 +00008
Chris Liechtia1d5c6d2015-08-07 14:41:24 +02009import os
10import sys
11import threading
cliechti21e2c842012-02-21 16:40:27 +000012try:
13 from serial.tools.list_ports import comports
14except ImportError:
15 comports = None
cliechti576de252002-02-28 23:54:44 +000016
Chris Liechtia1d5c6d2015-08-07 14:41:24 +020017import serial
18
19
Chris Liechti68340d72015-08-03 14:15:48 +020020try:
21 raw_input
22except NameError:
23 raw_input = input # in python3 it's "raw"
24
Chris Liechti89eb2472015-08-08 17:06:25 +020025EXITCHARCTER = b'\x1d' # GS/CTRL+]
26MENUCHARACTER = b'\x14' # Menu: CTRL+T
cliechtia128a702004-07-21 22:13:31 +000027
cliechti096e1962012-02-20 01:52:38 +000028DEFAULT_PORT = None
29DEFAULT_BAUDRATE = 9600
30DEFAULT_RTS = None
31DEFAULT_DTR = None
32
cliechti6c8eb2f2009-07-08 02:10:46 +000033
34def key_description(character):
35 """generate a readable description for a key"""
36 ascii_code = ord(character)
37 if ascii_code < 32:
38 return 'Ctrl+%c' % (ord('@') + ascii_code)
39 else:
40 return repr(character)
41
cliechti91165532011-03-18 02:02:52 +000042
cliechti6c8eb2f2009-07-08 02:10:46 +000043# help text, starts with blank line! it's a function so that the current values
44# for the shortcut keys is used and not the value at program start
45def get_help_text():
46 return """
cliechti6963b262010-01-02 03:01:21 +000047--- pySerial (%(version)s) - miniterm - help
cliechti6fa76fb2009-07-08 23:53:39 +000048---
49--- %(exit)-8s Exit program
50--- %(menu)-8s Menu escape key, followed by:
51--- Menu keys:
cliechti258ab0a2011-03-21 23:03:45 +000052--- %(itself)-7s Send the menu character itself to remote
53--- %(exchar)-7s Send the exit character itself to remote
54--- %(info)-7s Show info
55--- %(upload)-7s Upload file (prompt will be shown)
cliechti6fa76fb2009-07-08 23:53:39 +000056--- Toggles:
cliechti258ab0a2011-03-21 23:03:45 +000057--- %(rts)-7s RTS %(echo)-7s local echo
58--- %(dtr)-7s DTR %(break)-7s BREAK
59--- %(lfm)-7s line feed %(repr)-7s Cycle repr mode
cliechti6fa76fb2009-07-08 23:53:39 +000060---
61--- Port settings (%(menu)s followed by the following):
cliechti258ab0a2011-03-21 23:03:45 +000062--- p change port
63--- 7 8 set data bits
64--- n e o s m change parity (None, Even, Odd, Space, Mark)
65--- 1 2 3 set stop bits (1, 2, 1.5)
66--- b change baud rate
67--- x X disable/enable software flow control
68--- r R disable/enable hardware flow control
cliechti6c8eb2f2009-07-08 02:10:46 +000069""" % {
cliechti8c2ea842011-03-18 01:51:46 +000070 'version': getattr(serial, 'VERSION', 'unknown version'),
cliechti6c8eb2f2009-07-08 02:10:46 +000071 'exit': key_description(EXITCHARCTER),
72 'menu': key_description(MENUCHARACTER),
Chris Liechti89eb2472015-08-08 17:06:25 +020073 'rts': key_description(b'\x12'),
74 'repr': key_description(b'\x01'),
75 'dtr': key_description(b'\x04'),
76 'lfm': key_description(b'\x0c'),
77 'break': key_description(b'\x02'),
78 'echo': key_description(b'\x05'),
79 'info': key_description(b'\x09'),
80 'upload': key_description(b'\x15'),
cliechti6fa76fb2009-07-08 23:53:39 +000081 'itself': key_description(MENUCHARACTER),
82 'exchar': key_description(EXITCHARCTER),
cliechti6c8eb2f2009-07-08 02:10:46 +000083}
84
cliechti393fa0e2011-08-22 00:53:36 +000085
Chris Liechti89eb2472015-08-08 17:06:25 +020086LF = b'\n'
87CR = b'\r'
88CRLF = b'\r\n'
cliechtif467aa82013-10-13 21:36:49 +000089
Chris Liechti89eb2472015-08-08 17:06:25 +020090X00 = b'\x00'
91X0E = b'\x0e'
cliechtif467aa82013-10-13 21:36:49 +000092
cliechti6c8eb2f2009-07-08 02:10:46 +000093# first choose a platform dependant way to read single characters from the console
cliechti9c592b32008-06-16 22:00:14 +000094global console
95
cliechtifc9eb382002-03-05 01:12:29 +000096if os.name == 'nt':
cliechti576de252002-02-28 23:54:44 +000097 import msvcrt
cliechti91165532011-03-18 02:02:52 +000098 class Console(object):
cliechti9c592b32008-06-16 22:00:14 +000099 def __init__(self):
Chris Liechti89eb2472015-08-08 17:06:25 +0200100 if sys.version_info >= (3, 0):
101 self.output = sys.stdout.buffer
102 else:
103 self.output = sys.stdout
cliechti576de252002-02-28 23:54:44 +0000104
cliechti9c592b32008-06-16 22:00:14 +0000105 def setup(self):
106 pass # Do nothing for 'nt'
107
108 def cleanup(self):
109 pass # Do nothing for 'nt'
110
cliechti3a8bf092008-09-17 11:26:53 +0000111 def getkey(self):
cliechti91165532011-03-18 02:02:52 +0000112 while True:
cliechti9c592b32008-06-16 22:00:14 +0000113 z = msvcrt.getch()
cliechtif467aa82013-10-13 21:36:49 +0000114 if z == X00 or z == X0E: # functions keys, ignore
cliechti9c592b32008-06-16 22:00:14 +0000115 msvcrt.getch()
116 else:
cliechtif467aa82013-10-13 21:36:49 +0000117 if z == CR:
118 return LF
cliechti9c592b32008-06-16 22:00:14 +0000119 return z
cliechti53edb472009-02-06 21:18:46 +0000120
Chris Liechti89eb2472015-08-08 17:06:25 +0200121 def write(self, s):
122 sys.output.write(s)
123 sys.output.flush()
cliechti53edb472009-02-06 21:18:46 +0000124
cliechti576de252002-02-28 23:54:44 +0000125elif os.name == 'posix':
Chris Liechtia1d5c6d2015-08-07 14:41:24 +0200126 import atexit
127 import termios
cliechti91165532011-03-18 02:02:52 +0000128 class Console(object):
cliechti9c592b32008-06-16 22:00:14 +0000129 def __init__(self):
130 self.fd = sys.stdin.fileno()
cliechti5370cee2013-10-13 03:08:19 +0000131 self.old = None
Chris Liechti89eb2472015-08-08 17:06:25 +0200132 if sys.version_info >= (3, 0):
133 self.output = sys.stdout.buffer
134 else:
135 self.output = sys.stdout
136 atexit.register(self.cleanup)
cliechti9c592b32008-06-16 22:00:14 +0000137
138 def setup(self):
139 self.old = termios.tcgetattr(self.fd)
140 new = termios.tcgetattr(self.fd)
141 new[3] = new[3] & ~termios.ICANON & ~termios.ECHO & ~termios.ISIG
142 new[6][termios.VMIN] = 1
143 new[6][termios.VTIME] = 0
144 termios.tcsetattr(self.fd, termios.TCSANOW, new)
cliechti53edb472009-02-06 21:18:46 +0000145
cliechti9c592b32008-06-16 22:00:14 +0000146 def getkey(self):
147 c = os.read(self.fd, 1)
148 return c
cliechti53edb472009-02-06 21:18:46 +0000149
cliechti9c592b32008-06-16 22:00:14 +0000150 def cleanup(self):
cliechti5370cee2013-10-13 03:08:19 +0000151 if self.old is not None:
152 termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old)
cliechti9c592b32008-06-16 22:00:14 +0000153
Chris Liechti89eb2472015-08-08 17:06:25 +0200154 def write(self, s):
155 self.output.write(s)
156 self.output.flush()
cliechti576de252002-02-28 23:54:44 +0000157
158else:
cliechti8c2ea842011-03-18 01:51:46 +0000159 raise NotImplementedError("Sorry no implementation for your platform (%s) available." % sys.platform)
cliechti576de252002-02-28 23:54:44 +0000160
cliechti6fa76fb2009-07-08 23:53:39 +0000161
cliechti1351dde2012-04-12 16:47:47 +0000162def dump_port_list():
163 if comports:
164 sys.stderr.write('\n--- Available ports:\n')
165 for port, desc, hwid in sorted(comports()):
166 #~ sys.stderr.write('--- %-20s %s [%s]\n' % (port, desc, hwid))
167 sys.stderr.write('--- %-20s %s\n' % (port, desc))
168
169
cliechtia128a702004-07-21 22:13:31 +0000170CONVERT_CRLF = 2
171CONVERT_CR = 1
172CONVERT_LF = 0
cliechtif467aa82013-10-13 21:36:49 +0000173NEWLINE_CONVERISON_MAP = (LF, CR, CRLF)
cliechti6fa76fb2009-07-08 23:53:39 +0000174LF_MODES = ('LF', 'CR', 'CR/LF')
175
176REPR_MODES = ('raw', 'some control', 'all control', 'hex')
cliechti576de252002-02-28 23:54:44 +0000177
cliechti8c2ea842011-03-18 01:51:46 +0000178class Miniterm(object):
cliechti9743e222006-04-04 21:48:56 +0000179 def __init__(self, port, baudrate, parity, rtscts, xonxoff, echo=False, convert_outgoing=CONVERT_CRLF, repr_mode=0):
Chris Liechti89eb2472015-08-08 17:06:25 +0200180 self.console = Console()
Chris Liechtia1d5c6d2015-08-07 14:41:24 +0200181 self.serial = serial.serial_for_url(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1)
cliechti6385f2c2005-09-21 19:51:19 +0000182 self.echo = echo
183 self.repr_mode = repr_mode
184 self.convert_outgoing = convert_outgoing
cliechtibf6bb7d2006-03-30 00:28:18 +0000185 self.newline = NEWLINE_CONVERISON_MAP[self.convert_outgoing]
cliechti6c8eb2f2009-07-08 02:10:46 +0000186 self.dtr_state = True
187 self.rts_state = True
188 self.break_state = False
cliechti576de252002-02-28 23:54:44 +0000189
cliechti8c2ea842011-03-18 01:51:46 +0000190 def _start_reader(self):
191 """Start reader thread"""
192 self._reader_alive = True
cliechti6fa76fb2009-07-08 23:53:39 +0000193 # start serial->console thread
cliechti6385f2c2005-09-21 19:51:19 +0000194 self.receiver_thread = threading.Thread(target=self.reader)
cliechti8c2ea842011-03-18 01:51:46 +0000195 self.receiver_thread.setDaemon(True)
cliechti6385f2c2005-09-21 19:51:19 +0000196 self.receiver_thread.start()
cliechti8c2ea842011-03-18 01:51:46 +0000197
198 def _stop_reader(self):
199 """Stop reader thread only, wait for clean exit of thread"""
200 self._reader_alive = False
201 self.receiver_thread.join()
202
203
204 def start(self):
205 self.alive = True
206 self._start_reader()
cliechti6fa76fb2009-07-08 23:53:39 +0000207 # enter console->serial loop
cliechti6385f2c2005-09-21 19:51:19 +0000208 self.transmitter_thread = threading.Thread(target=self.writer)
cliechti8c2ea842011-03-18 01:51:46 +0000209 self.transmitter_thread.setDaemon(True)
cliechti6385f2c2005-09-21 19:51:19 +0000210 self.transmitter_thread.start()
Chris Liechti89eb2472015-08-08 17:06:25 +0200211 self.console.setup()
cliechti53edb472009-02-06 21:18:46 +0000212
cliechti6385f2c2005-09-21 19:51:19 +0000213 def stop(self):
214 self.alive = False
cliechti53edb472009-02-06 21:18:46 +0000215
cliechtibf6bb7d2006-03-30 00:28:18 +0000216 def join(self, transmit_only=False):
cliechti6385f2c2005-09-21 19:51:19 +0000217 self.transmitter_thread.join()
cliechtibf6bb7d2006-03-30 00:28:18 +0000218 if not transmit_only:
219 self.receiver_thread.join()
cliechti6385f2c2005-09-21 19:51:19 +0000220
cliechti6c8eb2f2009-07-08 02:10:46 +0000221 def dump_port_settings(self):
cliechti6fa76fb2009-07-08 23:53:39 +0000222 sys.stderr.write("\n--- Settings: %s %s,%s,%s,%s\n" % (
cliechti258ab0a2011-03-21 23:03:45 +0000223 self.serial.portstr,
224 self.serial.baudrate,
225 self.serial.bytesize,
226 self.serial.parity,
227 self.serial.stopbits))
228 sys.stderr.write('--- RTS: %-8s DTR: %-8s BREAK: %-8s\n' % (
229 (self.rts_state and 'active' or 'inactive'),
230 (self.dtr_state and 'active' or 'inactive'),
231 (self.break_state and 'active' or 'inactive')))
cliechti10114572009-08-05 23:40:50 +0000232 try:
cliechti258ab0a2011-03-21 23:03:45 +0000233 sys.stderr.write('--- CTS: %-8s DSR: %-8s RI: %-8s CD: %-8s\n' % (
234 (self.serial.getCTS() and 'active' or 'inactive'),
235 (self.serial.getDSR() and 'active' or 'inactive'),
236 (self.serial.getRI() and 'active' or 'inactive'),
237 (self.serial.getCD() and 'active' or 'inactive')))
cliechti10114572009-08-05 23:40:50 +0000238 except serial.SerialException:
239 # on RFC 2217 ports it can happen to no modem state notification was
240 # yet received. ignore this error.
241 pass
cliechti258ab0a2011-03-21 23:03:45 +0000242 sys.stderr.write('--- software flow control: %s\n' % (self.serial.xonxoff and 'active' or 'inactive'))
243 sys.stderr.write('--- hardware flow control: %s\n' % (self.serial.rtscts and 'active' or 'inactive'))
244 sys.stderr.write('--- data escaping: %s linefeed: %s\n' % (
245 REPR_MODES[self.repr_mode],
246 LF_MODES[self.convert_outgoing]))
cliechti6c8eb2f2009-07-08 02:10:46 +0000247
cliechti6385f2c2005-09-21 19:51:19 +0000248 def reader(self):
249 """loop and copy serial->console"""
cliechti6963b262010-01-02 03:01:21 +0000250 try:
cliechti8c2ea842011-03-18 01:51:46 +0000251 while self.alive and self._reader_alive:
Chris Liechti89eb2472015-08-08 17:06:25 +0200252 data = self.serial.read(1)
cliechti53edb472009-02-06 21:18:46 +0000253
cliechti6963b262010-01-02 03:01:21 +0000254 if self.repr_mode == 0:
255 # direct output, just have to care about newline setting
Chris Liechti89eb2472015-08-08 17:06:25 +0200256 if data == b'\r' and self.convert_outgoing == CONVERT_CR:
257 self.console.write(b'\n')
cliechti6963b262010-01-02 03:01:21 +0000258 else:
Chris Liechti89eb2472015-08-08 17:06:25 +0200259 self.console.write(data)
cliechti6963b262010-01-02 03:01:21 +0000260 elif self.repr_mode == 1:
261 # escape non-printable, let pass newlines
262 if self.convert_outgoing == CONVERT_CRLF and data in '\r\n':
Chris Liechti89eb2472015-08-08 17:06:25 +0200263 if data == b'\n':
264 self.console.write(b'\n')
265 elif data == b'\r':
cliechti6963b262010-01-02 03:01:21 +0000266 pass
Chris Liechti89eb2472015-08-08 17:06:25 +0200267 elif data == b'\n' and self.convert_outgoing == CONVERT_LF:
268 self.console.write(b'\n')
269 elif data == b'\r' and self.convert_outgoing == CONVERT_CR:
270 self.console.write(b'\n')
cliechti6963b262010-01-02 03:01:21 +0000271 else:
Chris Liechti89eb2472015-08-08 17:06:25 +0200272 self.console.write(repr(data)[1:-1])
cliechti6963b262010-01-02 03:01:21 +0000273 elif self.repr_mode == 2:
274 # escape all non-printable, including newline
Chris Liechti89eb2472015-08-08 17:06:25 +0200275 self.console.write(repr(data)[1:-1])
cliechti6963b262010-01-02 03:01:21 +0000276 elif self.repr_mode == 3:
277 # escape everything (hexdump)
cliechti393fa0e2011-08-22 00:53:36 +0000278 for c in data:
Chris Liechti89eb2472015-08-08 17:06:25 +0200279 self.console.write(b"%s " % c.encode('hex'))
Chris Liechti68340d72015-08-03 14:15:48 +0200280 except serial.SerialException as e:
cliechti6963b262010-01-02 03:01:21 +0000281 self.alive = False
282 # would be nice if the console reader could be interruptted at this
283 # point...
284 raise
cliechti576de252002-02-28 23:54:44 +0000285
cliechti576de252002-02-28 23:54:44 +0000286
cliechti6385f2c2005-09-21 19:51:19 +0000287 def writer(self):
cliechti8c2ea842011-03-18 01:51:46 +0000288 """\
289 Loop and copy console->serial until EXITCHARCTER character is
290 found. When MENUCHARACTER is found, interpret the next key
291 locally.
cliechti6c8eb2f2009-07-08 02:10:46 +0000292 """
293 menu_active = False
294 try:
295 while self.alive:
296 try:
Chris Liechti89eb2472015-08-08 17:06:25 +0200297 c = self.console.getkey()
cliechti6c8eb2f2009-07-08 02:10:46 +0000298 except KeyboardInterrupt:
Chris Liechti89eb2472015-08-08 17:06:25 +0200299 c = b'\x03'
cliechti6c8eb2f2009-07-08 02:10:46 +0000300 if menu_active:
301 if c == MENUCHARACTER or c == EXITCHARCTER: # Menu character again/exit char -> send itself
cliechti393fa0e2011-08-22 00:53:36 +0000302 self.serial.write(b) # send character
cliechti6c8eb2f2009-07-08 02:10:46 +0000303 if self.echo:
Chris Liechti89eb2472015-08-08 17:06:25 +0200304 self.console.write(c)
305 elif c == b'\x15': # CTRL+U -> upload file
cliechti6fa76fb2009-07-08 23:53:39 +0000306 sys.stderr.write('\n--- File to upload: ')
cliechti6c8eb2f2009-07-08 02:10:46 +0000307 sys.stderr.flush()
Chris Liechti89eb2472015-08-08 17:06:25 +0200308 self.console.cleanup()
cliechti6c8eb2f2009-07-08 02:10:46 +0000309 filename = sys.stdin.readline().rstrip('\r\n')
310 if filename:
311 try:
Chris Liechti89eb2472015-08-08 17:06:25 +0200312 with open(filename, 'rb') as f:
313 sys.stderr.write('--- Sending file %s ---\n' % filename)
314 while True:
315 block = f.read(1024)
316 if not block:
317 break
318 self.serial.write(block)
319 # Wait for output buffer to drain.
320 self.serial.flush()
321 sys.stderr.write('.') # Progress indicator.
cliechti6fa76fb2009-07-08 23:53:39 +0000322 sys.stderr.write('\n--- File %s sent ---\n' % filename)
Chris Liechti68340d72015-08-03 14:15:48 +0200323 except IOError as e:
cliechti6fa76fb2009-07-08 23:53:39 +0000324 sys.stderr.write('--- ERROR opening file %s: %s ---\n' % (filename, e))
Chris Liechti89eb2472015-08-08 17:06:25 +0200325 self.console.setup()
326 elif c in b'\x08hH?': # CTRL+H, h, H, ? -> Show help
cliechti6c8eb2f2009-07-08 02:10:46 +0000327 sys.stderr.write(get_help_text())
Chris Liechti89eb2472015-08-08 17:06:25 +0200328 elif c == b'\x12': # CTRL+R -> Toggle RTS
cliechti6c8eb2f2009-07-08 02:10:46 +0000329 self.rts_state = not self.rts_state
330 self.serial.setRTS(self.rts_state)
cliechti6fa76fb2009-07-08 23:53:39 +0000331 sys.stderr.write('--- RTS %s ---\n' % (self.rts_state and 'active' or 'inactive'))
Chris Liechti89eb2472015-08-08 17:06:25 +0200332 elif c == b'\x04': # CTRL+D -> Toggle DTR
cliechti6c8eb2f2009-07-08 02:10:46 +0000333 self.dtr_state = not self.dtr_state
334 self.serial.setDTR(self.dtr_state)
cliechti6fa76fb2009-07-08 23:53:39 +0000335 sys.stderr.write('--- DTR %s ---\n' % (self.dtr_state and 'active' or 'inactive'))
Chris Liechti89eb2472015-08-08 17:06:25 +0200336 elif c == b'\x02': # CTRL+B -> toggle BREAK condition
cliechti6c8eb2f2009-07-08 02:10:46 +0000337 self.break_state = not self.break_state
338 self.serial.setBreak(self.break_state)
cliechti6fa76fb2009-07-08 23:53:39 +0000339 sys.stderr.write('--- BREAK %s ---\n' % (self.break_state and 'active' or 'inactive'))
Chris Liechti89eb2472015-08-08 17:06:25 +0200340 elif c == b'\x05': # CTRL+E -> toggle local echo
cliechtie0af3972009-07-08 11:03:47 +0000341 self.echo = not self.echo
cliechti6fa76fb2009-07-08 23:53:39 +0000342 sys.stderr.write('--- local echo %s ---\n' % (self.echo and 'active' or 'inactive'))
Chris Liechti89eb2472015-08-08 17:06:25 +0200343 elif c == b'\x09': # CTRL+I -> info
cliechti6c8eb2f2009-07-08 02:10:46 +0000344 self.dump_port_settings()
Chris Liechti89eb2472015-08-08 17:06:25 +0200345 elif c == b'\x01': # CTRL+A -> cycle escape mode
cliechti6fa76fb2009-07-08 23:53:39 +0000346 self.repr_mode += 1
347 if self.repr_mode > 3:
348 self.repr_mode = 0
349 sys.stderr.write('--- escape data: %s ---\n' % (
350 REPR_MODES[self.repr_mode],
351 ))
Chris Liechti89eb2472015-08-08 17:06:25 +0200352 elif c == b'\x0c': # CTRL+L -> cycle linefeed mode
cliechti6fa76fb2009-07-08 23:53:39 +0000353 self.convert_outgoing += 1
354 if self.convert_outgoing > 2:
355 self.convert_outgoing = 0
356 self.newline = NEWLINE_CONVERISON_MAP[self.convert_outgoing]
357 sys.stderr.write('--- line feed %s ---\n' % (
358 LF_MODES[self.convert_outgoing],
359 ))
Chris Liechti89eb2472015-08-08 17:06:25 +0200360 elif c in b'pP': # P -> change port
cliechti1351dde2012-04-12 16:47:47 +0000361 dump_port_list()
cliechti21e2c842012-02-21 16:40:27 +0000362 sys.stderr.write('--- Enter port name: ')
cliechti8c2ea842011-03-18 01:51:46 +0000363 sys.stderr.flush()
Chris Liechti89eb2472015-08-08 17:06:25 +0200364 self.console.cleanup()
cliechti258ab0a2011-03-21 23:03:45 +0000365 try:
366 port = sys.stdin.readline().strip()
367 except KeyboardInterrupt:
368 port = None
Chris Liechti89eb2472015-08-08 17:06:25 +0200369 self.console.setup()
cliechti258ab0a2011-03-21 23:03:45 +0000370 if port and port != self.serial.port:
cliechti8c2ea842011-03-18 01:51:46 +0000371 # reader thread needs to be shut down
372 self._stop_reader()
373 # save settings
374 settings = self.serial.getSettingsDict()
cliechti8c2ea842011-03-18 01:51:46 +0000375 try:
cliechti258ab0a2011-03-21 23:03:45 +0000376 try:
377 new_serial = serial.serial_for_url(port, do_not_open=True)
378 except AttributeError:
379 # happens when the installed pyserial is older than 2.5. use the
380 # Serial class directly then.
381 new_serial = serial.Serial()
382 new_serial.port = port
383 # restore settings and open
384 new_serial.applySettingsDict(settings)
385 new_serial.open()
386 new_serial.setRTS(self.rts_state)
387 new_serial.setDTR(self.dtr_state)
388 new_serial.setBreak(self.break_state)
Chris Liechti68340d72015-08-03 14:15:48 +0200389 except Exception as e:
cliechti258ab0a2011-03-21 23:03:45 +0000390 sys.stderr.write('--- ERROR opening new port: %s ---\n' % (e,))
391 new_serial.close()
392 else:
393 self.serial.close()
394 self.serial = new_serial
395 sys.stderr.write('--- Port changed to: %s ---\n' % (self.serial.port,))
cliechti91165532011-03-18 02:02:52 +0000396 # and restart the reader thread
cliechti8c2ea842011-03-18 01:51:46 +0000397 self._start_reader()
Chris Liechti89eb2472015-08-08 17:06:25 +0200398 elif c in b'bB': # B -> change baudrate
cliechti6fa76fb2009-07-08 23:53:39 +0000399 sys.stderr.write('\n--- Baudrate: ')
cliechti6c8eb2f2009-07-08 02:10:46 +0000400 sys.stderr.flush()
Chris Liechti89eb2472015-08-08 17:06:25 +0200401 self.console.cleanup()
cliechti6c8eb2f2009-07-08 02:10:46 +0000402 backup = self.serial.baudrate
403 try:
404 self.serial.baudrate = int(sys.stdin.readline().strip())
Chris Liechti68340d72015-08-03 14:15:48 +0200405 except ValueError as e:
cliechti6fa76fb2009-07-08 23:53:39 +0000406 sys.stderr.write('--- ERROR setting baudrate: %s ---\n' % (e,))
cliechti6c8eb2f2009-07-08 02:10:46 +0000407 self.serial.baudrate = backup
cliechti6fa76fb2009-07-08 23:53:39 +0000408 else:
409 self.dump_port_settings()
Chris Liechti89eb2472015-08-08 17:06:25 +0200410 self.console.setup()
411 elif c == b'8': # 8 -> change to 8 bits
cliechti6c8eb2f2009-07-08 02:10:46 +0000412 self.serial.bytesize = serial.EIGHTBITS
413 self.dump_port_settings()
Chris Liechti89eb2472015-08-08 17:06:25 +0200414 elif c == b'7': # 7 -> change to 8 bits
cliechti6c8eb2f2009-07-08 02:10:46 +0000415 self.serial.bytesize = serial.SEVENBITS
416 self.dump_port_settings()
Chris Liechti89eb2472015-08-08 17:06:25 +0200417 elif c in b'eE': # E -> change to even parity
cliechti6c8eb2f2009-07-08 02:10:46 +0000418 self.serial.parity = serial.PARITY_EVEN
419 self.dump_port_settings()
Chris Liechti89eb2472015-08-08 17:06:25 +0200420 elif c in b'oO': # O -> change to odd parity
cliechti6c8eb2f2009-07-08 02:10:46 +0000421 self.serial.parity = serial.PARITY_ODD
422 self.dump_port_settings()
Chris Liechti89eb2472015-08-08 17:06:25 +0200423 elif c in b'mM': # M -> change to mark parity
cliechti6c8eb2f2009-07-08 02:10:46 +0000424 self.serial.parity = serial.PARITY_MARK
425 self.dump_port_settings()
Chris Liechti89eb2472015-08-08 17:06:25 +0200426 elif c in b'sS': # S -> change to space parity
cliechti6c8eb2f2009-07-08 02:10:46 +0000427 self.serial.parity = serial.PARITY_SPACE
428 self.dump_port_settings()
Chris Liechti89eb2472015-08-08 17:06:25 +0200429 elif c in b'nN': # N -> change to no parity
cliechti6c8eb2f2009-07-08 02:10:46 +0000430 self.serial.parity = serial.PARITY_NONE
431 self.dump_port_settings()
Chris Liechti89eb2472015-08-08 17:06:25 +0200432 elif c == b'1': # 1 -> change to 1 stop bits
cliechti6c8eb2f2009-07-08 02:10:46 +0000433 self.serial.stopbits = serial.STOPBITS_ONE
434 self.dump_port_settings()
Chris Liechti89eb2472015-08-08 17:06:25 +0200435 elif c == b'2': # 2 -> change to 2 stop bits
cliechti6c8eb2f2009-07-08 02:10:46 +0000436 self.serial.stopbits = serial.STOPBITS_TWO
437 self.dump_port_settings()
Chris Liechti89eb2472015-08-08 17:06:25 +0200438 elif c == b'3': # 3 -> change to 1.5 stop bits
cliechti6c8eb2f2009-07-08 02:10:46 +0000439 self.serial.stopbits = serial.STOPBITS_ONE_POINT_FIVE
440 self.dump_port_settings()
Chris Liechti89eb2472015-08-08 17:06:25 +0200441 elif c in b'xX': # X -> change software flow control
442 self.serial.xonxoff = (c == b'X')
cliechti6c8eb2f2009-07-08 02:10:46 +0000443 self.dump_port_settings()
Chris Liechti89eb2472015-08-08 17:06:25 +0200444 elif c in b'rR': # R -> change hardware flow control
445 self.serial.rtscts = (c == b'R')
cliechti6c8eb2f2009-07-08 02:10:46 +0000446 self.dump_port_settings()
447 else:
cliechti6fa76fb2009-07-08 23:53:39 +0000448 sys.stderr.write('--- unknown menu character %s --\n' % key_description(c))
cliechti6c8eb2f2009-07-08 02:10:46 +0000449 menu_active = False
450 elif c == MENUCHARACTER: # next char will be for menu
451 menu_active = True
452 elif c == EXITCHARCTER:
453 self.stop()
454 break # exit app
Chris Liechti89eb2472015-08-08 17:06:25 +0200455 elif c == b'\n':
cliechti6c8eb2f2009-07-08 02:10:46 +0000456 self.serial.write(self.newline) # send newline character(s)
457 if self.echo:
Chris Liechti89eb2472015-08-08 17:06:25 +0200458 sys.console.write(c) # local echo is a real newline in any case
cliechti6c8eb2f2009-07-08 02:10:46 +0000459 else:
Chris Liechti89eb2472015-08-08 17:06:25 +0200460 self.console.write(c) # send byte
cliechti6c8eb2f2009-07-08 02:10:46 +0000461 if self.echo:
Chris Liechti89eb2472015-08-08 17:06:25 +0200462 self.console.write(c)
cliechti6c8eb2f2009-07-08 02:10:46 +0000463 except:
464 self.alive = False
465 raise
cliechti6385f2c2005-09-21 19:51:19 +0000466
467def main():
468 import optparse
469
cliechti53edb472009-02-06 21:18:46 +0000470 parser = optparse.OptionParser(
471 usage = "%prog [options] [port [baudrate]]",
472 description = "Miniterm - A simple terminal program for the serial port."
473 )
cliechti6385f2c2005-09-21 19:51:19 +0000474
cliechti5370cee2013-10-13 03:08:19 +0000475 group = optparse.OptionGroup(parser, "Port settings")
476
477 group.add_option("-p", "--port",
cliechti53edb472009-02-06 21:18:46 +0000478 dest = "port",
cliechti91165532011-03-18 02:02:52 +0000479 help = "port, a number or a device name. (deprecated option, use parameter instead)",
cliechti096e1962012-02-20 01:52:38 +0000480 default = DEFAULT_PORT
cliechti53edb472009-02-06 21:18:46 +0000481 )
cliechti6385f2c2005-09-21 19:51:19 +0000482
cliechti5370cee2013-10-13 03:08:19 +0000483 group.add_option("-b", "--baud",
cliechti53edb472009-02-06 21:18:46 +0000484 dest = "baudrate",
485 action = "store",
486 type = 'int',
cliechti6fa76fb2009-07-08 23:53:39 +0000487 help = "set baud rate, default %default",
cliechti096e1962012-02-20 01:52:38 +0000488 default = DEFAULT_BAUDRATE
cliechti53edb472009-02-06 21:18:46 +0000489 )
490
cliechti5370cee2013-10-13 03:08:19 +0000491 group.add_option("--parity",
cliechti53edb472009-02-06 21:18:46 +0000492 dest = "parity",
493 action = "store",
cliechtie0af3972009-07-08 11:03:47 +0000494 help = "set parity, one of [N, E, O, S, M], default=N",
cliechti53edb472009-02-06 21:18:46 +0000495 default = 'N'
496 )
497
cliechti5370cee2013-10-13 03:08:19 +0000498 group.add_option("--rtscts",
cliechti53edb472009-02-06 21:18:46 +0000499 dest = "rtscts",
500 action = "store_true",
501 help = "enable RTS/CTS flow control (default off)",
502 default = False
503 )
504
cliechti5370cee2013-10-13 03:08:19 +0000505 group.add_option("--xonxoff",
cliechti53edb472009-02-06 21:18:46 +0000506 dest = "xonxoff",
507 action = "store_true",
508 help = "enable software flow control (default off)",
509 default = False
510 )
511
cliechti5370cee2013-10-13 03:08:19 +0000512 group.add_option("--rts",
513 dest = "rts_state",
514 action = "store",
515 type = 'int',
516 help = "set initial RTS line state (possible values: 0, 1)",
517 default = DEFAULT_RTS
518 )
519
520 group.add_option("--dtr",
521 dest = "dtr_state",
522 action = "store",
523 type = 'int',
524 help = "set initial DTR line state (possible values: 0, 1)",
525 default = DEFAULT_DTR
526 )
527
528 parser.add_option_group(group)
529
530 group = optparse.OptionGroup(parser, "Data handling")
531
532 group.add_option("-e", "--echo",
533 dest = "echo",
534 action = "store_true",
535 help = "enable local echo (default off)",
536 default = False
537 )
538
539 group.add_option("--cr",
cliechti53edb472009-02-06 21:18:46 +0000540 dest = "cr",
541 action = "store_true",
542 help = "do not send CR+LF, send CR only",
543 default = False
544 )
545
cliechti5370cee2013-10-13 03:08:19 +0000546 group.add_option("--lf",
cliechti53edb472009-02-06 21:18:46 +0000547 dest = "lf",
548 action = "store_true",
549 help = "do not send CR+LF, send LF only",
550 default = False
551 )
552
cliechti5370cee2013-10-13 03:08:19 +0000553 group.add_option("-D", "--debug",
cliechti53edb472009-02-06 21:18:46 +0000554 dest = "repr_mode",
555 action = "count",
556 help = """debug received data (escape non-printable chars)
cliechti9743e222006-04-04 21:48:56 +0000557--debug can be given multiple times:
5580: just print what is received
cliechti53edb472009-02-06 21:18:46 +00005591: escape non-printable characters, do newlines as unusual
cliechti9743e222006-04-04 21:48:56 +00005602: escape non-printable characters, newlines too
cliechti53edb472009-02-06 21:18:46 +00005613: hex dump everything""",
562 default = 0
563 )
cliechti6385f2c2005-09-21 19:51:19 +0000564
cliechti5370cee2013-10-13 03:08:19 +0000565 parser.add_option_group(group)
cliechtib7d746d2006-03-28 22:44:30 +0000566
cliechtib7d746d2006-03-28 22:44:30 +0000567
cliechti5370cee2013-10-13 03:08:19 +0000568 group = optparse.OptionGroup(parser, "Hotkeys")
cliechtibf6bb7d2006-03-30 00:28:18 +0000569
cliechti5370cee2013-10-13 03:08:19 +0000570 group.add_option("--exit-char",
cliechti53edb472009-02-06 21:18:46 +0000571 dest = "exit_char",
572 action = "store",
573 type = 'int',
574 help = "ASCII code of special character that is used to exit the application",
575 default = 0x1d
576 )
cliechti9c592b32008-06-16 22:00:14 +0000577
cliechti5370cee2013-10-13 03:08:19 +0000578 group.add_option("--menu-char",
cliechti6c8eb2f2009-07-08 02:10:46 +0000579 dest = "menu_char",
cliechti53edb472009-02-06 21:18:46 +0000580 action = "store",
581 type = 'int',
cliechtidfec0c82009-07-21 01:35:41 +0000582 help = "ASCII code of special character that is used to control miniterm (menu)",
cliechti6c8eb2f2009-07-08 02:10:46 +0000583 default = 0x14
cliechti53edb472009-02-06 21:18:46 +0000584 )
cliechti6385f2c2005-09-21 19:51:19 +0000585
cliechti5370cee2013-10-13 03:08:19 +0000586 parser.add_option_group(group)
587
588 group = optparse.OptionGroup(parser, "Diagnostics")
589
590 group.add_option("-q", "--quiet",
591 dest = "quiet",
592 action = "store_true",
593 help = "suppress non-error messages",
594 default = False
595 )
596
Chris Liechti91090912015-08-05 02:36:14 +0200597 group.add_option("", "--develop",
598 dest = "develop",
599 action = "store_true",
600 help = "show Python traceback on error",
601 default = False
602 )
603
604
605
cliechti5370cee2013-10-13 03:08:19 +0000606 parser.add_option_group(group)
607
608
cliechti6385f2c2005-09-21 19:51:19 +0000609 (options, args) = parser.parse_args()
610
cliechtie0af3972009-07-08 11:03:47 +0000611 options.parity = options.parity.upper()
612 if options.parity not in 'NEOSM':
613 parser.error("invalid parity")
614
cliechti9cf26222006-03-24 20:09:21 +0000615 if options.cr and options.lf:
cliechti53edb472009-02-06 21:18:46 +0000616 parser.error("only one of --cr or --lf can be specified")
617
cliechtic1ca0772009-08-05 12:34:04 +0000618 if options.menu_char == options.exit_char:
cliechti6c8eb2f2009-07-08 02:10:46 +0000619 parser.error('--exit-char can not be the same as --menu-char')
620
621 global EXITCHARCTER, MENUCHARACTER
Chris Liechti89eb2472015-08-08 17:06:25 +0200622 EXITCHARCTER = serial.to_bytes([options.exit_char])
623 MENUCHARACTER = serial.to_bytes([options.menu_char])
cliechti9c592b32008-06-16 22:00:14 +0000624
cliechti9743e222006-04-04 21:48:56 +0000625 port = options.port
626 baudrate = options.baudrate
cliechti9cf26222006-03-24 20:09:21 +0000627 if args:
cliechti9743e222006-04-04 21:48:56 +0000628 if options.port is not None:
629 parser.error("no arguments are allowed, options only when --port is given")
630 port = args.pop(0)
631 if args:
632 try:
633 baudrate = int(args[0])
634 except ValueError:
cliechti53edb472009-02-06 21:18:46 +0000635 parser.error("baud rate must be a number, not %r" % args[0])
cliechti9743e222006-04-04 21:48:56 +0000636 args.pop(0)
637 if args:
638 parser.error("too many arguments")
639 else:
cliechti7d448562014-08-03 21:57:45 +0000640 # no port given on command line -> ask user now
cliechti1351dde2012-04-12 16:47:47 +0000641 if port is None:
642 dump_port_list()
643 port = raw_input('Enter port name:')
cliechti53edb472009-02-06 21:18:46 +0000644
cliechti6385f2c2005-09-21 19:51:19 +0000645 convert_outgoing = CONVERT_CRLF
cliechti9cf26222006-03-24 20:09:21 +0000646 if options.cr:
cliechti6385f2c2005-09-21 19:51:19 +0000647 convert_outgoing = CONVERT_CR
cliechti9cf26222006-03-24 20:09:21 +0000648 elif options.lf:
cliechti6385f2c2005-09-21 19:51:19 +0000649 convert_outgoing = CONVERT_LF
650
651 try:
652 miniterm = Miniterm(
cliechti9743e222006-04-04 21:48:56 +0000653 port,
654 baudrate,
cliechti6385f2c2005-09-21 19:51:19 +0000655 options.parity,
656 rtscts=options.rtscts,
657 xonxoff=options.xonxoff,
658 echo=options.echo,
659 convert_outgoing=convert_outgoing,
660 repr_mode=options.repr_mode,
661 )
Chris Liechti68340d72015-08-03 14:15:48 +0200662 except serial.SerialException as e:
cliechtieb4a14f2009-08-03 23:48:35 +0000663 sys.stderr.write("could not open port %r: %s\n" % (port, e))
Chris Liechti91090912015-08-05 02:36:14 +0200664 if options.develop:
665 raise
cliechti6385f2c2005-09-21 19:51:19 +0000666 sys.exit(1)
667
cliechtibf6bb7d2006-03-30 00:28:18 +0000668 if not options.quiet:
cliechti6fa76fb2009-07-08 23:53:39 +0000669 sys.stderr.write('--- Miniterm on %s: %d,%s,%s,%s ---\n' % (
cliechti9743e222006-04-04 21:48:56 +0000670 miniterm.serial.portstr,
671 miniterm.serial.baudrate,
672 miniterm.serial.bytesize,
673 miniterm.serial.parity,
674 miniterm.serial.stopbits,
675 ))
cliechti6c8eb2f2009-07-08 02:10:46 +0000676 sys.stderr.write('--- Quit: %s | Menu: %s | Help: %s followed by %s ---\n' % (
cliechti9c592b32008-06-16 22:00:14 +0000677 key_description(EXITCHARCTER),
cliechti6c8eb2f2009-07-08 02:10:46 +0000678 key_description(MENUCHARACTER),
679 key_description(MENUCHARACTER),
Chris Liechti89eb2472015-08-08 17:06:25 +0200680 key_description(b'\x08'),
cliechti9c592b32008-06-16 22:00:14 +0000681 ))
cliechti6fa76fb2009-07-08 23:53:39 +0000682
cliechtib7d746d2006-03-28 22:44:30 +0000683 if options.dtr_state is not None:
cliechtibf6bb7d2006-03-30 00:28:18 +0000684 if not options.quiet:
685 sys.stderr.write('--- forcing DTR %s\n' % (options.dtr_state and 'active' or 'inactive'))
cliechtib7d746d2006-03-28 22:44:30 +0000686 miniterm.serial.setDTR(options.dtr_state)
cliechti6c8eb2f2009-07-08 02:10:46 +0000687 miniterm.dtr_state = options.dtr_state
cliechtibf6bb7d2006-03-30 00:28:18 +0000688 if options.rts_state is not None:
689 if not options.quiet:
690 sys.stderr.write('--- forcing RTS %s\n' % (options.rts_state and 'active' or 'inactive'))
691 miniterm.serial.setRTS(options.rts_state)
cliechti6c8eb2f2009-07-08 02:10:46 +0000692 miniterm.rts_state = options.rts_state
cliechti53edb472009-02-06 21:18:46 +0000693
cliechti6385f2c2005-09-21 19:51:19 +0000694 miniterm.start()
cliechti258ab0a2011-03-21 23:03:45 +0000695 try:
696 miniterm.join(True)
697 except KeyboardInterrupt:
698 pass
cliechtibf6bb7d2006-03-30 00:28:18 +0000699 if not options.quiet:
700 sys.stderr.write("\n--- exit ---\n")
cliechti6385f2c2005-09-21 19:51:19 +0000701 miniterm.join()
cliechti5370cee2013-10-13 03:08:19 +0000702 #~ console.cleanup()
cliechtibf6bb7d2006-03-30 00:28:18 +0000703
cliechti5370cee2013-10-13 03:08:19 +0000704# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
cliechti8b3ad392002-03-03 20:12:21 +0000705if __name__ == '__main__':
cliechti6385f2c2005-09-21 19:51:19 +0000706 main()