Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from umqtt.robust import MQTTClient
- import network
- import time
- import machine
- import json
- wlan = network.WLAN(network.STA_IF)
- ID = 'ESP32'
- mqtt_broker = '192.168.1.X'
- my_user = 'username'
- my_pass = 'password'
- topic = (b'home/garden/#')
- c = MQTTClient(ID, mqtt_broker, user=my_user, password=my_pass)
- # c.DEBUG = True
- def subscribe():
- try:
- c.connect(clean_session=False)
- c.set_callback(publish)
- c.subscribe(topic)
- print('Connected to MQTT broker, subscribed to', topic)
- except:
- print('Error, MQTT broker is not responding')
- def check_json(msg):
- try:
- msg = json.loads(msg)
- except:
- print('Message was not JSON')
- return False
- return True
- def check_int(time):
- try:
- time = int(time)
- except:
- print('Time field invalid')
- return False
- return True
- def publish(topic, msg):
- # print((topic, msg))
- if check_json(msg):
- message = {}
- message = json.loads(msg)
- relay = message['relay']
- state = message['state']
- time = int(message['time'])
- if check_int(time):
- print("Last received:", message)
- message = json.dumps(message)
- c.publish(topic, message)
- # response = json.dumps("Relay": relay, "State": state, "Time": time)
- else:
- # response = "json.dumps("Time Invalid": type(time))"
- print("Time entered was invalid. Type was", type(time))
- # Blocking wait for message (this is for single task code)
- # c.wait_msg()
- # Non-blocking wait for message (this is for multi tasking projects)
- # c.check_msg()
- def wlan_disconnect():
- tick = 1
- while not wlan.isconnected():
- print('WLAN is reconnecting...', tick, '/5')
- time.sleep(5)
- tick += 1
- if tick == 5:
- print("Restarting...")
- machine.reset()
- def main():
- if wlan.isconnected(): # Check if WiFi is connected
- if not c.connect(): # Check if MQTT broker is connected
- subscribe()
- print("Waiting for messages")
- while True:
- if wlan.isconnected():
- c.wait_msg()
- else: # If wifi is not connected...run a tick routine to reboot ESP32, then resubscribe
- wlan_disconnect()
- subscribe()
Advertisement
Add Comment
Please, Sign In to add comment