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
7
"""USAGE: tcp_serial_redirect.py [options]
8
Simple Serial to Network (TCP/IP) redirector.
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)
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.
23
import sys, os, serial, threading, getopt, socket
32
def __init__(self, serial, socket):
37
"""connect the serial port to the tcp port by copying everything
38
from one side to the other"""
40
self.thread_read = threading.Thread(target=self.reader)
41
self.thread_read.setDaemon(1)
42
self.thread_read.start()
46
"""loop forever and copy serial->socket"""
49
data = self.serial.read(1) #read one, blocking
50
n = self.serial.inWaiting() #look if there is more
52
data = data + self.serial.read(n) #and get as much as possible
54
self.socket.sendall(data) #send it over TCP
55
except socket.error, msg:
57
#probably got disconnected
62
"""loop forever and copy socket->serial"""
65
data = self.socket.recv(1024)
68
self.serial.write(data) #get a bunch of bytes and send them
69
except socket.error, msg:
71
#probably got disconnected
74
self.thread_read.join()
80
self.thread_read.join()
82
if __name__ == '__main__':
85
#parse command line options
87
opts, args = getopt.getopt(sys.argv[1:],
89
["help", "port=", "baud=", "rtscts", "xonxoff", "localport"])
90
except getopt.GetoptError:
91
# print help information and exit:
92
print >>sys.stderr, __doc__
99
ser.timeout = 1 #required so that the reader thread can exit
103
if o in ("-h", "--help"): #help text
106
elif o in ("-p", "--port"): #specified port
111
elif o in ("-b", "--baud"): #specified baudrate
113
ser.baudrate = int(a)
115
raise ValueError, "Baudrate must be a integer number"
116
elif o in ("-r", "--rtscts"):
118
elif o in ("-x", "--xonxoff"):
120
elif o in ("-P", "--localport"):
124
raise ValueError, "Local port must be an integer number"
126
print "--- TCP/IP to Serial redirector --- type Ctrl-C / BREAK to quit"
130
except serial.SerialException, e:
131
print "Could not open serial port %s: %s" % (ser.portstr, e)
134
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
135
srv.bind( ('', localport) )
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)
147
except socket.error, msg:
150
print "\n--- exit ---"