Bike-X  0.8
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
miniterm.py
Go to the documentation of this file.
1 #!/usr/bin/python
2 
3 # Very simple serial terminal
4 # (C)2002-2011 Chris Liechti <cliechti@gmx.net>
5 
6 # Input characters are sent directly (only LF -> CR/LF/CRLF translation is
7 # done), received characters are displayed as is (or escaped trough pythons
8 # repr, useful for debug purposes)
9 
10 
11 import sys, os, serial, threading
12 
13 EXITCHARCTER = '\x1d' # GS/CTRL+]
14 MENUCHARACTER = '\x14' # Menu: CTRL+T
15 
16 
17 def key_description(character):
18  """generate a readable description for a key"""
19  ascii_code = ord(character)
20  if ascii_code < 32:
21  return 'Ctrl+%c' % (ord('@') + ascii_code)
22  else:
23  return repr(character)
24 
25 
26 # help text, starts with blank line! it's a function so that the current values
27 # for the shortcut keys is used and not the value at program start
29  return """
30 --- pySerial (%(version)s) - miniterm - help
31 ---
32 --- %(exit)-8s Exit program
33 --- %(menu)-8s Menu escape key, followed by:
34 --- Menu keys:
35 --- %(itself)-7s Send the menu character itself to remote
36 --- %(exchar)-7s Send the exit character itself to remote
37 --- %(info)-7s Show info
38 --- %(upload)-7s Upload file (prompt will be shown)
39 --- Toggles:
40 --- %(rts)-7s RTS %(echo)-7s local echo
41 --- %(dtr)-7s DTR %(break)-7s BREAK
42 --- %(lfm)-7s line feed %(repr)-7s Cycle repr mode
43 ---
44 --- Port settings (%(menu)s followed by the following):
45 --- p change port
46 --- 7 8 set data bits
47 --- n e o s m change parity (None, Even, Odd, Space, Mark)
48 --- 1 2 3 set stop bits (1, 2, 1.5)
49 --- b change baud rate
50 --- x X disable/enable software flow control
51 --- r R disable/enable hardware flow control
52 """ % {
53  'version': getattr(serial, 'VERSION', 'unknown version'),
54  'exit': key_description(EXITCHARCTER),
55  'menu': key_description(MENUCHARACTER),
56  'rts': key_description('\x12'),
57  'repr': key_description('\x01'),
58  'dtr': key_description('\x04'),
59  'lfm': key_description('\x0c'),
60  'break': key_description('\x02'),
61  'echo': key_description('\x05'),
62  'info': key_description('\x09'),
63  'upload': key_description('\x15'),
64  'itself': key_description(MENUCHARACTER),
65  'exchar': key_description(EXITCHARCTER),
66 }
67 
68 if sys.version_info >= (3, 0):
69  def character(b):
70  return b.decode('latin1')
71 else:
72  def character(b):
73  return b
74 
75 # first choose a platform dependant way to read single characters from the console
76 global console
77 
78 if os.name == 'nt':
79  import msvcrt
80  class Console(object):
81  def __init__(self):
82  pass
83 
84  def setup(self):
85  pass # Do nothing for 'nt'
86 
87  def cleanup(self):
88  pass # Do nothing for 'nt'
89 
90  def getkey(self):
91  while True:
92  z = msvcrt.getch()
93  if z == '\0' or z == '\xe0': # functions keys, ignore
94  msvcrt.getch()
95  else:
96  if z == '\r':
97  return '\n'
98  return z
99 
100  console = Console()
101 
102 elif os.name == 'posix':
103  import termios, sys, os
104  class Console(object):
105  def __init__(self):
106  self.fd = sys.stdin.fileno()
107 
108  def setup(self):
109  self.old = termios.tcgetattr(self.fd)
110  new = termios.tcgetattr(self.fd)
111  new[3] = new[3] & ~termios.ICANON & ~termios.ECHO & ~termios.ISIG
112  new[6][termios.VMIN] = 1
113  new[6][termios.VTIME] = 0
114  termios.tcsetattr(self.fd, termios.TCSANOW, new)
115 
116  def getkey(self):
117  c = os.read(self.fd, 1)
118  return c
119 
120  def cleanup(self):
121  termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old)
122 
123  console = Console()
124 
126  console.cleanup()
127 
128  console.setup()
129  sys.exitfunc = cleanup_console # terminal modes have to be restored on exit...
130 
131 else:
132  raise NotImplementedError("Sorry no implementation for your platform (%s) available." % sys.platform)
133 
134 
135 CONVERT_CRLF = 2
136 CONVERT_CR = 1
137 CONVERT_LF = 0
138 NEWLINE_CONVERISON_MAP = ('\n', '\r', '\r\n')
139 LF_MODES = ('LF', 'CR', 'CR/LF')
140 
141 REPR_MODES = ('raw', 'some control', 'all control', 'hex')
142 
143 class Miniterm(object):
144  def __init__(self, port, baudrate, parity, rtscts, xonxoff, echo=False, convert_outgoing=CONVERT_CRLF, repr_mode=0):
145  try:
146  self.serial = serial.serial_for_url(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1)
147  except AttributeError:
148  # happens when the installed pyserial is older than 2.5. use the
149  # Serial class directly then.
150  self.serial = serial.Serial(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1)
151  self.echo = echo
152  self.repr_mode = repr_mode
153  self.convert_outgoing = convert_outgoing
154  self.newline = NEWLINE_CONVERISON_MAP[self.convert_outgoing]
155  self.dtr_state = True
156  self.rts_state = True
157  self.break_state = False
158 
159  def _start_reader(self):
160  """Start reader thread"""
161  self._reader_alive = True
162  # start serial->console thread
163  self.receiver_thread = threading.Thread(target=self.reader)
164  self.receiver_thread.setDaemon(True)
165  self.receiver_thread.start()
166 
167  def _stop_reader(self):
168  """Stop reader thread only, wait for clean exit of thread"""
169  self._reader_alive = False
170  self.receiver_thread.join()
171 
172 
173  def start(self):
174  self.alive = True
175  self._start_reader()
176  # enter console->serial loop
177  self.transmitter_thread = threading.Thread(target=self.writer)
178  self.transmitter_thread.setDaemon(True)
179  self.transmitter_thread.start()
180 
181  def stop(self):
182  self.alive = False
183 
184  def join(self, transmit_only=False):
185  self.transmitter_thread.join()
186  if not transmit_only:
187  self.receiver_thread.join()
188 
190  sys.stderr.write("\n--- Settings: %s %s,%s,%s,%s\n" % (
191  self.serial.portstr,
192  self.serial.baudrate,
193  self.serial.bytesize,
194  self.serial.parity,
195  self.serial.stopbits))
196  sys.stderr.write('--- RTS: %-8s DTR: %-8s BREAK: %-8s\n' % (
197  (self.rts_state and 'active' or 'inactive'),
198  (self.dtr_state and 'active' or 'inactive'),
199  (self.break_state and 'active' or 'inactive')))
200  try:
201  sys.stderr.write('--- CTS: %-8s DSR: %-8s RI: %-8s CD: %-8s\n' % (
202  (self.serial.getCTS() and 'active' or 'inactive'),
203  (self.serial.getDSR() and 'active' or 'inactive'),
204  (self.serial.getRI() and 'active' or 'inactive'),
205  (self.serial.getCD() and 'active' or 'inactive')))
206  except serial.SerialException:
207  # on RFC 2217 ports it can happen to no modem state notification was
208  # yet received. ignore this error.
209  pass
210  sys.stderr.write('--- software flow control: %s\n' % (self.serial.xonxoff and 'active' or 'inactive'))
211  sys.stderr.write('--- hardware flow control: %s\n' % (self.serial.rtscts and 'active' or 'inactive'))
212  sys.stderr.write('--- data escaping: %s linefeed: %s\n' % (
213  REPR_MODES[self.repr_mode],
214  LF_MODES[self.convert_outgoing]))
215 
216  def reader(self):
217  """loop and copy serial->console"""
218  try:
219  while self.alive and self._reader_alive:
220  data = character(self.serial.read(1))
221 
222  if self.repr_mode == 0:
223  # direct output, just have to care about newline setting
224  if data == '\r' and self.convert_outgoing == CONVERT_CR:
225  sys.stdout.write('\n')
226  else:
227  sys.stdout.write(data)
228  elif self.repr_mode == 1:
229  # escape non-printable, let pass newlines
230  if self.convert_outgoing == CONVERT_CRLF and data in '\r\n':
231  if data == '\n':
232  sys.stdout.write('\n')
233  elif data == '\r':
234  pass
235  elif data == '\n' and self.convert_outgoing == CONVERT_LF:
236  sys.stdout.write('\n')
237  elif data == '\r' and self.convert_outgoing == CONVERT_CR:
238  sys.stdout.write('\n')
239  else:
240  sys.stdout.write(repr(data)[1:-1])
241  elif self.repr_mode == 2:
242  # escape all non-printable, including newline
243  sys.stdout.write(repr(data)[1:-1])
244  elif self.repr_mode == 3:
245  # escape everything (hexdump)
246  for c in data:
247  sys.stdout.write("%s " % c.encode('hex'))
248  sys.stdout.flush()
249  except serial.SerialException, e:
250  self.alive = False
251  # would be nice if the console reader could be interruptted at this
252  # point...
253  raise
254 
255 
256  def writer(self):
257  """\
258  Loop and copy console->serial until EXITCHARCTER character is
259  found. When MENUCHARACTER is found, interpret the next key
260  locally.
261  """
262  menu_active = False
263  try:
264  while self.alive:
265  try:
266  b = console.getkey()
267  except KeyboardInterrupt:
268  b = serial.to_bytes([3])
269  c = character(b)
270  if menu_active:
271  if c == MENUCHARACTER or c == EXITCHARCTER: # Menu character again/exit char -> send itself
272  self.serial.write(b) # send character
273  if self.echo:
274  sys.stdout.write(c)
275  elif c == '\x15': # CTRL+U -> upload file
276  sys.stderr.write('\n--- File to upload: ')
277  sys.stderr.flush()
278  console.cleanup()
279  filename = sys.stdin.readline().rstrip('\r\n')
280  if filename:
281  try:
282  file = open(filename, 'r')
283  sys.stderr.write('--- Sending file %s ---\n' % filename)
284  while True:
285  line = file.readline().rstrip('\r\n')
286  if not line:
287  break
288  self.serial.write(line)
289  self.serial.write('\r\n')
290  # Wait for output buffer to drain.
291  self.serial.flush()
292  sys.stderr.write('.') # Progress indicator.
293  sys.stderr.write('\n--- File %s sent ---\n' % filename)
294  except IOError, e:
295  sys.stderr.write('--- ERROR opening file %s: %s ---\n' % (filename, e))
296  console.setup()
297  elif c in '\x08hH?': # CTRL+H, h, H, ? -> Show help
298  sys.stderr.write(get_help_text())
299  elif c == '\x12': # CTRL+R -> Toggle RTS
300  self.rts_state = not self.rts_state
301  self.serial.setRTS(self.rts_state)
302  sys.stderr.write('--- RTS %s ---\n' % (self.rts_state and 'active' or 'inactive'))
303  elif c == '\x04': # CTRL+D -> Toggle DTR
304  self.dtr_state = not self.dtr_state
305  self.serial.setDTR(self.dtr_state)
306  sys.stderr.write('--- DTR %s ---\n' % (self.dtr_state and 'active' or 'inactive'))
307  elif c == '\x02': # CTRL+B -> toggle BREAK condition
308  self.break_state = not self.break_state
309  self.serial.setBreak(self.break_state)
310  sys.stderr.write('--- BREAK %s ---\n' % (self.break_state and 'active' or 'inactive'))
311  elif c == '\x05': # CTRL+E -> toggle local echo
312  self.echo = not self.echo
313  sys.stderr.write('--- local echo %s ---\n' % (self.echo and 'active' or 'inactive'))
314  elif c == '\x09': # CTRL+I -> info
315  self.dump_port_settings()
316  elif c == '\x01': # CTRL+A -> cycle escape mode
317  self.repr_mode += 1
318  if self.repr_mode > 3:
319  self.repr_mode = 0
320  sys.stderr.write('--- escape data: %s ---\n' % (
321  REPR_MODES[self.repr_mode],
322  ))
323  elif c == '\x0c': # CTRL+L -> cycle linefeed mode
324  self.convert_outgoing += 1
325  if self.convert_outgoing > 2:
326  self.convert_outgoing = 0
327  self.newline = NEWLINE_CONVERISON_MAP[self.convert_outgoing]
328  sys.stderr.write('--- line feed %s ---\n' % (
329  LF_MODES[self.convert_outgoing],
330  ))
331  elif c in 'pP': # P -> change port
332  sys.stderr.write('\n--- Enter port name: ')
333  sys.stderr.flush()
334  console.cleanup()
335  try:
336  port = sys.stdin.readline().strip()
337  except KeyboardInterrupt:
338  port = None
339  console.setup()
340  if port and port != self.serial.port:
341  # reader thread needs to be shut down
342  self._stop_reader()
343  # save settings
344  settings = self.serial.getSettingsDict()
345  try:
346  try:
347  new_serial = serial.serial_for_url(port, do_not_open=True)
348  except AttributeError:
349  # happens when the installed pyserial is older than 2.5. use the
350  # Serial class directly then.
351  new_serial = serial.Serial()
352  new_serial.port = port
353  # restore settings and open
354  new_serial.applySettingsDict(settings)
355  new_serial.open()
356  new_serial.setRTS(self.rts_state)
357  new_serial.setDTR(self.dtr_state)
358  new_serial.setBreak(self.break_state)
359  except Exception, e:
360  sys.stderr.write('--- ERROR opening new port: %s ---\n' % (e,))
361  new_serial.close()
362  else:
363  self.serial.close()
364  self.serial = new_serial
365  sys.stderr.write('--- Port changed to: %s ---\n' % (self.serial.port,))
366  # and restart the reader thread
367  self._start_reader()
368  elif c in 'bB': # B -> change baudrate
369  sys.stderr.write('\n--- Baudrate: ')
370  sys.stderr.flush()
371  console.cleanup()
372  backup = self.serial.baudrate
373  try:
374  self.serial.baudrate = int(sys.stdin.readline().strip())
375  except ValueError, e:
376  sys.stderr.write('--- ERROR setting baudrate: %s ---\n' % (e,))
377  self.serial.baudrate = backup
378  else:
379  self.dump_port_settings()
380  console.setup()
381  elif c == '8': # 8 -> change to 8 bits
382  self.serial.bytesize = serial.EIGHTBITS
383  self.dump_port_settings()
384  elif c == '7': # 7 -> change to 8 bits
385  self.serial.bytesize = serial.SEVENBITS
386  self.dump_port_settings()
387  elif c in 'eE': # E -> change to even parity
388  self.serial.parity = serial.PARITY_EVEN
389  self.dump_port_settings()
390  elif c in 'oO': # O -> change to odd parity
391  self.serial.parity = serial.PARITY_ODD
392  self.dump_port_settings()
393  elif c in 'mM': # M -> change to mark parity
394  self.serial.parity = serial.PARITY_MARK
395  self.dump_port_settings()
396  elif c in 'sS': # S -> change to space parity
397  self.serial.parity = serial.PARITY_SPACE
398  self.dump_port_settings()
399  elif c in 'nN': # N -> change to no parity
400  self.serial.parity = serial.PARITY_NONE
401  self.dump_port_settings()
402  elif c == '1': # 1 -> change to 1 stop bits
403  self.serial.stopbits = serial.STOPBITS_ONE
404  self.dump_port_settings()
405  elif c == '2': # 2 -> change to 2 stop bits
406  self.serial.stopbits = serial.STOPBITS_TWO
407  self.dump_port_settings()
408  elif c == '3': # 3 -> change to 1.5 stop bits
409  self.serial.stopbits = serial.STOPBITS_ONE_POINT_FIVE
410  self.dump_port_settings()
411  elif c in 'xX': # X -> change software flow control
412  self.serial.xonxoff = (c == 'X')
413  self.dump_port_settings()
414  elif c in 'rR': # R -> change hardware flow control
415  self.serial.rtscts = (c == 'R')
416  self.dump_port_settings()
417  else:
418  sys.stderr.write('--- unknown menu character %s --\n' % key_description(c))
419  menu_active = False
420  elif c == MENUCHARACTER: # next char will be for menu
421  menu_active = True
422  elif c == EXITCHARCTER:
423  self.stop()
424  break # exit app
425  elif c == '\n':
426  self.serial.write(self.newline) # send newline character(s)
427  if self.echo:
428  sys.stdout.write(c) # local echo is a real newline in any case
429  sys.stdout.flush()
430  else:
431  self.serial.write(b) # send byte
432  if self.echo:
433  sys.stdout.write(c)
434  sys.stdout.flush()
435  except:
436  self.alive = False
437  raise
438 
439 def main():
440  import optparse
441 
442  parser = optparse.OptionParser(
443  usage = "%prog [options] [port [baudrate]]",
444  description = "Miniterm - A simple terminal program for the serial port."
445  )
446 
447  parser.add_option("-p", "--port",
448  dest = "port",
449  help = "port, a number or a device name. (deprecated option, use parameter instead)",
450  default = None
451  )
452 
453  parser.add_option("-b", "--baud",
454  dest = "baudrate",
455  action = "store",
456  type = 'int',
457  help = "set baud rate, default %default",
458  default = 9600
459  )
460 
461  parser.add_option("--parity",
462  dest = "parity",
463  action = "store",
464  help = "set parity, one of [N, E, O, S, M], default=N",
465  default = 'N'
466  )
467 
468  parser.add_option("-e", "--echo",
469  dest = "echo",
470  action = "store_true",
471  help = "enable local echo (default off)",
472  default = False
473  )
474 
475  parser.add_option("--rtscts",
476  dest = "rtscts",
477  action = "store_true",
478  help = "enable RTS/CTS flow control (default off)",
479  default = False
480  )
481 
482  parser.add_option("--xonxoff",
483  dest = "xonxoff",
484  action = "store_true",
485  help = "enable software flow control (default off)",
486  default = False
487  )
488 
489  parser.add_option("--cr",
490  dest = "cr",
491  action = "store_true",
492  help = "do not send CR+LF, send CR only",
493  default = False
494  )
495 
496  parser.add_option("--lf",
497  dest = "lf",
498  action = "store_true",
499  help = "do not send CR+LF, send LF only",
500  default = False
501  )
502 
503  parser.add_option("-D", "--debug",
504  dest = "repr_mode",
505  action = "count",
506  help = """debug received data (escape non-printable chars)
507 --debug can be given multiple times:
508 0: just print what is received
509 1: escape non-printable characters, do newlines as unusual
510 2: escape non-printable characters, newlines too
511 3: hex dump everything""",
512  default = 0
513  )
514 
515  parser.add_option("--rts",
516  dest = "rts_state",
517  action = "store",
518  type = 'int',
519  help = "set initial RTS line state (possible values: 0, 1)",
520  default = None
521  )
522 
523  parser.add_option("--dtr",
524  dest = "dtr_state",
525  action = "store",
526  type = 'int',
527  help = "set initial DTR line state (possible values: 0, 1)",
528  default = None
529  )
530 
531  parser.add_option("-q", "--quiet",
532  dest = "quiet",
533  action = "store_true",
534  help = "suppress non error messages",
535  default = False
536  )
537 
538  parser.add_option("--exit-char",
539  dest = "exit_char",
540  action = "store",
541  type = 'int',
542  help = "ASCII code of special character that is used to exit the application",
543  default = 0x1d
544  )
545 
546  parser.add_option("--menu-char",
547  dest = "menu_char",
548  action = "store",
549  type = 'int',
550  help = "ASCII code of special character that is used to control miniterm (menu)",
551  default = 0x14
552  )
553 
554  (options, args) = parser.parse_args()
555 
556  options.parity = options.parity.upper()
557  if options.parity not in 'NEOSM':
558  parser.error("invalid parity")
559 
560  if options.cr and options.lf:
561  parser.error("only one of --cr or --lf can be specified")
562 
563  if options.menu_char == options.exit_char:
564  parser.error('--exit-char can not be the same as --menu-char')
565 
566  global EXITCHARCTER, MENUCHARACTER
567  EXITCHARCTER = chr(options.exit_char)
568  MENUCHARACTER = chr(options.menu_char)
569 
570  port = options.port
571  baudrate = options.baudrate
572  if args:
573  if options.port is not None:
574  parser.error("no arguments are allowed, options only when --port is given")
575  port = args.pop(0)
576  if args:
577  try:
578  baudrate = int(args[0])
579  except ValueError:
580  parser.error("baud rate must be a number, not %r" % args[0])
581  args.pop(0)
582  if args:
583  parser.error("too many arguments")
584  else:
585  if port is None: port = 0
586 
587  convert_outgoing = CONVERT_CRLF
588  if options.cr:
589  convert_outgoing = CONVERT_CR
590  elif options.lf:
591  convert_outgoing = CONVERT_LF
592 
593  try:
594  miniterm = Miniterm(
595  port,
596  baudrate,
597  options.parity,
598  rtscts=options.rtscts,
599  xonxoff=options.xonxoff,
600  echo=options.echo,
601  convert_outgoing=convert_outgoing,
602  repr_mode=options.repr_mode,
603  )
604  except serial.SerialException, e:
605  sys.stderr.write("could not open port %r: %s\n" % (port, e))
606  sys.exit(1)
607 
608  if not options.quiet:
609  sys.stderr.write('--- Miniterm on %s: %d,%s,%s,%s ---\n' % (
610  miniterm.serial.portstr,
611  miniterm.serial.baudrate,
612  miniterm.serial.bytesize,
613  miniterm.serial.parity,
614  miniterm.serial.stopbits,
615  ))
616  sys.stderr.write('--- Quit: %s | Menu: %s | Help: %s followed by %s ---\n' % (
617  key_description(EXITCHARCTER),
618  key_description(MENUCHARACTER),
619  key_description(MENUCHARACTER),
620  key_description('\x08'),
621  ))
622 
623  if options.dtr_state is not None:
624  if not options.quiet:
625  sys.stderr.write('--- forcing DTR %s\n' % (options.dtr_state and 'active' or 'inactive'))
626  miniterm.serial.setDTR(options.dtr_state)
627  miniterm.dtr_state = options.dtr_state
628  if options.rts_state is not None:
629  if not options.quiet:
630  sys.stderr.write('--- forcing RTS %s\n' % (options.rts_state and 'active' or 'inactive'))
631  miniterm.serial.setRTS(options.rts_state)
632  miniterm.rts_state = options.rts_state
633 
634  miniterm.start()
635  try:
636  miniterm.join(True)
637  except KeyboardInterrupt:
638  pass
639  if not options.quiet:
640  sys.stderr.write("\n--- exit ---\n")
641  miniterm.join()
642 
643 
644 if __name__ == '__main__':
645  main()