gpio.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # Copyright 2016 by MPI-SWS and Data-Ken Research.
  2. # Licensed under the Apache 2.0 License.
  3. """
  4. Output on raspberry pi gpio pins
  5. """
  6. import RPi.GPIO as gpio
  7. from thingflow.base import InputThing, SensorEvent
  8. class GpioPinOut(InputThing):
  9. """Actuator for an output pin on the GPIO bus.
  10. """
  11. def __init__(self, port=11):
  12. self.port = port
  13. gpio.setmode(gpio.BOARD)
  14. gpio.setup(port, gpio.OUT, initial=gpio.LOW)
  15. self.current_state = False
  16. self.closed = False
  17. def on_next(self, x):
  18. """If x is a truthy value, we turn the light on
  19. """
  20. assert not isinstance(x, SensorEvent), "Send a raw value, not a sensor event"
  21. if x and not self.current_state:
  22. gpio.output(self.port, gpio.HIGH)
  23. self.current_state = True
  24. elif (not x) and self.current_state:
  25. gpio.output(self.port, gpio.LOW)
  26. self.current_state = False
  27. def _cleanup(self):
  28. if not self.closed:
  29. gpio.output(self.port, gpio.LOW)
  30. gpio.cleanup()
  31. self.closed = True
  32. def on_completed(self):
  33. self._cleanup()
  34. def on_error(self, e):
  35. self._cleanup()
  36. def __str__(self):
  37. return "GpioPinOut(port=%s, state=%s)" % \
  38. (self.port, 'ON' if self.current_state else 'OFF')