import time
import network
from umqtt.simple import MQTTClient
import ujson
import random # à remplacer par tes vrais capteurs
# ---------- WiFi ----------
WIFI_SSID = "nyhome5G"
WIFI_PASS = "bm@1574d"
# ---------- ThingsBoard ----------
THINGSBOARD_HOST = "192.168.1.1"
MQTT_PORT = 1884 # ou 1883 selon ton serveur
ACCESS_TOKEN = "81qyBt6mbpldVTBfzjcj"
TOPIC_TELEMETRY = b"v1/devices/me/telemetry"
TOPIC_ATTRIBUTES = b"v1/devices/me/attributes"
# ---------- Attributes (infos carte) ----------
DEVICE_NAME = "ESP32_WeatherST_S1"
DEVICE_LOCATION = "Salle IoT - Etage 1" # LOCALISATION
def connecter_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
wlan.connect(WIFI_SSID, WIFI_PASS)
while not wlan.isconnected():
time.sleep(0.5)
print("Wi-Fi OK:", wlan.ifconfig())
return wlan
def connecter_mqtt():
client_id = b"esp32_weatherst_S1"
c = MQTTClient(
client_id=client_id,
server=THINGSBOARD_HOST,
port=MQTT_PORT,
user=ACCESS_TOKEN, # token = username
password="",
keepalive=30
)
c.connect()
print("MQTT OK")
return c
def publier_attributes(client):
# Attributes = infos statiques (nom, localisation)
attrs = {
"device_name": DEVICE_NAME,
"location": DEVICE_LOCATION
}
client.publish(TOPIC_ATTRIBUTES, ujson.dumps(attrs))
print("Attributes envoyés:", attrs)
def publier_telemetry(client):
# Remplace random par lecture de tes capteurs réels
data = {
"temperature": round(20 + random.random() * 10, 2),
"humidite": round(40 + random.random() * 30, 2),
"qualite_air": int(350 + random.random() * 300)
}
client.publish(TOPIC_TELEMETRY, ujson.dumps(data))
print("Telemetry envoyée:", data)
# ---------- Main ----------
connecter_wifi()
client = connecter_mqtt()
# Envoyer les attributes une seule fois au démarrage
publier_attributes(client)
# Envoyer la telemetry toutes les 5 secondes
while True:
publier_telemetry(client)
time.sleep(5)