~swe3tdave-deactivatedaccount/ubuntu/trusty/pyserial/fix-for-pronterface

« back to all changes in this revision

Viewing changes to examples/tcp_serial_redirect.py

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2008-06-24 19:14:57 UTC
  • mfrom: (3.1.4 lenny)
  • Revision ID: james.westby@ubuntu.com-20080624191457-l7snsahtf9ngtuti
Tags: 2.3-1
* New upstream version.
* Update watch file. Closes: #450106.
* Mention the upstream name in the package description. Closes: #459590.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/env python
2
 
 
3
 
#(C)2002-2003 Chris Liechti <cliechti@gmx.net>
4
 
#redirect data from a TCP/IP connection to a serial port and vice versa
5
 
#requires Python 2.2 'cause socket.sendall is used
6
 
 
7
 
"""USAGE: tcp_serial_redirect.py [options]
8
 
Simple Serial to Network (TCP/IP) redirector.
9
 
 
10
 
Options:
11
 
  -p, --port=PORT   serial port, a number, defualt = 0 or a device name
12
 
  -b, --baud=BAUD   baudrate, default 9600
13
 
  -r, --rtscts      enable RTS/CTS flow control (default off)
14
 
  -x, --xonxoff     enable software flow control (default off)
15
 
  -P, --localport   TCP/IP port on which to run the server (default 7777)
16
 
 
17
 
Note: no security measures are implemeted. Anyone can remotely connect
18
 
to this service over the network.
19
 
Only one connection at once is supported. If the connection is terminaed
20
 
it waits for the next connect.
21
 
"""
22
 
 
23
 
import sys, os, serial, threading, getopt, socket
24
 
 
25
 
try:
26
 
    True
27
 
except NameError:
28
 
    True = 1
29
 
    False = 0
30
 
 
31
 
class Redirector:
32
 
    def __init__(self, serial, socket):
33
 
        self.serial = serial
34
 
        self.socket = socket
35
 
 
36
 
    def shortcut(self):
37
 
        """connect the serial port to the tcp port by copying everything
38
 
           from one side to the other"""
39
 
        self.alive = True
40
 
        self.thread_read = threading.Thread(target=self.reader)
41
 
        self.thread_read.setDaemon(1)
42
 
        self.thread_read.start()
43
 
        self.writer()
44
 
    
45
 
    def reader(self):
46
 
        """loop forever and copy serial->socket"""
47
 
        while self.alive:
48
 
            try:
49
 
                data = self.serial.read(1)              #read one, blocking
50
 
                n = self.serial.inWaiting()             #look if there is more
51
 
                if n:
52
 
                    data = data + self.serial.read(n)   #and get as much as possible
53
 
                if data:
54
 
                    self.socket.sendall(data)           #send it over TCP
55
 
            except socket.error, msg:
56
 
                print msg
57
 
                #probably got disconnected
58
 
                break
59
 
        self.alive = False
60
 
    
61
 
    def writer(self):
62
 
        """loop forever and copy socket->serial"""
63
 
        while self.alive:
64
 
            try:
65
 
                data = self.socket.recv(1024)
66
 
                if not data:
67
 
                    break
68
 
                self.serial.write(data)                 #get a bunch of bytes and send them
69
 
            except socket.error, msg:
70
 
                print msg
71
 
                #probably got disconnected
72
 
                break
73
 
        self.alive = False
74
 
        self.thread_read.join()
75
 
 
76
 
    def stop(self):
77
 
        """Stop copying"""
78
 
        if self.alive:
79
 
            self.alive = False
80
 
            self.thread_read.join()
81
 
 
82
 
if __name__ == '__main__':
83
 
    ser = serial.Serial()
84
 
    
85
 
    #parse command line options
86
 
    try:
87
 
        opts, args = getopt.getopt(sys.argv[1:],
88
 
                "hp:b:rxP",
89
 
                ["help", "port=", "baud=", "rtscts", "xonxoff", "localport="])
90
 
    except getopt.GetoptError:
91
 
        # print help information and exit:
92
 
        print >>sys.stderr, __doc__
93
 
        sys.exit(2)
94
 
    
95
 
    ser.port    = 0
96
 
    ser.baudrate = 9600
97
 
    ser.rtscts  = False
98
 
    ser.xonxoff = False
99
 
    ser.timeout = 1     #required so that the reader thread can exit
100
 
    
101
 
    localport = 7777
102
 
    for o, a in opts:
103
 
        if o in ("-h", "--help"):   #help text
104
 
            usage()
105
 
            sys.exit()
106
 
        elif o in ("-p", "--port"):   #specified port
107
 
            try:
108
 
                ser.port = int(a)
109
 
            except ValueError:
110
 
                ser.port = a
111
 
        elif o in ("-b", "--baud"):   #specified baudrate
112
 
            try:
113
 
                ser.baudrate = int(a)
114
 
            except ValueError:
115
 
                raise ValueError, "Baudrate must be a integer number"
116
 
        elif o in ("-r", "--rtscts"):
117
 
            ser.rtscts = True
118
 
        elif o in ("-x", "--xonxoff"):
119
 
            ser.xonxoff = True
120
 
        elif o in ("-P", "--localport"):
121
 
            try:
122
 
                localport = int(a)
123
 
            except ValueError:
124
 
                raise ValueError, "Local port must be an integer number"
125
 
 
126
 
    print "--- TCP/IP to Serial redirector --- type Ctrl-C / BREAK to quit"
127
 
 
128
 
    try:
129
 
        ser.open()
130
 
    except serial.SerialException, e:
131
 
        print "Could not open serial port %s: %s" % (ser.portstr, e)
132
 
        sys.exit(1)
133
 
 
134
 
    srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
135
 
    srv.bind( ('', localport) )
136
 
    srv.listen(1)
137
 
    while 1:
138
 
        try:
139
 
            print "Waiting for connection..."
140
 
            connection, addr = srv.accept()
141
 
            print 'Connected by', addr
142
 
            #enter console->serial loop
143
 
            r = Redirector(ser, connection)
144
 
            r.shortcut()
145
 
            print 'Disconnected'
146
 
            connection.close()
147
 
        except socket.error, msg:
148
 
            print msg
149
 
 
150
 
    print "\n--- exit ---"
 
1
#!/usr/bin/env python
 
2
 
 
3
# (C) 2002-2006 Chris Liechti <cliechti@gmx.net>
 
4
# redirect data from a TCP/IP connection to a serial port and vice versa
 
5
# requires Python 2.2 'cause socket.sendall is used
 
6
 
 
7
 
 
8
import sys, os, serial, threading, socket
 
9
 
 
10
try:
 
11
    True
 
12
except NameError:
 
13
    True = 1
 
14
    False = 0
 
15
 
 
16
class Redirector:
 
17
    def __init__(self, serial, socket):
 
18
        self.serial = serial
 
19
        self.socket = socket
 
20
 
 
21
    def shortcut(self):
 
22
        """connect the serial port to the tcp port by copying everything
 
23
           from one side to the other"""
 
24
        self.alive = True
 
25
        self.thread_read = threading.Thread(target=self.reader)
 
26
        self.thread_read.setDaemon(1)
 
27
        self.thread_read.start()
 
28
        self.writer()
 
29
    
 
30
    def reader(self):
 
31
        """loop forever and copy serial->socket"""
 
32
        while self.alive:
 
33
            try:
 
34
                data = self.serial.read(1)              #read one, blocking
 
35
                n = self.serial.inWaiting()             #look if there is more
 
36
                if n:
 
37
                    data = data + self.serial.read(n)   #and get as much as possible
 
38
                if data:
 
39
                    self.socket.sendall(data)           #send it over TCP
 
40
            except socket.error, msg:
 
41
                print msg
 
42
                #probably got disconnected
 
43
                break
 
44
        self.alive = False
 
45
    
 
46
    def writer(self):
 
47
        """loop forever and copy socket->serial"""
 
48
        while self.alive:
 
49
            try:
 
50
                data = self.socket.recv(1024)
 
51
                if not data:
 
52
                    break
 
53
                self.serial.write(data)                 #get a bunch of bytes and send them
 
54
            except socket.error, msg:
 
55
                print msg
 
56
                #probably got disconnected
 
57
                break
 
58
        self.alive = False
 
59
        self.thread_read.join()
 
60
 
 
61
    def stop(self):
 
62
        """Stop copying"""
 
63
        if self.alive:
 
64
            self.alive = False
 
65
            self.thread_read.join()
 
66
 
 
67
 
 
68
if __name__ == '__main__':
 
69
    import optparse
 
70
 
 
71
    parser = optparse.OptionParser(usage="""\
 
72
%prog [options] [port [baudrate]]
 
73
Simple Serial to Network (TCP/IP) redirector.
 
74
 
 
75
Note: no security measures are implemeted. Anyone can remotely connect
 
76
to this service over the network.
 
77
Only one connection at once is supported. When the connection is terminated
 
78
it waits for the next connect.
 
79
""")
 
