Skip to content

Commit d72fb0c

Browse files
author
Nicolas Berthel
authored
Merge pull request #2 from markbergsma/master
Add socket reconnection
2 parents 69c5892 + 5547462 commit d72fb0c

File tree

1 file changed

+18
-6
lines changed

1 file changed

+18
-6
lines changed

pybecker/becker.py

+18-6
Original file line numberDiff line numberDiff line change
@@ -63,18 +63,30 @@ def __init__(self, device_name=DEFAULT_DEVICE_NAME, init_dummy=False):
6363
if not units and init_dummy:
6464
self.db.init_dummy()
6565

66+
self._connect()
67+
68+
def _connect(self):
6669
if self.is_serial:
6770
self.s = serial.Serial(self.device, 115200, timeout=1)
6871
self.write_function = self.s.write
6972
else:
70-
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
71-
if ':' in device_name:
72-
host, port = self.device.split(':')
73+
if ':' in self.device:
74+
host, port = self.device.split(':', 1)
7375
else:
74-
host = device_name
76+
host = self.device
7577
port = '5000'
76-
self.s.connect((host, int(port)))
77-
self.write_function = self.s.sendall
78+
self.s = socket.create_connection((host, port))
79+
self.write_function = self._reconnecting_sendall
80+
81+
def _reconnecting_sendall(self, *args, **kwargs):
82+
"""Wrapper for socker.sendall that reconnects (once) on failure"""
83+
84+
try:
85+
return self.s.sendall(*args, **kwargs)
86+
except OSError:
87+
# Assume the connection failed, and connect again
88+
self._connect()
89+
return self.s.sendall(*args, **kwargs)
7890

7991
async def write(self, codes):
8092
for code in codes:

0 commit comments

Comments
 (0)