forked from ianhalpern/rentshare-arduino
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrentshare_arduino_proxy.py
61 lines (50 loc) · 1.29 KB
/
rentshare_arduino_proxy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/usr/bin/env python
"""
An echo server that uses select to handle multiple clients at a time.
Entering any line of input at the terminal will exit the server.
"""
import select
import socket
import sys
import serial
sock_host = 'localhost'
sock_port = 8888
ser_host = '/dev/ttyACM0' if len(sys.argv) <= 1 else sys.argv[1]
ser_port = 9600
backlog = 5
size = 1
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((sock_host,sock_port))
server.listen(backlog)
ser = serial.Serial(ser_host, ser_port)
input = [server,sys.stdin]
running = 1
print 'RentShare Arduino Proxy'
print ' Usage: write message and press enter. (max 8 characters)'
print ''
sys.stdout.write('>>> ')
sys.stdout.flush()
while running:
inputready,outputready,exceptready = select.select(input,[],[])
for s in inputready:
if s == server:
# handle the server socket
client, address = server.accept()
input.append(client)
elif s == sys.stdin:
# handle standard input
data = sys.stdin.readline()
ser.write(data)
ser.write(chr(0))
sys.stdout.write('>>> ')
sys.stdout.flush()
else:
# handle all other sockets
data = s.recv(size)
if data:
ser.write(data)
else:
s.close()
input.remove(s)
server.close()