80
    parser.add_option("-p", "--port", dest="port",
 
81
        help="port, a number (default 0) or a device name (deprecated option)",
 
82
        default=None)
 
83
    
 
84
    parser.add_option("-b", "--baud", dest="baudrate", action="store", type='int',
 
85
        help="set baudrate, default 9600", default=9600)
 
86
        
 
87
    parser.add_option("", "--parity", dest="parity", action="store",
 
88
        help="set parity, one of [N, E, O], default=N", default='N')
 
89
    
 
90
    parser.add_option("", "--rtscts", dest="rtscts", action="store_true",
 
91
        help="enable RTS/CTS flow control (default off)", default=False)
 
92
    
 
93
    parser.add_option("", "--xonxoff", dest="xonxoff", action="store_true",
 
94
        help="enable software flow control (default off)", default=False)
 
95
    
 
96
    parser.add_option("", "--cr", dest="cr", action="store_true",
 
97
        help="do not send CR+LF, send CR only", default=False)
 
98
        
 
99
    parser.add_option("", "--lf", dest="lf", action="store_true",
 
100
        help="do not send CR+LF, send LF only", default=False)
 
101
    
 
102
    parser.add_option("", "--rts", dest="rts_state", action="store", type='int',
 
103
        help="set initial RTS line state (possible values: 0, 1)", default=None)
 
104
 
 
105
    parser.add_option("", "--dtr", dest="dtr_state", action="store", type='int',
 
106
        help="set initial DTR line state (possible values: 0, 1)", default=None)
 
107
 
 
108
    parser.add_option("-q", "--quiet", dest="quiet", action="store_true",
 
109
        help="suppress non error messages", default=False)
 
110
 
 
111
    parser.add_option("-P", "--localport", dest="local_port", action="store", type='int',
 
112
        help="local TCP port", default=7777)
 
113
 
 
114
 
 
115
    (options, args) = parser.parse_args()
 
116
 
 
117
    port = options.port
 
118
    baudrate = options.baudrate
 
119
    if args:
 
120
        if options.port is not None:
 
121
            parser.error("no arguments are allowed, options only when --port is given")
 
122
        port = args.pop(0)
 
123
        if args:
 
124
            try:
 
125
                baudrate = int(args[0])
 
126
            except ValueError:
 
127
                parser.error("baudrate must be a number, not %r" % args[0])
 
128
            args.pop(0)
 
129
        if args:
 
130
            parser.error("too many arguments")
 
131
    else:
 
132
        if port is None: port = 0
 
133
 
 
134
    if options.cr and options.lf:
 
135
        parser.error("ony one of --cr or --lf can be specified")
 
136
 
 
137
    ser = serial.Serial()
 
138
    ser.port    = port
 
139
    ser.baudrate = baudrate
 
140
    ser.rtscts  = options.rtscts
 
141
    ser.xonxoff = options.xonxoff
 
142
    ser.timeout = 1     #required so that the reader thread can exit
 
143
    
 
144
    if not options.quiet:
 
145
        print "--- TCP/IP to Serial redirector --- type Ctrl-C / BREAK to quit"
 
146
        print "--- %s %s,%s,%s,%s ---" % (ser.portstr, ser.baudrate, 8, ser.parity, 1)
 
147
 
 
148
    try:
 
149
        ser.open()
 
150
    except serial.SerialException, e:
 
151
        print "Could not open serial port %s: %s" % (ser.portstr, e)
 
152
        sys.exit(1)
 
153
 
 
154
    if options.rts_state is not None:
 
155
        ser.setRTS(options.rts_state)
 
156
 
 
157
    if options.dtr_state is not None:
 
158
        ser.setDTR(options.dtr_state)
 
159
 
 
160
    srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 
161
    srv.bind( ('', options.local_port) )
 
162
    srv.listen(1)
 
163
    while 1:
 
164
        try:
 
165
            print "Waiting for connection on %s..." % options.local_port
 
166
            connection, addr = srv.accept()
 
167
            print 'Connected by', addr
 
168
            #enter console->serial loop
 
169
            r = Redirector(ser, connection)
 
170
            r.shortcut()
 
171
            print 'Disconnected'
 
172
            connection.close()
 
173
        except socket.error, msg:
 
174
            print msg
 
175
 
 
176
    print "\n--- exit ---"