from machine import Pin,ADC,PWM
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)
led2 = PWM(Pin(13))
while not wifi.isconnected():
print("connecting to wifi")
print(wifi.ifconfig())
# MQTT & NETPIE Setup
client = "e1ccda9d-1ca8-42cb-9e5f-cb9bc3b8bb4c" # กรอก client ID
broker = "mqtt.netpie.io"
token = "oGcfRUUzKJmPbCPNCHjjdx6AcRA5U61v" # กรอก token
secret = "RRBfADCuJZgFXNXRRBSu1JosZFQ4zmki" # กรอก secret
topic = "@msg/operator"
last_msg = 0
netpie = MQTTClient(client, broker, user=token, password=secret, port=1883)
# -------------------------
# ฟังก์ชัน callback สำหรับรับ MSG
# -------------------------
def on_message(topic, msg):
global last_msg
last_msg = ujson.loads(msg.decode()) #ตรงนี้ใช้ๅ ujson.load และทำการ decode
print("MSG Received :", last_msg, type(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()
led2.duty(last_msg)
time.sleep(5)