-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwasherwatcher.py
169 lines (117 loc) · 4.06 KB
/
washerwatcher.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import ujson
import urequests
import time
import machine
from umqtt.robust import MQTTClient
""" Config file format
{
"mqtt":{
"key":"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"device_name":"laundry-esp8266",
"port":8883,
"host":"io.adafruit.com",
"user":"bobobox",
"ssl":true
},
"prowl":{
"key":"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
}
}
"""
def run():
"""Run app."""
config = get_config()
mqtt_client = MQTTClient(
config['mqtt']['device_name'],
config['mqtt']['host'],
user=config['mqtt']['user'],
password=config['mqtt']['key'],
ssl=config['mqtt'].get('ssl', True),
port=8883 if config['mqtt'].get('ssl', True) else 1883
)
washer = WasherDryer('Washing Machine', 4)
send_mqtt_data(
mqtt_client,
'{}/feeds/{}'.format(
config['mqtt']['user'],
'washer-running'),
0
)
send_prowl_alert(config['prowl']['key'], "Starting WasherWatcher", -2)
while True:
old_washer_state = washer.state
washer.update_state()
if old_washer_state != washer.state:
# Notify that state has changed.
send_mqtt_data(
mqtt_client,
'{}/feeds/{}'.format(
config['mqtt']['user'],
'washer-running'),
1 if washer.state == 'running' else 0
)
prowl_msg = '{} Started...' if washer.state == 'running' else '{} Done!'
# -1 == moderate, 1 == high
prowl_priority = -1 if washer.state == 'running' else 1
send_prowl_alert(
config['prowl']['key'],
prowl_msg.format(washer.name),
prowl_priority
)
def get_config(path='washerwatcher.json'):
"""Gets config from JSON file.
Returns dict."""
with open(path, 'r') as config_fh:
return ujson.load(config_fh)
def send_mqtt_data(mqtt_client, topic, data):
mqtt_client.connect()
mqtt_client.publish(topic, str(data))
mqtt_client.disconnect()
def send_prowl_alert(api_key, msg, priority):
"""Sends alert to Prowl."""
prowl_url = 'https://prowlapp.com/publicapi/add'
payload = {
'apikey': api_key,
'application': 'Laundry:',
'description': msg.replace(' ', '%20'),
'priority': priority
}
param_string = '&'.join(['{}={}'.format(k,v) for k,v in payload.items()])
req = urequests.get('{}?{}'.format(prowl_url, param_string))
print(req.status_code)
class WasherDryer:
def __init__(self, name, sensor_pin):
self.name = name
self.sensor = machine.Pin(sensor_pin, machine.Pin.IN)
self.state = 'stopped'
self.test_sample_count = 1000
self.test_sample_period_ms = 5
self.test_running_threshold = 10
self.state_change_result_threshold = 4
self.state_change_test_gap_s = 7
def test_state(self):
counter = self.test_sample_count
test_accumulator = 0
while counter > 0:
test_accumulator += self.sensor.value()
time.sleep_ms(self.test_sample_period_ms)
counter -= 1
print(test_accumulator)
print(test_accumulator / self.test_sample_count * 100)
if test_accumulator / self.test_sample_count * 100 >= self.test_running_threshold:
return 'running'
else:
return 'stopped'
def update_state(self):
# Require multiple checks all returning the same result to consider
# state changed.
for test in range(self.state_change_result_threshold):
print("Test {}".format(test + 1))
result = self.test_state()
if result == self.state:
print('State unchanged.')
return
time.sleep(self.state_change_test_gap_s)
self.state = result
print("State changed. Now {}.".format(self.state))
return