Commit b8b6e14e authored by Ralf's avatar Ralf
Browse files

update the SpaceAPI at least once every 10 minutes (so the server could check for this heartbeat)

parent 2300f481
from threading import Lock from threading import Lock
from libtuer import ThreadFunction, logger from libtuer import ThreadFunction, logger
import urllib.request import urllib.request, time
from config import spaceApiKey from config import spaceApiKey
RETRY_TIME = 30
HEARTBEAT_TIME = 10*60
class SpaceApi: class SpaceApi:
def __init__ (self, waker): def __init__ (self, waker):
self._state_to_set = None self._local_state = None
self._state_last_set = None self._remote_state = None
self._last_set_at = 0
self._running = True self._running = True
self.set_state = ThreadFunction(self._set_state, "Space API") self.set_state = ThreadFunction(self._set_state, "Space API")
self._set_state_lock = Lock() waker.register(self.set_state, RETRY_TIME)
waker.register(self.set_state, 10.0) # re-try setting the state every 10 seconds
def stop (self): def stop (self):
self.set_state.stop() self.set_state.stop()
...@@ -34,24 +37,14 @@ class SpaceApi: ...@@ -34,24 +37,14 @@ class SpaceApi:
def _set_state (self, state = None): def _set_state (self, state = None):
'''Sets the state, if None: leave state unchanged and re-try if previous attempts failed''' '''Sets the state, if None: leave state unchanged and re-try if previous attempts failed'''
if state is not None: if state is not None:
self._state_to_set = state self._local_state = state
else: # check if there's something we need to do: There's a valid state, and either the state has changed or
# always have a local variable because of parallelism # we need to refresh our heartbeta)
state = self._state_to_set now = time.time()
if self._local_state is not None and (self._local_state != self._remote_state or now > self._last_set_at+HEARTBEAT_TIME):
if not self._set_state_lock.acquire(False): # take action!
# we don't want many threads to wait here success = self._do_request(self._local_state)
# the next status update will fix everything anyways # TODO error too often -> log critical to send mails
pass if success:
else: self._remote_state = self._local_state
# got the lock self._last_set_at = now
try:
# check if there's something we need to do
if self._state_last_set == state: return
# take action!
success = self._do_request(state)
# TODO error too often -> log critical to send mails
if success:
self._state_last_set = state
finally:
self._set_state_lock.release()
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment