8e36b0fe21a3d372e0b8e03f443f80baf60365c8
[saartuer.git] / spaceapi.py
1 from threading import Lock
2 from libtuer import ThreadFunction, logger
3 import urllib.request, time
4
5 from config import spaceApiKey
6
7 RETRY_TIME = 60
8 HEARTBEAT_TIME = 10*60
9
10 class SpaceApi:
11         def __init__ (self, waker):
12                 self._local_state = None
13                 self._remote_state = None
14                 self._last_set_at = 0
15                 self._running = True
16                 self.set_state = ThreadFunction(self._set_state, "Space API")
17                 waker.register(self.set_state, RETRY_TIME)
18         
19         def stop (self):
20                 self.set_state.stop()
21         
22         def _do_request(self, state):
23                 state_val = 1 if state else 0
24                 try:
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))
31                         return False
32                 except urllib.request.URLError as e:
33                         logger.error("SpaceAPI update returned error: %s" % str(e))
34                         return False
35         
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'''
39                 if state is not None:
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)
43                 now = time.time()
44                 if self._local_state is not None and (self._local_state != self._remote_state or now > self._last_set_at+HEARTBEAT_TIME):
45                         # take action!
46                         success = self._do_request(self._local_state)
47                         # TODO error too often -> log critical to send mails
48                         if success:
49                                 self._remote_state = self._local_state
50                                 self._last_set_at = now