-
Notifications
You must be signed in to change notification settings - Fork 0
/
esmart_server.py
executable file
·97 lines (84 loc) · 2.56 KB
/
esmart_server.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# eSmart USB to TCP server
#
# Copyright (2019) Jonathan Schultz
#
import serial
import socket
import select
import queue
HOST=''
PORT=8888
ESMART="/dev/ttyUSB{}"
n = 0
while True:
try:
serdevice = ESMART.format(n)
ser = serial.Serial(serdevice, 9600, timeout=0.1)
break
except serial.serialutil.SerialException:
n += 1
if n == 10: # Arbitrary
raise RuntimeError('Can''t connect to eSmart.')
server = socket.socket()
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((HOST, PORT))
server.listen(5)
inputs = [server]
outputs = []
message_queues = {}
while inputs:
readable, writable, exceptional = select.select(inputs, outputs, inputs)
for s in readable:
if s is server:
connection, client_address = s.accept()
connection.setblocking(0)
inputs.append(connection)
message_queues[connection] = queue.Queue()
else:
try:
data = s.recv(1024)
except ConnectionResetError:
data = None
if data:
try:
ser.write(data)
except (serial.serialutil.SerialException, OSError):
# https://stackoverflow.com/questions/33441579/io-error-errno-5-with-long-term-serial-connection-in-python
ser.close()
n = 0
while True:
try:
ser = serial.Serial(serdevice, 9600, timeout=0.1)
break
except serial.serialutil.SerialException:
n += 1
if n == 10: # Arbitrary
raise RuntimeError('Can''t connect to eSmart.')
ser.write(data)
reply = ser.read(1024)
message_queues[s].put(reply)
if s not in outputs:
outputs.append(s)
else:
if s in outputs:
outputs.remove(s)
inputs.remove(s)
s.close()
del message_queues[s]
for s in writable:
try:
next_msg = message_queues[s].get_nowait()
except queue.Empty:
outputs.remove(s)
else:
s.send(next_msg)
for s in exceptional:
inputs.remove(s)
if s in outputs:
outputs.remove(s)
s.close()
del message_queues[s]
server.close()