~ubuntu-branches/ubuntu/karmic/pyserial/karmic

« back to all changes in this revision

Viewing changes to pyserial-2.0/examples/tcp_serial_redirect.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
 
#!/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 ---"