-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdryermon.py
102 lines (81 loc) · 2.62 KB
/
dryermon.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import paho.mqtt.client as mqtt
import datetime
import time
import json
class State(object):
"""
We define a state object which provides some utility functions for the
individual states within the state machine.
"""
def __init__(self):
print 'Processing current state:', str(self)
self.threshold = 100
self.timer = 0
self.end_delay = 300 #time to wait before confirming we're done in seconds
def on_event(self, event):
"""
Handle events that are delegated to this State.
"""
pass
def __repr__(self):
"""
Leverages the __str__ method to describe the State.
"""
return self.__str__()
def __str__(self):
"""
Returns the name of the State.
"""
return self.__class__.__name__
class idle(State):
def on_event(self, event):
if event > self.threshold:
client.publish("myhome/garage/dryer/state",payload="running",retain=True)
return running()
else:
return idle()
class running(State):
def on_event(self, event):
if event < self.threshold:
return maybe_finished()
else:
return running()
class maybe_finished(State):
def on_event(self, event):
#If the power's gone back up then we're not finished
if event > self.threshold:
return running()
else:
if self.timer == 0:
self.timer = time.time()
return self
elif (time.time() - self.end_delay) > self.timer:
client.publish("myhome/garage/dryer/state",payload="idle",retain=True)
return idle()
else:
#client.publish("myhome/garage/dryer/state",payload="maybe_finished",retain=True)
return self
class dryer(object):
def __init__(self):
self.state = idle()
def on_event(self, event):
self.state = self.state.on_event(event)
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("myhome/garage/dryer/tele/SENSOR")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
dryer.on_event(json.loads(msg.payload)["ENERGY"]["Power"])
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("127.0.0.1", 1883, 60)
dryer = dryer()
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()