-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.py
More file actions
executable file
·372 lines (327 loc) · 12.8 KB
/
Copy pathcode.py
File metadata and controls
executable file
·372 lines (327 loc) · 12.8 KB
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
# SPDX-FileCopyrightText: 2020 John Park for Adafruit Industries
#
# SPDX-License-Identifier: MIT
# Matrix Weather display
# For Metro M4 Airlift with RGB Matrix shield, 64 x 32 RGB LED Matrix display
"""
This example queries the Open Weather Maps site API to find out the current
weather for your location... and display it on a screen!
if you can find something that spits out JSON data, we can display it
"""
from os import getenv
import gc
import time
import rtc
import json
import board
import busio
import displayio
import microcontroller
from digitalio import DigitalInOut
import adafruit_connection_manager
import adafruit_requests
from adafruit_matrixportal.matrix import Matrix
from adafruit_esp32spi import adafruit_esp32spi
import adafruit_minimqtt.adafruit_minimqtt as MQTT
import custom_display
secrets = {
"ssid": getenv("CIRCUITPY_WIFI_SSID"),
"password": getenv("CIRCUITPY_WIFI_PASSWORD"),
"mqtt_host": getenv("MQTT_BROKER"),
"mqtt_user": getenv("MQTT_USER"),
"mqtt_pass": getenv("MQTT_PASS"),
"airgradient_id": getenv("AIRGRADIENT_ID")
}
UTC_OFFSET = int(getenv("UTC_OFFSET") or 0)
TEST_MODE = int(getenv("TEST_MODE") or 0)
NIGHT_START = 23 # 10 PM
NIGHT_END = 7 # 7 AM
NTP_RESYNC_INTERVAL = 6 * 3600
gc.enable()
matrix = Matrix(width=32, height=32)
print("\n" * 10)
display = matrix.display
display.root_group = displayio.Group()
group = displayio.Group()
bitmap = displayio.Bitmap(32, 32, 4)
color = displayio.Palette(4)
color[0] = 0x000000 # black background
color[1] = 0xFF0000 # red
color[2] = 0xCC4000 # amber
color[3] = 0x00FF00 # greenish
tile_grid = displayio.TileGrid(bitmap, pixel_shader=color)
group.append(tile_grid)
display.root_group = group
STATUS_LIGHT_X = {1: 8, 2: 15, 3: 22} # 1=wifi, 2=ntp, 3=sensor; centered, even spread
def set_status_light(light_id, color_idx):
x_start = STATUS_LIGHT_X[light_id]
for x in range(x_start, x_start + 2):
for y in range(15, 17):
bitmap[x, y] = color_idx
def clear_status_lights():
for x in range(STATUS_LIGHT_X[1], STATUS_LIGHT_X[3] + 2):
for y in range(15, 17):
bitmap[x, y] = 0
if TEST_MODE:
import test_harness
test_harness.run(matrix, bitmap, set_status_light, clear_status_lights)
if secrets == {"ssid": None, "password": None}:
try:
# Fallback on secrets.py until depreciation is over and option is removed
from secrets import secrets
except ImportError:
print("WiFi secrets are kept in settings.toml, please add them there!")
raise
# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)
# Secondary (SCK1) SPI used to connect to WiFi board on Arduino Nano Connect RP2040
if "SCK1" in dir(board):
spi = busio.SPI(board.SCK1, board.MOSI1, board.MISO1)
else:
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
pool = adafruit_connection_manager.get_radio_socketpool(esp)
ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp)
requests = adafruit_requests.Session(pool, ssl_context)
has_error = False
MAX_WIFI_RETRIES = 20
MAX_MQTT_RETRIES = 5
MAX_ERRORS = 5
STALE_TIMEOUT = 300 # seconds before assuming silent disconnect
# Light 1: WiFi Connecting (amber)
set_status_light(1, 2)
# Light 2: NTP Syncing (amber)
set_status_light(2, 2)
# Light 3: Sensor message (amber)
set_status_light(3, 2)
print("Connecting to " + secrets["ssid"] + "...")
wifi_retry = 0
while not esp.is_connected:
try:
esp.connect_AP(secrets["ssid"], secrets["password"])
has_error = False
except OSError as e:
print("could not connect to AP, retrying: ", e)
wifi_retry += 1
has_error = True
esp.reset()
time.sleep(1)
if wifi_retry >= MAX_WIFI_RETRIES:
print("WiFi failed after max retries, resetting")
microcontroller.reset()
continue
print("Connected to", esp.ap_info.ssid, "\tRSSI:", esp.ap_info.rssi)
print("IP address is", esp.ipv4_address)
# Light 1: WiFi Connected (green)
set_status_light(1, 3)
ntp_synced = False
last_ntp_sync = 0
try:
rtc.RTC().datetime = time.localtime(esp.get_time()[0])
ntp_synced = True
last_ntp_sync = time.monotonic()
set_status_light(2, 3) # green: synced
print("NTP synced:", time.localtime())
except Exception as e:
set_status_light(2, 1) # red: failed
print("NTP sync failed:", e)
def is_night():
h = (time.localtime().tm_hour + UTC_OFFSET) % 24
return h >= NIGHT_START or h < NIGHT_END
# Set up a MiniMQTT Client
mqtt_client = MQTT.MQTT(
broker=secrets["mqtt_host"],
username=secrets["mqtt_user"],
password=secrets["mqtt_pass"],
socket_pool=pool,
ssl_context=ssl_context,
)
mqtt_topic = f"airgradient/readings/" + secrets["airgradient_id"]
mqtt_topic_aqi = f"homeassistant/sensor/ag_outdoors_calc_aqi/state"
mqtt_topic_night = f"homeassistant/binary_sensor/night_time/state"
mqtt_topic_is_home = f"homeassistant/input_boolean/is_home/state"
main_display = custom_display.CustomDisplay(matrix.display)
last_message_time = [time.monotonic()]
last_sensor_time = [None] # monotonic time of last good temp/humidity reading
SENSOR_STALE_TIMEOUT = 300 # seconds before marking readings stale
sensor_received = [False, False] # [temperature, humidity] seen at least once
# Define callback methods which are called when events occur
def connect(mqtt_client, userdata, flags, rc):
# This function will be called when the mqtt_client is connected
# successfully to the broker.
print("Connected to MQTT Broker!")
print(f"Flags: {flags}\n RC: {rc}")
def disconnect(mqtt_client, userdata, rc):
# This method is called when the mqtt_client disconnects
# from the broker.
print("Disconnected from MQTT Broker!")
def subscribe(mqtt_client, userdata, topic, granted_qos):
# This method is called when the mqtt_client subscribes to a new feed.
print(f"Subscribed to {topic} with QOS level {granted_qos}")
def unsubscribe(mqtt_client, userdata, topic, pid):
# This method is called when the mqtt_client unsubscribes from a feed.
print(f"Unsubscribed from {topic} with PID {pid}")
def publish(mqtt_client, userdata, topic, pid):
# This method is called when the mqtt_client publishes data to a feed.
print(f"Published to {topic} with PID {pid}")
def message(client, topic, message):
print(f"New message on topic {topic}: {message}")
last_message_time[0] = time.monotonic()
if topic == mqtt_topic:
try:
parsed = json.loads(str(message))
main_display.set_temperature((float(parsed["atmpCompensated"]) * 9.0 / 5.0) + 32.0 )
sensor_received[0] = True
main_display.set_humidity(float(parsed["rhumCompensated"]))
sensor_received[1] = True
last_sensor_time[0] = time.monotonic()
except (ValueError, KeyError) as e:
# keep last good values, leave stale indicator to the main loop
print("Failed to parse sensor message: ", e)
if topic == mqtt_topic_aqi:
try:
main_display.set_aqi(float(message))
except ValueError:
main_display.set_aqi(float(888))
if topic == mqtt_topic_night:
try:
is_night = str(message).strip().lower() in ("on", "true", "1")
main_display.set_night_time(is_night)
except Exception as e:
print("Failed to parse night_time message: ", e)
if topic == mqtt_topic_is_home:
try:
is_home = str(message).strip().lower() in ("on", "true", "1")
main_display.set_is_home(is_home)
except Exception as e:
print("Failed to parse is_home message: ", e)
# Connect callback handlers to mqtt_client
mqtt_client.on_connect = connect
mqtt_client.on_disconnect = disconnect
mqtt_client.on_subscribe = subscribe
mqtt_client.on_unsubscribe = unsubscribe
mqtt_client.on_publish = publish
mqtt_client.on_message = message
def subscribe_topics():
mqtt_client.subscribe(mqtt_topic)
mqtt_client.subscribe(mqtt_topic_aqi)
mqtt_client.subscribe(mqtt_topic_night)
mqtt_client.subscribe(mqtt_topic_is_home)
mqtt_retry = 0
while True:
try:
print(f"Attempting to connect to {mqtt_client.broker}")
mqtt_client.connect()
break
except Exception as e:
print("MQTT connect failed: ", e)
mqtt_retry += 1
if mqtt_retry >= MAX_MQTT_RETRIES:
print("MQTT failed after max retries, resetting")
microcontroller.reset()
time.sleep(3)
subscribe_topics()
reset_counter = 0
display_switched = False
while True:
if not ntp_synced or time.monotonic() - last_ntp_sync > NTP_RESYNC_INTERVAL:
try:
rtc.RTC().datetime = time.localtime(esp.get_time()[0])
last_ntp_sync = time.monotonic()
if not ntp_synced:
ntp_synced = True
set_status_light(2, 3) # green: synced
print("NTP synced:", time.localtime())
except Exception as e:
print("NTP sync failed:", e)
if ntp_synced and (has_error or not main_display._night_mode_received):
main_display.set_night_time(is_night())
if not display_switched:
both_received = sensor_received[0] and sensor_received[1]
# night/home take priority: if either says "off" while we're still
# waiting on sensor data, blank the boot lights instead of showing them.
hide_boot = (main_display._night_mode_received and main_display.night_time) \
or (main_display._is_home_received and not main_display.is_home)
if both_received:
set_status_light(3, 3) # green: both readings in
# Pre-render real values before the group becomes visible
sensor_stale = (last_sensor_time[0] is None
or time.monotonic() - last_sensor_time[0] > SENSOR_STALE_TIMEOUT)
main_display.set_stale(sensor_stale)
main_display.set_error(has_error)
main_display.update_display()
display.root_group = main_display.root_group
display_switched = True
elif hide_boot:
clear_status_lights()
else:
set_status_light(3, 2) # amber: waiting on readings
sensor_stale = (last_sensor_time[0] is None
or time.monotonic() - last_sensor_time[0] > SENSOR_STALE_TIMEOUT)
main_display.set_stale(sensor_stale)
if time.monotonic() - last_message_time[0] > STALE_TIMEOUT:
print("No MQTT messages in 5 minutes, pinging broker...")
try:
mqtt_client.ping()
print("Broker alive, resetting stale timer")
last_message_time[0] = time.monotonic()
except Exception as pe:
print("Ping failed: ", pe)
try:
esp.reset()
time.sleep(1)
esp.connect_AP(secrets["ssid"], secrets["password"])
mqtt_client.connect()
subscribe_topics()
last_message_time[0] = time.monotonic()
print("Recovered after ping failure")
except Exception as re:
print("Soft recovery failed, resetting: ", re)
microcontroller.reset()
try:
main_display.set_error(has_error)
main_display.update_display()
gc.collect()
mqtt_client.loop()
has_error = False
reset_counter = 0
except Exception as e:
print("err: ", str(e))
has_error = True
try:
main_display.set_error(has_error)
main_display.update_display()
except Exception as display_err:
print("Failed to update display with error status: ", display_err)
recovered = False
try:
print("Attempting MQTT reconnect...")
mqtt_client.reconnect()
subscribe_topics()
recovered = True
print("MQTT reconnected")
except Exception as re:
print("MQTT reconnect failed: ", re)
try:
print("Attempting WiFi+MQTT reconnect...")
esp.reset()
time.sleep(1)
esp.connect_AP(secrets["ssid"], secrets["password"])
mqtt_client.connect()
subscribe_topics()
recovered = True
print("WiFi+MQTT reconnected")
except Exception as we:
print("WiFi reconnect failed: ", we)
if recovered:
reset_counter = 0
has_error = False
last_message_time[0] = time.monotonic()
else:
reset_counter += 1
if reset_counter >= MAX_ERRORS:
print("Too many unrecoverable errors, resetting")
microcontroller.reset()
time.sleep(5)