~ubuntu-branches/ubuntu/quantal/pyserial/quantal

« back to all changes in this revision

Viewing changes to examples/miniterm.py

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2004-08-29 14:49:57 UTC
  • mfrom: (1.1.1 upstream)
  • Revision ID: james.westby@ubuntu.com-20040829144957-moa3k4yx4qte5qth
Tags: 2.1-1
New upstream version.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
#!/usr/bin/env python
2
2
 
3
 
#very simple serial terminal
4
 
#(C)2002 Chris Liechti >cliecht@gmx.net>
 
3
# Very simple serial terminal
 
4
# (C)2002-2004 Chris Liechti <cliecht@gmx.net>
5
5
 
6
 
#input characters are sent directly, received characters are displays as is
7
 
#baudrate and echo configuartion is done through globals
 
6
# Input characters are sent directly (only LF -> CR/LF/CRLF translation is
 
7
# done), received characters are displayed as is (or as trough pythons
 
8
# repr, useful for debug purposes)
 
9
# Baudrate and echo configuartion is done through globals
8
10
 
9
11
 
10
12
import sys, os, serial, threading, getopt
11
 
#EXITCHARCTER = '\x1b'   #ESC
12
 
EXITCHARCTER = '\x04'   #ctrl+d
13
 
 
14
 
#first choosea platform dependant way to read single characters from the console
 
13
 
 
14
EXITCHARCTER = '\x04'   #ctrl+D
 
15
 
 
16
#first choose a platform dependant way to read single characters from the console
15
17
if os.name == 'nt':
16
18
    import msvcrt
17
19
    def getkey():
23
25
            if z == '\0' or z == '\xe0':    #functions keys
24
26
                msvcrt.getch()
25
27
            else:
 
28
                if z == '\r':
 
29
                    return '\n'
26
30
                return z
27
31
 
28
32
elif os.name == 'posix':
29
 
    #XXX: Untested code drrived from the Python FAQ....
30
 
    import termios, TERMIOS, sys, os
 
33
    import termios, sys, os
31
34
    fd = sys.stdin.fileno()
32
35
    old = termios.tcgetattr(fd)
33
36
    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)
 
37
    new[3] = new[3] & ~termios.ICANON & ~termios.ECHO
 
38
    new[6][termios.VMIN] = 1
 
39
    new[6][termios.VTIME] = 0
 
40
    termios.tcsetattr(fd, termios.TCSANOW, new)
38
41
    s = ''    # We'll save the characters typed and add them to the pool.
39
42
    def getkey():
40
 
        #~ c = os.read(fd, 1)
41
 
        c = sys.stdin.read(1)
42
 
        if echo: sys.stdout.write(c)
 
43
        c = os.read(fd, 1)
 
44
        #~ c = sys.stdin.read(1)
 
45
        if echo: sys.stdout.write(c); sys.stdout.flush()
43
46
        return c
44
47
    def clenaup_console():
45
 
        termios.tcsetattr(fd, TERMIOS.TCSAFLUSH, old)
46
 
    sys.exitfunc = clenaup_console  #terminal modes have to be restored on exit...
 
48
        termios.tcsetattr(fd, termios.TCSAFLUSH, old)
 
49
    sys.exitfunc = clenaup_console      #terminal modes have to be restored on exit...
47
50
 
48
51
else:
49
52
    raise "Sorry no implementation for your platform (%s) available." % sys.platform
50
53
 
 
54
CONVERT_CRLF = 2
 
55
CONVERT_CR   = 1
 
56
CONVERT_LF   = 0
51
57
 
52
58
def reader():
53
59
    """loop forever and copy serial->console"""
54
60
    while 1:
55
 
        sys.stdout.write(s.read())
 
61
        data = s.read()
 
62
        if repr_mode:
 
63
            sys.stdout.write(repr(data)[1:-1])
 
64
        else:
 
65
            sys.stdout.write(data)
 
66
        sys.stdout.flush()
56
67
 
57
68
def writer():
58
69
    """loop and copy console->serial until EOF character is found"""
59
70
    while 1:
60
71
        c = getkey()
61
 
        if c == EXITCHARCTER: break   #exit on esc
62
 
        s.write(c)              #send character
63
 
        if convert_outgoing_cr and c == '\r':
64
 
            s.write('\n')
65
 
            if echo: sys.stdout.write('\n')
 
72
        if c == EXITCHARCTER: 
 
73
            break                       #exit app
 
74
        elif c == '\n':
 
75
            if convert_outgoing == CONVERT_CRLF:
 
76
                s.write('\r\n')         #make it a CR+LF
 
77
            elif convert_outgoing == CONVERT_CR:
 
78
                s.write('\r')           #make it a CR
 
79
            elif convert_outgoing == CONVERT_LF:
 
