flyte
2/8/2014 - 4:31 AM

serial_to_network.py

import serial
import socket
import argparse
import sys

from time import sleep

NEWLINE = "\r\n"

def connect_tcp(sock, target):
	connected = False
	while not connected:
		try:
			sock.connect(target)
			connected = True
		except Exception, e:
			sys.stderr.write("Unable to connect to target host %s:%s: %s\n" % (
				target[0], target[1], e))
			sleep(5)

if __name__ == "__main__":
	p = argparse.ArgumentParser()
	p.add_argument("com_port")
	p.add_argument("target_host")
	p.add_argument("target_port", type=int)
	p.add_argument("--baud", default=9600, type=int)
	p.add_argument("--strip_newlines", action="store_true")
	p.add_argument("--tcp", action="store_true")

	args = p.parse_args()

	ser = serial.Serial()
	ser.port = args.com_port
	ser.baudrate = args.baud

	sock_type = socket.SOCK_STREAM if args.tcp else socket.SOCK_DGRAM
	sock = socket.socket(socket.AF_INET, sock_type)

	while not ser.isOpen():
		try:
			ser.open()
		except (serial.SerialException, OSError), e:
			sys.stderr.write("Could not open serial port: %s\n" % e)
			sleep(1)

	if args.tcp:
		connect_tcp(sock, (args.target_host, args.target_port))
		sock.setblocking(False)

	while True:
		try:
			data = ""
			while NEWLINE not in data:
				data = data + ser.read(1)

			if args.strip_newlines:
				data = data.strip(NEWLINE)

			sys.stderr.write(".")
			if args.tcp:
				try:
					sock.send(data)
				except socket.error, e:
					print "Error sending packet to target via TCP: %s" % e.strerror
					sleep(1)
					print "Reconnecting.."
					sock.close()
					connect_tcp(sock, (args.target_host, args.target_port))
			else:
				try:
					sock.sendto(data, (args.target_host, args.target_port))
				except socket.error, e:
					print "Error sending packet to target via UDP: %s" % e.strerror
					sleep(1)
		except Exception, e:
			print "Unhandled error: %s" % e
			sleep(5)