From 84ce8640e9ff7cbdcba3ed2a3639f4c171f0357f Mon Sep 17 00:00:00 2001 From: Wolfgang Hottgenroth Date: Sun, 9 Oct 2022 12:04:27 +0200 Subject: [PATCH] change broker, introduce mqtt authentication --- config.py | 14 ++++++++++---- main.py | 25 +++++++++++++++---------- 2 files changed, 25 insertions(+), 14 deletions(-) diff --git a/config.py b/config.py index 433a5b4..ca564ee 100644 --- a/config.py +++ b/config.py @@ -1,5 +1,11 @@ -ssid = 'telemetry' +import secrets -mqtt_server = '172.16.10.47' -heartbeat_topic = b'IoT/rpipwThermometer/0/Heartbeat' -watchdog_topic = b'IoT/Watchdog' +SSID = 'telemetry' +WPA_KEY = secrets.WPA_KEY +MQTT_SERVER = '172.16.10.47' +MQTT_LOGIN = 'thermo-anna' +MQTT_PASSWORD = secrets.MQTT_PASSWORD +HEARTBEAT_TOPIC = b'IoT/rpipwThermometer/0/Heartbeat' +WATCHDOG_TOPIC = b'IoT/Watchdog' + +MAX_CONNECT_RETRY_CNT = 1000000 \ No newline at end of file diff --git a/main.py b/main.py index 36aadc9..5c9f04d 100644 --- a/main.py +++ b/main.py @@ -1,13 +1,12 @@ # main.py -- put your code here! -from umqttsimple import MQTTClient +from umqttsimple import MQTTClient, MQTTException import time import ubinascii from machine import WDT import network import os import config -import secrets last_message = 0 message_interval = 5 @@ -20,20 +19,26 @@ client = None def init(): wlan = network.WLAN(network.STA_IF) wlan.active(True) - wlan.connect(config.ssid, secrets.wpakey) + wlan.connect(config.SSID, config.WPA_KEY) - while (not wlan.isconnected()): - print('Not yet connected to WLAN') + connectCnt = 0 + while (not wlan.isconnected() or connectCnt > config.MAX_CONNECT_RETRY_CNT): + connectCnt += 1 + if (not wlan.isconnected()): + print("Failed to connect to wlan, restarting") + machine.reset() print('Connected to WLAN') global client clientId = ubinascii.hexlify(bytearray(os.urandom(16))).decode() - client = MQTTClient(clientId, config.mqtt_server, keepalive=60, ssl=True) + client = MQTTClient(clientId, config.MQTT_SERVER, keepalive=60, + ssl=True, user=config.MQTT_LOGIN, password=config.MQTT_PASSWORD) client.set_callback(mqtt_callback) client.connect() - client.subscribe(config.watchdog_topic) - print(f"Connected to {config.mqtt_server} MQTT Broker") + print(f"Connected to MQTT broker {config.MQTT_SERVER} ") + client.subscribe(config.WATCHDOG_TOPIC) + print(f"Subscribed to {config.WATCHDOG_TOPIC}") global wdt wdt = WDT(timeout=5000) @@ -44,7 +49,7 @@ def init(): def mqtt_callback(topic, msg): global wdt, wdtCnt print(f"Received: {topic}: {msg}") - if topic == config.watchdog_topic: + if topic == config.WATCHDOG_TOPIC: wdtCnt += 1 print(f"feed watchdog {wdtCnt}") wdt.feed() @@ -57,7 +62,7 @@ def main(): try: init() except Exception as e: - print(f"Some error when starting: {e}") + print(f"Some error when starting: {e.__class__.__name__}, {e}") time.sleep(15) machine.reset()