0f251d7d4b3c1e3b065566ef407c0180c4a62ba4
[saartuer.git] / concept_spaceapi.py
1 from threading import Lock
2
3 class SpaceApi:
4         __init__ (self, waker):
5                 self._state_to_set = None
6                 self._state_last_set = None
7                 self._running = True
8                 self.set_state = ThreadFunction(self._set_state, "Space API")
9                 self._set_state_lock = Lock()
10                 waker.register(self.set_state, 10.0) # re-try setting the state every 10 seconds
11         
12         def stop (self):
13                 self.set_state.stop()
14         
15         # set_state is the asynchronous version of _set_state (see __init__)
16         def _set_state (self, state = None):
17                 '''Sets the state, if None: leave state unchanged and re-try if previous attempts failed'''
18                 if state is not None:
19                         self._state_to_set = state
20                 else:
21                         # always have a local variable because of parallelism
22                         state = self._state_to_set
23                 
24                 if not self._set_state_lock.acquire(False):
25                         # we don't want many threads to wait here
26                         # the next status update will fix everything anyways
27                         pass
28                 else:
29                         # got the lock
30                         try:
31                                 # check if there's something we need to do
32                                 if self._state_last_set == state: return
33                                 # take action!
34                                 error = do_request(stts) # TODO
35                                 #TODO logging
36                                 #TODO error too often -> log critical to send mails
37                                 if not error:
38                                         self.state_last_set = stts
39                         finally:
40                                 self._set_state_lock.release()