Skip to content

Instantly share code, notes, and snippets.

@stephenemslie
Forked from flyte/serial_to_network.py
Last active August 29, 2015 13:56
Show Gist options
  • Save stephenemslie/8877078 to your computer and use it in GitHub Desktop.
Save stephenemslie/8877078 to your computer and use it in GitHub Desktop.
import serial
import socket
import argparse
import sys
NEWLINE = "\r\n"
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")
args = p.parse_args()
ser = serial.Serial()
ser.port = args.com_port
ser.baudrate = args.baud
try:
ser.open()
except serial.SerialException, e:
sys.stderr.write("Could not open serial port: %s" % e)
sys.exit(1)
while True:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((args.target_host, args.target_port))
sock.listen(5)
conn, addr = sock.accept()
while True:
data = ""
while NEWLINE not in data:
data = data + ser.read(1)
if args.strip_newlines:
data = data.strip(NEWLINE)
sys.stderr.write(".")
try:
conn.sendall(data)
except socket.error:
conn.close()
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment