import time
import network
from umqtt.simple import MQTTClient
import ujson
from machine import Pin
LEDPIN = 15
led = Pin(LEDPIN, Pin.OUT)
LEDBUILTIN = 2
ledbuiltin = Pin(LEDBUILTIN, Pin.OUT)
lightStatus = False
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
time.sleep(0.5)
print(".", end="")
pass
print("WiFi connected")
client = MQTTClient(
client_id="client123133412232145",
keepalive=9,
server="broker.emqx.io",
ssl=False)
client.connect()
print('Mqtt server connected.')
def get_msg(topic, msg):
print("Incoming message:", msg)
print("Incoming topic:", topic)
responseTopic = topic
responseTopic = responseTopic.replace(b"request",b"response")
try:
msg = ujson.loads(msg)
print(msg)
if(msg['method']=='command' and msg['params']):
led.on()
client.publish(responseTopic,'''{"light": "on"}''')
else:
led.off()
client.publish(responseTopic,'''{"light": "off"}''')
except Exception as e:
print("Error:", e)
client.set_callback(get_msg)
client.subscribe(b'v1/devices/cxy/rpc/request')
counter = 0
# while True:
# client.check_msg()
# print(counter)
# counter = counter + 1
# if(counter%5==0): client.ping()
# time.sleep(1)
while True:
lightStatus = not lightStatus
if lightStatus:
ledbuiltin.on()
else:
ledbuiltin.off()
print('wifi status', sta_if.status())
if(not sta_if.isconnected()):
print("wifi reconnectting...")
while not sta_if.isconnected(): pass
print("WiFi connected")
print("MQTT reconnecting...")
client.connect(False) # 重新連線時也採用 False 不清除會談資料
print("MQTT reconected.")
client.set_callback(get_msg)
client.subscribe(b'v1/devices/cxy/rpc/request')
try:
client.check_msg()
print(counter)
counter = counter + 1
if(counter%10==0):
client.ping()
message = ujson.dumps({
"counter": counter
})
client.publish(b'v1/devices/cxy/telemetry', message)
print('publish message:', message)
time.sleep(1)
except OSError as e:
print("MQTT disconnectted, now reconnecting...")
client.connect(False) # 重新連線時也採用 False 不清除會談資料
print("MQTT reconected.")
client.set_callback(get_msg)
client.subscribe(b'v1/devices/cxy/rpc/request')