Created
September 4, 2012 02:28
-
-
Save projectgus/3615866 to your computer and use it in GitHub Desktop.
Quick serial port to tcp socket muxer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import argparse, serial, socket, select | |
parser = argparse.ArgumentParser(description='Connect to a serial port and allow multiple TCP clients to talk to it (simultaneous output shared between all TCP clients, any client can write to port.)') | |
parser.add_argument('--baud', help="Baud rate", default=115200, type=int) | |
parser.add_argument('port', help="Port to listen on.", type=int) | |
parser.add_argument('serial', help="Serial port to share.") | |
def main(): | |
args = parser.parse_args() | |
listen_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
listen_sock.bind(('', args.port)) | |
listen_sock.listen(1) | |
port = serial.Serial(args.serial, baudrate=args.baud) | |
clients = set() # existing client connections | |
while True: | |
listeners = [ listen_sock, port ] + list(clients) | |
pending_reads,_,_ = select.select(listeners, [], []) | |
for reader in pending_reads: | |
if reader == listen_sock: # new connection | |
conn,_ = listen_sock.accept() | |
clients.add(conn) | |
elif reader == port: # new data from serial port | |
data = port.read(port.inWaiting()) | |
for out in clients: | |
try: | |
out.send(data) | |
except socket.error: | |
clients.remove(out) | |
else: # new data from a network client | |
try: | |
data = reader.recv(128) | |
if len(data) == 0: | |
raise socket.error("Remove this socket") | |
port.write(data) | |
except socket.error: | |
clients.remove(reader) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment