2 #very simple serial terminal
3 #http://pyserial.sf.net package required
4 #input characters are sent directly, received characters are displays as is
5 #baudrate and echo configuartion is done through globals:
9 import sys, os, serial, threading, getopt
10 #EXITCHARCTER = '\x1b' #ESC
11 EXITCHARCTER = '\x04' #ctrl+d
13 #first choosea platform dependant way to read single characters from the console
14 if os.name == 'nt': #sys.platform == 'win32':
22 if z == '\0' or z == '\xe0': #functions keys
27 elif os.name == 'posix':
28 #XXX: Untested code derrived from the Python FAQ....
29 # import termios, TERMIOS, sys, os
30 import termios, sys, os
31 fd = sys.stdin.fileno()
32 old = termios.tcgetattr(fd)
33 new = termios.tcgetattr(fd)
34 new[3] = new[3] & ~TERMIOS.ICANON & ~TERMIOS.ECHO
35 new[6][TERMIOS.VMIN] = 1
36 new[6][TERMIOS.VTIME] = 0
37 termios.tcsetattr(fd, TERMIOS.TCSANOW, new)
38 s = '' # We'll save the characters typed and add them to the pool.
41 if echo: sys.stdout.write(c)
43 def clenaup_console():
44 termios.tcsetattr(fd, TERMIOS.TCSAFLUSH, old)
45 sys.exitfunc = clenaup_console #terminal modes have to be restored on exit...
48 raise "Sorry no implementation for your platform (%s) available." % sys.platform
52 """loop forever and copy serial->console"""
54 sys.stdout.write(s.read())
57 """loop forever and copy console->serial"""
60 if c == EXITCHARCTER: break #exit on esc
61 s.write(c) #send character
62 if convert_outgoing_cr and c == '\r':
64 if echo: sys.stdout.write('\n')
67 #print a short help message
69 print >>sys.stderr, """USAGE: %s [options]
70 Simple Terminal Programm for the serial port.
73 -p, --port=PORT: port, a number, defualt = 0 or a device name
74 -b, --baud=BAUD: baudrate, default 9600
75 -r, --rtscts: enable RTS/CTS flow control (default off)
76 -x, --xonxoff: enable software flow control (default off)
77 -e, --echo: enable local echo (default off)
78 -c, --cr: disable CR -> CR+LF translation
82 if __name__ == '__main__':
83 #parse command line options
85 opts, args = getopt.getopt(sys.argv[1:],
87 ["help", "port=", "baud=", "rtscts", "xonxoff", "echo", "cr"])
88 except getopt.GetoptError:
89 # print help information and exit:
96 convert_outgoing_cr = 1
100 if o in ("-h", "--help"): #help text
103 elif o in ("-p", "--port"): #specified port
108 elif o in ("-b", "--baud"): #specified baudrate
112 raise ValueError, "Baudrate must be a integer number"
113 elif o in ("-r", "--rtscts"):
115 elif o in ("-x", "--xonxoff"):
117 elif o in ("-e", "--echo"):
119 elif o in ("-c", "--cr"):
120 convert_outgoing_cr = 0
123 s = serial.Serial(port, baudrate, rtscts=rtscts, xonxoff=xonxoff)
125 print "could not open port"
127 print "--- Miniterm --- type Ctrl-D to quit"
128 #start serial->console thread
129 r = threading.Thread(target=reader)
132 #enter console->serial loop
135 print "\n--- exit ---"