import network
import time
from umqtt.simple import MQTTClient
WiFi_SSID = 'Wokwi-GUEST'
WiFi_PASS = ''
MOTT_BROKER = 'broker.hivemq.com'
MQTT_CLIENT_ID = 'Weerapong-026' #Change to a unique name to avoid collision
MQTT_USER = ''
MQTT_PASS = ''
#Connect to Wifi
wlan = network.WLAN(network.STA_IF) #Create a Wifi Station Interface
wlan.active(True)
wlan.connect(WiFi_SSID, WiFi_PASS) # Start Connecting
print('WiFi', end='')
while not wlan.isconnected():
print('.', end='')
time.sleep(0.5)
print('', wlan.ifconfig()[0], '[Connected]')
# Connect to MQTT broker
client = MQTTClient(MQTT_CLIENT_ID, MOTT_BROKER,
user=MQTT_USER, password=MQTT_PASS)
print('MQTT ... ', MOTT_BROKER, end='')
try:
client.connect()
print('[Connected]')
except:
print(' [Error]')
# Callback function for responding to the subscribed topics
def on_message(topic, msg):
incoming_message = msg.decode('utf8')
print('{}: {}'.format(topic, incoming_message))
client.set_callback(on_message) # Attach the CALLBACK routine
client.subscribe('ae_iot/#') # Hook up to a subscribed topic
while True:
client.check_msg() # Periodically chack the incoming message