chickenhouse/src/gate_guard.py

68 lines
1.9 KiB
Python
Raw Normal View History

2016-12-19 15:38:30 +00:00
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):
2016-12-19 15:52:19 +00:00
self.__light_read_delay_s = 60
2016-12-19 15:38:30 +00:00
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()
2016-12-19 15:52:19 +00:00
self.__gate_state.set_state("close")
2016-12-19 15:38:30 +00:00
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()
2016-12-19 15:52:19 +00:00
self.__gate_state.set_state("open")
2016-12-19 15:38:30 +00:00
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":
2016-12-19 15:52:19 +00:00
if light_avg > self.__light_lx_open:
2016-12-19 15:38:30 +00:00
self.open_gate()
elif self.__gate_state.get_state() == "unknown":
'''TODO: bring gate in a defined position'''
def run(self):
2016-12-19 15:47:26 +00:00
if self.__gate_state.get_state() == "unknown":
2016-12-19 15:52:19 +00:00
self.__gate_state.set_state("open")
2016-12-19 15:38:30 +00:00
try:
while True:
2016-12-19 15:52:19 +00:00
rd = self.__light_sensor.read()
self.__light_data.push(rd)
light_avg = self.__light_data.average()
if light_avg != None:
2016-12-19 15:38:30 +00:00
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())