From 2be2677963275509465d0107393c24434c901b7c Mon Sep 17 00:00:00 2001 From: Fabio Manganiello Date: Fri, 6 Apr 2018 17:19:01 +0200 Subject: [PATCH] Added light sensor backend --- platypush/backend/sensor/light/__init__.py | 51 +++++++++++++++++++ .../message/event/sensor/light/__init__.py | 15 ++++++ 2 files changed, 66 insertions(+) create mode 100644 platypush/backend/sensor/light/__init__.py create mode 100644 platypush/message/event/sensor/light/__init__.py diff --git a/platypush/backend/sensor/light/__init__.py b/platypush/backend/sensor/light/__init__.py new file mode 100644 index 00000000..e8d38faa --- /dev/null +++ b/platypush/backend/sensor/light/__init__.py @@ -0,0 +1,51 @@ +import logging +import time + +import RPi.GPIO as gpio + +from platypush.backend import Backend +from platypush.message.event.sensor.light import LightOnEvent, LightOffEvent + + +class SensorLightBackend(Backend): + state = None + + def __init__(self, pin, threshold=0.5, poll_seconds=0.5, **kwargs): + super().__init__(**kwargs) + + self.pin = pin + self.threshold = threshold + self.poll_seconds = poll_seconds + + def send_message(self, msg): + pass + + def get_state(self): + return self.state + + def run(self): + super().run() + + gpio.setmode(gpio.BCM) + gpio.setup(self.pin, gpio.IN) + logging.info('Initialized light sensor backend on pin {}'.format(self.pin)) + + try: + while not self.should_stop(): + value = float(gpio.input(self.pin)) + new_state = True if value >= self.threshold else False + + if self.state is not None and new_state != self.state: + if new_state is True: + self.bus.post(LightOnEvent()) + else: + self.bus.post(LightOffEvent()) + + self.state = new_state + time.sleep(self.poll_seconds) + finally: + gpio.cleanup() + + +# vim:sw=4:ts=4:et: + diff --git a/platypush/message/event/sensor/light/__init__.py b/platypush/message/event/sensor/light/__init__.py new file mode 100644 index 00000000..85997e73 --- /dev/null +++ b/platypush/message/event/sensor/light/__init__.py @@ -0,0 +1,15 @@ +from platypush.message.event import Event + + +class LightOnEvent(Event): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + +class LightOffEvent(Event): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + +# vim:sw=4:ts=4:et: +