88 lines
2.4 KiB
Python
88 lines
2.4 KiB
Python
import machine
|
|
from umqttsimple import MQTTClient
|
|
import time
|
|
import ubinascii
|
|
from machine import Pin, WDT
|
|
from onewire import OneWire
|
|
from ds18x20 import DS18X20
|
|
import network
|
|
import json
|
|
import config
|
|
|
|
|
|
SENSOR_PIN = 16
|
|
|
|
|
|
print("Hello")
|
|
resetCause = machine.reset_cause()
|
|
|
|
wdt = WDT(timeout=8000)
|
|
wdt.feed()
|
|
print("Watchdog enabled")
|
|
|
|
try:
|
|
wlan = network.WLAN(network.STA_IF)
|
|
wlan.active(True)
|
|
wlan.connect(config.SSID, config.WPA_KEY)
|
|
|
|
connectCnt = 0
|
|
while (not wlan.isconnected() or (connectCnt > config.MAX_CONNECT_RETRY_CNT)):
|
|
print("Not yet connected")
|
|
wdt.feed()
|
|
connectCnt += 1
|
|
time.sleep(1)
|
|
|
|
if (not wlan.isconnected()):
|
|
print("Failed to connect to wlan, restarting")
|
|
machine.reset()
|
|
|
|
print(f"Connected to WLAN: {resetCause} {connectCnt} {wlan.ifconfig()}")
|
|
wdt.feed()
|
|
|
|
except Exception as e:
|
|
print(f"Some error when starting: {e.__class__.__name__}, {e}")
|
|
print("Restarting")
|
|
time.sleep(5)
|
|
machine.reset()
|
|
|
|
while True:
|
|
try:
|
|
clientId = f"rpipwtherm-{ubinascii.hexlify(machine.unique_id())}"
|
|
client = MQTTClient(clientId, config.MQTT_SERVER, keepalive=60,
|
|
ssl=True, user=config.MQTT_LOGIN, password=config.MQTT_PASSWORD)
|
|
client.connect()
|
|
print(f"Connected to MQTT broker {config.MQTT_SERVER} ")
|
|
wdt.feed()
|
|
|
|
# client.publish(config.STARTUP_TOPIC, f"Hello, rpipw thermometer is alive now at {wlan.ifconfig()}")
|
|
sensor = DS18X20(OneWire(Pin(SENSOR_PIN, Pin.IN, Pin.PULL_UP)))
|
|
devices = sensor.scan()
|
|
sensor.convert_temp()
|
|
time.sleep(1)
|
|
for idx, device in enumerate(devices):
|
|
t = sensor.read_temp(device)
|
|
msg = {
|
|
"sensor" : idx,
|
|
"location": config.LOCATION,
|
|
"temperature": t
|
|
}
|
|
print(f"Sensor: {idx}, {json.dumps(msg)}")
|
|
client.publish(config.PAYLOAD_TOPIC, json.dumps(msg))
|
|
print(f"Payload {idx} sent")
|
|
wdt.feed()
|
|
|
|
client.disconnect()
|
|
print("Disconnected from broker")
|
|
|
|
for w in range(config.MAIN_PERIOD_S):
|
|
print(f"Waiting {w}...")
|
|
wdt.feed()
|
|
time.sleep(1)
|
|
except Exception as e:
|
|
print(f"Error in main loop: {e.__class__.__name__}, {e}")
|
|
print("Restarting")
|
|
time.sleep(5)
|
|
machine.reset()
|
|
|
|
|