import network
import time
from umqtt.simple import MQTTClient
# WiFi Configuration
SSID = 'Wokwi-GUEST'
PASSWORD = ''
# MQTT Broker Configuration
BROKER = 'broker.emqx.io'
PORT = 1883
TOPIC = b'test11'
CLIENT_ID = b'wokwi-publisher'
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('Connecting to WiFi...')
wlan.connect(SSID, PASSWORD)
while not wlan.isconnected():
time.sleep(1)
print('WiFi connected:', wlan.ifconfig())
def publish_loop():
client = MQTTClient(CLIENT_ID, BROKER, PORT)
client.connect()
print('Connected to MQTT broker')
try:
while True:
message = b'hello this is frank'
client.publish(TOPIC, message)
print('Published:', message.decode())
time.sleep(2) # wait 2 seconds before next publish
finally:
client.disconnect()
print('Disconnected from MQTT broker')
connect_wifi()
publish_loop()