您的位置:首页 >教育 > 活动 > 正文

BPI-Pico-RP2040 开发板 mqtt连接服务器

来源:华仔的编程随笔 时间:2023-05-25 09:43:50


(资料图片仅供参考)

​1、安装umqtt,点击菜单工具->管理包

2、搜索umqtt

3、在查找结果里面点击按装:

4、然后在已安装的包里就看到umqtt了。

5、书如程序代码如下:

from umqtt.simple import MQTTClientfrom machine import Pinimport networkimport timessid="ssid"passwd="wifipwd"client_id = "po20t"mserver = "ip"port=1883mqttuser = "user"mqttpwd = "pwd"topic_ctl = b"led_ctl"#设备订阅的主题,客户端推送消息的主题topic_sta = b"led_sta"#客户端订阅的主题,设备推送消息的主题client = Nonewlan = Noneled1=Pin(2, Pin.OUT, value=1)led2=Pin(5, Pin.OUT, value=1)    def sub_callback(topic, msg):    """    收到订阅消息回调    """    global client    print((topic_ctl, msg))    if msg == b"led1 ON" or msg == b"led1 on":        pub_msg = "LED1: ON-state"        led1.value(0)    elif msg == b"led1 OFF" or msg == b"led1 off":        pub_msg = "LED1: OFF-state"        led1.value(1)    elif msg == b"led2 ON" or msg == b"led2 on":        pub_msg = "LED2: ON-state"        led2.value(0)    elif msg == b"led2 OFF" or msg == b"led2 off":        pub_msg = "LED2: OFF-state"        led2.value(1)    else:        pub_msg = "other msg"    client.publish(topic_sta, pub_msg, retain=True)def connectWiFi():    """    连接到WiFi网络"""    global wlan    wlan = network.WLAN(network.STA_IF)    wlan.active(True)    wlan.disconnect()    wlan.connect("HUAWEI-H10R9U", "18977381885@")    while(wlan.ifconfig()[0]=="0.0.0.0"):        time.sleep(1)    print(wlan.ifconfig())try:    connectWiFi()    client = MQTTClient(client_id, mserver, port=1883,user=mqttuser,password=mqttpwd)    client.set_callback(sub_callback)    client.connect()    client.subscribe(topic_ctl)    client.publish(topic_sta, "ESP32Device online", retain=True)    print("Connected to %s, subscribed to %s topic" % (mserver, topic_ctl))    while True:        client.wait_msg()finally:    if client is not None:        print("off line")        client.disconnect()    wlan.disconnect()    wlan.active(False)

5、保存到开发板,然后执行:

6、打开mqttx发送消息:这样连接到远程的Mqtt就愉快的完成了,后面可以完成一些数据交换与控制了。

审核编辑:汤梓红

标签:

相关阅读