#
# udpudp.py
# I0 UDP<->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, sys

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)

#
# I0 init
#
count = -1
length = 10000
packet = []
ser.flushInput()

while 1:
   #
   # check for an incoming I0 character
   #
   if (ser.inWaiting() != 0):
      #
      # read rest of packet
      #
      while 1:
         x = ord(ser.read())
         if (x == END):
	    #
	    # end of SLIP packet
	    #
            count = -1
            length = 10000
            packet = []
            break
         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])
         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):
            #
            # end of IP packet, send it on UDP socket
            #
            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)
            sock = socket(AF_INET,SOCK_DGRAM)
            host = destination_address
            port = destination_port
            sock.sendto(data,(host,port))
            sock.close()
         elif (count > length):
            print "error: count > length"
   #
   # check for an incoming UDP packet
   # (to be written)
   #
