X-Git-Url: https://git.ralfj.de/saartuer.git/blobdiff_plain/b8b6e14e6923809efc61c71dd94b1e66026aad9b..a7c0b8e1ba3fc6170f14bb0c964e5ac9e9ba4881:/spaceapi.py diff --git a/spaceapi.py b/spaceapi.py deleted file mode 100644 index eea73f6..0000000 --- a/spaceapi.py +++ /dev/null @@ -1,50 +0,0 @@ -from threading import Lock -from libtuer import ThreadFunction, logger -import urllib.request, time - -from config import spaceApiKey - -RETRY_TIME = 30 -HEARTBEAT_TIME = 10*60 - -class SpaceApi: - def __init__ (self, waker): - self._local_state = None - self._remote_state = None - self._last_set_at = 0 - self._running = True - self.set_state = ThreadFunction(self._set_state, "Space API") - waker.register(self.set_state, RETRY_TIME) - - def stop (self): - self.set_state.stop() - - def _do_request(self, state): - state_val = 1 if state else 0 - try: - logger.info("Setting SpaceAPI to %d" % state_val) - url = "https://spaceapi.hacksaar.de/status.php?action=update&key=%s&status=%d" % (spaceApiKey, state_val) - response = urllib.request.urlopen(url, timeout=5.0) - responseText = response.read().decode('utf-8').strip() - if response.getcode() == 200 and responseText == "UpdateSuccessful": return True - logger.error("SpaceAPI returned unexpected code %d, content %s" % (response.getcode(), responseText)) - return False - except urllib.request.URLError as e: - logger.error("SpaceAPI update returned error: %s" % str(e)) - return False - - # set_state is the asynchronous version of _set_state (see __init__) - def _set_state (self, state = None): - '''Sets the state, if None: leave state unchanged and re-try if previous attempts failed''' - if state is not None: - self._local_state = state - # check if there's something we need to do: There's a valid state, and either the state has changed or - # we need to refresh our heartbeta) - 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): - # take action! - success = self._do_request(self._local_state) - # TODO error too often -> log critical to send mails - if success: - self._remote_state = self._local_state - self._last_set_at = now