From d812c440e1200ba56f14b9b6f2545341b9ce7a9c Mon Sep 17 00:00:00 2001 From: Kevin Date: Sun, 3 Oct 2021 18:27:47 +0200 Subject: [PATCH] Setup relay controller, includes db for saving state Pin represents rpi gpio pin & controls is string describing what the relay controls. Any state change is save to sqlite database. --- brewRelay.py | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 brewRelay.py diff --git a/brewRelay.py b/brewRelay.py new file mode 100644 index 0000000..3d943c9 --- /dev/null +++ b/brewRelay.py @@ -0,0 +1,60 @@ +import RPi.GPIO as GPIO +from logger import logger +import sqlite3 + +class BrewRelay(): + def __init__(self, pin, controls): +# GPIO.setmode(GPIO.BOARD) + self.pin = pin + self.controls = controls + + self.conn = sqlite3.connect('brew.db', check_same_thread=False) + self.cur = self.conn.cursor() + + GPIO.setup(self.pin, GPIO.OUT) + self.set(self.state, True) + + @property + def state(self): + query = 'select state from relay where pin = {}'.format(self.pin) + self.cur.execute(query) + + return True if self.cur.fetchone()[0] == 1 else False + + def saveStateToDB(self, state): + query = 'update relay set state = {} where pin = {}' + self.cur.execute(query.format(state, self.pin)) + self.conn.commit() + + def set(self, state, setup=False): + GPIO.output(self.pin, not state) # for some reason this is negated + if setup is False: + logger.info('Relay toggled', es={'relayState': state, 'relayType': self.controls}) + else: + logger.info('Resuming relay state', es={'relayState': state, 'relayType': self.controls}) + + self.saveStateToDB(state) + + def toggle(self): + self.set(not state) + + @staticmethod + def fromYaml(loader, node): + return BrewRelay(**loader.construct_mapping(node)) + + @staticmethod + def getRelayByWhatItControls(relays, controls): + return next(( relay for relay in relays if relay.controls == controls), None) + + def __exit__(self): + self.conn.close() + +if __name__ == '__main__': + brewRelay = BrewRelay() + + import time + while True: + print('toggling!') + brewRelay.toggle() + time.sleep(1) +