import time
import network
from umqtt.simple import MQTTClient
import ujson
from machine import Pin
# uasyncio针对的是esp32,一般的micropython是asyncio
import uasyncio
LEDPIN2 = 4
led2 = Pin(LEDPIN2, Pin.OUT)
LEDPIN = 15
led = Pin(LEDPIN, Pin.OUT)
LEDBUILTIN = 2
ledbuiltin = Pin(LEDBUILTIN, Pin.OUT)
lightStatus = False
sta_if = network.WLAN(network.STA_IF)
counter = 0
client = MQTTClient(
client_id="client123133412232145",
keepalive=9,
server="broker.emqx.io",
ssl=False)
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)
async def lightloop():
light2status = False
while True:
light2status = not light2status
if light2status:
led2.on()
else:
led2.off()
await uasyncio.sleep(3)
async def mainloop():
global lightStatus
global counter
while True:
uasyncio.sleep(1)
try:
client.connect()
print('Mqtt server connected.')
client.set_callback(get_msg)
client.subscribe(b'v1/devices/cxy/rpc/request')
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():
await uasyncio.sleep(1)
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)
await uasyncio.sleep(1)
except OSError as e:
print("MQTT disconnectted, now reconnecting...")
break
# client.connect(False) # 重新連線時也採用 False 不清除會談資料
# print("MQTT reconected.")
# client.set_callback(get_msg)
# client.subscribe(b'v1/devices/cxy/rpc/request')
except Exception as e:
print(e)
print("retrying...")
continue
if __name__ == '__main__':
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
time.sleep(0.5)
print(".", end="")
pass
print("WiFi connected")
# 以上代码是同步代码,以下代码使用异步代码,ESP32使用的micropython要导入的不是asyncio,而是uasyncio
# 启动异步的2个协程任务:
# task1: mainloop()监测wifi和mqtt连接是否断开,断开则重连,用一个内置的led灯指示该循环,1秒钟循环一次
# task2: lightloop()每2秒切换天蓝色led灯状态
uasyncio.run(uasyncio.gather(mainloop(),lightloop()))