blob: 761b5b2efb6d2dcaffc9ce0043cb01ab50969808 [file] [log] [blame]
cliechti576de252002-02-28 23:54:44 +00001#!/usr/bin/env python
2
cliechtia128a702004-07-21 22:13:31 +00003# Very simple serial terminal
Chris Liechti68340d72015-08-03 14:15:48 +02004# (C)2002-2015 Chris Liechti <cliechti@gmx.net>
cliechtifc9eb382002-03-05 01:12:29 +00005
cliechtia128a702004-07-21 22:13:31 +00006# Input characters are sent directly (only LF -> CR/LF/CRLF translation is
cliechtibf6bb7d2006-03-30 00:28:18 +00007# done), received characters are displayed as is (or escaped trough pythons
cliechtia128a702004-07-21 22:13:31 +00008# repr, useful for debug purposes)
cliechti576de252002-02-28 23:54:44 +00009
10
cliechti88028022007-11-13 16:06:46 +000011import sys, os, serial, 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 Liechti68340d72015-08-03 14:15:48 +020017try:
18 raw_input
19except NameError:
20 raw_input = input # in python3 it's "raw"
21
cliechtif467aa82013-10-13 21:36:49 +000022EXITCHARCTER = serial.to_bytes([0x1d]) # GS/CTRL+]
23MENUCHARACTER = serial.to_bytes([0x14]) # Menu: CTRL+T
cliechtia128a702004-07-21 22:13:31 +000024
cliechti096e1962012-02-20 01:52:38 +000025DEFAULT_PORT = None
26DEFAULT_BAUDRATE = 9600
27DEFAULT_RTS = None
28DEFAULT_DTR = None
29
cliechti6c8eb2f2009-07-08 02:10:46 +000030
31def key_description(character):
32 """generate a readable description for a key"""
33 ascii_code = ord(character)
34 if ascii_code < 32:
35 return 'Ctrl+%c' % (ord('@') + ascii_code)
36 else:
37 return repr(character)
38
cliechti91165532011-03-18 02:02:52 +000039
cliechti6c8eb2f2009-07-08 02:10:46 +000040# help text, starts with blank line! it's a function so that the current values
41# for the shortcut keys is used and not the value at program start
42def get_help_text():
43 return """
cliechti6963b262010-01-02 03:01:21 +000044--- pySerial (%(version)s) - miniterm - help
cliechti6fa76fb2009-07-08 23:53:39 +000045---
46--- %(exit)-8s Exit program
47--- %(menu)-8s Menu escape key, followed by:
48--- Menu keys:
cliechti258ab0a2011-03-21 23:03:45 +000049--- %(itself)-7s Send the menu character itself to remote
50--- %(exchar)-7s Send the exit character itself to remote
51--- %(info)-7s Show info
52--- %(upload)-7s Upload file (prompt will be shown)
cliechti6fa76fb2009-07-08 23:53:39 +000053--- Toggles:
cliechti258ab0a2011-03-21 23:03:45 +000054--- %(rts)-7s RTS %(echo)-7s local echo
55--- %(dtr)-7s DTR %(break)-7s BREAK
56--- %(lfm)-7s line feed %(repr)-7s Cycle repr mode
cliechti6fa76fb2009-07-08 23:53:39 +000057---
58--- Port settings (%(menu)s followed by the following):
cliechti258ab0a2011-03-21 23:03:45 +000059--- p change port
60--- 7 8 set data bits
61--- n e o s m change parity (None, Even, Odd, Space, Mark)
62--- 1 2 3 set stop bits (1, 2, 1.5)
63--- b change baud rate
64--- x X disable/enable software flow control
65--- r R disable/enable hardware flow control
cliechti6c8eb2f2009-07-08 02:10:46 +000066""" % {
cliechti8c2ea842011-03-18 01:51:46 +000067 'version': getattr(serial, 'VERSION', 'unknown version'),
cliechti6c8eb2f2009-07-08 02:10:46 +000068 'exit': key_description(EXITCHARCTER),
69 'menu': key_description(MENUCHARACTER),
cliechti6fa76fb2009-07-08 23:53:39 +000070 'rts': key_description('\x12'),
71 'repr': key_description('\x01'),
72 'dtr': key_description('\x04'),
73 'lfm': key_description('\x0c'),
74 'break': key_description('\x02'),
75 'echo': key_description('\x05'),
76 'info': key_description('\x09'),
77 'upload': key_description('\x15'),
78 'itself': key_description(MENUCHARACTER),
79 'exchar': key_description(EXITCHARCTER),
cliechti6c8eb2f2009-07-08 02:10:46 +000080}
81
cliechti393fa0e2011-08-22 00:53:36 +000082if sys.version_info >= (3, 0):
83 def character(b):
84 return b.decode('latin1')
85else:
86 def character(b):
87 return b
88
cliechtif467aa82013-10-13 21:36:49 +000089LF = serial.to_bytes([10])
90CR = serial.to_bytes([13])
91CRLF = serial.to_bytes([13, 10])
92
93X00 = serial.to_bytes([0])
94X0E = serial.to_bytes([0x0e])
95
cliechti6c8eb2f2009-07-08 02:10:46 +000096# first choose a platform dependant way to read single characters from the console
cliechti9c592b32008-06-16 22:00:14 +000097global console
98
cliechtifc9eb382002-03-05 01:12:29 +000099if os.name == 'nt':
cliechti576de252002-02-28 23:54:44 +0000100 import msvcrt
cliechti91165532011-03-18 02:02:52 +0000101 class Console(object):
cliechti9c592b32008-06-16 22:00:14 +0000102 def __init__(self):
103 pass
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
cliechti9c592b32008-06-16 22:00:14 +0000121 console = Console()
cliechti53edb472009-02-06 21:18:46 +0000122
cliechti576de252002-02-28 23:54:44 +0000123elif os.name == 'posix':
cliechtib7466da2004-07-11 20:04:41 +0000124 import termios, sys, os
cliechti91165532011-03-18 02:02:52 +0000125 class Console(object):
cliechti9c592b32008-06-16 22:00:14 +0000126 def __init__(self):
127 self.fd = sys.stdin.fileno()
cliechti5370cee2013-10-13 03:08:19 +0000128 self.old = None
cliechti9c592b32008-06-16 22:00:14 +0000129
130 def setup(self):
131 self.old = termios.tcgetattr(self.fd)
132 new = termios.tcgetattr(self.fd)
133 new[3] = new[3] & ~termios.ICANON & ~termios.ECHO & ~termios.ISIG
134 new[6][termios.VMIN] = 1
135 new[6][termios.VTIME] = 0
136 termios.tcsetattr(self.fd, termios.TCSANOW, new)
cliechti53edb472009-02-06 21:18:46 +0000137
cliechti9c592b32008-06-16 22:00:14 +0000138 def getkey(self):
139 c = os.read(self.fd, 1)
140 return c
cliechti53edb472009-02-06 21:18:46 +0000141
cliechti9c592b32008-06-16 22:00:14 +0000142 def cleanup(self):
cliechti5370cee2013-10-13 03:08:19 +0000143 if self.old is not None:
144 termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old)
cliechti9c592b32008-06-16 22:00:14 +0000145
146 console = Console()
147
148 def cleanup_console():
149 console.cleanup()
150
cliechti8c2ea842011-03-18 01:51:46 +0000151 sys.exitfunc = cleanup_console # terminal modes have to be restored on exit...
cliechti576de252002-02-28 23:54:44 +0000152
153else:
cliechti8c2ea842011-03-18 01:51:46 +0000154 raise NotImplementedError("Sorry no implementation for your platform (%s) available." % sys.platform)
cliechti576de252002-02-28 23:54:44 +0000155
cliechti6fa76fb2009-07-08 23:53:39 +0000156
cliechti1351dde2012-04-12 16:47:47 +0000157def dump_port_list():
158 if comports:
159 sys.stderr.write('\n--- Available ports:\n')
160 for port, desc, hwid in sorted(comports()):
161 #~ sys.stderr.write('--- %-20s %s [%s]\n' % (port, desc, hwid))
162 sys.stderr.write('--- %-20s %s\n' % (port, desc))
163
164
cliechtia128a702004-07-21 22:13:31 +0000165CONVERT_CRLF = 2
166CONVERT_CR = 1
167CONVERT_LF = 0
cliechtif467aa82013-10-13 21:36:49 +0000168NEWLINE_CONVERISON_MAP = (LF, CR, CRLF)
cliechti6fa76fb2009-07-08 23:53:39 +0000169LF_MODES = ('LF', 'CR', 'CR/LF')
170
171REPR_MODES = ('raw', 'some control', 'all control', 'hex')
cliechti576de252002-02-28 23:54:44 +0000172
cliechti8c2ea842011-03-18 01:51:46 +0000173class Miniterm(object):
cliechti9743e222006-04-04 21:48:56 +0000174 def __init__(self, port, baudrate, parity, rtscts, xonxoff, echo=False, convert_outgoing=CONVERT_CRLF, repr_mode=0):
cliechti3fc527d2009-09-30 01:54:45 +0000175 try:
176 self.serial = serial.serial_for_url(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1)
177 except AttributeError:
178 # happens when the installed pyserial is older than 2.5. use the
179 # Serial class directly then.
180 self.serial = serial.Serial(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1)
cliechti6385f2c2005-09-21 19:51:19 +0000181 self.echo = echo
182 self.repr_mode = repr_mode
183 self.convert_outgoing = convert_outgoing
cliechtibf6bb7d2006-03-30 00:28:18 +0000184 self.newline = NEWLINE_CONVERISON_MAP[self.convert_outgoing]
cliechti6c8eb2f2009-07-08 02:10:46 +0000185 self.dtr_state = True
186 self.rts_state = True
187 self.break_state = False
cliechti576de252002-02-28 23:54:44 +0000188
cliechti8c2ea842011-03-18 01:51:46 +0000189 def _start_reader(self):
190 """Start reader thread"""
191 self._reader_alive = True
cliechti6fa76fb2009-07-08 23:53:39 +0000192 # start serial->console thread
cliechti6385f2c2005-09-21 19:51:19 +0000193 self.receiver_thread = threading.Thread(target=self.reader)
cliechti8c2ea842011-03-18 01:51:46 +0000194 self.receiver_thread.setDaemon(True)
cliechti6385f2c2005-09-21 19:51:19 +0000195 self.receiver_thread.start()
cliechti8c2ea842011-03-18 01:51:46 +0000196
197 def _stop_reader(self):
198 """Stop reader thread only, wait for clean exit of thread"""
199 self._reader_alive = False
200 self.receiver_thread.join()
201
202
203 def start(self):
204 self.alive = True
205 self._start_reader()
cliechti6fa76fb2009-07-08 23:53:39 +0000206 # enter console->serial loop
cliechti6385f2c2005-09-21 19:51:19 +0000207 self.transmitter_thread = threading.Thread(target=self.writer)
cliechti8c2ea842011-03-18 01:51:46 +0000208 self.transmitter_thread.setDaemon(True)
cliechti6385f2c2005-09-21 19:51:19 +0000209 self.transmitter_thread.start()
cliechti53edb472009-02-06 21:18:46 +0000210
cliechti6385f2c2005-09-21 19:51:19 +0000211 def stop(self):
212 self.alive = False
cliechti53edb472009-02-06 21:18:46 +0000213
cliechtibf6bb7d2006-03-30 00:28:18 +0000214 def join(self, transmit_only=False):
cliechti6385f2c2005-09-21 19:51:19 +0000215 self.transmitter_thread.join()
cliechtibf6bb7d2006-03-30 00:28:18 +0000216 if not transmit_only:
217 self.receiver_thread.join()
cliechti6385f2c2005-09-21 19:51:19 +0000218
cliechti6c8eb2f2009-07-08 02:10:46 +0000219 def dump_port_settings(self):
cliechti6fa76fb2009-07-08 23:53:39 +0000220 sys.stderr.write("\n--- Settings: %s %s,%s,%s,%s\n" % (
cliechti258ab0a2011-03-21 23:03:45 +0000221 self.serial.portstr,
222 self.serial.baudrate,
223 self.serial.bytesize,
224 self.serial.parity,
225 self.serial.stopbits))
226 sys.stderr.write('--- RTS: %-8s DTR: %-8s BREAK: %-8s\n' % (
227 (self.rts_state and 'active' or 'inactive'),
228 (self.dtr_state and 'active' or 'inactive'),
229 (self.break_state and 'active' or 'inactive')))
cliechti10114572009-08-05 23:40:50 +0000230 try:
cliechti258ab0a2011-03-21 23:03:45 +0000231 sys.stderr.write('--- CTS: %-8s DSR: %-8s RI: %-8s CD: %-8s\n' % (
232 (self.serial.getCTS() and 'active' or 'inactive'),
233 (self.serial.getDSR() and 'active' or 'inactive'),
234 (self.serial.getRI() and 'active' or 'inactive'),
235 (self.serial.getCD() and 'active' or 'inactive')))
cliechti10114572009-08-05 23:40:50 +0000236 except serial.SerialException:
237 # on RFC 2217 ports it can happen to no modem state notification was
238 # yet received. ignore this error.
239 pass
cliechti258ab0a2011-03-21 23:03:45 +0000240 sys.stderr.write('--- software flow control: %s\n' % (self.serial.xonxoff and 'active' or 'inactive'))
241 sys.stderr.write('--- hardware flow control: %s\n' % (self.serial.rtscts and 'active' or 'inactive'))
242 sys.stderr.write('--- data escaping: %s linefeed: %s\n' % (
243 REPR_MODES[self.repr_mode],
244 LF_MODES[self.convert_outgoing]))
cliechti6c8eb2f2009-07-08 02:10:46 +0000245
cliechti6385f2c2005-09-21 19:51:19 +0000246 def reader(self):
247 """loop and copy serial->console"""
cliechti6963b262010-01-02 03:01:21 +0000248 try:
cliechti8c2ea842011-03-18 01:51:46 +0000249 while self.alive and self._reader_alive:
cliechti393fa0e2011-08-22 00:53:36 +0000250 data = character(self.serial.read(1))
cliechti53edb472009-02-06 21:18:46 +0000251
cliechti6963b262010-01-02 03:01:21 +0000252 if self.repr_mode == 0:
253 # direct output, just have to care about newline setting
254 if data == '\r' and self.convert_outgoing == CONVERT_CR:
cliechti9743e222006-04-04 21:48:56 +0000255 sys.stdout.write('\n')
cliechti6963b262010-01-02 03:01:21 +0000256 else:
257 sys.stdout.write(data)
258 elif self.repr_mode == 1:
259 # escape non-printable, let pass newlines
260 if self.convert_outgoing == CONVERT_CRLF and data in '\r\n':
261 if data == '\n':
262 sys.stdout.write('\n')
263 elif data == '\r':
264 pass
265 elif data == '\n' and self.convert_outgoing == CONVERT_LF:
266 sys.stdout.write('\n')
267 elif data == '\r' and self.convert_outgoing == CONVERT_CR:
268 sys.stdout.write('\n')
269 else:
270 sys.stdout.write(repr(data)[1:-1])
271 elif self.repr_mode == 2:
272 # escape all non-printable, including newline
cliechti9743e222006-04-04 21:48:56 +0000273 sys.stdout.write(repr(data)[1:-1])
cliechti6963b262010-01-02 03:01:21 +0000274 elif self.repr_mode == 3:
275 # escape everything (hexdump)
cliechti393fa0e2011-08-22 00:53:36 +0000276 for c in data:
277 sys.stdout.write("%s " % c.encode('hex'))
cliechti6963b262010-01-02 03:01:21 +0000278 sys.stdout.flush()
Chris Liechti68340d72015-08-03 14:15:48 +0200279 except serial.SerialException as e:
cliechti6963b262010-01-02 03:01:21 +0000280 self.alive = False
281 # would be nice if the console reader could be interruptted at this
282 # point...
283 raise
cliechti576de252002-02-28 23:54:44 +0000284
cliechti576de252002-02-28 23:54:44 +0000285
cliechti6385f2c2005-09-21 19:51:19 +0000286 def writer(self):
cliechti8c2ea842011-03-18 01:51:46 +0000287 """\
288 Loop and copy console->serial until EXITCHARCTER character is
289 found. When MENUCHARACTER is found, interpret the next key
290 locally.
cliechti6c8eb2f2009-07-08 02:10:46 +0000291 """
292 menu_active = False
293 try:
294 while self.alive:
295 try:
cliechti393fa0e2011-08-22 00:53:36 +0000296 b = console.getkey()
cliechti6c8eb2f2009-07-08 02:10:46 +0000297 except KeyboardInterrupt:
cliechti393fa0e2011-08-22 00:53:36 +0000298 b = serial.to_bytes([3])
299 c = character(b)
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:
304 sys.stdout.write(c)
305 elif c == '\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()
308 console.cleanup()
309 filename = sys.stdin.readline().rstrip('\r\n')
310 if filename:
311 try:
312 file = open(filename, 'r')
cliechti6fa76fb2009-07-08 23:53:39 +0000313 sys.stderr.write('--- Sending file %s ---\n' % filename)
cliechti6c8eb2f2009-07-08 02:10:46 +0000314 while True:
315 line = file.readline().rstrip('\r\n')
316 if not line:
317 break
318 self.serial.write(line)
319 self.serial.write('\r\n')
320 # Wait for output buffer to drain.
321 self.serial.flush()
322 sys.stderr.write('.') # Progress indicator.
cliechti6fa76fb2009-07-08 23:53:39 +0000323 sys.stderr.write('\n--- File %s sent ---\n' % filename)
Chris Liechti68340d72015-08-03 14:15:48 +0200324 except IOError as e:
cliechti6fa76fb2009-07-08 23:53:39 +0000325 sys.stderr.write('--- ERROR opening file %s: %s ---\n' % (filename, e))
cliechti6c8eb2f2009-07-08 02:10:46 +0000326 console.setup()
327 elif c in '\x08hH?': # CTRL+H, h, H, ? -> Show help
328 sys.stderr.write(get_help_text())
329 elif c == '\x12': # CTRL+R -> Toggle RTS
330 self.rts_state = not self.rts_state
331 self.serial.setRTS(self.rts_state)
cliechti6fa76fb2009-07-08 23:53:39 +0000332 sys.stderr.write('--- RTS %s ---\n' % (self.rts_state and 'active' or 'inactive'))
cliechti6c8eb2f2009-07-08 02:10:46 +0000333 elif c == '\x04': # CTRL+D -> Toggle DTR
334 self.dtr_state = not self.dtr_state
335 self.serial.setDTR(self.dtr_state)
cliechti6fa76fb2009-07-08 23:53:39 +0000336 sys.stderr.write('--- DTR %s ---\n' % (self.dtr_state and 'active' or 'inactive'))
cliechti6c8eb2f2009-07-08 02:10:46 +0000337 elif c == '\x02': # CTRL+B -> toggle BREAK condition
338 self.break_state = not self.break_state
339 self.serial.setBreak(self.break_state)
cliechti6fa76fb2009-07-08 23:53:39 +0000340 sys.stderr.write('--- BREAK %s ---\n' % (self.break_state and 'active' or 'inactive'))
cliechtie0af3972009-07-08 11:03:47 +0000341 elif c == '\x05': # CTRL+E -> toggle local echo
342 self.echo = not self.echo
cliechti6fa76fb2009-07-08 23:53:39 +0000343 sys.stderr.write('--- local echo %s ---\n' % (self.echo and 'active' or 'inactive'))
cliechti6c8eb2f2009-07-08 02:10:46 +0000344 elif c == '\x09': # CTRL+I -> info
345 self.dump_port_settings()
cliechti6fa76fb2009-07-08 23:53:39 +0000346 elif c == '\x01': # CTRL+A -> cycle escape mode
347 self.repr_mode += 1
348 if self.repr_mode > 3:
349 self.repr_mode = 0
350 sys.stderr.write('--- escape data: %s ---\n' % (
351 REPR_MODES[self.repr_mode],
352 ))
353 elif c == '\x0c': # CTRL+L -> cycle linefeed mode
354 self.convert_outgoing += 1
355 if self.convert_outgoing > 2:
356 self.convert_outgoing = 0
357 self.newline = NEWLINE_CONVERISON_MAP[self.convert_outgoing]
358 sys.stderr.write('--- line feed %s ---\n' % (
359 LF_MODES[self.convert_outgoing],
360 ))
cliechti8c2ea842011-03-18 01:51:46 +0000361 elif c in 'pP': # P -> change port
cliechti1351dde2012-04-12 16:47:47 +0000362 dump_port_list()
cliechti21e2c842012-02-21 16:40:27 +0000363 sys.stderr.write('--- Enter port name: ')
cliechti8c2ea842011-03-18 01:51:46 +0000364 sys.stderr.flush()
365 console.cleanup()
cliechti258ab0a2011-03-21 23:03:45 +0000366 try:
367 port = sys.stdin.readline().strip()
368 except KeyboardInterrupt:
369 port = None
cliechti8c2ea842011-03-18 01:51:46 +0000370 console.setup()
cliechti258ab0a2011-03-21 23:03:45 +0000371 if port and port != self.serial.port:
cliechti8c2ea842011-03-18 01:51:46 +0000372 # reader thread needs to be shut down
373 self._stop_reader()
374 # save settings
375 settings = self.serial.getSettingsDict()
cliechti8c2ea842011-03-18 01:51:46 +0000376 try:
cliechti258ab0a2011-03-21 23:03:45 +0000377 try:
378 new_serial = serial.serial_for_url(port, do_not_open=True)
379 except AttributeError:
380 # happens when the installed pyserial is older than 2.5. use the
381 # Serial class directly then.
382 new_serial = serial.Serial()
383 new_serial.port = port
384 # restore settings and open
385 new_serial.applySettingsDict(settings)
386 new_serial.open()
387 new_serial.setRTS(self.rts_state)
388 new_serial.setDTR(self.dtr_state)
389 new_serial.setBreak(self.break_state)
Chris Liechti68340d72015-08-03 14:15:48 +0200390 except Exception as e:
cliechti258ab0a2011-03-21 23:03:45 +0000391 sys.stderr.write('--- ERROR opening new port: %s ---\n' % (e,))
392 new_serial.close()
393 else:
394 self.serial.close()
395 self.serial = new_serial
396 sys.stderr.write('--- Port changed to: %s ---\n' % (self.serial.port,))
cliechti91165532011-03-18 02:02:52 +0000397 # and restart the reader thread
cliechti8c2ea842011-03-18 01:51:46 +0000398 self._start_reader()
cliechti6c8eb2f2009-07-08 02:10:46 +0000399 elif c in 'bB': # B -> change baudrate
cliechti6fa76fb2009-07-08 23:53:39 +0000400 sys.stderr.write('\n--- Baudrate: ')
cliechti6c8eb2f2009-07-08 02:10:46 +0000401 sys.stderr.flush()
402 console.cleanup()
403 backup = self.serial.baudrate
404 try:
405 self.serial.baudrate = int(sys.stdin.readline().strip())
Chris Liechti68340d72015-08-03 14:15:48 +0200406 except ValueError as e:
cliechti6fa76fb2009-07-08 23:53:39 +0000407 sys.stderr.write('--- ERROR setting baudrate: %s ---\n' % (e,))
cliechti6c8eb2f2009-07-08 02:10:46 +0000408 self.serial.baudrate = backup
cliechti6fa76fb2009-07-08 23:53:39 +0000409 else:
410 self.dump_port_settings()
cliechti6c8eb2f2009-07-08 02:10:46 +0000411 console.setup()
cliechti6c8eb2f2009-07-08 02:10:46 +0000412 elif c == '8': # 8 -> change to 8 bits
413 self.serial.bytesize = serial.EIGHTBITS
414 self.dump_port_settings()
415 elif c == '7': # 7 -> change to 8 bits
416 self.serial.bytesize = serial.SEVENBITS
417 self.dump_port_settings()
418 elif c in 'eE': # E -> change to even parity
419 self.serial.parity = serial.PARITY_EVEN
420 self.dump_port_settings()
421 elif c in 'oO': # O -> change to odd parity
422 self.serial.parity = serial.PARITY_ODD
423 self.dump_port_settings()
424 elif c in 'mM': # M -> change to mark parity
425 self.serial.parity = serial.PARITY_MARK
426 self.dump_port_settings()
427 elif c in 'sS': # S -> change to space parity
428 self.serial.parity = serial.PARITY_SPACE
429 self.dump_port_settings()
430 elif c in 'nN': # N -> change to no parity
431 self.serial.parity = serial.PARITY_NONE
432 self.dump_port_settings()
433 elif c == '1': # 1 -> change to 1 stop bits
434 self.serial.stopbits = serial.STOPBITS_ONE
435 self.dump_port_settings()
436 elif c == '2': # 2 -> change to 2 stop bits
437 self.serial.stopbits = serial.STOPBITS_TWO
438 self.dump_port_settings()
439 elif c == '3': # 3 -> change to 1.5 stop bits
440 self.serial.stopbits = serial.STOPBITS_ONE_POINT_FIVE
441 self.dump_port_settings()
442 elif c in 'xX': # X -> change software flow control
443 self.serial.xonxoff = (c == 'X')
444 self.dump_port_settings()
445 elif c in 'rR': # R -> change hardware flow control
446 self.serial.rtscts = (c == 'R')
447 self.dump_port_settings()
448 else:
cliechti6fa76fb2009-07-08 23:53:39 +0000449 sys.stderr.write('--- unknown menu character %s --\n' % key_description(c))
cliechti6c8eb2f2009-07-08 02:10:46 +0000450 menu_active = False
451 elif c == MENUCHARACTER: # next char will be for menu
452 menu_active = True
453 elif c == EXITCHARCTER:
454 self.stop()
455 break # exit app
456 elif c == '\n':
457 self.serial.write(self.newline) # send newline character(s)
458 if self.echo:
459 sys.stdout.write(c) # local echo is a real newline in any case
cliechti6fa76fb2009-07-08 23:53:39 +0000460 sys.stdout.flush()
cliechti6c8eb2f2009-07-08 02:10:46 +0000461 else:
cliechti393fa0e2011-08-22 00:53:36 +0000462 self.serial.write(b) # send byte
cliechti6c8eb2f2009-07-08 02:10:46 +0000463 if self.echo:
464 sys.stdout.write(c)
cliechti6fa76fb2009-07-08 23:53:39 +0000465 sys.stdout.flush()
cliechti6c8eb2f2009-07-08 02:10:46 +0000466 except:
467 self.alive = False
468 raise
cliechti6385f2c2005-09-21 19:51:19 +0000469
470def main():
471 import optparse
472
cliechti53edb472009-02-06 21:18:46 +0000473 parser = optparse.OptionParser(
474 usage = "%prog [options] [port [baudrate]]",
475 description = "Miniterm - A simple terminal program for the serial port."
476 )
cliechti6385f2c2005-09-21 19:51:19 +0000477
cliechti5370cee2013-10-13 03:08:19 +0000478 group = optparse.OptionGroup(parser, "Port settings")
479
480 group.add_option("-p", "--port",
cliechti53edb472009-02-06 21:18:46 +0000481 dest = "port",
cliechti91165532011-03-18 02:02:52 +0000482 help = "port, a number or a device name. (deprecated option, use parameter instead)",
cliechti096e1962012-02-20 01:52:38 +0000483 default = DEFAULT_PORT
cliechti53edb472009-02-06 21:18:46 +0000484 )
cliechti6385f2c2005-09-21 19:51:19 +0000485
cliechti5370cee2013-10-13 03:08:19 +0000486 group.add_option("-b", "--baud",
cliechti53edb472009-02-06 21:18:46 +0000487 dest = "baudrate",
488 action = "store",
489 type = 'int',
cliechti6fa76fb2009-07-08 23:53:39 +0000490 help = "set baud rate, default %default",
cliechti096e1962012-02-20 01:52:38 +0000491 default = DEFAULT_BAUDRATE
cliechti53edb472009-02-06 21:18:46 +0000492 )
493
cliechti5370cee2013-10-13 03:08:19 +0000494 group.add_option("--parity",
cliechti53edb472009-02-06 21:18:46 +0000495 dest = "parity",
496 action = "store",
cliechtie0af3972009-07-08 11:03:47 +0000497 help = "set parity, one of [N, E, O, S, M], default=N",
cliechti53edb472009-02-06 21:18:46 +0000498 default = 'N'
499 )
500
cliechti5370cee2013-10-13 03:08:19 +0000501 group.add_option("--rtscts",
cliechti53edb472009-02-06 21:18:46 +0000502 dest = "rtscts",
503 action = "store_true",
504 help = "enable RTS/CTS flow control (default off)",
505 default = False
506 )
507
cliechti5370cee2013-10-13 03:08:19 +0000508 group.add_option("--xonxoff",
cliechti53edb472009-02-06 21:18:46 +0000509 dest = "xonxoff",
510 action = "store_true",
511 help = "enable software flow control (default off)",
512 default = False
513 )
514
cliechti5370cee2013-10-13 03:08:19 +0000515 group.add_option("--rts",
516 dest = "rts_state",
517 action = "store",
518 type = 'int',
519 help = "set initial RTS line state (possible values: 0, 1)",
520 default = DEFAULT_RTS
521 )
522
523 group.add_option("--dtr",
524 dest = "dtr_state",
525 action = "store",
526 type = 'int',
527 help = "set initial DTR line state (possible values: 0, 1)",
528 default = DEFAULT_DTR
529 )
530
531 parser.add_option_group(group)
532
533 group = optparse.OptionGroup(parser, "Data handling")
534
535 group.add_option("-e", "--echo",
536 dest = "echo",
537 action = "store_true",
538 help = "enable local echo (default off)",
539 default = False
540 )
541
542 group.add_option("--cr",
cliechti53edb472009-02-06 21:18:46 +0000543 dest = "cr",
544 action = "store_true",
545 help = "do not send CR+LF, send CR only",
546 default = False
547 )
548
cliechti5370cee2013-10-13 03:08:19 +0000549 group.add_option("--lf",
cliechti53edb472009-02-06 21:18:46 +0000550 dest = "lf",
551 action = "store_true",
552 help = "do not send CR+LF, send LF only",
553 default = False
554 )
555
cliechti5370cee2013-10-13 03:08:19 +0000556 group.add_option("-D", "--debug",
cliechti53edb472009-02-06 21:18:46 +0000557 dest = "repr_mode",
558 action = "count",
559 help = """debug received data (escape non-printable chars)
cliechti9743e222006-04-04 21:48:56 +0000560--debug can be given multiple times:
5610: just print what is received
cliechti53edb472009-02-06 21:18:46 +00005621: escape non-printable characters, do newlines as unusual
cliechti9743e222006-04-04 21:48:56 +00005632: escape non-printable characters, newlines too
cliechti53edb472009-02-06 21:18:46 +00005643: hex dump everything""",
565 default = 0
566 )
cliechti6385f2c2005-09-21 19:51:19 +0000567
cliechti5370cee2013-10-13 03:08:19 +0000568 parser.add_option_group(group)
cliechtib7d746d2006-03-28 22:44:30 +0000569
cliechtib7d746d2006-03-28 22:44:30 +0000570
cliechti5370cee2013-10-13 03:08:19 +0000571 group = optparse.OptionGroup(parser, "Hotkeys")
cliechtibf6bb7d2006-03-30 00:28:18 +0000572
cliechti5370cee2013-10-13 03:08:19 +0000573 group.add_option("--exit-char",
cliechti53edb472009-02-06 21:18:46 +0000574 dest = "exit_char",
575 action = "store",
576 type = 'int',
577 help = "ASCII code of special character that is used to exit the application",
578 default = 0x1d
579 )
cliechti9c592b32008-06-16 22:00:14 +0000580
cliechti5370cee2013-10-13 03:08:19 +0000581 group.add_option("--menu-char",
cliechti6c8eb2f2009-07-08 02:10:46 +0000582 dest = "menu_char",
cliechti53edb472009-02-06 21:18:46 +0000583 action = "store",
584 type = 'int',
cliechtidfec0c82009-07-21 01:35:41 +0000585 help = "ASCII code of special character that is used to control miniterm (menu)",
cliechti6c8eb2f2009-07-08 02:10:46 +0000586 default = 0x14
cliechti53edb472009-02-06 21:18:46 +0000587 )
cliechti6385f2c2005-09-21 19:51:19 +0000588
cliechti5370cee2013-10-13 03:08:19 +0000589 parser.add_option_group(group)
590
591 group = optparse.OptionGroup(parser, "Diagnostics")
592
593 group.add_option("-q", "--quiet",
594 dest = "quiet",
595 action = "store_true",
596 help = "suppress non-error messages",
597 default = False
598 )
599
Chris Liechti91090912015-08-05 02:36:14 +0200600 group.add_option("", "--develop",
601 dest = "develop",
602 action = "store_true",
603 help = "show Python traceback on error",
604 default = False
605 )
606
607
608
cliechti5370cee2013-10-13 03:08:19 +0000609 parser.add_option_group(group)
610
611
cliechti6385f2c2005-09-21 19:51:19 +0000612 (options, args) = parser.parse_args()
613
cliechtie0af3972009-07-08 11:03:47 +0000614 options.parity = options.parity.upper()
615 if options.parity not in 'NEOSM':
616 parser.error("invalid parity")
617
cliechti9cf26222006-03-24 20:09:21 +0000618 if options.cr and options.lf:
cliechti53edb472009-02-06 21:18:46 +0000619 parser.error("only one of --cr or --lf can be specified")
620
cliechtic1ca0772009-08-05 12:34:04 +0000621 if options.menu_char == options.exit_char:
cliechti6c8eb2f2009-07-08 02:10:46 +0000622 parser.error('--exit-char can not be the same as --menu-char')
623
624 global EXITCHARCTER, MENUCHARACTER
cliechti9c592b32008-06-16 22:00:14 +0000625 EXITCHARCTER = chr(options.exit_char)
cliechti6c8eb2f2009-07-08 02:10:46 +0000626 MENUCHARACTER = chr(options.menu_char)
cliechti9c592b32008-06-16 22:00:14 +0000627
cliechti9743e222006-04-04 21:48:56 +0000628 port = options.port
629 baudrate = options.baudrate
cliechti9cf26222006-03-24 20:09:21 +0000630 if args:
cliechti9743e222006-04-04 21:48:56 +0000631 if options.port is not None:
632 parser.error("no arguments are allowed, options only when --port is given")
633 port = args.pop(0)
634 if args:
635 try:
636 baudrate = int(args[0])
637 except ValueError:
cliechti53edb472009-02-06 21:18:46 +0000638 parser.error("baud rate must be a number, not %r" % args[0])
cliechti9743e222006-04-04 21:48:56 +0000639 args.pop(0)
640 if args:
641 parser.error("too many arguments")
642 else:
cliechti7d448562014-08-03 21:57:45 +0000643 # no port given on command line -> ask user now
cliechti1351dde2012-04-12 16:47:47 +0000644 if port is None:
645 dump_port_list()
646 port = raw_input('Enter port name:')
cliechti53edb472009-02-06 21:18:46 +0000647
cliechti6385f2c2005-09-21 19:51:19 +0000648 convert_outgoing = CONVERT_CRLF
cliechti9cf26222006-03-24 20:09:21 +0000649 if options.cr:
cliechti6385f2c2005-09-21 19:51:19 +0000650 convert_outgoing = CONVERT_CR
cliechti9cf26222006-03-24 20:09:21 +0000651 elif options.lf:
cliechti6385f2c2005-09-21 19:51:19 +0000652 convert_outgoing = CONVERT_LF
653
654 try:
655 miniterm = Miniterm(
cliechti9743e222006-04-04 21:48:56 +0000656 port,
657 baudrate,
cliechti6385f2c2005-09-21 19:51:19 +0000658 options.parity,
659 rtscts=options.rtscts,
660 xonxoff=options.xonxoff,
661 echo=options.echo,
662 convert_outgoing=convert_outgoing,
663 repr_mode=options.repr_mode,
664 )
Chris Liechti68340d72015-08-03 14:15:48 +0200665 except serial.SerialException as e:
cliechtieb4a14f2009-08-03 23:48:35 +0000666 sys.stderr.write("could not open port %r: %s\n" % (port, e))
Chris Liechti91090912015-08-05 02:36:14 +0200667 if options.develop:
668 raise
cliechti6385f2c2005-09-21 19:51:19 +0000669 sys.exit(1)
670
cliechtibf6bb7d2006-03-30 00:28:18 +0000671 if not options.quiet:
cliechti6fa76fb2009-07-08 23:53:39 +0000672 sys.stderr.write('--- Miniterm on %s: %d,%s,%s,%s ---\n' % (
cliechti9743e222006-04-04 21:48:56 +0000673 miniterm.serial.portstr,
674 miniterm.serial.baudrate,
675 miniterm.serial.bytesize,
676 miniterm.serial.parity,
677 miniterm.serial.stopbits,
678 ))
cliechti6c8eb2f2009-07-08 02:10:46 +0000679 sys.stderr.write('--- Quit: %s | Menu: %s | Help: %s followed by %s ---\n' % (
cliechti9c592b32008-06-16 22:00:14 +0000680 key_description(EXITCHARCTER),
cliechti6c8eb2f2009-07-08 02:10:46 +0000681 key_description(MENUCHARACTER),
682 key_description(MENUCHARACTER),
683 key_description('\x08'),
cliechti9c592b32008-06-16 22:00:14 +0000684 ))
cliechti6fa76fb2009-07-08 23:53:39 +0000685
cliechtib7d746d2006-03-28 22:44:30 +0000686 if options.dtr_state is not None:
cliechtibf6bb7d2006-03-30 00:28:18 +0000687 if not options.quiet:
688 sys.stderr.write('--- forcing DTR %s\n' % (options.dtr_state and 'active' or 'inactive'))
cliechtib7d746d2006-03-28 22:44:30 +0000689 miniterm.serial.setDTR(options.dtr_state)
cliechti6c8eb2f2009-07-08 02:10:46 +0000690 miniterm.dtr_state = options.dtr_state
cliechtibf6bb7d2006-03-30 00:28:18 +0000691 if options.rts_state is not None:
692 if not options.quiet:
693 sys.stderr.write('--- forcing RTS %s\n' % (options.rts_state and 'active' or 'inactive'))
694 miniterm.serial.setRTS(options.rts_state)
cliechti6c8eb2f2009-07-08 02:10:46 +0000695 miniterm.rts_state = options.rts_state
cliechti53edb472009-02-06 21:18:46 +0000696
cliechti5370cee2013-10-13 03:08:19 +0000697 console.setup()
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()