import time
import json
import dht
import machine
from umqtt.simple import MQTTClient
import network
# Paramètres MQTT
SERVER = "" # Adresse du broker
CLIENT_ID = ""
TOPIC_DHT = ""
TOPIC_RELAY1 = ""
TOPIC_RELAY2 = ""
MQTT_USER = ""
MQTT_PASSWORD = ""
# WiFi
WIFI_SSID = "VotreSSID"
WIFI_PASSWORD = "VotreMDP"
# Broches matérielles
RELAY1_PIN = 12 # Relais physique
DHT_PIN = 27 # Capteur DHT11
# Initialisation
relay1 = machine.Pin(RELAY1_PIN, machine.Pin.OUT)
dht_sensor = dht.DHT11(machine.Pin(DHT_PIN))
# État du relais 2 (simulé)
relay2_state = "OFF"
# Connexion WiFi
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("Connexion WiFi...")
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
while not wlan.isconnected():
pass
print("Connecté WiFi :", wlan.ifconfig())
# Lecture capteur réel
def read_dht():
try:
dht_sensor.measure()
temp = dht_sensor.temperature()
hum = dht_sensor.humidity()
return temp, hum
except Exception as e:
print("Erreur capteur DHT :", e)
return None, None
# Publication capteurs uniquement
def publish_sensor_data(temp, hum):
data = {
"temperature": temp,
"humidity": hum
}
mqtt_client.publish(TOPIC_DHT, json.dumps(data))
print("Publié sur", TOPIC_DHT, ":", data)
# Callback pour réception des commandes relais
def on_message(topic, message):
global relay2_state
topic = topic.decode("utf-8")
print("Message reçu - Topic:", topic, "Message:", message)
try:
data = json.loads(message.decode("utf-8"))
if "etat" in data:
etat = data["etat"].upper()
if topic == TOPIC_RELAY1:
if etat == "ON":
relay1.value(1)
else:
relay1.value(0)
print("→ Relais 1 :", "ON" if relay1.value() else "OFF")
elif topic == TOPIC_RELAY2:
relay2_state = "ON" if etat == "ON" else "OFF"
print("→ Relais 2 (simulé) :", relay2_state)
except Exception as e:
print("Erreur JSON :", e)
# Connexion
connect_wifi()
mqtt_client = MQTTClient(CLIENT_ID, SERVER, user=MQTT_USER, password=MQTT_PASSWORD)
mqtt_client.set_callback(on_message)
mqtt_client.connect()
mqtt_client.subscribe(TOPIC_RELAY1)
mqtt_client.subscribe(TOPIC_RELAY2)
print("MQTT connecté et abonné.")
# Boucle principale
while True:
try:
temp, hum = read_dht()
if temp is not None and hum is not None:
publish_sensor_data(temp, hum)
mqtt_client.check_msg() # Vérifie les commandes entrantes
time.sleep(3)
except Exception as e:
print("Erreur dans la boucle :", e)
time.sleep(2)