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','')
#set up variables
mode = "automatic"
led = Pin(26, Pin.OUT)
ldr = ADC(Pin(34))
while not wifi.isconnected():
print("connecting to wifi")
print(wifi.ifconfig())
# MQTT & NETPIE Setup
client = "53dd19ca-7dcc-4196-b08f-549e6f60e5ee" # กรอก client ID
broker = "mqtt.netpie.io"
token = "r3qyspYw8igvsY8CgxEceaGu2UXEUuyi" # กรอก token
secret = "JBSacAZeh7NCoQrvYD1cMkPuncJ9Qijq" # กรอก secret
topic = "@msg/operator"
last_msg = ""
netpie = MQTTClient(client, broker, user=token, password=secret, port=1883)
# -------------------------
# callback for MSG
# -------------------------
def on_message(topic, msg):
global last_msg
global mode
last_msg = msg.decode().upper()
print("MSG Received :", last_msg)
#check messahges
#change mode
if last_msg == "MANUAL":
print("manual")
mode = "manual"
elif last_msg == "AUTOMATIC":
print("automatic")
mode = "automatic"
# for toggle
if mode == "manual":
if last_msg == "TOGGLE_LED":
if led.value() == 1:
print("off led")
elif led.value() == 0:
print("on led")
new_value = not led.value()
led.value(new_value)
time.sleep(1)
# เปิดระบบรับข้อความ
netpie.set_callback(on_message)
netpie.connect()
netpie.subscribe(topic)
print("Connect to Netpie & Subscribed")
# main loop
while True:
netpie.check_msg()
light_value = (1-(ldr.read()/4095))*100
if mode == "automatic":
if light_value > 50.0: # light outside
led.value(0)
elif light_value <= 50.0: # dark outside
led.value(1)
payload = {
"data":{
"lux":light_value,
"led":led.value(),
"mode":mode
}
}
netpie.publish("@shadow/data/update", ujson.dumps(payload))
print(payload)
time.sleep(0.5)