from communiate.protocol import mqtt from gate.gate_state import gate_state from light_data.light_data import light_data from light_sensor.light_sensor import light_sensor import sys import time class gate_guard: def __init__(self): self.__light_read_delay_s = 6 self.__consequtive_light_reads = 10 self.__light_lx_close = 0 self.__light_lx_open = 0 self.__light_sensor = light_sensor(1, 0x23) self.__light_data = light_data(self.__consequtive_light_reads) self.__comserver = mqtt("gitlab") self.__gate_state = gate_state() def close_gate(self): topic = "outdoor/chickenhouse/gate" payload = str(time.time()) + " closing" self.__comserver.connect() self.__comserver.transmit(topic, payload) self.__comserver.disconnect() return None def open_gate(self): topic = "outdoor/chickenhouse/gate" payload = str(time.time()) + " opening" self.__comserver.connect() self.__comserver.transmit(topic, payload) self.__comserver.disconnect() return None def handle_gate_state(self, light_avg=0): if self.__gate_state.get_state() == "open": if light_avg <= self.__light_lx_close: self.close_gate() elif self.__gate_state.get_state() == "close": if light_avg >= self.__light_lx_open: self.open_gate() elif self.__gate_state.get_state() == "unknown": '''TODO: bring gate in a defined position''' def run(self): if self.__gate_state() == "unknown": self.handle_gate_state() try: while True: light_data.push(light_sensor.read()) light_avg = light_data.average() if light_avg: print "light average: " + str(light_avg) self.handle_gate_state(light_avg) time.sleep(self.__light_read_delay_s) except KeyboardInterrupt: return None if __name__ == "__main__": gate_guard = gate_guard() sys.exit(gate_guard.run())