Skip to content

Commit 4610635

Browse files
Merge pull request #4 from kirberich/speed-up-communication
Speed up communication
2 parents aa1cafd + a04ed62 commit 4610635

File tree

1 file changed

+20
-7
lines changed

1 file changed

+20
-7
lines changed

orvibo/s20.py

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import binascii
44
import logging
55
import socket
6+
import time
67

78
_LOGGER = logging.getLogger(__name__)
89

@@ -27,6 +28,9 @@
2728
ON = b'\x01'
2829
OFF = b'\x00'
2930

31+
# Timeout after which to renew device subscriptions
32+
SUBSCRIPTION_TIMEOUT = 60
33+
3034

3135
def _is_discovery_response(data):
3236
""" Is this a discovery response?
@@ -77,6 +81,8 @@ def __init__(self, host):
7781
self._socket.bind(('', PORT))
7882
(self._mac, self._mac_reversed) = self._discover_mac()
7983

84+
self._subscribe()
85+
8086
@property
8187
def on(self):
8288
""" State property.
@@ -131,18 +137,27 @@ def _subscribe(self):
131137
+ PADDING_1 + self._mac_reversed + PADDING_1
132138
status = self._udp_transact(cmd, self._subscribe_resp)
133139
if status is not None:
140+
self.last_subscribed = time.time()
134141
return status == ON
135142
else:
136143
raise S20Exception(
137144
"No status could be found for {}".format(self.host))
138145

146+
def _subscription_is_recent(self):
147+
return self.last_subscribed > time.time() - SUBSCRIPTION_TIMEOUT
148+
139149
def _control(self, state):
140150
""" Control device state.
141151
142152
Possible states are ON or OFF.
143153
144154
:param state: Switch to this state.
145155
"""
156+
157+
# Renew subscription if necessary
158+
if not self._subscription_is_recent():
159+
self._subscribe()
160+
146161
cmd = MAGIC + CONTROL + self._mac + PADDING_1 + PADDING_2 + state
147162
_LOGGER.debug("Sending new state to %s: %s", self.host, ord(state))
148163
ack_state = self._udp_transact(cmd, self._control_resp, state)
@@ -217,18 +232,16 @@ def _udp_transact(self, payload, handler, *args,
217232
# From the right device?
218233
if addr[0] == self.host:
219234
retval = handler(data, *args)
235+
# Return as soon as a response is received
236+
if retval:
237+
return retval
220238
except socket.timeout:
221239
break
222-
if retval:
223-
break
224-
return retval
225240

226241
def _turn_on(self):
227242
""" Turn on the device. """
228-
if not self._subscribe():
229-
self._control(ON)
243+
self._control(ON)
230244

231245
def _turn_off(self):
232246
""" Turn off the device. """
233-
if self._subscribe():
234-
self._control(OFF)
247+
self._control(OFF)

0 commit comments

Comments
 (0)