import time
from umqtt_simple import MQTTClient
import network
import ujson
def connect_to_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("Wokwi-GUEST", "")
print("Connecting to Wi-Fi...")
while not wlan.isconnected():
time.sleep(1)
print("Wi-Fi connected")
def on_message(topic, msg):
print("Received: {}:{}".format(topic.decode(), msg.decode()))
# Wi-Fi connection
connect_to_wifi()
# Paramètres du serveur MQTT
mqtt_server = "broker.mqttdashboard.com"
mqtt_port = 1883
mqtt_topic = "iot/data"
print("Connexion au serveur MQTT... ", end="")
client = MQTTClient("raspberry-pi", mqtt_server, port=mqtt_port)
def connect_to_mqtt():
print("Connecting to MQTT...")
while client.connect() != 0:
print("MQTT connection failed. Retrying in 5 seconds...")
time.sleep(5)
# Subscribe to the MQTT topic
client.subscribe(mqtt_topic)
print("MQTT connection successful")
client.set_callback(on_message)
connect_to_mqtt()
client.publish(mqtt_topic, "test")
client.disconnect()