import machine
import time
pin2 = machine.Pin(2, machine.Pin.OUT)
while True:
pin2.value(1)
time.sleep(1)
pin2.value(0)
time.sleep(1)
import network#导入网络模块
from umqtt.simple import MQTTClient
import machine
client_id = "slim_id"
mserver = 'broker.emqx.io'
port=8083
topic_ctl = b'topic/led'#设备订阅的主题,客户端推送消息的主题
topic_sta = b'led_sta'#客户端订阅的主题,设备推送消息的主题
client = None
wlan = None
import json,time
led1=machine.Pin(2, machine.Pin.OUT, value=1)
led2=machine.Pin(5, machine.Pin.OUT, value=1)
from machine import Timer #系统定时器
def sub_callback(topic, msg):
"""
收到订阅消息回调
"""
global client
print((topic_ctl, msg))
if topic_ctl==b'topic/led':
msg = json.loads(msg)
print(msg['msg'])
if msg['msg']=='on':
led1.value(1)
else:
led1.value(0)
#client.publish(topic_sta, pub_msg, retain=True)
def connect_wifi():#连接程序
#并将网络凭据(ssid和密码)存储在两个变量上。
ssid = "zzz"
password = "qazwsx12"
try:
#获取站点WiFi接口的实例并将其存储在变量上
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('Connecting to network...')
wlan.connect(ssid, password)
while not wlan.isconnected():
time.sleep(1)
print('Network connected:', wlan.ifconfig())
except:
print('--')
pass
connect_wifi()
while True:
try:
client = MQTTClient(client_id, mserver, 0)
client.set_callback(sub_callback)
client.connect()
client.subscribe(topic_ctl)
#client.publish(topic_sta, 'ESP32 Device online', retain=True)
print("Connected to %s, subscribed to %s topic" % (mserver, topic_ctl))
while True:
client.wait_msg()
except:
print('mqtt error')
time.sleep(2)
connect_wifi()
pass