blob: 9c6b4fb6093c660c3f5fb1211b48d070cfa4fc41 [file] [log] [blame]
cliechti576de252002-02-28 23:54:44 +00001#!/usr/bin/env python
Chris Liechtifbdd8a02015-08-09 02:37:45 +02002#
cliechtia128a702004-07-21 22:13:31 +00003# Very simple serial terminal
Chris Liechtifbdd8a02015-08-09 02:37:45 +02004#
Chris Liechti68340d72015-08-03 14:15:48 +02005# (C)2002-2015 Chris Liechti <cliechti@gmx.net>
Chris Liechtifbdd8a02015-08-09 02:37:45 +02006#
7# SPDX-License-Identifier: BSD-3-Clause
cliechtifc9eb382002-03-05 01:12:29 +00008
cliechtia128a702004-07-21 22:13:31 +00009# Input characters are sent directly (only LF -> CR/LF/CRLF translation is
Chris Liechti89eb2472015-08-08 17:06:25 +020010# done), received characters are displayed as is (or escaped through pythons
cliechtia128a702004-07-21 22:13:31 +000011# repr, useful for debug purposes)
cliechti576de252002-02-28 23:54:44 +000012
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020013import codecs
Chris Liechtia1d5c6d2015-08-07 14:41:24 +020014import os
15import sys
16import threading
cliechti21e2c842012-02-21 16:40:27 +000017try:
18 from serial.tools.list_ports import comports
19except ImportError:
20 comports = None
cliechti576de252002-02-28 23:54:44 +000021
Chris Liechtia1d5c6d2015-08-07 14:41:24 +020022import serial
23
24
Chris Liechti68340d72015-08-03 14:15:48 +020025try:
26 raw_input
27except NameError:
28 raw_input = input # in python3 it's "raw"
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020029 unichr = chr
Chris Liechti68340d72015-08-03 14:15:48 +020030
Chris Liechti89eb2472015-08-08 17:06:25 +020031EXITCHARCTER = b'\x1d' # GS/CTRL+]
32MENUCHARACTER = b'\x14' # Menu: CTRL+T
cliechtia128a702004-07-21 22:13:31 +000033
cliechti096e1962012-02-20 01:52:38 +000034DEFAULT_PORT = None
35DEFAULT_BAUDRATE = 9600
36DEFAULT_RTS = None
37DEFAULT_DTR = None
38
cliechti6c8eb2f2009-07-08 02:10:46 +000039
40def key_description(character):
41 """generate a readable description for a key"""
42 ascii_code = ord(character)
43 if ascii_code < 32:
44 return 'Ctrl+%c' % (ord('@') + ascii_code)
45 else:
46 return repr(character)
47
cliechti91165532011-03-18 02:02:52 +000048
cliechti6c8eb2f2009-07-08 02:10:46 +000049# help text, starts with blank line! it's a function so that the current values
50# for the shortcut keys is used and not the value at program start
51def get_help_text():
52 return """
cliechti6963b262010-01-02 03:01:21 +000053--- pySerial (%(version)s) - miniterm - help
cliechti6fa76fb2009-07-08 23:53:39 +000054---
55--- %(exit)-8s Exit program
56--- %(menu)-8s Menu escape key, followed by:
57--- Menu keys:
cliechti258ab0a2011-03-21 23:03:45 +000058--- %(itself)-7s Send the menu character itself to remote
59--- %(exchar)-7s Send the exit character itself to remote
60--- %(info)-7s Show info
61--- %(upload)-7s Upload file (prompt will be shown)
cliechti6fa76fb2009-07-08 23:53:39 +000062--- Toggles:
cliechti258ab0a2011-03-21 23:03:45 +000063--- %(rts)-7s RTS %(echo)-7s local echo
64--- %(dtr)-7s DTR %(break)-7s BREAK
cliechti6fa76fb2009-07-08 23:53:39 +000065---
66--- Port settings (%(menu)s followed by the following):
cliechti258ab0a2011-03-21 23:03:45 +000067--- p change port
68--- 7 8 set data bits
69--- n e o s m change parity (None, Even, Odd, Space, Mark)
70--- 1 2 3 set stop bits (1, 2, 1.5)
71--- b change baud rate
72--- x X disable/enable software flow control
73--- r R disable/enable hardware flow control
cliechti6c8eb2f2009-07-08 02:10:46 +000074""" % {
cliechti8c2ea842011-03-18 01:51:46 +000075 'version': getattr(serial, 'VERSION', 'unknown version'),
cliechti6c8eb2f2009-07-08 02:10:46 +000076 'exit': key_description(EXITCHARCTER),
77 'menu': key_description(MENUCHARACTER),
Chris Liechti89eb2472015-08-08 17:06:25 +020078 'rts': key_description(b'\x12'),
Chris Liechti89eb2472015-08-08 17:06:25 +020079 'dtr': key_description(b'\x04'),
Chris Liechti89eb2472015-08-08 17:06:25 +020080 'break': key_description(b'\x02'),
81 'echo': key_description(b'\x05'),
82 'info': key_description(b'\x09'),
83 'upload': key_description(b'\x15'),
cliechti6fa76fb2009-07-08 23:53:39 +000084 'itself': key_description(MENUCHARACTER),
85 'exchar': key_description(EXITCHARCTER),
cliechti6c8eb2f2009-07-08 02:10:46 +000086}
87
cliechti393fa0e2011-08-22 00:53:36 +000088
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020089class ConsoleBase(object):
90 def __init__(self):
91 if sys.version_info >= (3, 0):
92 self.byte_output = sys.stdout.buffer
93 else:
94 self.byte_output = sys.stdout
95 self.output = sys.stdout
cliechtif467aa82013-10-13 21:36:49 +000096
Chris Liechtic7a5d4c2015-08-11 23:32:20 +020097 def setup(self):
98 pass # Do nothing for 'nt'
cliechtif467aa82013-10-13 21:36:49 +000099
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200100 def cleanup(self):
101 pass # Do nothing for 'nt'
102
103 def getkey(self):
104 return None
105
106 def write_bytes(self, s):
107 self.byte_output.write(s)
108 self.byte_output.flush()
109
110 def write(self, s):
111 self.output.write(s)
112 self.output.flush()
113
cliechti9c592b32008-06-16 22:00:14 +0000114
cliechtifc9eb382002-03-05 01:12:29 +0000115if os.name == 'nt':
cliechti576de252002-02-28 23:54:44 +0000116 import msvcrt
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200117 import ctypes
118 class Console(ConsoleBase):
cliechti3a8bf092008-09-17 11:26:53 +0000119 def getkey(self):
cliechti91165532011-03-18 02:02:52 +0000120 while True:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200121 z = msvcrt.getwch()
122 if z == '\r':
123 return '\n'
124 elif z in '\x00\x0e': # functions keys, ignore
125 msvcrt.getwch()
cliechti9c592b32008-06-16 22:00:14 +0000126 else:
cliechti9c592b32008-06-16 22:00:14 +0000127 return z
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200128
Chris Liechti89eb2472015-08-08 17:06:25 +0200129 def write(self, s):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200130 # works, kind of.. can't print unicode
131 self.byte_output.write(s.encode(sys.stdout.encoding, 'replace'))
132 #~ sys.stdout.write(s) # fails with encoding errors
133 #~ for byte in data: # fails for python3 as it returns ints instead of b''
134 #~ for x in range(len(s)):
135 #~ byte = s[x:x+1]
136 #~ msvcrt.putwch(byte) # blocks?!? non-overlapped win io?
137
138 def write_bytes(self, data):
139 #~ for byte in data: # fails for python3 as it returns ints instead of b''
140 for x in range(len(data)):
141 byte = data[x:x+1]
142 msvcrt.putch(byte)
cliechti53edb472009-02-06 21:18:46 +0000143
cliechti576de252002-02-28 23:54:44 +0000144elif os.name == 'posix':
Chris Liechtia1d5c6d2015-08-07 14:41:24 +0200145 import atexit
146 import termios
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200147 class Console(ConsoleBase):
cliechti9c592b32008-06-16 22:00:14 +0000148 def __init__(self):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200149 super(Console, self).__init__()
cliechti9c592b32008-06-16 22:00:14 +0000150 self.fd = sys.stdin.fileno()
cliechti5370cee2013-10-13 03:08:19 +0000151 self.old = None
Chris Liechti89eb2472015-08-08 17:06:25 +0200152 atexit.register(self.cleanup)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200153 if sys.version_info < (3, 0):
154 sys.stdin = codecs.getreader(sys.stdin.encoding)(sys.stdin)
cliechti9c592b32008-06-16 22:00:14 +0000155
156 def setup(self):
157 self.old = termios.tcgetattr(self.fd)
158 new = termios.tcgetattr(self.fd)
159 new[3] = new[3] & ~termios.ICANON & ~termios.ECHO & ~termios.ISIG
160 new[6][termios.VMIN] = 1
161 new[6][termios.VTIME] = 0
162 termios.tcsetattr(self.fd, termios.TCSANOW, new)
cliechti53edb472009-02-06 21:18:46 +0000163
cliechti9c592b32008-06-16 22:00:14 +0000164 def getkey(self):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200165 return sys.stdin.read(1)
166 #~ c = os.read(self.fd, 1)
167 #~ return c
cliechti53edb472009-02-06 21:18:46 +0000168
cliechti9c592b32008-06-16 22:00:14 +0000169 def cleanup(self):
cliechti5370cee2013-10-13 03:08:19 +0000170 if self.old is not None:
171 termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old)
cliechti9c592b32008-06-16 22:00:14 +0000172
cliechti576de252002-02-28 23:54:44 +0000173else:
cliechti8c2ea842011-03-18 01:51:46 +0000174 raise NotImplementedError("Sorry no implementation for your platform (%s) available." % sys.platform)
cliechti576de252002-02-28 23:54:44 +0000175
cliechti6fa76fb2009-07-08 23:53:39 +0000176
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200177# XXX how to handle multi byte sequences like CRLF?
178# codecs.IncrementalEncoder would be a good choice
179
180class Transform(object):
181 def input(self, text):
182 """text received from serial port"""
183 return text
184
185 def output(self, text):
186 """text to be sent to serial port"""
187 return text
188
189 def echo(self, text):
190 """text to be sent but displayed on console"""
191 return text
192
193class CRLF(Transform):
194 """ENTER sends CR+LF"""
195 def input(self, text):
196 return text.replace('\r\n', '\n')
197
198 def output(self, text):
199 return text.replace('\n', '\r\n')
200
201class CR(Transform):
202 """ENTER sends CR"""
203 def input(self, text):
204 return text.replace('\r', '\n')
205
206 def output(self, text):
207 return text.replace('\n', '\r')
208
209class LF(Transform):
210 """ENTER sends LF"""
211
212
213class NoTerminal(Transform):
214 """remove typical terminal control codes from input"""
215 def input(self, text):
Chris Liechti7e9cfd42015-08-12 15:28:19 +0200216 return ''.join(t if t >= ' ' or t in '\r\n\b\t' else unichr(0x2400 + ord(t)) for t in text)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200217
218 echo = input
219
220
221class NoControls(Transform):
222 """Remove all control codes, incl. CR+LF"""
223 def input(self, text):
224 return ''.join(t if t >= ' ' else unichr(0x2400 + ord(t)) for t in text)
225
226 echo = input
227
228
229class HexDump(Transform):
230 """Complete hex dump"""
231 def input(self, text):
232 return ''.join('{:02x} '.format(ord(t)) for t in text)
233
234 echo = input
235
236
237class Printable(Transform):
Chris Liechti7e9cfd42015-08-12 15:28:19 +0200238 """Show decimal code for all non-ASCII characters and most control codes"""
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200239 def input(self, text):
240 r = []
241 for t in text:
Chris Liechti7e9cfd42015-08-12 15:28:19 +0200242 if ' ' <= t < '\x7f' or t in '\r\n\b\t':
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200243 r.append(t)
244 else:
245 r.extend(unichr(0x2080 + ord(d) - 48) for d in '{:d}'.format(ord(t)))
246 r.append(' ')
247 return ''.join(r)
248
249 echo = input
250
251
252
253class Colorize(Transform):
254 """Apply different colors for input and echo"""
255 def __init__(self):
256 # XXX make it configurable, use colorama?
257 self.input_color = '\x1b[37m'
258 self.echo_color = '\x1b[31m'
259
260 def input(self, text):
261 return self.input_color + text
262
263 def echo(self, text):
264 return self.echo_color + text
265
266class DebugIO(Transform):
267 """Apply different colors for input and echo"""
268 def input(self, text):
269 sys.stderr.write('in: %r\n' % text)
270 return text
271
272 def echo(self, text):
273 sys.stderr.write('out: %r\n' % text)
274 return text
275
276# other ideas:
277# - add date/time for each newline
278# - insert newline after: a) timeout b) packet end character
279
280TRANSFORMATIONS = {
281 'crlf': CRLF,
282 'cr': CR,
283 'lf': LF,
284 'default': NoTerminal,
285 'nocontrol': NoControls,
286 'printable': Printable,
287 'hex': HexDump,
288 'colorize': Colorize,
289 'debug': DebugIO,
290 }
291
292
cliechti1351dde2012-04-12 16:47:47 +0000293def dump_port_list():
294 if comports:
295 sys.stderr.write('\n--- Available ports:\n')
296 for port, desc, hwid in sorted(comports()):
297 #~ sys.stderr.write('--- %-20s %s [%s]\n' % (port, desc, hwid))
298 sys.stderr.write('--- %-20s %s\n' % (port, desc))
299
300
cliechti8c2ea842011-03-18 01:51:46 +0000301class Miniterm(object):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200302 def __init__(self, port, baudrate, parity, rtscts, xonxoff, echo=False, transformations=()):
Chris Liechti89eb2472015-08-08 17:06:25 +0200303 self.console = Console()
Chris Liechtia1d5c6d2015-08-07 14:41:24 +0200304 self.serial = serial.serial_for_url(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1)
cliechti6385f2c2005-09-21 19:51:19 +0000305 self.echo = echo
cliechti6c8eb2f2009-07-08 02:10:46 +0000306 self.dtr_state = True
307 self.rts_state = True
308 self.break_state = False
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200309 self.raw = False
310 self.input_encoding = 'latin1'
311 self.input_error_handling = 'replace'
312 self.output_encoding = 'latin1'
313 self.output_error_handling = 'ignore'
314 self.transformations = [TRANSFORMATIONS[t]() for t in transformations]
315 self.transformation_names = transformations
cliechti576de252002-02-28 23:54:44 +0000316
cliechti8c2ea842011-03-18 01:51:46 +0000317 def _start_reader(self):
318 """Start reader thread"""
319 self._reader_alive = True
cliechti6fa76fb2009-07-08 23:53:39 +0000320 # start serial->console thread
cliechti6385f2c2005-09-21 19:51:19 +0000321 self.receiver_thread = threading.Thread(target=self.reader)
cliechti8c2ea842011-03-18 01:51:46 +0000322 self.receiver_thread.setDaemon(True)
cliechti6385f2c2005-09-21 19:51:19 +0000323 self.receiver_thread.start()
cliechti8c2ea842011-03-18 01:51:46 +0000324
325 def _stop_reader(self):
326 """Stop reader thread only, wait for clean exit of thread"""
327 self._reader_alive = False
328 self.receiver_thread.join()
329
330
331 def start(self):
332 self.alive = True
333 self._start_reader()
cliechti6fa76fb2009-07-08 23:53:39 +0000334 # enter console->serial loop
cliechti6385f2c2005-09-21 19:51:19 +0000335 self.transmitter_thread = threading.Thread(target=self.writer)
cliechti8c2ea842011-03-18 01:51:46 +0000336 self.transmitter_thread.setDaemon(True)
cliechti6385f2c2005-09-21 19:51:19 +0000337 self.transmitter_thread.start()
Chris Liechti89eb2472015-08-08 17:06:25 +0200338 self.console.setup()
cliechti53edb472009-02-06 21:18:46 +0000339
cliechti6385f2c2005-09-21 19:51:19 +0000340 def stop(self):
341 self.alive = False
cliechti53edb472009-02-06 21:18:46 +0000342
cliechtibf6bb7d2006-03-30 00:28:18 +0000343 def join(self, transmit_only=False):
cliechti6385f2c2005-09-21 19:51:19 +0000344 self.transmitter_thread.join()
cliechtibf6bb7d2006-03-30 00:28:18 +0000345 if not transmit_only:
346 self.receiver_thread.join()
cliechti6385f2c2005-09-21 19:51:19 +0000347
cliechti6c8eb2f2009-07-08 02:10:46 +0000348 def dump_port_settings(self):
cliechti6fa76fb2009-07-08 23:53:39 +0000349 sys.stderr.write("\n--- Settings: %s %s,%s,%s,%s\n" % (
cliechti258ab0a2011-03-21 23:03:45 +0000350 self.serial.portstr,
351 self.serial.baudrate,
352 self.serial.bytesize,
353 self.serial.parity,
354 self.serial.stopbits))
355 sys.stderr.write('--- RTS: %-8s DTR: %-8s BREAK: %-8s\n' % (
356 (self.rts_state and 'active' or 'inactive'),
357 (self.dtr_state and 'active' or 'inactive'),
358 (self.break_state and 'active' or 'inactive')))
cliechti10114572009-08-05 23:40:50 +0000359 try:
cliechti258ab0a2011-03-21 23:03:45 +0000360 sys.stderr.write('--- CTS: %-8s DSR: %-8s RI: %-8s CD: %-8s\n' % (
361 (self.serial.getCTS() and 'active' or 'inactive'),
362 (self.serial.getDSR() and 'active' or 'inactive'),
363 (self.serial.getRI() and 'active' or 'inactive'),
364 (self.serial.getCD() and 'active' or 'inactive')))
cliechti10114572009-08-05 23:40:50 +0000365 except serial.SerialException:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200366 # on RFC 2217 ports, it can happen to no modem state notification was
cliechti10114572009-08-05 23:40:50 +0000367 # yet received. ignore this error.
368 pass
cliechti258ab0a2011-03-21 23:03:45 +0000369 sys.stderr.write('--- software flow control: %s\n' % (self.serial.xonxoff and 'active' or 'inactive'))
370 sys.stderr.write('--- hardware flow control: %s\n' % (self.serial.rtscts and 'active' or 'inactive'))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200371 #~ sys.stderr.write('--- data escaping: %s linefeed: %s\n' % (
372 #~ REPR_MODES[self.repr_mode],
373 #~ LF_MODES[self.convert_outgoing]))
374 sys.stderr.write('--- serial input encoding: %s\n' % (self.input_encoding,))
375 sys.stderr.write('--- serial output encoding: %s\n' % (self.output_encoding,))
376 sys.stderr.write('--- transformations: %s\n' % ' '.join(self.transformation_names))
cliechti6c8eb2f2009-07-08 02:10:46 +0000377
cliechti6385f2c2005-09-21 19:51:19 +0000378 def reader(self):
379 """loop and copy serial->console"""
cliechti6963b262010-01-02 03:01:21 +0000380 try:
cliechti8c2ea842011-03-18 01:51:46 +0000381 while self.alive and self._reader_alive:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200382 data = self.serial.read(1) + self.serial.read(self.serial.inWaiting())
383 if data:
384 if self.raw:
385 self.console.write_bytes(data)
cliechti6963b262010-01-02 03:01:21 +0000386 else:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200387 text = codecs.decode(
388 data,
389 self.input_encoding,
390 self.input_error_handling)
391 for transformation in self.transformations:
392 text = transformation.input(text)
393 self.console.write(text)
Chris Liechti68340d72015-08-03 14:15:48 +0200394 except serial.SerialException as e:
cliechti6963b262010-01-02 03:01:21 +0000395 self.alive = False
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200396 # XXX would be nice if the writer could be interrupted at this
397 # point... to exit completely
cliechti6963b262010-01-02 03:01:21 +0000398 raise
cliechti576de252002-02-28 23:54:44 +0000399
cliechti576de252002-02-28 23:54:44 +0000400
cliechti6385f2c2005-09-21 19:51:19 +0000401 def writer(self):
cliechti8c2ea842011-03-18 01:51:46 +0000402 """\
403 Loop and copy console->serial until EXITCHARCTER character is
404 found. When MENUCHARACTER is found, interpret the next key
405 locally.
cliechti6c8eb2f2009-07-08 02:10:46 +0000406 """
407 menu_active = False
408 try:
409 while self.alive:
410 try:
Chris Liechti89eb2472015-08-08 17:06:25 +0200411 c = self.console.getkey()
cliechti6c8eb2f2009-07-08 02:10:46 +0000412 except KeyboardInterrupt:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200413 c = '\x03'
cliechti6c8eb2f2009-07-08 02:10:46 +0000414 if menu_active:
415 if c == MENUCHARACTER or c == EXITCHARCTER: # Menu character again/exit char -> send itself
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200416 b = codecs.encode(
417 c,
418 self.output_encoding,
419 self.output_error_handling)
420 self.serial.write(b)
cliechti6c8eb2f2009-07-08 02:10:46 +0000421 if self.echo:
Chris Liechti89eb2472015-08-08 17:06:25 +0200422 self.console.write(c)
423 elif c == b'\x15': # CTRL+U -> upload file
cliechti6fa76fb2009-07-08 23:53:39 +0000424 sys.stderr.write('\n--- File to upload: ')
cliechti6c8eb2f2009-07-08 02:10:46 +0000425 sys.stderr.flush()
Chris Liechti89eb2472015-08-08 17:06:25 +0200426 self.console.cleanup()
cliechti6c8eb2f2009-07-08 02:10:46 +0000427 filename = sys.stdin.readline().rstrip('\r\n')
428 if filename:
429 try:
Chris Liechti89eb2472015-08-08 17:06:25 +0200430 with open(filename, 'rb') as f:
431 sys.stderr.write('--- Sending file %s ---\n' % filename)
432 while True:
433 block = f.read(1024)
434 if not block:
435 break
436 self.serial.write(block)
437 # Wait for output buffer to drain.
438 self.serial.flush()
439 sys.stderr.write('.') # Progress indicator.
cliechti6fa76fb2009-07-08 23:53:39 +0000440 sys.stderr.write('\n--- File %s sent ---\n' % filename)
Chris Liechti68340d72015-08-03 14:15:48 +0200441 except IOError as e:
cliechti6fa76fb2009-07-08 23:53:39 +0000442 sys.stderr.write('--- ERROR opening file %s: %s ---\n' % (filename, e))
Chris Liechti89eb2472015-08-08 17:06:25 +0200443 self.console.setup()
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200444 elif c in '\x08hH?': # CTRL+H, h, H, ? -> Show help
cliechti6c8eb2f2009-07-08 02:10:46 +0000445 sys.stderr.write(get_help_text())
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200446 elif c == '\x12': # CTRL+R -> Toggle RTS
cliechti6c8eb2f2009-07-08 02:10:46 +0000447 self.rts_state = not self.rts_state
448 self.serial.setRTS(self.rts_state)
cliechti6fa76fb2009-07-08 23:53:39 +0000449 sys.stderr.write('--- RTS %s ---\n' % (self.rts_state and 'active' or 'inactive'))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200450 elif c == '\x04': # CTRL+D -> Toggle DTR
cliechti6c8eb2f2009-07-08 02:10:46 +0000451 self.dtr_state = not self.dtr_state
452 self.serial.setDTR(self.dtr_state)
cliechti6fa76fb2009-07-08 23:53:39 +0000453 sys.stderr.write('--- DTR %s ---\n' % (self.dtr_state and 'active' or 'inactive'))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200454 elif c == '\x02': # CTRL+B -> toggle BREAK condition
cliechti6c8eb2f2009-07-08 02:10:46 +0000455 self.break_state = not self.break_state
456 self.serial.setBreak(self.break_state)
cliechti6fa76fb2009-07-08 23:53:39 +0000457 sys.stderr.write('--- BREAK %s ---\n' % (self.break_state and 'active' or 'inactive'))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200458 elif c == '\x05': # CTRL+E -> toggle local echo
cliechtie0af3972009-07-08 11:03:47 +0000459 self.echo = not self.echo
cliechti6fa76fb2009-07-08 23:53:39 +0000460 sys.stderr.write('--- local echo %s ---\n' % (self.echo and 'active' or 'inactive'))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200461 elif c == '\x09': # CTRL+I -> info
cliechti6c8eb2f2009-07-08 02:10:46 +0000462 self.dump_port_settings()
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200463 #~ elif c == '\x01': # CTRL+A -> cycle escape mode
464 #~ elif c == '\x0c': # CTRL+L -> cycle linefeed mode
465 elif c in 'pP': # P -> change port
cliechti1351dde2012-04-12 16:47:47 +0000466 dump_port_list()
cliechti21e2c842012-02-21 16:40:27 +0000467 sys.stderr.write('--- Enter port name: ')
cliechti8c2ea842011-03-18 01:51:46 +0000468 sys.stderr.flush()
Chris Liechti89eb2472015-08-08 17:06:25 +0200469 self.console.cleanup()
cliechti258ab0a2011-03-21 23:03:45 +0000470 try:
471 port = sys.stdin.readline().strip()
472 except KeyboardInterrupt:
473 port = None
Chris Liechti89eb2472015-08-08 17:06:25 +0200474 self.console.setup()
cliechti258ab0a2011-03-21 23:03:45 +0000475 if port and port != self.serial.port:
cliechti8c2ea842011-03-18 01:51:46 +0000476 # reader thread needs to be shut down
477 self._stop_reader()
478 # save settings
479 settings = self.serial.getSettingsDict()
cliechti8c2ea842011-03-18 01:51:46 +0000480 try:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200481 new_serial = serial.serial_for_url(port, do_not_open=True)
cliechti258ab0a2011-03-21 23:03:45 +0000482 # restore settings and open
483 new_serial.applySettingsDict(settings)
484 new_serial.open()
485 new_serial.setRTS(self.rts_state)
486 new_serial.setDTR(self.dtr_state)
487 new_serial.setBreak(self.break_state)
Chris Liechti68340d72015-08-03 14:15:48 +0200488 except Exception as e:
cliechti258ab0a2011-03-21 23:03:45 +0000489 sys.stderr.write('--- ERROR opening new port: %s ---\n' % (e,))
490 new_serial.close()
491 else:
492 self.serial.close()
493 self.serial = new_serial
494 sys.stderr.write('--- Port changed to: %s ---\n' % (self.serial.port,))
cliechti91165532011-03-18 02:02:52 +0000495 # and restart the reader thread
cliechti8c2ea842011-03-18 01:51:46 +0000496 self._start_reader()
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200497 elif c in 'bB': # B -> change baudrate
cliechti6fa76fb2009-07-08 23:53:39 +0000498 sys.stderr.write('\n--- Baudrate: ')
cliechti6c8eb2f2009-07-08 02:10:46 +0000499 sys.stderr.flush()
Chris Liechti89eb2472015-08-08 17:06:25 +0200500 self.console.cleanup()
cliechti6c8eb2f2009-07-08 02:10:46 +0000501 backup = self.serial.baudrate
502 try:
503 self.serial.baudrate = int(sys.stdin.readline().strip())
Chris Liechti68340d72015-08-03 14:15:48 +0200504 except ValueError as e:
cliechti6fa76fb2009-07-08 23:53:39 +0000505 sys.stderr.write('--- ERROR setting baudrate: %s ---\n' % (e,))
cliechti6c8eb2f2009-07-08 02:10:46 +0000506 self.serial.baudrate = backup
cliechti6fa76fb2009-07-08 23:53:39 +0000507 else:
508 self.dump_port_settings()
Chris Liechti89eb2472015-08-08 17:06:25 +0200509 self.console.setup()
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200510 elif c == '8': # 8 -> change to 8 bits
cliechti6c8eb2f2009-07-08 02:10:46 +0000511 self.serial.bytesize = serial.EIGHTBITS
512 self.dump_port_settings()
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200513 elif c == '7': # 7 -> change to 8 bits
cliechti6c8eb2f2009-07-08 02:10:46 +0000514 self.serial.bytesize = serial.SEVENBITS
515 self.dump_port_settings()
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200516 elif c in 'eE': # E -> change to even parity
cliechti6c8eb2f2009-07-08 02:10:46 +0000517 self.serial.parity = serial.PARITY_EVEN
518 self.dump_port_settings()
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200519 elif c in 'oO': # O -> change to odd parity
cliechti6c8eb2f2009-07-08 02:10:46 +0000520 self.serial.parity = serial.PARITY_ODD
521 self.dump_port_settings()
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200522 elif c in 'mM': # M -> change to mark parity
cliechti6c8eb2f2009-07-08 02:10:46 +0000523 self.serial.parity = serial.PARITY_MARK
524 self.dump_port_settings()
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200525 elif c in 'sS': # S -> change to space parity
cliechti6c8eb2f2009-07-08 02:10:46 +0000526 self.serial.parity = serial.PARITY_SPACE
527 self.dump_port_settings()
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200528 elif c in 'nN': # N -> change to no parity
cliechti6c8eb2f2009-07-08 02:10:46 +0000529 self.serial.parity = serial.PARITY_NONE
530 self.dump_port_settings()
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200531 elif c == '1': # 1 -> change to 1 stop bits
cliechti6c8eb2f2009-07-08 02:10:46 +0000532 self.serial.stopbits = serial.STOPBITS_ONE
533 self.dump_port_settings()
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200534 elif c == '2': # 2 -> change to 2 stop bits
cliechti6c8eb2f2009-07-08 02:10:46 +0000535 self.serial.stopbits = serial.STOPBITS_TWO
536 self.dump_port_settings()
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200537 elif c == '3': # 3 -> change to 1.5 stop bits
cliechti6c8eb2f2009-07-08 02:10:46 +0000538 self.serial.stopbits = serial.STOPBITS_ONE_POINT_FIVE
539 self.dump_port_settings()
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200540 elif c in 'xX': # X -> change software flow control
541 self.serial.xonxoff = (c == 'X')
cliechti6c8eb2f2009-07-08 02:10:46 +0000542 self.dump_port_settings()
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200543 elif c in 'rR': # R -> change hardware flow control
544 self.serial.rtscts = (c == 'R')
cliechti6c8eb2f2009-07-08 02:10:46 +0000545 self.dump_port_settings()
546 else:
cliechti6fa76fb2009-07-08 23:53:39 +0000547 sys.stderr.write('--- unknown menu character %s --\n' % key_description(c))
cliechti6c8eb2f2009-07-08 02:10:46 +0000548 menu_active = False
549 elif c == MENUCHARACTER: # next char will be for menu
550 menu_active = True
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200551 elif c == EXITCHARCTER:
cliechti6c8eb2f2009-07-08 02:10:46 +0000552 self.stop()
553 break # exit app
cliechti6c8eb2f2009-07-08 02:10:46 +0000554 else:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200555 #~ if self.raw:
556 text = c
557 echo_text = text
558 for transformation in self.transformations:
559 text = transformation.output(text)
560 echo_text = transformation.echo(echo_text)
561 b = codecs.encode(
562 text,
563 self.output_encoding,
564 self.output_error_handling)
565 self.serial.write(b)
cliechti6c8eb2f2009-07-08 02:10:46 +0000566 if self.echo:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200567 self.console.write(echo_text)
cliechti6c8eb2f2009-07-08 02:10:46 +0000568 except:
569 self.alive = False
570 raise
cliechti6385f2c2005-09-21 19:51:19 +0000571
572def main():
573 import optparse
574
cliechti53edb472009-02-06 21:18:46 +0000575 parser = optparse.OptionParser(
576 usage = "%prog [options] [port [baudrate]]",
577 description = "Miniterm - A simple terminal program for the serial port."
578 )
cliechti6385f2c2005-09-21 19:51:19 +0000579
cliechti5370cee2013-10-13 03:08:19 +0000580 group = optparse.OptionGroup(parser, "Port settings")
581
582 group.add_option("-p", "--port",
cliechti53edb472009-02-06 21:18:46 +0000583 dest = "port",
cliechti91165532011-03-18 02:02:52 +0000584 help = "port, a number or a device name. (deprecated option, use parameter instead)",
cliechti096e1962012-02-20 01:52:38 +0000585 default = DEFAULT_PORT
cliechti53edb472009-02-06 21:18:46 +0000586 )
cliechti6385f2c2005-09-21 19:51:19 +0000587
cliechti5370cee2013-10-13 03:08:19 +0000588 group.add_option("-b", "--baud",
cliechti53edb472009-02-06 21:18:46 +0000589 dest = "baudrate",
590 action = "store",
591 type = 'int',
cliechti6fa76fb2009-07-08 23:53:39 +0000592 help = "set baud rate, default %default",
cliechti096e1962012-02-20 01:52:38 +0000593 default = DEFAULT_BAUDRATE
cliechti53edb472009-02-06 21:18:46 +0000594 )
595
cliechti5370cee2013-10-13 03:08:19 +0000596 group.add_option("--parity",
cliechti53edb472009-02-06 21:18:46 +0000597 dest = "parity",
598 action = "store",
cliechtie0af3972009-07-08 11:03:47 +0000599 help = "set parity, one of [N, E, O, S, M], default=N",
cliechti53edb472009-02-06 21:18:46 +0000600 default = 'N'
601 )
602
cliechti5370cee2013-10-13 03:08:19 +0000603 group.add_option("--rtscts",
cliechti53edb472009-02-06 21:18:46 +0000604 dest = "rtscts",
605 action = "store_true",
606 help = "enable RTS/CTS flow control (default off)",
607 default = False
608 )
609
cliechti5370cee2013-10-13 03:08:19 +0000610 group.add_option("--xonxoff",
cliechti53edb472009-02-06 21:18:46 +0000611 dest = "xonxoff",
612 action = "store_true",
613 help = "enable software flow control (default off)",
614 default = False
615 )
616
cliechti5370cee2013-10-13 03:08:19 +0000617 group.add_option("--rts",
618 dest = "rts_state",
619 action = "store",
620 type = 'int',
621 help = "set initial RTS line state (possible values: 0, 1)",
622 default = DEFAULT_RTS
623 )
624
625 group.add_option("--dtr",
626 dest = "dtr_state",
627 action = "store",
628 type = 'int',
629 help = "set initial DTR line state (possible values: 0, 1)",
630 default = DEFAULT_DTR
631 )
632
633 parser.add_option_group(group)
634
635 group = optparse.OptionGroup(parser, "Data handling")
636
637 group.add_option("-e", "--echo",
638 dest = "echo",
639 action = "store_true",
640 help = "enable local echo (default off)",
641 default = False
642 )
643
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200644 group.add_option("-t", "--transformation",
645 dest = "transformations",
646 action = "append",
647 help = "Add text transformation",
648 default = []
649 )
650
cliechti5370cee2013-10-13 03:08:19 +0000651 group.add_option("--cr",
cliechti53edb472009-02-06 21:18:46 +0000652 dest = "cr",
653 action = "store_true",
654 help = "do not send CR+LF, send CR only",
655 default = False
656 )
657
cliechti5370cee2013-10-13 03:08:19 +0000658 group.add_option("--lf",
cliechti53edb472009-02-06 21:18:46 +0000659 dest = "lf",
660 action = "store_true",
661 help = "do not send CR+LF, send LF only",
662 default = False
663 )
664
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200665 group.add_option("--raw",
666 dest = "raw",
667 action = "store_true",
668 help = "Do no apply any encodings/transformations",
669 default = False
cliechti53edb472009-02-06 21:18:46 +0000670 )
cliechti6385f2c2005-09-21 19:51:19 +0000671
cliechti5370cee2013-10-13 03:08:19 +0000672 parser.add_option_group(group)
cliechtib7d746d2006-03-28 22:44:30 +0000673
cliechti5370cee2013-10-13 03:08:19 +0000674 group = optparse.OptionGroup(parser, "Hotkeys")
cliechtibf6bb7d2006-03-30 00:28:18 +0000675
cliechti5370cee2013-10-13 03:08:19 +0000676 group.add_option("--exit-char",
cliechti53edb472009-02-06 21:18:46 +0000677 dest = "exit_char",
678 action = "store",
679 type = 'int',
680 help = "ASCII code of special character that is used to exit the application",
681 default = 0x1d
682 )
cliechti9c592b32008-06-16 22:00:14 +0000683
cliechti5370cee2013-10-13 03:08:19 +0000684 group.add_option("--menu-char",
cliechti6c8eb2f2009-07-08 02:10:46 +0000685 dest = "menu_char",
cliechti53edb472009-02-06 21:18:46 +0000686 action = "store",
687 type = 'int',
cliechtidfec0c82009-07-21 01:35:41 +0000688 help = "ASCII code of special character that is used to control miniterm (menu)",
cliechti6c8eb2f2009-07-08 02:10:46 +0000689 default = 0x14
cliechti53edb472009-02-06 21:18:46 +0000690 )
cliechti6385f2c2005-09-21 19:51:19 +0000691
cliechti5370cee2013-10-13 03:08:19 +0000692 parser.add_option_group(group)
693
694 group = optparse.OptionGroup(parser, "Diagnostics")
695
696 group.add_option("-q", "--quiet",
697 dest = "quiet",
698 action = "store_true",
699 help = "suppress non-error messages",
700 default = False
701 )
702
Chris Liechti91090912015-08-05 02:36:14 +0200703 group.add_option("", "--develop",
704 dest = "develop",
705 action = "store_true",
706 help = "show Python traceback on error",
707 default = False
708 )
709
cliechti5370cee2013-10-13 03:08:19 +0000710 parser.add_option_group(group)
711
712
cliechti6385f2c2005-09-21 19:51:19 +0000713 (options, args) = parser.parse_args()
714
cliechtie0af3972009-07-08 11:03:47 +0000715 options.parity = options.parity.upper()
716 if options.parity not in 'NEOSM':
717 parser.error("invalid parity")
718
cliechti9cf26222006-03-24 20:09:21 +0000719 if options.cr and options.lf:
cliechti53edb472009-02-06 21:18:46 +0000720 parser.error("only one of --cr or --lf can be specified")
721
cliechtic1ca0772009-08-05 12:34:04 +0000722 if options.menu_char == options.exit_char:
cliechti6c8eb2f2009-07-08 02:10:46 +0000723 parser.error('--exit-char can not be the same as --menu-char')
724
725 global EXITCHARCTER, MENUCHARACTER
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200726 EXITCHARCTER = chr(options.exit_char)
727 MENUCHARACTER = chr(options.menu_char)
cliechti9c592b32008-06-16 22:00:14 +0000728
cliechti9743e222006-04-04 21:48:56 +0000729 port = options.port
730 baudrate = options.baudrate
cliechti9cf26222006-03-24 20:09:21 +0000731 if args:
cliechti9743e222006-04-04 21:48:56 +0000732 if options.port is not None:
733 parser.error("no arguments are allowed, options only when --port is given")
734 port = args.pop(0)
735 if args:
736 try:
737 baudrate = int(args[0])
738 except ValueError:
cliechti53edb472009-02-06 21:18:46 +0000739 parser.error("baud rate must be a number, not %r" % args[0])
cliechti9743e222006-04-04 21:48:56 +0000740 args.pop(0)
741 if args:
742 parser.error("too many arguments")
743 else:
cliechti7d448562014-08-03 21:57:45 +0000744 # no port given on command line -> ask user now
cliechti1351dde2012-04-12 16:47:47 +0000745 if port is None:
746 dump_port_list()
747 port = raw_input('Enter port name:')
cliechti53edb472009-02-06 21:18:46 +0000748
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200749 if options.transformations:
750 if 'help' in options.transformations:
751 sys.stderr.write('Available Transformations:\n')
752 sys.stderr.write('\n'.join('{:<20} = {.__doc__}'.format(k,v) for k,v in sorted(TRANSFORMATIONS.items())))
753 sys.stderr.write('\n')
754 sys.exit(1)
755 transformations = options.transformations
756 else:
757 transformations = ['default']
758
cliechti9cf26222006-03-24 20:09:21 +0000759 if options.cr:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200760 transformations.append('cr')
cliechti9cf26222006-03-24 20:09:21 +0000761 elif options.lf:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200762 transformations.append('lf')
763 else:
764 transformations.append('crlf')
cliechti6385f2c2005-09-21 19:51:19 +0000765
766 try:
767 miniterm = Miniterm(
cliechti9743e222006-04-04 21:48:56 +0000768 port,
769 baudrate,
cliechti6385f2c2005-09-21 19:51:19 +0000770 options.parity,
771 rtscts=options.rtscts,
772 xonxoff=options.xonxoff,
773 echo=options.echo,
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200774 transformations=transformations,
cliechti6385f2c2005-09-21 19:51:19 +0000775 )
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200776 miniterm.raw = options.raw
Chris Liechti68340d72015-08-03 14:15:48 +0200777 except serial.SerialException as e:
cliechtieb4a14f2009-08-03 23:48:35 +0000778 sys.stderr.write("could not open port %r: %s\n" % (port, e))
Chris Liechti91090912015-08-05 02:36:14 +0200779 if options.develop:
780 raise
cliechti6385f2c2005-09-21 19:51:19 +0000781 sys.exit(1)
782
cliechtibf6bb7d2006-03-30 00:28:18 +0000783 if not options.quiet:
cliechti6fa76fb2009-07-08 23:53:39 +0000784 sys.stderr.write('--- Miniterm on %s: %d,%s,%s,%s ---\n' % (
cliechti9743e222006-04-04 21:48:56 +0000785 miniterm.serial.portstr,
786 miniterm.serial.baudrate,
787 miniterm.serial.bytesize,
788 miniterm.serial.parity,
789 miniterm.serial.stopbits,
790 ))
cliechti6c8eb2f2009-07-08 02:10:46 +0000791 sys.stderr.write('--- Quit: %s | Menu: %s | Help: %s followed by %s ---\n' % (
cliechti9c592b32008-06-16 22:00:14 +0000792 key_description(EXITCHARCTER),
cliechti6c8eb2f2009-07-08 02:10:46 +0000793 key_description(MENUCHARACTER),
794 key_description(MENUCHARACTER),
Chris Liechti89eb2472015-08-08 17:06:25 +0200795 key_description(b'\x08'),
cliechti9c592b32008-06-16 22:00:14 +0000796 ))
cliechti6fa76fb2009-07-08 23:53:39 +0000797
cliechtib7d746d2006-03-28 22:44:30 +0000798 if options.dtr_state is not None:
cliechtibf6bb7d2006-03-30 00:28:18 +0000799 if not options.quiet:
800 sys.stderr.write('--- forcing DTR %s\n' % (options.dtr_state and 'active' or 'inactive'))
cliechtib7d746d2006-03-28 22:44:30 +0000801 miniterm.serial.setDTR(options.dtr_state)
cliechti6c8eb2f2009-07-08 02:10:46 +0000802 miniterm.dtr_state = options.dtr_state
cliechtibf6bb7d2006-03-30 00:28:18 +0000803 if options.rts_state is not None:
804 if not options.quiet:
805 sys.stderr.write('--- forcing RTS %s\n' % (options.rts_state and 'active' or 'inactive'))
806 miniterm.serial.setRTS(options.rts_state)
cliechti6c8eb2f2009-07-08 02:10:46 +0000807 miniterm.rts_state = options.rts_state
cliechti53edb472009-02-06 21:18:46 +0000808
cliechti6385f2c2005-09-21 19:51:19 +0000809 miniterm.start()
cliechti258ab0a2011-03-21 23:03:45 +0000810 try:
811 miniterm.join(True)
812 except KeyboardInterrupt:
813 pass
cliechtibf6bb7d2006-03-30 00:28:18 +0000814 if not options.quiet:
815 sys.stderr.write("\n--- exit ---\n")
cliechti6385f2c2005-09-21 19:51:19 +0000816 miniterm.join()
cliechtibf6bb7d2006-03-30 00:28:18 +0000817
cliechti5370cee2013-10-13 03:08:19 +0000818# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
cliechti8b3ad392002-03-03 20:12:21 +0000819if __name__ == '__main__':
cliechti6385f2c2005-09-21 19:51:19 +0000820 main()