Files
badkamer_d1mini/delayedswitch.py

92 lines
2.5 KiB
Python

import machine
import time
from machine import Timer
import urequests as requests
#
# Class for handling alarms and calling FHEM
#
class DelayedSwitch:
def __init__(self,delay,rtc):
self.__delay = delay
self.__alarm = None
self.__is_light_on = False
self.__rtc = rtc
def _get_switch_status(self):
# check status of light
r = self._call_ccu3("http://10.0.10.81/addons/red/switch/state")
try:
data = r.json()
self.__is_light_on = data.get('state', False)
except:
print("Error parsing JSON response")
self.__is_light_on = False
r.close()
if self.__is_light_on:
print("Light is already on.")
else:
print("Light is off.")
#
# Switch of the light through FHEM
def _switch_off_handler(self, alarm):
print("Switching light off")
r = self._call_ccu3("http://10.0.10.81/addons/red/switch/off")
self.__is_light_on = False
# close the response object
r.close()
#
# Call CCU3
#
def _call_ccu3(self,url):
try:
r = requests.get(url)
except OSError as oer:
print("Resetting. We received OSSeror: ", oer)
machine.reset()
return r
def is_light_on(self):
return self.__is_light_on
def set_delay(self,d):
self.__delay = d
def absence(self):
# cancel any previous time (if any)
if self.__alarm != None:
print("Canceling previous alarm")
self.__alarm.deinit()
print("Alarm started to switch off in:", self.__delay)
self.__alarm = Timer(-1)
self.__alarm.init(period=self.__delay, mode=Timer.ONE_SHOT, callback=self._switch_off_handler)
#self.__alarm = Timer.Alarm(self._switch_off_handler, self.__delay, periodic=False)
def presence(self):
# cancel any previous time (if any)
if self.__alarm != None:
print("Canceling previous alarm")
self.__alarm.deinit()
# Check if we light is really on
# (in case somebody manually switched it off)
if self.__is_light_on:
self._get_switch_status()
#
# Switch light on
#
if not self.__is_light_on:
print("Switching light on")
r = self._call_ccu3("http://10.0.10.81/addons/red/switch/on")
self.__is_light_on = True
# close the response object
r.close()