# # thtp.py # I0 TCP<->UDP bridge # # Neil Gershenfeld CBA MIT 11/27/05 # (c) Massachusetts Institute of Technology 2005 # Permission granted for experimental and personal use; # license for commercial use available from MIT from socket import * from string import * import serial PORT = 4096 END = 192 ESC = 219 ESC_END = 220 ESC_ESC = 221 TOTAL_LENGTH = 3 SOURCE_ADDRESS = 15 DESTINATION_ADDRESS = 19 SOURCE_PORT = 21 DESTINATION_PORT = 23 DATA = 28 #ser = serial.Serial(port='/dev/usb/ttyUSB0', baudrate=9600) #ser = serial.Serial(port='COM1', baudrate=9600) ser = serial.Serial(port='/dev/ttyS0', baudrate=9600) sock = socket(AF_INET, SOCK_STREAM) sock.bind(("", PORT)) sock.listen(1) source_address = gethostbyname("localhost") print "listening on port",PORT while 1: # # wait for an incoming TCP connection # (client_socket, client_address) = sock.accept() data = client_socket.recv(1000) # # wait for an I0 packet # count = -1 length = 10000 packet = [] ser.flushInput() while 1: x = ord(ser.read()) if (x == END): count = -1 length = 10000 packet = [] continue if (x == ESC): x = ord(ser.read()) if (x == ESC_END): x = END elif (x == ESC_ESC): x = ESC else: print "error: unknown ESC" packet.append(x) count += 1 if (count == TOTAL_LENGTH): length = 256*packet[count-1] + packet[count] elif (count == SOURCE_ADDRESS): source_address = "%d.%d.%d.%d"%\ (packet[count-3],packet[count-2],packet[count-1],packet[count]) elif (count == DESTINATION_ADDRESS): destination_address = "%d.%d.%d.%d"%\ (packet[count-3],packet[count-2],packet[count-1],packet[count]) #destination_address = "127.0.0.1" elif (count == SOURCE_PORT): source_port = 256*packet[count-1] + packet[count] elif (count == DESTINATION_PORT): destination_port = 256*packet[count-1] + packet[count] elif (count == length-1): data = join(map(chr,packet[DATA:count+1]),sep="") print 'received packet from %s to address %s port %d'%\ (source_address,destination_address,destination_port) break elif (count > length): print "error: count > length" # # send the I0 packet on the TCP socket # client_socket.send("%s"%data) client_socket.close()