import time
import network
from umqtt.simple import MQTTClient
import ujson
import random
WIFI_SSID = "nyhome5G"
WIFI_PASS = "bm@1574d"
THINGSBOARD_HOST = "192.168.1.1"
ACCESS_TOKEN = "z609few43cgvfvjw5n3p"
TOPIC_TELEMETRY = b"v1/devices/me/telemetry"
TOPIC_RPC_SUB = b"v1/devices/me/rpc/request/+"
etat = "OFF" # état local
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
#RPC response
def on_rpc(topic, msg):
global etat, client
try:
# topic: b"v1/devices/me/rpc/request/<id>"
t = topic.decode() if isinstance(topic, bytes) else topic
req_id = t.split('/')[-1]
data = ujson.loads(msg)
method = data.get("method")
params = data.get("params")
if method == "setState":
if params in (True, 1, "ON", "on", "1"):
etat = "ON"
else:
etat = "OFF"
print("Commande RPC -> etat =", etat)
# (Optionnel mais recommandé) publier l'état en telemetry pour le dashboard
client.publish(TOPIC_TELEMETRY, ujson.dumps({"etat": etat}))
# TWO-WAY RPC RESPONSE: répondre avec le même requestId
resp_topic = "v1/devices/me/rpc/response/{}".format(req_id)
client.publish(resp_topic, ujson.dumps({"success": True, "etat": etat}))
elif method == "read_state":
resp_topic = "v1/devices/me/rpc/response/{}".format(req_id)
client.publish(resp_topic, ujson.dumps({"success": True, "etat": etat}))
else:
# si méthode inconnue, on répond quand même
resp_topic = "v1/devices/me/rpc/response/{}".format(req_id)
client.publish(resp_topic, ujson.dumps({"success": False, "error": "unknown method"}))
except Exception as e:
print("RPC error:", e)
def connecter_mqtt():
client_id = b"esp32_001"
c = MQTTClient(
client_id=client_id,
server=THINGSBOARD_HOST,
port=1884, # ou 1883 selon config
user=ACCESS_TOKEN,
password="",
keepalive=30
)
c.set_callback(on_rpc)
c.connect()
c.subscribe(TOPIC_RPC_SUB)
print("MQTT OK + Sub RPC")
return c
wlan = connecter_wifi()
client = connecter_mqtt()
# Publier état initial
client.publish(TOPIC_TELEMETRY, ujson.dumps({"etat": etat}))
t_last = 0
while True:
# IMPORTANT: check_msg() pour recevoir les commandes
client.check_msg()
# Telemetry périodique (optionnel)
if time.time() - t_last >= 5:
t_last = time.time()
data = {
"temperature": round(33 + random.random() * 10, 2),
"humidite": round(40 + random.random() * 30, 2),
"qualite_air": int(350 + random.random() * 300),
"etat": etat
}
client.publish(TOPIC_TELEMETRY, ujson.dumps(data))
print("Envoyé:", data)
time.sleep(0.1)