from machine import Pin,ADC
import time
import network
import ujson
from umqtt.simple import MQTTClient
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect('Wokwi-GUEST','')
led = Pin(14, Pin.OUT)
while not wifi.isconnected():
print("connecting to wifi")
print(wifi.ifconfig())
# MQTT & NETPIE Setup
client = "d7b24732-17a1-45f3-b55f-eaec9c7df729" # กรอก client ID
broker = "mqtt.netpie.io"
token = "pcNhe4nLB6XNqxxSb5qU7DjB9kyhZPug" # กรอก token
secret = "893oyJioXQKFr4wmrGRLThY4hYqiGS63" # กรอก secret
topic = "@msg/operator"
last_msg = ""
netpie = MQTTClient(client, broker, user=token, password=secret, port=1883)
# -------------------------
# ฟังก์ชัน callback สำหรับรับ MSG
# -------------------------
def on_message(topic, msg):
global last_msg
last_msg = msg.decode().upper()
print("MSG Received :", last_msg)
# ตรวจจับคำสั่ง
if last_msg == "ONLED":
led.value(1)
time.sleep(1)
elif last_msg == "OFFLED":
led.value(0)
time.sleep(1)
# เปิดระบบรับข้อความ
netpie.set_callback(on_message)
netpie.connect()
netpie.subscribe(topic)
print("Connect to Netpie & Subscribed")
# -------------------------
# Loop หลัก
# -------------------------
while True:
netpie.check_msg()
#netpie.publish("@shadow/data/update", ujson.dumps({"data":{"LED": led.value()}}))
print("LED State :", led.value())
time.sleep(0.5)