-
Notifications
You must be signed in to change notification settings - Fork 0
/
maschinendeck-ittt.py
85 lines (74 loc) · 2.88 KB
/
maschinendeck-ittt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/usr/bin/env python3
MQTT_HEARTBEAT_INTERVAL_SECONDS = 60
FOREVER = True
import paho.mqtt.client as mqtt
import sched
import time
from datetime import datetime, timedelta
import ephem
import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
class Auto():
s = sched.scheduler(time.time, time.sleep)
state = None
def isSunSettingInOrSet(delta):
trier = ephem.Observer()
trier.lat, trier.lon = '49.7596', '6.6439'
trier.elevation = 136
prev_ris = ephem.localtime(trier.previous_rising(ephem.Sun()))
prev_set = ephem.localtime(trier.previous_setting(ephem.Sun()))
next_set = ephem.localtime(trier.next_setting(ephem.Sun()))
now = datetime.now()
if prev_set < prev_ris: #we have daytime (between sunrise and sunset), check if less than delta to sunset
pre_set = next_set - delta
if now > pre_set: #we are closer than delta to sunset
return True
else:
return False
else: #we have nighttime (between sunset and sunrise), so sun is set
return True
def on_message(self, client, userdata, msg):
logging.debug("got on topic %s message %s" % (msg.topic, msg.payload));
if msg.topic == "/maschinendeck/raum/status":
if msg.payload == b"open":
self.state = True
if not msg.retain:
if self.isSunSettingInOrSet(timedelta(hours=1)):
logger.debug("sun is set, switch on lamp")
client.publish("/maschinendeck/esper/1bfe7f/socket/set", "1")
else:
logger.debug("sun is not set")
else:
logger.debug("message was retained, do not act on it")
elif msg.payload == b"closed":
self.state = False
if not msg.retain:
logger.debug("disabling lamp")
client.publish("/maschinendeck/esper/1bfe7f/socket/set", "0")
else:
logger.debug("message was retained, do not act on it")
else:
logger.warning("unable to parse raumstatus '%s', setting state to unknown"%msg.payload)
self.state = None
def on_connect(self, client, userdata, flags, rc):
logging.info("Connected with result code " + str(rc))
client.subscribe("/maschinendeck/raum/status")
self.mqttHeartbeat(False)
def mqttHeartbeat(self, enqueue=True):
if(FOREVER and enqueue):
self.s.enter(MQTT_HEARTBEAT_INTERVAL_SECONDS, 0, self.mqttHeartbeat, ())
self.client.publish("/maschinendeck/esper/heartbeat")
self.client.publish("/members/ranlvor/esper/heartbeat")
def start(self):
logging.info("Connecting to MQTT")
client = mqtt.Client()
self.client = client
client.on_connect = self.on_connect
client.on_message = self.on_message
client.connect_async("mqtt.starletp9.de")
client.loop_start()
self.s.enter(MQTT_HEARTBEAT_INTERVAL_SECONDS, 0, self.mqttHeartbeat, ())
self.s.run()
auto = Auto()
auto.start()