1 from threading import Lock
2 from libtuer import ThreadFunction, logger
3 import urllib.request, time
5 from config import spaceApiKey
11 def __init__ (self, waker):
12 self._local_state = None
13 self._remote_state = None
16 self.set_state = ThreadFunction(self._set_state, "Space API")
17 waker.register(self.set_state, RETRY_TIME)
22 def _do_request(self, state):
23 state_val = 1 if state else 0
25 logger.info("Setting SpaceAPI to %d" % state_val)
26 url = "https://spaceapi.hacksaar.de/status.php?action=update&key=%s&status=%d" % (spaceApiKey, state_val)
27 response = urllib.request.urlopen(url, timeout=5.0)
28 responseText = response.read().decode('utf-8').strip()
29 if response.getcode() == 200 and responseText == "UpdateSuccessful": return True
30 logger.error("SpaceAPI returned unexpected code %d, content %s" % (response.getcode(), responseText))
32 except urllib.request.URLError as e:
33 logger.error("SpaceAPI update returned error: %s" % str(e))
36 # set_state is the asynchronous version of _set_state (see __init__)
37 def _set_state (self, state = None):
38 '''Sets the state, if None: leave state unchanged and re-try if previous attempts failed'''
40 self._local_state = state
41 # check if there's something we need to do: There's a valid state, and either the state has changed or
42 # we need to refresh our heartbeta)
44 if self._local_state is not None and (self._local_state != self._remote_state or now > self._last_set_at+HEARTBEAT_TIME):
46 success = self._do_request(self._local_state)
47 # TODO error too often -> log critical to send mails
49 self._remote_state = self._local_state
50 self._last_set_at = now