blob: ca48b94513ad4ac1be5a5dc2bf1499380b703130 [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):
Chris Liechticbb00b22015-08-13 22:58:49 +0200119 def __init__(self):
120 super(Console, self).__init__()
121 ctypes.windll.kernel32.SetConsoleOutputCP(65001)
122 ctypes.windll.kernel32.SetConsoleCP(65001)
123 if sys.version_info < (3, 0):
124 class Out:
125 def __init__(self):
126 self.fd = sys.stdout.fileno()
127 def flush(self):
128 pass
129 def write(self, s):
130 os.write(self.fd, s)
131 self.output = codecs.getwriter('UTF-8')(Out(), 'replace')
132 self.byte_output = Out()
133 else:
134 self.output = codecs.getwriter('UTF-8')(sys.stdout.buffer, 'replace')
135
cliechti3a8bf092008-09-17 11:26:53 +0000136 def getkey(self):
cliechti91165532011-03-18 02:02:52 +0000137 while True:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200138 z = msvcrt.getwch()
139 if z == '\r':
140 return '\n'
141 elif z in '\x00\x0e': # functions keys, ignore
142 msvcrt.getwch()
cliechti9c592b32008-06-16 22:00:14 +0000143 else:
cliechti9c592b32008-06-16 22:00:14 +0000144 return z
cliechti53edb472009-02-06 21:18:46 +0000145
cliechti576de252002-02-28 23:54:44 +0000146elif os.name == 'posix':
Chris Liechtia1d5c6d2015-08-07 14:41:24 +0200147 import atexit
148 import termios
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200149 class Console(ConsoleBase):
cliechti9c592b32008-06-16 22:00:14 +0000150 def __init__(self):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200151 super(Console, self).__init__()
cliechti9c592b32008-06-16 22:00:14 +0000152 self.fd = sys.stdin.fileno()
cliechti5370cee2013-10-13 03:08:19 +0000153 self.old = None
Chris Liechti89eb2472015-08-08 17:06:25 +0200154 atexit.register(self.cleanup)
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200155 if sys.version_info < (3, 0):
156 sys.stdin = codecs.getreader(sys.stdin.encoding)(sys.stdin)
cliechti9c592b32008-06-16 22:00:14 +0000157
158 def setup(self):
159 self.old = termios.tcgetattr(self.fd)
160 new = termios.tcgetattr(self.fd)
161 new[3] = new[3] & ~termios.ICANON & ~termios.ECHO & ~termios.ISIG
162 new[6][termios.VMIN] = 1
163 new[6][termios.VTIME] = 0
164 termios.tcsetattr(self.fd, termios.TCSANOW, new)
cliechti53edb472009-02-06 21:18:46 +0000165
cliechti9c592b32008-06-16 22:00:14 +0000166 def getkey(self):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200167 return sys.stdin.read(1)
168 #~ c = os.read(self.fd, 1)
169 #~ return c
cliechti53edb472009-02-06 21:18:46 +0000170
cliechti9c592b32008-06-16 22:00:14 +0000171 def cleanup(self):
cliechti5370cee2013-10-13 03:08:19 +0000172 if self.old is not None:
173 termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old)
cliechti9c592b32008-06-16 22:00:14 +0000174
cliechti576de252002-02-28 23:54:44 +0000175else:
cliechti8c2ea842011-03-18 01:51:46 +0000176 raise NotImplementedError("Sorry no implementation for your platform (%s) available." % sys.platform)
cliechti576de252002-02-28 23:54:44 +0000177
cliechti6fa76fb2009-07-08 23:53:39 +0000178
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200179# XXX how to handle multi byte sequences like CRLF?
180# codecs.IncrementalEncoder would be a good choice
181
182class Transform(object):
Chris Liechticbb00b22015-08-13 22:58:49 +0200183 """do-nothing: forward all data unchanged"""
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200184 def input(self, text):
185 """text received from serial port"""
186 return text
187
188 def output(self, text):
189 """text to be sent to serial port"""
190 return text
191
192 def echo(self, text):
193 """text to be sent but displayed on console"""
194 return text
195
196class CRLF(Transform):
197 """ENTER sends CR+LF"""
198 def input(self, text):
199 return text.replace('\r\n', '\n')
200
201 def output(self, text):
202 return text.replace('\n', '\r\n')
203
204class CR(Transform):
205 """ENTER sends CR"""
206 def input(self, text):
207 return text.replace('\r', '\n')
208
209 def output(self, text):
210 return text.replace('\n', '\r')
211
212class LF(Transform):
213 """ENTER sends LF"""
214
215
216class NoTerminal(Transform):
217 """remove typical terminal control codes from input"""
218 def input(self, text):
Chris Liechti7e9cfd42015-08-12 15:28:19 +0200219 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 +0200220
221 echo = input
222
223
224class NoControls(Transform):
225 """Remove all control codes, incl. CR+LF"""
226 def input(self, text):
227 return ''.join(t if t >= ' ' else unichr(0x2400 + ord(t)) for t in text)
228
229 echo = input
230
231
232class HexDump(Transform):
233 """Complete hex dump"""
234 def input(self, text):
235 return ''.join('{:02x} '.format(ord(t)) for t in text)
236
237 echo = input
238
239
240class Printable(Transform):
Chris Liechti7e9cfd42015-08-12 15:28:19 +0200241 """Show decimal code for all non-ASCII characters and most control codes"""
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200242 def input(self, text):
243 r = []
244 for t in text:
Chris Liechti7e9cfd42015-08-12 15:28:19 +0200245 if ' ' <= t < '\x7f' or t in '\r\n\b\t':
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200246 r.append(t)
247 else:
248 r.extend(unichr(0x2080 + ord(d) - 48) for d in '{:d}'.format(ord(t)))
249 r.append(' ')
250 return ''.join(r)
251
252 echo = input
253
254
255
256class Colorize(Transform):
257 """Apply different colors for input and echo"""
258 def __init__(self):
259 # XXX make it configurable, use colorama?
260 self.input_color = '\x1b[37m'
261 self.echo_color = '\x1b[31m'
262
263 def input(self, text):
264 return self.input_color + text
265
266 def echo(self, text):
267 return self.echo_color + text
268
269class DebugIO(Transform):
270 """Apply different colors for input and echo"""
271 def input(self, text):
272 sys.stderr.write('in: %r\n' % text)
273 return text
274
275 def echo(self, text):
276 sys.stderr.write('out: %r\n' % text)
277 return text
278
279# other ideas:
280# - add date/time for each newline
281# - insert newline after: a) timeout b) packet end character
282
283TRANSFORMATIONS = {
284 'crlf': CRLF,
285 'cr': CR,
286 'lf': LF,
Chris Liechticbb00b22015-08-13 22:58:49 +0200287 'direct': Transform, # no transformation
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200288 'default': NoTerminal,
289 'nocontrol': NoControls,
290 'printable': Printable,
291 'hex': HexDump,
292 'colorize': Colorize,
293 'debug': DebugIO,
294 }
295
296
cliechti1351dde2012-04-12 16:47:47 +0000297def dump_port_list():
298 if comports:
299 sys.stderr.write('\n--- Available ports:\n')
300 for port, desc, hwid in sorted(comports()):
301 #~ sys.stderr.write('--- %-20s %s [%s]\n' % (port, desc, hwid))
302 sys.stderr.write('--- %-20s %s\n' % (port, desc))
303
304
cliechti8c2ea842011-03-18 01:51:46 +0000305class Miniterm(object):
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200306 def __init__(self, port, baudrate, parity, rtscts, xonxoff, echo=False, transformations=()):
Chris Liechti89eb2472015-08-08 17:06:25 +0200307 self.console = Console()
Chris Liechtia1d5c6d2015-08-07 14:41:24 +0200308 self.serial = serial.serial_for_url(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1)
cliechti6385f2c2005-09-21 19:51:19 +0000309 self.echo = echo
cliechti6c8eb2f2009-07-08 02:10:46 +0000310 self.dtr_state = True
311 self.rts_state = True
312 self.break_state = False
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200313 self.raw = False
314 self.input_encoding = 'latin1'
315 self.input_error_handling = 'replace'
316 self.output_encoding = 'latin1'
317 self.output_error_handling = 'ignore'
318 self.transformations = [TRANSFORMATIONS[t]() for t in transformations]
319 self.transformation_names = transformations
cliechti576de252002-02-28 23:54:44 +0000320
cliechti8c2ea842011-03-18 01:51:46 +0000321 def _start_reader(self):
322 """Start reader thread"""
323 self._reader_alive = True
cliechti6fa76fb2009-07-08 23:53:39 +0000324 # start serial->console thread
cliechti6385f2c2005-09-21 19:51:19 +0000325 self.receiver_thread = threading.Thread(target=self.reader)
cliechti8c2ea842011-03-18 01:51:46 +0000326 self.receiver_thread.setDaemon(True)
cliechti6385f2c2005-09-21 19:51:19 +0000327 self.receiver_thread.start()
cliechti8c2ea842011-03-18 01:51:46 +0000328
329 def _stop_reader(self):
330 """Stop reader thread only, wait for clean exit of thread"""
331 self._reader_alive = False
332 self.receiver_thread.join()
333
334
335 def start(self):
336 self.alive = True
337 self._start_reader()
cliechti6fa76fb2009-07-08 23:53:39 +0000338 # enter console->serial loop
cliechti6385f2c2005-09-21 19:51:19 +0000339 self.transmitter_thread = threading.Thread(target=self.writer)
cliechti8c2ea842011-03-18 01:51:46 +0000340 self.transmitter_thread.setDaemon(True)
cliechti6385f2c2005-09-21 19:51:19 +0000341 self.transmitter_thread.start()
Chris Liechti89eb2472015-08-08 17:06:25 +0200342 self.console.setup()
cliechti53edb472009-02-06 21:18:46 +0000343
cliechti6385f2c2005-09-21 19:51:19 +0000344 def stop(self):
345 self.alive = False
cliechti53edb472009-02-06 21:18:46 +0000346
cliechtibf6bb7d2006-03-30 00:28:18 +0000347 def join(self, transmit_only=False):
cliechti6385f2c2005-09-21 19:51:19 +0000348 self.transmitter_thread.join()
cliechtibf6bb7d2006-03-30 00:28:18 +0000349 if not transmit_only:
350 self.receiver_thread.join()
cliechti6385f2c2005-09-21 19:51:19 +0000351
cliechti6c8eb2f2009-07-08 02:10:46 +0000352 def dump_port_settings(self):
cliechti6fa76fb2009-07-08 23:53:39 +0000353 sys.stderr.write("\n--- Settings: %s %s,%s,%s,%s\n" % (
cliechti258ab0a2011-03-21 23:03:45 +0000354 self.serial.portstr,
355 self.serial.baudrate,
356 self.serial.bytesize,
357 self.serial.parity,
358 self.serial.stopbits))
359 sys.stderr.write('--- RTS: %-8s DTR: %-8s BREAK: %-8s\n' % (
360 (self.rts_state and 'active' or 'inactive'),
361 (self.dtr_state and 'active' or 'inactive'),
362 (self.break_state and 'active' or 'inactive')))
cliechti10114572009-08-05 23:40:50 +0000363 try:
cliechti258ab0a2011-03-21 23:03:45 +0000364 sys.stderr.write('--- CTS: %-8s DSR: %-8s RI: %-8s CD: %-8s\n' % (
365 (self.serial.getCTS() and 'active' or 'inactive'),
366 (self.serial.getDSR() and 'active' or 'inactive'),
367 (self.serial.getRI() and 'active' or 'inactive'),
368 (self.serial.getCD() and 'active' or 'inactive')))
cliechti10114572009-08-05 23:40:50 +0000369 except serial.SerialException:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200370 # on RFC 2217 ports, it can happen to no modem state notification was
cliechti10114572009-08-05 23:40:50 +0000371 # yet received. ignore this error.
372 pass
cliechti258ab0a2011-03-21 23:03:45 +0000373 sys.stderr.write('--- software flow control: %s\n' % (self.serial.xonxoff and 'active' or 'inactive'))
374 sys.stderr.write('--- hardware flow control: %s\n' % (self.serial.rtscts and 'active' or 'inactive'))
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200375 #~ sys.stderr.write('--- data escaping: %s linefeed: %s\n' % (
376 #~ REPR_MODES[self.repr_mode],
377 #~ LF_MODES[self.convert_outgoing]))
378 sys.stderr.write('--- serial input encoding: %s\n' % (self.input_encoding,))
379 sys.stderr.write('--- serial output encoding: %s\n' % (self.output_encoding,))
380 sys.stderr.write('--- transformations: %s\n' % ' '.join(self.transformation_names))
cliechti6c8eb2f2009-07-08 02:10:46 +0000381
cliechti6385f2c2005-09-21 19:51:19 +0000382 def reader(self):
383 """loop and copy serial->console"""
cliechti6963b262010-01-02 03:01:21 +0000384 try:
cliechti8c2ea842011-03-18 01:51:46 +0000385 while self.alive and self._reader_alive:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200386 data = self.serial.read(1) + self.serial.read(self.serial.inWaiting())
387 if data:
388 if self.raw:
389 self.console.write_bytes(data)
cliechti6963b262010-01-02 03:01:21 +0000390 else:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200391 text = codecs.decode(
392 data,
393 self.input_encoding,
394 self.input_error_handling)
395 for transformation in self.transformations:
396 text = transformation.input(text)
397 self.console.write(text)
Chris Liechti68340d72015-08-03 14:15:48 +0200398 except serial.SerialException as e:
cliechti6963b262010-01-02 03:01:21 +0000399 self.alive = False
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200400 # XXX would be nice if the writer could be interrupted at this
401 # point... to exit completely
cliechti6963b262010-01-02 03:01:21 +0000402 raise
cliechti576de252002-02-28 23:54:44 +0000403
cliechti576de252002-02-28 23:54:44 +0000404
cliechti6385f2c2005-09-21 19:51:19 +0000405 def writer(self):
cliechti8c2ea842011-03-18 01:51:46 +0000406 """\
407 Loop and copy console->serial until EXITCHARCTER character is
408 found. When MENUCHARACTER is found, interpret the next key
409 locally.
cliechti6c8eb2f2009-07-08 02:10:46 +0000410 """
411 menu_active = False
412 try:
413 while self.alive:
414 try:
Chris Liechti89eb2472015-08-08 17:06:25 +0200415 c = self.console.getkey()
cliechti6c8eb2f2009-07-08 02:10:46 +0000416 except KeyboardInterrupt:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200417 c = '\x03'
cliechti6c8eb2f2009-07-08 02:10:46 +0000418 if menu_active:
Chris Liechti7af7c752015-08-12 15:45:19 +0200419 self.handle_menu_key(c)
cliechti6c8eb2f2009-07-08 02:10:46 +0000420 menu_active = False
Chris Liechti7af7c752015-08-12 15:45:19 +0200421 elif c == MENUCHARACTER:
422 menu_active = True # next char will be for menu
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200423 elif c == EXITCHARCTER:
Chris Liechti7af7c752015-08-12 15:45:19 +0200424 self.stop() # exit app
425 break
cliechti6c8eb2f2009-07-08 02:10:46 +0000426 else:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200427 #~ if self.raw:
428 text = c
429 echo_text = text
430 for transformation in self.transformations:
431 text = transformation.output(text)
432 echo_text = transformation.echo(echo_text)
433 b = codecs.encode(
434 text,
435 self.output_encoding,
436 self.output_error_handling)
437 self.serial.write(b)
cliechti6c8eb2f2009-07-08 02:10:46 +0000438 if self.echo:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200439 self.console.write(echo_text)
cliechti6c8eb2f2009-07-08 02:10:46 +0000440 except:
441 self.alive = False
442 raise
cliechti6385f2c2005-09-21 19:51:19 +0000443
Chris Liechti7af7c752015-08-12 15:45:19 +0200444 def handle_menu_key(self, c):
445 """Implement a simple menu / settings"""
446 if c == MENUCHARACTER or c == EXITCHARCTER: # Menu character again/exit char -> send itself
447 b = codecs.encode(
448 c,
449 self.output_encoding,
450 self.output_error_handling)
451 self.serial.write(b)
452 if self.echo:
453 self.console.write(c)
454 elif c == b'\x15': # CTRL+U -> upload file
455 sys.stderr.write('\n--- File to upload: ')
456 sys.stderr.flush()
457 self.console.cleanup()
458 filename = sys.stdin.readline().rstrip('\r\n')
459 if filename:
460 try:
461 with open(filename, 'rb') as f:
462 sys.stderr.write('--- Sending file %s ---\n' % filename)
463 while True:
464 block = f.read(1024)
465 if not block:
466 break
467 self.serial.write(block)
468 # Wait for output buffer to drain.
469 self.serial.flush()
470 sys.stderr.write('.') # Progress indicator.
471 sys.stderr.write('\n--- File %s sent ---\n' % filename)
472 except IOError as e:
473 sys.stderr.write('--- ERROR opening file %s: %s ---\n' % (filename, e))
474 self.console.setup()
475 elif c in '\x08hH?': # CTRL+H, h, H, ? -> Show help
476 sys.stderr.write(get_help_text())
477 elif c == '\x12': # CTRL+R -> Toggle RTS
478 self.rts_state = not self.rts_state
479 self.serial.setRTS(self.rts_state)
480 sys.stderr.write('--- RTS %s ---\n' % (self.rts_state and 'active' or 'inactive'))
481 elif c == '\x04': # CTRL+D -> Toggle DTR
482 self.dtr_state = not self.dtr_state
483 self.serial.setDTR(self.dtr_state)
484 sys.stderr.write('--- DTR %s ---\n' % (self.dtr_state and 'active' or 'inactive'))
485 elif c == '\x02': # CTRL+B -> toggle BREAK condition
486 self.break_state = not self.break_state
487 self.serial.setBreak(self.break_state)
488 sys.stderr.write('--- BREAK %s ---\n' % (self.break_state and 'active' or 'inactive'))
489 elif c == '\x05': # CTRL+E -> toggle local echo
490 self.echo = not self.echo
491 sys.stderr.write('--- local echo %s ---\n' % (self.echo and 'active' or 'inactive'))
492 elif c == '\x09': # CTRL+I -> info
493 self.dump_port_settings()
494 #~ elif c == '\x01': # CTRL+A -> cycle escape mode
495 #~ elif c == '\x0c': # CTRL+L -> cycle linefeed mode
496 elif c in 'pP': # P -> change port
497 dump_port_list()
498 sys.stderr.write('--- Enter port name: ')
499 sys.stderr.flush()
500 self.console.cleanup()
501 try:
502 port = sys.stdin.readline().strip()
503 except KeyboardInterrupt:
504 port = None
505 self.console.setup()
506 if port and port != self.serial.port:
507 # reader thread needs to be shut down
508 self._stop_reader()
509 # save settings
510 settings = self.serial.getSettingsDict()
511 try:
512 new_serial = serial.serial_for_url(port, do_not_open=True)
513 # restore settings and open
514 new_serial.applySettingsDict(settings)
515 new_serial.open()
516 new_serial.setRTS(self.rts_state)
517 new_serial.setDTR(self.dtr_state)
518 new_serial.setBreak(self.break_state)
519 except Exception as e:
520 sys.stderr.write('--- ERROR opening new port: %s ---\n' % (e,))
521 new_serial.close()
522 else:
523 self.serial.close()
524 self.serial = new_serial
525 sys.stderr.write('--- Port changed to: %s ---\n' % (self.serial.port,))
526 # and restart the reader thread
527 self._start_reader()
528 elif c in 'bB': # B -> change baudrate
529 sys.stderr.write('\n--- Baudrate: ')
530 sys.stderr.flush()
531 self.console.cleanup()
532 backup = self.serial.baudrate
533 try:
534 self.serial.baudrate = int(sys.stdin.readline().strip())
535 except ValueError as e:
536 sys.stderr.write('--- ERROR setting baudrate: %s ---\n' % (e,))
537 self.serial.baudrate = backup
538 else:
539 self.dump_port_settings()
540 self.console.setup()
541 elif c == '8': # 8 -> change to 8 bits
542 self.serial.bytesize = serial.EIGHTBITS
543 self.dump_port_settings()
544 elif c == '7': # 7 -> change to 8 bits
545 self.serial.bytesize = serial.SEVENBITS
546 self.dump_port_settings()
547 elif c in 'eE': # E -> change to even parity
548 self.serial.parity = serial.PARITY_EVEN
549 self.dump_port_settings()
550 elif c in 'oO': # O -> change to odd parity
551 self.serial.parity = serial.PARITY_ODD
552 self.dump_port_settings()
553 elif c in 'mM': # M -> change to mark parity
554 self.serial.parity = serial.PARITY_MARK
555 self.dump_port_settings()
556 elif c in 'sS': # S -> change to space parity
557 self.serial.parity = serial.PARITY_SPACE
558 self.dump_port_settings()
559 elif c in 'nN': # N -> change to no parity
560 self.serial.parity = serial.PARITY_NONE
561 self.dump_port_settings()
562 elif c == '1': # 1 -> change to 1 stop bits
563 self.serial.stopbits = serial.STOPBITS_ONE
564 self.dump_port_settings()
565 elif c == '2': # 2 -> change to 2 stop bits
566 self.serial.stopbits = serial.STOPBITS_TWO
567 self.dump_port_settings()
568 elif c == '3': # 3 -> change to 1.5 stop bits
569 self.serial.stopbits = serial.STOPBITS_ONE_POINT_FIVE
570 self.dump_port_settings()
571 elif c in 'xX': # X -> change software flow control
572 self.serial.xonxoff = (c == 'X')
573 self.dump_port_settings()
574 elif c in 'rR': # R -> change hardware flow control
575 self.serial.rtscts = (c == 'R')
576 self.dump_port_settings()
577 else:
578 sys.stderr.write('--- unknown menu character %s --\n' % key_description(c))
579
580
581
cliechti6385f2c2005-09-21 19:51:19 +0000582def main():
583 import optparse
584
cliechti53edb472009-02-06 21:18:46 +0000585 parser = optparse.OptionParser(
586 usage = "%prog [options] [port [baudrate]]",
587 description = "Miniterm - A simple terminal program for the serial port."
588 )
cliechti6385f2c2005-09-21 19:51:19 +0000589
cliechti5370cee2013-10-13 03:08:19 +0000590 group = optparse.OptionGroup(parser, "Port settings")
591
592 group.add_option("-p", "--port",
cliechti53edb472009-02-06 21:18:46 +0000593 dest = "port",
cliechti91165532011-03-18 02:02:52 +0000594 help = "port, a number or a device name. (deprecated option, use parameter instead)",
cliechti096e1962012-02-20 01:52:38 +0000595 default = DEFAULT_PORT
cliechti53edb472009-02-06 21:18:46 +0000596 )
cliechti6385f2c2005-09-21 19:51:19 +0000597
cliechti5370cee2013-10-13 03:08:19 +0000598 group.add_option("-b", "--baud",
cliechti53edb472009-02-06 21:18:46 +0000599 dest = "baudrate",
600 action = "store",
601 type = 'int',
cliechti6fa76fb2009-07-08 23:53:39 +0000602 help = "set baud rate, default %default",
cliechti096e1962012-02-20 01:52:38 +0000603 default = DEFAULT_BAUDRATE
cliechti53edb472009-02-06 21:18:46 +0000604 )
605
cliechti5370cee2013-10-13 03:08:19 +0000606 group.add_option("--parity",
cliechti53edb472009-02-06 21:18:46 +0000607 dest = "parity",
608 action = "store",
cliechtie0af3972009-07-08 11:03:47 +0000609 help = "set parity, one of [N, E, O, S, M], default=N",
cliechti53edb472009-02-06 21:18:46 +0000610 default = 'N'
611 )
612
cliechti5370cee2013-10-13 03:08:19 +0000613 group.add_option("--rtscts",
cliechti53edb472009-02-06 21:18:46 +0000614 dest = "rtscts",
615 action = "store_true",
616 help = "enable RTS/CTS flow control (default off)",
617 default = False
618 )
619
cliechti5370cee2013-10-13 03:08:19 +0000620 group.add_option("--xonxoff",
cliechti53edb472009-02-06 21:18:46 +0000621 dest = "xonxoff",
622 action = "store_true",
623 help = "enable software flow control (default off)",
624 default = False
625 )
626
cliechti5370cee2013-10-13 03:08:19 +0000627 group.add_option("--rts",
628 dest = "rts_state",
629 action = "store",
630 type = 'int',
631 help = "set initial RTS line state (possible values: 0, 1)",
632 default = DEFAULT_RTS
633 )
634
635 group.add_option("--dtr",
636 dest = "dtr_state",
637 action = "store",
638 type = 'int',
639 help = "set initial DTR line state (possible values: 0, 1)",
640 default = DEFAULT_DTR
641 )
642
643 parser.add_option_group(group)
644
645 group = optparse.OptionGroup(parser, "Data handling")
646
647 group.add_option("-e", "--echo",
648 dest = "echo",
649 action = "store_true",
650 help = "enable local echo (default off)",
651 default = False
652 )
653
Chris Liechti2b1b3552015-08-12 15:35:33 +0200654 group.add_option("--encoding",
655 dest = "serial_port_encoding",
656 metavar="CODEC",
657 action = "store",
658 help = "Set the encoding for the serial port (default: %default)",
659 default = 'latin1'
660 )
661
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200662 group.add_option("-t", "--transformation",
663 dest = "transformations",
Chris Liechti2b1b3552015-08-12 15:35:33 +0200664 metavar="NAME",
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200665 action = "append",
666 help = "Add text transformation",
667 default = []
668 )
669
cliechti5370cee2013-10-13 03:08:19 +0000670 group.add_option("--cr",
cliechti53edb472009-02-06 21:18:46 +0000671 dest = "cr",
672 action = "store_true",
673 help = "do not send CR+LF, send CR only",
674 default = False
675 )
676
cliechti5370cee2013-10-13 03:08:19 +0000677 group.add_option("--lf",
cliechti53edb472009-02-06 21:18:46 +0000678 dest = "lf",
679 action = "store_true",
680 help = "do not send CR+LF, send LF only",
681 default = False
682 )
683
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200684 group.add_option("--raw",
685 dest = "raw",
686 action = "store_true",
687 help = "Do no apply any encodings/transformations",
688 default = False
cliechti53edb472009-02-06 21:18:46 +0000689 )
cliechti6385f2c2005-09-21 19:51:19 +0000690
cliechti5370cee2013-10-13 03:08:19 +0000691 parser.add_option_group(group)
cliechtib7d746d2006-03-28 22:44:30 +0000692
cliechti5370cee2013-10-13 03:08:19 +0000693 group = optparse.OptionGroup(parser, "Hotkeys")
cliechtibf6bb7d2006-03-30 00:28:18 +0000694
cliechti5370cee2013-10-13 03:08:19 +0000695 group.add_option("--exit-char",
cliechti53edb472009-02-06 21:18:46 +0000696 dest = "exit_char",
697 action = "store",
698 type = 'int',
699 help = "ASCII code of special character that is used to exit the application",
700 default = 0x1d
701 )
cliechti9c592b32008-06-16 22:00:14 +0000702
cliechti5370cee2013-10-13 03:08:19 +0000703 group.add_option("--menu-char",
cliechti6c8eb2f2009-07-08 02:10:46 +0000704 dest = "menu_char",
cliechti53edb472009-02-06 21:18:46 +0000705 action = "store",
706 type = 'int',
cliechtidfec0c82009-07-21 01:35:41 +0000707 help = "ASCII code of special character that is used to control miniterm (menu)",
cliechti6c8eb2f2009-07-08 02:10:46 +0000708 default = 0x14
cliechti53edb472009-02-06 21:18:46 +0000709 )
cliechti6385f2c2005-09-21 19:51:19 +0000710
cliechti5370cee2013-10-13 03:08:19 +0000711 parser.add_option_group(group)
712
713 group = optparse.OptionGroup(parser, "Diagnostics")
714
715 group.add_option("-q", "--quiet",
716 dest = "quiet",
717 action = "store_true",
718 help = "suppress non-error messages",
719 default = False
720 )
721
Chris Liechti91090912015-08-05 02:36:14 +0200722 group.add_option("", "--develop",
723 dest = "develop",
724 action = "store_true",
725 help = "show Python traceback on error",
726 default = False
727 )
728
cliechti5370cee2013-10-13 03:08:19 +0000729 parser.add_option_group(group)
730
731
cliechti6385f2c2005-09-21 19:51:19 +0000732 (options, args) = parser.parse_args()
733
cliechtie0af3972009-07-08 11:03:47 +0000734 options.parity = options.parity.upper()
735 if options.parity not in 'NEOSM':
736 parser.error("invalid parity")
737
cliechti9cf26222006-03-24 20:09:21 +0000738 if options.cr and options.lf:
cliechti53edb472009-02-06 21:18:46 +0000739 parser.error("only one of --cr or --lf can be specified")
740
cliechtic1ca0772009-08-05 12:34:04 +0000741 if options.menu_char == options.exit_char:
cliechti6c8eb2f2009-07-08 02:10:46 +0000742 parser.error('--exit-char can not be the same as --menu-char')
743
744 global EXITCHARCTER, MENUCHARACTER
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200745 EXITCHARCTER = chr(options.exit_char)
746 MENUCHARACTER = chr(options.menu_char)
cliechti9c592b32008-06-16 22:00:14 +0000747
cliechti9743e222006-04-04 21:48:56 +0000748 port = options.port
749 baudrate = options.baudrate
cliechti9cf26222006-03-24 20:09:21 +0000750 if args:
cliechti9743e222006-04-04 21:48:56 +0000751 if options.port is not None:
752 parser.error("no arguments are allowed, options only when --port is given")
753 port = args.pop(0)
754 if args:
755 try:
756 baudrate = int(args[0])
757 except ValueError:
cliechti53edb472009-02-06 21:18:46 +0000758 parser.error("baud rate must be a number, not %r" % args[0])
cliechti9743e222006-04-04 21:48:56 +0000759 args.pop(0)
760 if args:
761 parser.error("too many arguments")
762 else:
cliechti7d448562014-08-03 21:57:45 +0000763 # no port given on command line -> ask user now
cliechti1351dde2012-04-12 16:47:47 +0000764 if port is None:
765 dump_port_list()
766 port = raw_input('Enter port name:')
cliechti53edb472009-02-06 21:18:46 +0000767
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200768 if options.transformations:
769 if 'help' in options.transformations:
770 sys.stderr.write('Available Transformations:\n')
771 sys.stderr.write('\n'.join('{:<20} = {.__doc__}'.format(k,v) for k,v in sorted(TRANSFORMATIONS.items())))
772 sys.stderr.write('\n')
773 sys.exit(1)
774 transformations = options.transformations
775 else:
776 transformations = ['default']
777
cliechti9cf26222006-03-24 20:09:21 +0000778 if options.cr:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200779 transformations.append('cr')
cliechti9cf26222006-03-24 20:09:21 +0000780 elif options.lf:
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200781 transformations.append('lf')
782 else:
783 transformations.append('crlf')
cliechti6385f2c2005-09-21 19:51:19 +0000784
785 try:
786 miniterm = Miniterm(
cliechti9743e222006-04-04 21:48:56 +0000787 port,
788 baudrate,
cliechti6385f2c2005-09-21 19:51:19 +0000789 options.parity,
790 rtscts=options.rtscts,
791 xonxoff=options.xonxoff,
792 echo=options.echo,
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200793 transformations=transformations,
cliechti6385f2c2005-09-21 19:51:19 +0000794 )
Chris Liechtic7a5d4c2015-08-11 23:32:20 +0200795 miniterm.raw = options.raw
Chris Liechti2b1b3552015-08-12 15:35:33 +0200796 miniterm.input_encoding = options.serial_port_encoding
797 miniterm.output_encoding = options.serial_port_encoding
Chris Liechti68340d72015-08-03 14:15:48 +0200798 except serial.SerialException as e:
cliechtieb4a14f2009-08-03 23:48:35 +0000799 sys.stderr.write("could not open port %r: %s\n" % (port, e))
Chris Liechti91090912015-08-05 02:36:14 +0200800 if options.develop:
801 raise
cliechti6385f2c2005-09-21 19:51:19 +0000802 sys.exit(1)
803
cliechtibf6bb7d2006-03-30 00:28:18 +0000804 if not options.quiet:
cliechti6fa76fb2009-07-08 23:53:39 +0000805 sys.stderr.write('--- Miniterm on %s: %d,%s,%s,%s ---\n' % (
cliechti9743e222006-04-04 21:48:56 +0000806 miniterm.serial.portstr,
807 miniterm.serial.baudrate,
808 miniterm.serial.bytesize,
809 miniterm.serial.parity,
810 miniterm.serial.stopbits,
811 ))
cliechti6c8eb2f2009-07-08 02:10:46 +0000812 sys.stderr.write('--- Quit: %s | Menu: %s | Help: %s followed by %s ---\n' % (
cliechti9c592b32008-06-16 22:00:14 +0000813 key_description(EXITCHARCTER),
cliechti6c8eb2f2009-07-08 02:10:46 +0000814 key_description(MENUCHARACTER),
815 key_description(MENUCHARACTER),
Chris Liechti89eb2472015-08-08 17:06:25 +0200816 key_description(b'\x08'),
cliechti9c592b32008-06-16 22:00:14 +0000817 ))
cliechti6fa76fb2009-07-08 23:53:39 +0000818
cliechtib7d746d2006-03-28 22:44:30 +0000819 if options.dtr_state is not None:
cliechtibf6bb7d2006-03-30 00:28:18 +0000820 if not options.quiet:
821 sys.stderr.write('--- forcing DTR %s\n' % (options.dtr_state and 'active' or 'inactive'))
cliechtib7d746d2006-03-28 22:44:30 +0000822 miniterm.serial.setDTR(options.dtr_state)
cliechti6c8eb2f2009-07-08 02:10:46 +0000823 miniterm.dtr_state = options.dtr_state
cliechtibf6bb7d2006-03-30 00:28:18 +0000824 if options.rts_state is not None:
825 if not options.quiet:
826 sys.stderr.write('--- forcing RTS %s\n' % (options.rts_state and 'active' or 'inactive'))
827 miniterm.serial.setRTS(options.rts_state)
cliechti6c8eb2f2009-07-08 02:10:46 +0000828 miniterm.rts_state = options.rts_state
cliechti53edb472009-02-06 21:18:46 +0000829
cliechti6385f2c2005-09-21 19:51:19 +0000830 miniterm.start()
cliechti258ab0a2011-03-21 23:03:45 +0000831 try:
832 miniterm.join(True)
833 except KeyboardInterrupt:
834 pass
cliechtibf6bb7d2006-03-30 00:28:18 +0000835 if not options.quiet:
836 sys.stderr.write("\n--- exit ---\n")
cliechti6385f2c2005-09-21 19:51:19 +0000837 miniterm.join()
cliechtibf6bb7d2006-03-30 00:28:18 +0000838
cliechti5370cee2013-10-13 03:08:19 +0000839# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
cliechti8b3ad392002-03-03 20:12:21 +0000840if __name__ == '__main__':
cliechti6385f2c2005-09-21 19:51:19 +0000841 main()