add a device implementation for GPIOs
authorHelmut Grohne <helmut@subdivi.de>
Sun, 20 Aug 2017 07:28:24 +0000 (09:28 +0200)
committerHelmut Grohne <helmut@subdivi.de>
Sun, 20 Aug 2017 07:28:24 +0000 (09:28 +0200)
onoff/gpio.py [new file with mode: 0644]

diff --git a/onoff/gpio.py b/onoff/gpio.py
new file mode 100644 (file)
index 0000000..bea9708
--- /dev/null
@@ -0,0 +1,42 @@
+import os.path
+
+from .common import OnoffDevice, ST_ACTIVE
+
+def _write_file_value(path, content):
+    with open(path, "w") as f:
+        f.write(content)
+
+class OnoffGPIO(OnoffDevice):
+    """A GPIO."""
+    def __init__(self, gpionumber, active_low=False):
+        """
+        @type gpionumber: int
+        @param gpionumber: a Linux GPIO number. That includes a controller
+                           offset if necessary.
+        @type active_low: bool
+        @param active_low: whether the GPIO should be inverted
+        """
+        OnoffDevice.__init__(self)
+        self.current_state = 0
+        basedir = "/sys/class/gpio"
+        self.gpiodir = "%s/gpio%d" % (basedir, gpionumber)
+        if not os.path.isdir(self.gpiodir):
+            _write_file_value("%s/export" % basedir, "%d" % gpionumber)
+        _write_file_value("%s/direction" % self.gpiodir, "out")
+        _write_file_value("%s/active_low" % self.gpiodir, "%d" % active_low)
+
+    def _set_state(self, state):
+        self.current_state = state
+        _write_file_value("%s/value" % self.gpiodir,
+                         "1" if self.current_state == ST_ACTIVE else "0")
+        self.changestate(self.current_state)
+
+    @property
+    def state(self):
+        return self.current_state
+
+    def activate(self):
+        self._set_state(ST_ACTIVE)
+
+    def deactivate(self):
+        self._set_state(0)