1 #!/usr/bin/env python
2 #
3 # Very simple serial terminal
4 #
5 # This file is part of pySerial. https://github.com/pyserial/pyserial
6 # (C)2002-2015 Chris Liechti <cliechti@gmx.net>
7 #
8 # SPDX-License-Identifier: BSD-3-Clause
10 import codecs
11 import os
12 import sys
13 import threading
15 import serial
16 from serial.tools.list_ports import comports
17 from serial.tools import hexlify_codec
19 # pylint: disable=wrong-import-order,wrong-import-position
21 codecs.register(lambda c: hexlify_codec.getregentry() if c == 'hexlify' else None)
23 try:
24 raw_input
25 except NameError:
26 # pylint: disable=redefined-builtin,invalid-name
27 raw_input = input # in python3 it's "raw"
28 unichr = chr
31 def 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}'.format(ord('@') + ascii_code)
36 else:
37 return repr(character)
40 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
41 class ConsoleBase(object):
42 """OS abstraction for console (input/output codec, no echo)"""
44 def __init__(self):
45 if sys.version_info >= (3, 0):
46 self.byte_output = sys.stdout.buffer
47 else:
48 self.byte_output = sys.stdout
49 self.output = sys.stdout
51 def setup(self):
52 """Set console to read single characters, no echo"""
54 def cleanup(self):
55 """Restore default console settings"""
57 def getkey(self):
58 """Read a single key from the console"""
59 return None
61 def write_bytes(self, byte_string):
62 """Write bytes (already encoded)"""
63 self.byte_output.write(byte_string)
64 self.byte_output.flush()
66 def write(self, text):
67 """Write string"""
68 self.output.write(text)
69 self.output.flush()
71 def cancel(self):
72 """Cancel getkey operation"""
74 # - - - - - - - - - - - - - - - - - - - - - - - -
75 # context manager:
76 # switch terminal temporary to normal mode (e.g. to get user input)
78 def __enter__(self):
79 self.cleanup()
80 return self
82 def __exit__(self, *args, **kwargs):
83 self.setup()
86 if os.name == 'nt': # noqa
87 import msvcrt
88 import ctypes
90 class Out(object):
91 """file-like wrapper that uses os.write"""
93 def __init__(self, fd):
94 self.fd = fd
96 def flush(self):
97 pass
99 def write(self, s):
100 os.write(self.fd, s)
102 class Console(ConsoleBase):
103 def __init__(self):
104 super(Console, self).__init__()
105 self._saved_ocp = ctypes.windll.kernel32.GetConsoleOutputCP()
106 self._saved_icp = ctypes.windll.kernel32.GetConsoleCP()
107 ctypes.windll.kernel32.SetConsoleOutputCP(65001)
108 ctypes.windll.kernel32.SetConsoleCP(65001)
109 self.output = codecs.getwriter('UTF-8')(Out(sys.stdout.fileno()), 'replace')
110 # the change of the code page is not propagated to Python, manually fix it
111 sys.stderr = codecs.getwriter('UTF-8')(Out(sys.stderr.fileno()), 'replace')
112 sys.stdout = self.output
113 self.output.encoding = 'UTF-8' # needed for input
115 def __del__(self):
116 ctypes.windll.kernel32.SetConsoleOutputCP(self._saved_ocp)
117 ctypes.windll.kernel32.SetConsoleCP(self._saved_icp)
119 def getkey(self):
120 while True:
121 z = msvcrt.getwch()
122 if z == unichr(13):
123 return unichr(10)
124 elif z in (unichr(0), unichr(0x0e)): # functions keys, ignore
125 msvcrt.getwch()
126 else:
127 return z
129 def cancel(self):
130 # CancelIo, CancelSynchronousIo do not seem to work when using
131 # getwch, so instead, send a key to the window with the console
132 hwnd = ctypes.windll.kernel32.GetConsoleWindow()
133 ctypes.windll.user32.PostMessageA(hwnd, 0x100, 0x0d, 0)
135 elif os.name == 'posix':
136 import atexit
137 import termios
138 import select
140 class Console(ConsoleBase):
141 def __init__(self):
142 super(Console, self).__init__()
143 self.fd = sys.stdin.fileno()
144 # an additional pipe is used in getkey, so that the cancel method
145 # can abort the waiting getkey method
146 self.pipe_r, self.pipe_w = os.pipe()
147 self.old = termios.tcgetattr(self.fd)
148 atexit.register(self.cleanup)
149 if sys.version_info < (3, 0):
150 self.enc_stdin = codecs.getreader(sys.stdin.encoding)(sys.stdin)
151 else:
152 self.enc_stdin = sys.stdin
154 def setup(self):
155 new = termios.tcgetattr(self.fd)
156 new[3] = new[3] & ~termios.ICANON & ~termios.ECHO & ~termios.ISIG
157 new[6][termios.VMIN] = 1
158 new[6][termios.VTIME] = 0
159 termios.tcsetattr(self.fd, termios.TCSANOW, new)
161 def getkey(self):
162 ready, _, _ = select.select([self.enc_stdin, self.pipe_r], [], [], None)
163 if self.pipe_r in ready:
164 os.read(self.pipe_r, 1)
165 return
166 c = self.enc_stdin.read(1)
167 if c == unichr(0x7f):
168 c = unichr(8) # map the BS key (which yields DEL) to backspace
169 return c
171 def cancel(self):
172 os.write(self.pipe_w, "x")
174 def cleanup(self):
175 termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old)
177 else:
178 raise NotImplementedError(
179 'Sorry no implementation for your platform ({}) available.'.format(sys.platform))
182 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
184 class Transform(object):
185 """do-nothing: forward all data unchanged"""
186 def rx(self, text):
187 """text received from serial port"""
188 return text
190 def tx(self, text):
191 """text to be sent to serial port"""
192 return text
194 def echo(self, text):
195 """text to be sent but displayed on console"""
196 return text
199 class CRLF(Transform):
200 """ENTER sends CR+LF"""
202 def tx(self, text):
203 return text.replace('\n', '\r\n')
206 class CR(Transform):
207 """ENTER sends CR"""
209 def rx(self, text):
210 return text.replace('\r', '\n')
212 def tx(self, text):
213 return text.replace('\n', '\r')
216 class LF(Transform):
217 """ENTER sends LF"""
220 class NoTerminal(Transform):
221 """remove typical terminal control codes from input"""
223 REPLACEMENT_MAP = dict((x, 0x2400 + x) for x in range(32) if unichr(x) not in '\r\n\b\t')
224 REPLACEMENT_MAP.update(
225 {
226 0x7F: 0x2421, # DEL
227 0x9B: 0x2425, # CSI
228 })
230 def rx(self, text):
231 return text.translate(self.REPLACEMENT_MAP)
233 echo = rx
236 class NoControls(NoTerminal):
237 """Remove all control codes, incl. CR+LF"""
239 REPLACEMENT_MAP = dict((x, 0x2400 + x) for x in range(32))
240 REPLACEMENT_MAP.update(
241 {
242 0x20: 0x2423, # visual space
243 0x7F: 0x2421, # DEL
244 0x9B: 0x2425, # CSI
245 })
248 class Printable(Transform):
249 """Show decimal code for all non-ASCII characters and replace most control codes"""
251 def rx(self, text):
252 r = []
253 for c in text:
254 if ' ' <= c < '\x7f' or c in '\r\n\b\t':
255 r.append(c)
256 elif c < ' ':
257 r.append(unichr(0x2400 + ord(c)))
258 else:
259 r.extend(unichr(0x2080 + ord(d) - 48) for d in '{:d}'.format(ord(c)))
260 r.append(' ')
261 return ''.join(r)
263 echo = rx
266 class Colorize(Transform):
267 """Apply different colors for received and echo"""
269 def __init__(self):
270 # XXX make it configurable, use colorama?
271 self.input_color = '\x1b[37m'
272 self.echo_color = '\x1b[31m'
274 def rx(self, text):
275 return self.input_color + text
277 def echo(self, text):
278 return self.echo_color + text
281 class DebugIO(Transform):
282 """Print what is sent and received"""
284 def rx(self, text):
285 sys.stderr.write(' [RX:{}] '.format(repr(text)))
286 sys.stderr.flush()
287 return text
289 def tx(self, text):
290 sys.stderr.write(' [TX:{}] '.format(repr(text)))
291 sys.stderr.flush()
292 return text
295 # other ideas:
296 # - add date/time for each newline
297 # - insert newline after: a) timeout b) packet end character
299 EOL_TRANSFORMATIONS = {
300 'crlf': CRLF,
301 'cr': CR,
302 'lf': LF,
303 }
305 TRANSFORMATIONS = {
306 'direct': Transform, # no transformation
307 'default': NoTerminal,
308 'nocontrol': NoControls,
309 'printable': Printable,
310 'colorize': Colorize,
311 'debug': DebugIO,
312 }
315 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
316 def ask_for_port():
317 """\
318 Show a list of ports and ask the user for a choice. To make selection
319 easier on systems with long device names, also allow the input of an
320 index.
321 """
322 sys.stderr.write('\n--- Available ports:\n')
323 ports = []
324 for n, (port, desc, hwid) in enumerate(sorted(comports()), 1):
325 sys.stderr.write('--- {:2}: {:20} {}\n'.format(n, port, desc))
326 ports.append(port)
327 while True:
328 port = raw_input('--- Enter port index or full name: ')
329 try:
330 index = int(port) - 1
331 if not 0 <= index < len(ports):
332 sys.stderr.write('--- Invalid index!\n')
333 continue
334 except ValueError:
335 pass
336 else:
337 port = ports[index]
338 return port
341 class Miniterm(object):
342 """\
343 Terminal application. Copy data from serial port to console and vice versa.
344 Handle special keys from the console to show menu etc.
345 """
347 def __init__(self, serial_instance, echo=False, eol='crlf', filters=()):
348 self.console = Console()
349 self.serial = serial_instance
350 self.echo = echo
351 self.raw = False
352 self.input_encoding = 'UTF-8'
353 self.output_encoding = 'UTF-8'
354 self.eol = eol
355 self.filters = filters
356 self.update_transformations()
357 self.exit_character = 0x1d # GS/CTRL+]
358 self.menu_character = 0x14 # Menu: CTRL+T
359 self.alive = None
360 self._reader_alive = None
361 self.receiver_thread = None
362 self.rx_decoder = None
363 self.tx_decoder = None
365 def _start_reader(self):
366 """Start reader thread"""
367 self._reader_alive = True
368 # start serial->console thread
369 self.receiver_thread = threading.Thread(target=self.reader, name='rx')
370 self.receiver_thread.daemon = True
371 self.receiver_thread.start()
373 def _stop_reader(self):
374 """Stop reader thread only, wait for clean exit of thread"""
375 self._reader_alive = False
376 if hasattr(self.serial, 'cancel_read'):
377 self.serial.cancel_read()
378 self.receiver_thread.join()
380 def start(self):
381 """start worker threads"""
382 self.alive = True
383 self._start_reader()
384 # enter console->serial loop
385 self.transmitter_thread = threading.Thread(target=self.writer, name='tx')
386 self.transmitter_thread.daemon = True
387 self.transmitter_thread.start()
388 self.console.setup()
390 def stop(self):
391 """set flag to stop worker threads"""
392 self.alive = False
394 def join(self, transmit_only=False):
395 """wait for worker threads to terminate"""
396 self.transmitter_thread.join()
397 if not transmit_only:
398 if hasattr(self.serial, 'cancel_read'):
399 self.serial.cancel_read()
400 self.receiver_thread.join()
402 def close(self):
403 self.serial.close()
405 def update_transformations(self):
406 """take list of transformation classes and instantiate them for rx and tx"""
407 transformations = [EOL_TRANSFORMATIONS[self.eol]] + [TRANSFORMATIONS[f]
408 for f in self.filters]
409 self.tx_transformations = [t() for t in transformations]
410 self.rx_transformations = list(reversed(self.tx_transformations))
412 def set_rx_encoding(self, encoding, errors='replace'):
413 """set encoding for received data"""
414 self.input_encoding = encoding
415 self.rx_decoder = codecs.getincrementaldecoder(encoding)(errors)
417 def set_tx_encoding(self, encoding, errors='replace'):
418 """set encoding for transmitted data"""
419 self.output_encoding = encoding
420 self.tx_encoder = codecs.getincrementalencoder(encoding)(errors)
422 def dump_port_settings(self):
423 """Write current settings to sys.stderr"""
424 sys.stderr.write("\n--- Settings: {p.name} {p.baudrate},{p.bytesize},{p.parity},{p.stopbits}\n".format(
425 p=self.serial))
426 sys.stderr.write('--- RTS: {:8} DTR: {:8} BREAK: {:8}\n'.format(
427 ('active' if self.serial.rts else 'inactive'),
428 ('active' if self.serial.dtr else 'inactive'),
429 ('active' if self.serial.break_condition else 'inactive')))
430 try:
431 sys.stderr.write('--- CTS: {:8} DSR: {:8} RI: {:8} CD: {:8}\n'.format(
432 ('active' if self.serial.cts else 'inactive'),
433 ('active' if self.serial.dsr else 'inactive'),
434 ('active' if self.serial.ri else 'inactive'),
435 ('active' if self.serial.cd else 'inactive')))
436 except serial.SerialException:
437 # on RFC 2217 ports, it can happen if no modem state notification was
438 # yet received. ignore this error.
439 pass
440 sys.stderr.write('--- software flow control: {}\n'.format('active' if self.serial.xonxoff else 'inactive'))
441 sys.stderr.write('--- hardware flow control: {}\n'.format('active' if self.serial.rtscts else 'inactive'))
442 sys.stderr.write('--- serial input encoding: {}\n'.format(self.input_encoding))
443 sys.stderr.write('--- serial output encoding: {}\n'.format(self.output_encoding))
444 sys.stderr.write('--- EOL: {}\n'.format(self.eol.upper()))
445 sys.stderr.write('--- filters: {}\n'.format(' '.join(self.filters)))
447 def reader(self):
448 """loop and copy serial->console"""
449 try:
450 while self.alive and self._reader_alive:
451 # read all that is there or wait for one byte
452 data = self.serial.read(self.serial.in_waiting or 1)
453 if data:
454 if self.raw:
455 self.console.write_bytes(data)
456 else:
457 text = self.rx_decoder.decode(data)
458 for transformation in self.rx_transformations:
459 text = transformation.rx(text)
460 self.console.write(text)
461 except serial.SerialException:
462 self.alive = False
463 self.console.cancel()
464 raise # XXX handle instead of re-raise?
466 def writer(self):
467 """\
468 Loop and copy console->serial until self.exit_character character is
469 found. When self.menu_character is found, interpret the next key
470 locally.
471 """
472 menu_active = False
473 try:
474 while self.alive:
475 try:
476 c = self.console.getkey()
477 except KeyboardInterrupt:
478 c = '\x03'
479 if not self.alive:
480 break
481 if menu_active:
482 self.handle_menu_key(c)
483 menu_active = False
484 elif c == self.menu_character:
485 menu_active = True # next char will be for menu
486 elif c == self.exit_character:
487 self.stop() # exit app
488 break
489 else:
490 #~ if self.raw:
491 text = c
492 for transformation in self.tx_transformations:
493 text = transformation.tx(text)
494 self.serial.write(self.tx_encoder.encode(text))
495 if self.echo:
496 echo_text = c
497 for transformation in self.tx_transformations:
498 echo_text = transformation.echo(echo_text)
499 self.console.write(echo_text)
500 except:
501 self.alive = False
502 raise
504 def handle_menu_key(self, c):
505 """Implement a simple menu / settings"""
506 if c == self.menu_character or c == self.exit_character:
507 # Menu/exit character again -> send itself
508 self.serial.write(self.tx_encoder.encode(c))
509 if self.echo:
510 self.console.write(c)
511 elif c == '\x15': # CTRL+U -> upload file
512 sys.stderr.write('\n--- File to upload: ')
513 sys.stderr.flush()
514 with self.console:
515 filename = sys.stdin.readline().rstrip('\r\n')
516 if filename:
517 try:
518 with open(filename, 'rb') as f:
519 sys.stderr.write('--- Sending file {} ---\n'.format(filename))
520 while True:
521 block = f.read(1024)
522 if not block:
523 break
524 self.serial.write(block)
525 # Wait for output buffer to drain.
526 self.serial.flush()
527 sys.stderr.write('.') # Progress indicator.
528 sys.stderr.write('\n--- File {} sent ---\n'.format(filename))
529 except IOError as e:
530 sys.stderr.write('--- ERROR opening file {}: {} ---\n'.format(filename, e))
531 elif c in '\x08hH?': # CTRL+H, h, H, ? -> Show help
532 sys.stderr.write(self.get_help_text())
533 elif c == '\x12': # CTRL+R -> Toggle RTS
534 self.serial.rts = not self.serial.rts
535 sys.stderr.write('--- RTS {} ---\n'.format('active' if self.serial.rts else 'inactive'))
536 elif c == '\x04': # CTRL+D -> Toggle DTR
537 self.serial.dtr = not self.serial.dtr
538 sys.stderr.write('--- DTR {} ---\n'.format('active' if self.serial.dtr else 'inactive'))
539 elif c == '\x02': # CTRL+B -> toggle BREAK condition
540 self.serial.break_condition = not self.serial.break_condition
541 sys.stderr.write('--- BREAK {} ---\n'.format('active' if self.serial.break_condition else 'inactive'))
542 elif c == '\x05': # CTRL+E -> toggle local echo
543 self.echo = not self.echo
544 sys.stderr.write('--- local echo {} ---\n'.format('active' if self.echo else 'inactive'))
545 elif c == '\x06': # CTRL+F -> edit filters
546 sys.stderr.write('\n--- Available Filters:\n')
547 sys.stderr.write('\n'.join(
548 '--- {:<10} = {.__doc__}'.format(k, v)
549 for k, v in sorted(TRANSFORMATIONS.items())))
550 sys.stderr.write('\n--- Enter new filter name(s) [{}]: '.format(' '.join(self.filters)))
551 with self.console:
552 new_filters = sys.stdin.readline().lower().split()
553 if new_filters:
554 for f in new_filters:
555 if f not in TRANSFORMATIONS:
556 sys.stderr.write('--- unknown filter: {}'.format(repr(f)))
557 break
558 else:
559 self.filters = new_filters
560 self.update_transformations()
561 sys.stderr.write('--- filters: {}\n'.format(' '.join(self.filters)))
562 elif c == '\x0c': # CTRL+L -> EOL mode
563 modes = list(EOL_TRANSFORMATIONS) # keys
564 eol = modes.index(self.eol) + 1
565 if eol >= len(modes):
566 eol = 0
567 self.eol = modes[eol]
568 sys.stderr.write('--- EOL: {} ---\n'.format(self.eol.upper()))
569 self.update_transformations()
570 elif c == '\x01': # CTRL+A -> set encoding
571 sys.stderr.write('\n--- Enter new encoding name [{}]: '.format(self.input_encoding))
572 with self.console:
573 new_encoding = sys.stdin.readline().strip()
574 if new_encoding:
575 try:
576 codecs.lookup(new_encoding)
577 except LookupError:
578 sys.stderr.write('--- invalid encoding name: {}\n'.format(new_encoding))
579 else:
580 self.set_rx_encoding(new_encoding)
581 self.set_tx_encoding(new_encoding)
582 sys.stderr.write('--- serial input encoding: {}\n'.format(self.input_encoding))
583 sys.stderr.write('--- serial output encoding: {}\n'.format(self.output_encoding))
584 elif c == '\x09': # CTRL+I -> info
585 self.dump_port_settings()
586 #~ elif c == '\x01': # CTRL+A -> cycle escape mode
587 #~ elif c == '\x0c': # CTRL+L -> cycle linefeed mode
588 elif c in 'pP': # P -> change port
589 with self.console:
590 try:
591 port = ask_for_port()
592 except KeyboardInterrupt:
593 port = None
594 if port and port != self.serial.port:
595 # reader thread needs to be shut down
596 self._stop_reader()
597 # save settings
598 settings = self.serial.getSettingsDict()
599 try:
600 new_serial = serial.serial_for_url(port, do_not_open=True)
601 # restore settings and open
602 new_serial.applySettingsDict(settings)
603 new_serial.rts = self.serial.rts
604 new_serial.dtr = self.serial.dtr
605 new_serial.open()
606 new_serial.break_condition = self.serial.break_condition
607 except Exception as e:
608 sys.stderr.write('--- ERROR opening new port: {} ---\n'.format(e))
609 new_serial.close()
610 else:
611 self.serial.close()
612 self.serial = new_serial
613 sys.stderr.write('--- Port changed to: {} ---\n'.format(self.serial.port))
614 # and restart the reader thread
615 self._start_reader()
616 elif c in 'bB': # B -> change baudrate
617 sys.stderr.write('\n--- Baudrate: ')
618 sys.stderr.flush()
619 with self.console:
620 backup = self.serial.baudrate
621 try:
622 self.serial.baudrate = int(sys.stdin.readline().strip())
623 except ValueError as e:
624 sys.stderr.write('--- ERROR setting baudrate: {} ---\n'.format(e))
625 self.serial.baudrate = backup
626 else:
627 self.dump_port_settings()
628 elif c == '8': # 8 -> change to 8 bits
629 self.serial.bytesize = serial.EIGHTBITS
630 self.dump_port_settings()
631 elif c == '7': # 7 -> change to 8 bits
632 self.serial.bytesize = serial.SEVENBITS
633 self.dump_port_settings()
634 elif c in 'eE': # E -> change to even parity
635 self.serial.parity = serial.PARITY_EVEN
636 self.dump_port_settings()
637 elif c in 'oO': # O -> change to odd parity
638 self.serial.parity = serial.PARITY_ODD
639 self.dump_port_settings()
640 elif c in 'mM': # M -> change to mark parity
641 self.serial.parity = serial.PARITY_MARK
642 self.dump_port_settings()
643 elif c in 'sS': # S -> change to space parity
644 self.serial.parity = serial.PARITY_SPACE
645 self.dump_port_settings()
646 elif c in 'nN': # N -> change to no parity
647 self.serial.parity = serial.PARITY_NONE
648 self.dump_port_settings()
649 elif c == '1': # 1 -> change to 1 stop bits
650 self.serial.stopbits = serial.STOPBITS_ONE
651 self.dump_port_settings()
652 elif c == '2': # 2 -> change to 2 stop bits
653 self.serial.stopbits = serial.STOPBITS_TWO
654 self.dump_port_settings()
655 elif c == '3': # 3 -> change to 1.5 stop bits
656 self.serial.stopbits = serial.STOPBITS_ONE_POINT_FIVE
657 self.dump_port_settings()
658 elif c in 'xX': # X -> change software flow control
659 self.serial.xonxoff = (c == 'X')
660 self.dump_port_settings()
661 elif c in 'rR': # R -> change hardware flow control
662 self.serial.rtscts = (c == 'R')
663 self.dump_port_settings()
664 else:
665 sys.stderr.write('--- unknown menu character {} --\n'.format(key_description(c)))
667 def get_help_text(self):
668 """return the help text"""
669 # help text, starts with blank line!
670 return """
671 --- pySerial ({version}) - miniterm - help
672 ---
673 --- {exit:8} Exit program
674 --- {menu:8} Menu escape key, followed by:
675 --- Menu keys:
676 --- {menu:7} Send the menu character itself to remote
677 --- {exit:7} Send the exit character itself to remote
678 --- {info:7} Show info
679 --- {upload:7} Upload file (prompt will be shown)
680 --- {repr:7} encoding
681 --- {filter:7} edit filters
682 --- Toggles:
683 --- {rts:7} RTS {dtr:7} DTR {brk:7} BREAK
684 --- {echo:7} echo {eol:7} EOL
685 ---
686 --- Port settings ({menu} followed by the following):
687 --- p change port
688 --- 7 8 set data bits
689 --- N E O S M change parity (None, Even, Odd, Space, Mark)
690 --- 1 2 3 set stop bits (1, 2, 1.5)
691 --- b change baud rate
692 --- x X disable/enable software flow control
693 --- r R disable/enable hardware flow control
694 """.format(version=getattr(serial, 'VERSION', 'unknown version'),
695 exit=key_description(self.exit_character),
696 menu=key_description(self.menu_character),
697 rts=key_description('\x12'),
698 dtr=key_description('\x04'),
699 brk=key_description('\x02'),
700 echo=key_description('\x05'),
701 info=key_description('\x09'),
702 upload=key_description('\x15'),
703 repr=key_description('\x01'),
704 filter=key_description('\x06'),
705 eol=key_description('\x0c'))
708 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
709 # default args can be used to override when calling main() from an other script
710 # e.g to create a miniterm-my-device.py
711 def main(default_port=None, default_baudrate=9600, default_rts=None, default_dtr=None):
712 """Command line tool, entry point"""
714 import argparse
716 parser = argparse.ArgumentParser(
717 description="Miniterm - A simple terminal program for the serial port.")
719 parser.add_argument(
720 "port",
721 nargs='?',
722 help="serial port name ('-' to show port list)",
723 default=default_port)
725 parser.add_argument(
726 "baudrate",
727 nargs='?',
728 type=int,
729 help="set baud rate, default: %(default)s",
730 default=default_baudrate)
732 group = parser.add_argument_group("port settings")
734 group.add_argument(
735 "--parity",
736 choices=['N', 'E', 'O', 'S', 'M'],
737 type=lambda c: c.upper(),
738 help="set parity, one of {N E O S M}, default: N",
739 default='N')
741 group.add_argument(
742 "--rtscts",
743 action="store_true",
744 help="enable RTS/CTS flow control (default off)",
745 default=False)
747 group.add_argument(
748 "--xonxoff",
749 action="store_true",
750 help="enable software flow control (default off)",
751 default=False)
753 group.add_argument(
754 "--rts",
755 type=int,
756 help="set initial RTS line state (possible values: 0, 1)",
757 default=default_rts)
759 group.add_argument(
760 "--dtr",
761 type=int,
762 help="set initial DTR line state (possible values: 0, 1)",
763 default=default_dtr)
765 group.add_argument(
766 "--ask",
767 action="store_true",
768 help="ask again for port when open fails",
769 default=False)
771 group = parser.add_argument_group("data handling")
773 group.add_argument(
774 "-e", "--echo",
775 action="store_true",
776 help="enable local echo (default off)",
777 default=False)
779 group.add_argument(
780 "--encoding",
781 dest="serial_port_encoding",
782 metavar="CODEC",
783 help="set the encoding for the serial port (e.g. hexlify, Latin1, UTF-8), default: %(default)s",
784 default='UTF-8')
786 group.add_argument(
787 "-f", "--filter",
788 action="append",
789 metavar="NAME",
790 help="add text transformation",
791 default=[])
793 group.add_argument(
794 "--eol",
795 choices=['CR', 'LF', 'CRLF'],
796 type=lambda c: c.upper(),
797 help="end of line mode",
798 default='CRLF')
800 group.add_argument(
801 "--raw",
802 action="store_true",
803 help="Do no apply any encodings/transformations",
804 default=False)
806 group = parser.add_argument_group("hotkeys")
808 group.add_argument(
809 "--exit-char",
810 type=int,
811 metavar='NUM',
812 help="Unicode of special character that is used to exit the application, default: %(default)s",
813 default=0x1d) # GS/CTRL+]
815 group.add_argument(
816 "--menu-char",
817 type=int,
818 metavar='NUM',
819 help="Unicode code of special character that is used to control miniterm (menu), default: %(default)s",
820 default=0x14) # Menu: CTRL+T
822 group = parser.add_argument_group("diagnostics")
824 group.add_argument(
825 "-q", "--quiet",
826 action="store_true",
827 help="suppress non-error messages",
828 default=False)
830 group.add_argument(
831 "--develop",
832 action="store_true",
833 help="show Python traceback on error",
834 default=False)
836 args = parser.parse_args()
838 if args.menu_char == args.exit_char:
839 parser.error('--exit-char can not be the same as --menu-char')
841 if args.filter:
842 if 'help' in args.filter:
843 sys.stderr.write('Available filters:\n')
844 sys.stderr.write('\n'.join(
845 '{:<10} = {.__doc__}'.format(k, v)
846 for k, v in sorted(TRANSFORMATIONS.items())))
847 sys.stderr.write('\n')
848 sys.exit(1)
849 filters = args.filter
850 else:
851 filters = ['default']
853 while True:
854 # no port given on command line -> ask user now
855 if args.port is None or args.port == '-':
856 try:
857 args.port = ask_for_port()
858 except KeyboardInterrupt:
859 sys.stderr.write('\n')
860 parser.error('user aborted and port is not given')
861 else:
862 if not args.port:
863 parser.error('port is not given')
864 try:
865 serial_instance = serial.serial_for_url(
866 args.port,
867 args.baudrate,
868 parity=args.parity,
869 rtscts=args.rtscts,
870 xonxoff=args.xonxoff,
871 do_not_open=True)
873 if not hasattr(serial_instance, 'cancel_read'):
874 # enable timeout for alive flag polling if cancel_read is not available
875 serial_instance.timeout = 1
877 if args.dtr is not None:
878 if not args.quiet:
879 sys.stderr.write('--- forcing DTR {}\n'.format('active' if args.dtr else 'inactive'))
880 serial_instance.dtr = args.dtr
881 if args.rts is not None:
882 if not args.quiet:
883 sys.stderr.write('--- forcing RTS {}\n'.format('active' if args.rts else 'inactive'))
884 serial_instance.rts = args.rts
886 serial_instance.open()
887 except serial.SerialException as e:
888 sys.stderr.write('could not open port {}: {}\n'.format(repr(args.port), e))
889 if args.develop:
890 raise
891 if not args.ask:
892 sys.exit(1)
893 else:
894 args.port = '-'
895 else:
896 break
898 miniterm = Miniterm(
899 serial_instance,
900 echo=args.echo,
901 eol=args.eol.lower(),
902 filters=filters)
903 miniterm.exit_character = unichr(args.exit_char)
904 miniterm.menu_character = unichr(args.menu_char)
905 miniterm.raw = args.raw
906 miniterm.set_rx_encoding(args.serial_port_encoding)
907 miniterm.set_tx_encoding(args.serial_port_encoding)
909 if not args.quiet:
910 sys.stderr.write('--- Miniterm on {p.name} {p.baudrate},{p.bytesize},{p.parity},{p.stopbits} ---\n'.format(
911 p=miniterm.serial))
912 sys.stderr.write('--- Quit: {} | Menu: {} | Help: {} followed by {} ---\n'.format(
913 key_description(miniterm.exit_character),
914 key_description(miniterm.menu_character),
915 key_description(miniterm.menu_character),
916 key_description('\x08')))
918 miniterm.start()
919 try:
920 miniterm.join(True)
921 except KeyboardInterrupt:
922 pass
923 if not args.quiet:
924 sys.stderr.write("\n--- exit ---\n")
925 miniterm.join()
926 miniterm.close()
928 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
929 if __name__ == '__main__':
930 main()