complete SpaceAPI integration
[saartuer.git] / spaceapi.py
similarity index 52%
rename from concept_spaceapi.py
rename to spaceapi.py
index 0f251d7d4b3c1e3b065566ef407c0180c4a62ba4..89e3678290e652773306d697aa642a364b2c1e55 100644 (file)
@@ -1,7 +1,11 @@
 from threading import Lock
+from libtuer import ThreadFunction, logger
+import urllib.request
+
+from config import spaceApiKey
 
 class SpaceApi:
-       __init__ (self, waker):
+       def __init__ (self, waker):
                self._state_to_set = None
                self._state_last_set = None
                self._running = True
@@ -12,6 +16,20 @@ class SpaceApi:
        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 = "http://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'''
@@ -31,10 +49,9 @@ class SpaceApi:
                                # check if there's something we need to do
                                if self._state_last_set == state: return
                                # take action!
-                               error = do_request(stts) # TODO
-                               #TODO logging
-                               #TODO error too often -> log critical to send mails
-                               if not error:
-                                       self.state_last_set = stts
+                               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()