draft device api
authorHelmut Grohne <helmut@subdivi.de>
Sun, 16 Jun 2013 22:03:44 +0000 (00:03 +0200)
committerHelmut Grohne <helmut@subdivi.de>
Sun, 16 Jun 2013 22:03:44 +0000 (00:03 +0200)
onoff/common.py

index e8fde4a..0120e8f 100644 (file)
@@ -8,3 +8,56 @@ Defined states:
 
 ST_ACTIVE = 1
 ST_TRANSITION = 2
+
+class OnoffDevice(object):
+    """
+    @type notify: {int -> None}
+    @ivar notify: A set of functions taking a changed state.
+
+    @type state: int
+    @ivar state: is a read-only attribute to retrieve the current state
+    """
+    def __init__(self):
+        self.notify = set()
+
+    def changestate(self, state):
+        """Tell interested parties that the state has changed to the given
+        state."""
+        for func in self.notify:
+            func(state)
+
+    def activate(self):
+        """Ask the device to power on."""
+        raise NotImplementedError
+
+    def deactivate(self):
+        """Ask the device to power off."""
+        raise NotImplementedError
+
+    def close(self):
+        """Release resources acquired by the constructor."""
+        pass
+
+class InvertedDevice(OnoffDevice):
+    def __init__(self, device):
+        OnoffDevice.__init__(self)
+        self.device = device
+        self.device.activate()
+        self.device.notify.add(self.changestate)
+
+    def changestate(self, state):
+        OnoffDevice.changestate(self, state ^ ST_ACTIVE)
+
+    @property
+    def state(self):
+        return self.device.state ^ ST_ACTIVE
+
+    def activate(self):
+        self.device.deactivate()
+
+    def deactivate(self):
+        self.device.activate()
+
+    def close(self):
+        self.device.notify.remove(self.changestate)
+        self.device.close()