So I created a minimal application to to make it easy hopefully to identify what I’m doing wrong.
Any suggestions where my issue is?
import time
import ubinascii
from umqtt.simple import MQTTClient
import machine
import random, network
# Default MQTT_BROKER to connect to
MQTT_BROKER = "192.168.1.68" #home assistant
CLIENT_ID = ubinascii.hexlify(machine.unique_id())
SUBSCRIBE_TOPIC = b"garage_door/set"
PUBLISH_TOPIC = b"garage_door/state"
SSID = "myssid"
SSID_PASSWORD = "mypassword"
# Default MQTT_BROKER to connect to
CLIENT_ID = ubinascii.hexlify(machine.unique_id())
# Setup built in PICO LED as Output
led = machine.Pin("LED",machine.Pin.OUT)
# Publish MQTT messages after every set timeout
last_publish = time.time()
publish_interval = 5
# Received messages from subscriptions will be delivered to this callback
def sub_cb(topic, msg):
print((topic, msg))
if msg.decode() == "OPEN":
led.value(1)
else:
led.value(0)
def reset():
print("Resetting...")
time.sleep(5)
machine.reset()
def do_connect():
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print('12.connecting to network...')
sta_if.active(True)
sta_if.connect(SSID, SSID_PASSWORD)
while not sta_if.isconnected():
print("13.Attempting to connect....")
utime.sleep(1)
print('14.Connected! Network config:', sta_if.ifconfig())
#end do_connect()
def main():
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
for _ in range(10):
sta_if.connect(SSID, SSID_PASSWORD)
time.sleep(1)
print('15.Wifi failed to connect, retrying')
if sta_if.isconnected():
print('16.Wifi connected.')
break
time.sleep(11)
else:
print('17.Wifi Fail')
led_state(WIFI_ERROR)
time.sleep(100)
reset()
print(f"Begin connection with MQTT Broker :: {MQTT_BROKER}")
mqttClient = MQTTClient(CLIENT_ID, MQTT_BROKER, keepalive=60)
mqttClient.set_callback(sub_cb)
mqttClient.connect()
mqttClient.subscribe(SUBSCRIBE_TOPIC)
print(f"Connected to MQTT Broker :: {MQTT_BROKER}, and waiting for callback function to be called!")
while True:
# Non-blocking wait for message
mqttClient.check_msg()
global last_publish
if (time.time() - last_publish) >= publish_interval:
mqttClient.publish(PUBLISH_TOPIC, "closed")
last_publish = time.time()
time.sleep(1)
if __name__ == "__main__":
while True:
try:
main()
except OSError as e:
print("Error: " + str(e))
reset()