use the enum module to represent states
[~helmut/onoff.git] / onoff / gpio.py
1 import os.path
2
3 from .common import OnoffDevice, OnoffState
4
5 def _write_file_value(path, content):
6     with open(path, "w") as f:
7         f.write(content)
8
9 class OnoffGPIO(OnoffDevice):
10     """A GPIO."""
11     def __init__(self, gpionumber, active_low=False):
12         """
13         @type gpionumber: int
14         @param gpionumber: a Linux GPIO number. That includes a controller
15                            offset if necessary.
16         @type active_low: bool
17         @param active_low: whether the GPIO should be inverted
18         """
19         OnoffDevice.__init__(self)
20         self.current_state = OnoffState.inactive
21         basedir = "/sys/class/gpio"
22         self.gpiodir = "%s/gpio%d" % (basedir, gpionumber)
23         if not os.path.isdir(self.gpiodir):
24             _write_file_value("%s/export" % basedir, "%d" % gpionumber)
25         _write_file_value("%s/direction" % self.gpiodir, "out")
26         _write_file_value("%s/active_low" % self.gpiodir, "%d" % active_low)
27
28     def _set_state(self, state):
29         self.current_state = state
30         _write_file_value("%s/value" % self.gpiodir,
31                           "1" if state == OnoffState.active else "0")
32         self.changestate(self.current_state)
33
34     @property
35     def state(self):
36         return self.current_state
37
38     def activate(self):
39         self._set_state(OnoffState.active)
40
41     def deactivate(self):
42         self._set_state(OnoffState.inactive)