import network
import time
import json
from umqtt.simple import MQTTClient
#Connecting the Controller with Internet
print("Connecting to Internet")
sta=network.WLAN(network.STA_IF)
sta.active(True)
sta.connect('Wokwi-GUEST','')
while not sta.isconnected():
print(".",end="")
time.sleep(0.2)
print("connected")
#Declaring Constant
mqtt_bro="broker.hivemq.com"
mqtt_port=1883
mqtt_topic="T"
client_id="subigeer"
#MQTT Instance
mqtt=MQTTClient(client_id,mqtt_bro,port=mqtt_port)
#function for connecting mqtt
def conn_mqtt():
try:
print("Connecting MQTT")
mqtt.connect()
except Exception as e:
print("Exception due to",str(e))
conn_mqtt()
def on_msg(topic,message):
print(f"recived msg with topic {topic}:{message.decode()}")
data=json.loads(message.decode())
mqtt.set_callback(on_msg)
mqtt.subscribe(mqtt_topic)
print("subscribed topic",mqtt_topic)
try:
while True:
mqtt.check_msg()
time.sleep(1)
except KeyboardInterrupt:
print("disconnecting")
mqtt.disconnect()