-
+from threading import Lock
class SpaceApi:
__init__ (self, waker):
- self._state_to_set = None # public write
- self._state_last_set = None # public read FIXME why? getter?
+ self._state_to_set = None
+ self._state_last_set = None
self._running = True
self.set_state = ThreadFunction(self._set_state, "Space API")
+ self._set_state_lock = Lock()
waker.register(self.set_state, 10.0) # re-try setting the state every 10 seconds
def stop (self):
self.set_state.stop()
+ # 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._state_to_set = state
- # check if there's something we need to do
- if self._state_last_set == self._state_to_set: return
- # take action!
- error = do_request(stts) # TODO
- #TODO logging
- if not error:
- self.state_last_set = stts
+ else:
+ # always have a local variable because of parallelism
+ state = self._state_to_set
+
+ if not self._set_state_lock.acquire(False):
+ # we don't want many threads to wait here
+ # the next status update will fix everything anyways
+ pass
+ else:
+ # got the lock
+ try:
+ # 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
+ finally:
+ self._set_state_lock.release()