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 = "189ee04d-1464-4f9f-beee-447b8c10a18d"
broker = "mqtt.netpie.io"
token = "kAxxERNxuMwfzPjpMmHykYfhKvGvVoYq"
secret = "JfzYSP1Guykax1B9D89scYRws8YzSJu8"
topic = "@msg/chanomkaima"
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 == "ON":
led.value(1)
time.sleep(1)
elif last_msg == "OFF":
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()
print("LED State :", led.value())
time.sleep(1)