Archived
1
0

Updated main.py to be more failsafe. Now using umqtt.robust too.

This commit is contained in:
Shaun Setlock
2022-12-06 21:17:34 -05:00
parent e14a2d0a9e
commit 5f182f8732

54
main.py
View File

@@ -4,7 +4,7 @@ import time
import json
import machine
from machine import Pin
from umqtt.simple import MQTTClient
from umqtt.robust import MQTTClient
import dht
import urequests
import wifi_config
@@ -115,7 +115,10 @@ def main():
wlan = network.WLAN(network.STA_IF)
# Create MQTT Client
mqtt_client = MQTTClient(mqtt_config.MQTT_CLIENT_ID, mqtt_config.MQTT_HOST_NAME)
mqtt_client = MQTTClient(
client_id = mqtt_config.MQTT_CLIENT_ID,
server = mqtt_config.MQTT_HOST_NAME,
)
# Create DHT22
sensor = dht.DHT22(Pin(DHT_22_GPIO_PIN))
@@ -132,7 +135,28 @@ def main():
if DEBUG:
print(f'\nStarting loop #{count}... \nWiFI Status is {wlan.status()}.')
# Create Local Flags for Control
wifi_ready = False
mqtt_ready = False
dht22_ready = False
# DHT22 and CPU Reading.
try:
# CPU Reading.
cpu_temp = read_cpu_temp()
# DHT22 Reading.
dht22_reading = read_dht_22(sensor)
#debug_str = "None"
if dht22_reading is not None:
temp,hum = dht22_reading
temp = temp * 9/5. + 32.0
dht22_ready = True
except:
continue
# WiFi Connection.
try:
if wlan.status() != 3:
ifconfig = wlan_up(wlan)
if ifconfig is None:
@@ -142,16 +166,22 @@ def main():
time.sleep(10)
continue
else:
wifi_ready = True
if DEBUG:
print("Connected to WiFi: {}".format(ifconfig))
else:
wifi_ready = True
ifconfig = wlan.ifconfig()
if DEBUG:
print(f"Skipping WiFi Activation since WiFi Status is {wlan.status()} \n{ifconfig}.")
except:
continue
# MQTT Conneciton.
try:
mqtt_client.connect()
try:
mqtt_client.connect(clean_session = False)
mqtt_ready = True
if DEBUG:
print(f'MQTT Connected.')
@@ -161,17 +191,12 @@ def main():
led_error_code(led, 2)
time.sleep(5)
continue # Start back at the top of the While Loop
except:
continue
# DHT22 Reading.
dht22_reading = read_dht_22(sensor)
#debug_str = "None"
if dht22_reading is not None:
temp,hum = dht22_reading
temp = temp * 9/5. + 32.0
# CPU Reading.
cpu_temp = read_cpu_temp()
# Ready to Publish?
try:
if wifi_ready and mqtt_ready and dht22_ready:
# Timestamp
time_now = time.localtime()
timestamp = "{}/{}/{} {}:{}:{}".format(time_now[1],time_now[2],time_now[0],time_now[3],time_now[4],time_now[5])
@@ -200,6 +225,9 @@ def main():
if DEBUG:
print(f'MQTT Disconnected.')
except:
continue
# Sleep for a bit.
if DEBUG:
print(f'Finished loop #{count}.')