chickenhouse/src/gate_guard.py

67 lines
1.8 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):
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):
2016-12-19 15:47:26 +00:00
if self.__gate_state.get_state() == "unknown":
2016-12-19 15:38:30 +00:00
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())