import time
import network
import ujson
from machine import Pin
from umqtt.simple import MQTTClient
# ========== CẤU HÌNH ========== #
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASS = ""
THINGSBOARD_HOST = "demo.thingsboard.io"
ACCESS_TOKEN = "HVXzPxbGDfuaqqkoGZbz"
# ========== GPIO ========== #
LDR_DO = Pin(26, Pin.IN)
RELAY = Pin(27, Pin.OUT)
RELAY.value(0)
# ========== WIFI ========== #
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASS)
print("🔌 Kết nối WiFi...")
while not wlan.isconnected():
time.sleep(0.5)
print("✅ Đã kết nối WiFi:", wlan.ifconfig())
# ========== MQTT ========== #
connect_wifi()
client = MQTTClient("pico", THINGSBOARD_HOST, user=ACCESS_TOKEN, password="")
client.connect()
print("✅ MQTT connected")
# ========== BIẾN TOÀN CỤC ========== #
on_count = 0
status = "OFF"
control_mode = "AUTO"
start_time = time.time()
# ========== LOOP ========== #
while True:
try:
light_detected = LDR_DO.value() # 0 = tối, 1 = sáng
if control_mode == "AUTO":
if light_detected == 0 and status != "ON":
RELAY.value(1)
status = "ON"
on_count += 1
elif light_detected == 1 and status != "OFF":
RELAY.value(0)
status = "OFF"
telemetry = {
"ambient_light": int(not light_detected) * 1023,
"status": status,
"mode": control_mode,
"on_count": on_count,
"uptime": int(time.time() - start_time),
"model": "Pico-LDR-v1"
}
client.publish("v1/devices/me/telemetry", ujson.dumps(telemetry))
print("📤 Sent:", telemetry)
except Exception as e:
print("❌ Error sending data:", e)
time.sleep(3)