80
                s.write('\n')           #make it a LF
 
81
        else:
 
82
            s.write(c)                  #send character
66
83
 
67
84
 
68
85
#print a short help message
69
86
def usage():
70
 
    print >>sys.stderr, """USAGE: %s [options]
71
 
    Simple Terminal Programm for the serial port.
 
87
    sys.stderr.write("""USAGE: %s [options]
 
88
    Miniterm - A simple terminal program for the serial port.
72
89
 
73
90
    options:
74
 
    -p, --port=PORT: port, a number, defualt = 0 or a device name
 
91
    -p, --port=PORT: port, a number, default = 0 or a device name
75
92
    -b, --baud=BAUD: baudrate, default 9600
76
93
    -r, --rtscts:    enable RTS/CTS flow control (default off)
77
94
    -x, --xonxoff:   enable software flow control (default off)
78
95
    -e, --echo:      enable local echo (default off)
79
 
    -c, --cr:        disable CR -> CR+LF translation
 
96
    -c, --cr:        do not send CR+LF, send CR only
 
97
    -n, --newline:   do not send CR+LF, send LF only
 
98
    -D, --debug:     debug received data (escape nonprintable chars)
80
99
 
81
 
    """ % sys.argv[0]
 
100
""" % (sys.argv[0], ))
82
101
 
83
102
if __name__ == '__main__':
 
103
    #initialize with defaults
 
104
    port  = 0
 
105
    baudrate = 9600
 
106
    echo = 0
 
107
    convert_outgoing = CONVERT_CRLF
 
108
    rtscts = 0
 
109
    xonxoff = 0
 
110
    repr_mode = 0
 
111
    
84
112
    #parse command line options
85
113
    try:
86
114
        opts, args = getopt.getopt(sys.argv[1:],
87
 
                "hp:b:rxec",
88
 
                ["help", "port=", "baud=", "rtscts", "xonxoff", "echo", "cr"])
 
115
            "hp:b:rxecnD",
 
116
            ["help", "port=", "baud=", "rtscts", "xonxoff", "echo",
 
117
            "cr", "newline", "debug"]
 
118
        )
89
119
    except getopt.GetoptError:
90
120
        # print help information and exit:
91
121
        usage()
92
122
        sys.exit(2)
93
123
    
94
 
    port  = 0
95
 
    baudrate = 9600
96
 
    echo = 0
97
 
    convert_outgoing_cr = 1
98
 
    rtscts = 0
99
 
    xonxoff = 0
100
124
    for o, a in opts:
101
 
        if o in ("-h", "--help"):   #help text
 
125
        if o in ("-h", "--help"):       #help text
102
126
            usage()
103
127
            sys.exit()
104
 
        elif o in ("-p", "--port"):   #specified port
 
128
        elif o in ("-p", "--port"):     #specified port
105
129
            try:
106
130
                port = int(a)
107
131
            except ValueError:
108
132
                port = a
109
 
        elif o in ("-b", "--baud"):   #specified baudrate
 
133
        elif o in ("-b", "--baud"):     #specified baudrate
110
134
            try:
111
135
                baudrate = int(a)
112
136
            except ValueError:
113
 
                raise ValueError, "Baudrate must be a integer number"
 
137
                raise ValueError, "Baudrate must be a integer number, not %r" % a
114
138
        elif o in ("-r", "--rtscts"):
115
139
            rtscts = 1
116
140
        elif o in ("-x", "--xonxoff"):
118
142
        elif o in ("-e", "--echo"):
119
143
            echo = 1
120
144
        elif o in ("-c", "--cr"):
121
 
            convert_outgoing_cr = 0
 
145
            convert_outgoing = CONVERT_CR
 
146
        elif o in ("-n", "--newline"):
 
147
            convert_outgoing = CONVERT_LF
 
148
        elif o in ("-D", "--debug"):
 
149
            repr_mode = 1
122
150
 
 
151
    #open the port
123
152
    try:
124
153
        s = serial.Serial(port, baudrate, rtscts=rtscts, xonxoff=xonxoff)
125
154
    except:
126
 
        print "could not open port"
 
155
        sys.stderr.write("Could not open port\n")
127
156
        sys.exit(1)
128
 
    print "--- Miniterm --- type Ctrl-D to quit"
 
157
    sys.stderr.write("--- Miniterm --- type Ctrl-D to quit\n")
129
158
    #start serial->console thread
130
159
    r = threading.Thread(target=reader)
131
160
    r.setDaemon(1)
132
161
    r.start()
133
 
    #enter console->serial loop
 
162
    #and enter console->serial loop
134
163
    writer()
135
164
 
136
 
    print "\n--- exit ---"
 
165
    sys.stderr.write("\n--- exit ---\n")