程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

Onenet物联网Mqtt初探(micropython_mqtt登陆与数据收发)

hfteth 2025-05-25 12:46:44 技术文章 2 ℃

请先去去看Onenet 物联网Mqtt初探(MQTT.fx模拟登陆与数据收发)和Onenet物联网Mqtt初探(python_mqtt登陆与数据收发)的文章,否则可能不明被我输入的是什么消息。这里直接做micropython代码的mqtt连接:

1、上电烧录好micropython的ESP32

2、在控制台下输入arp -a查一下ESP32的IP地址,因为之前已经记录ESP32的MAC地址,所以看到有这个地址就对应上IP了:

3、,打开webrepl.html页面,输入IP连接,输入密码回车,连接成功了:

4、先看看有哪些支持的模块,输入:help('modules')

晕~~~我的esp32-cam自定义camera的固件没有mqtt的模块,

没有的话就用upip在ESP32上安装MQTT库

>>> import upip

>>> upip.install('micropython-umqtt.simple')

安装完成,再次输入:help('modules')

没变化,是什么鬼。

找了一网上解决办法都不没有答案,就要放弃了,再尝试输入一下:

from umqtt.simple import MQTTClient

居然能调用了….我~~~~~擦~,难道是upip安装后没给help('modules')这东西标记,导致没显示?还是本来就有的?一脸懵逼。

直接上代码,功能:发送6秒发一次温湿度数据,永远等待开关led消息,控制led灯亮灭。

import time
import dht11
from umqtt.simple import MQTTClient
from machine import Pin

led = Pin(4,Pin.OUT)#led引脚输出模式
client_id='pc_esp32' #设备的ID
server = 'mqtts.heclouds.com' #onenet地址
port = 1883 #连接的端口
user = '449990' #产品的数字ID
password = 'version=2018-10-31&res=products%2F449990%2Fdevices%2Fpc_esp32&et=1735660800&method=md5&sign=i1CJFxX6Od4vtdtXCgjp9w%3D%3D'
# Publish test messages e.g. with:
# mosquitto_pub -t foo_topic -m hello

# Received messages from subscriptions will be delivered to this callback
c = MQTTClient(client_id, server,port,user,password,60) #(self, client_id, server, port=0, user=None, password=None, keepalive=0,ssl=False, ssl_params={}):
def sub_cb(topic, msg):
    print((topic, msg))
    msg_str = msg.decode()#消息转换为二进制转换字符串
    if(msg_str == "TurnOn"):
        led.value(1)
        topic_str = topic.decode() #二进制转换字符串,转换"request","response"变成消息
        #b'$sys/449990/pc_esp32/cmd/request/90651f67-14fc-431c-97b7-6321911728ed'
        #b'$sys/449990/pc_esp32/cmd/response/90651f67-14fc-431c-97b7-6321911728ed'
        topic = topic_str.replace("request","response").encode()
        if(led.value()):c.publish(topic,b"light is turn on")
    if(msg_str == "TurnOff"):
        led.value(0)
        topic_str = topic.decode() #二进制转换字符串,转换"request","response"变成消息
        topic = topic_str.replace("request","response").encode()
        if(led.value() == 0):c.publish(topic,b"light is turn off")



def main():   # test server : iot.eclipse.org
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(b"$sys/449990/pc_esp32/cmd/#")# subscribe foo_topic tipic
    while True:
        try:#防止dht11读取错误异常退出(leb灯打开后会有超时情况:File "dht.py", line 17, in measure   -->>   OSError: [Errno 116] ETIMEDOUT)
            _,temperature,Humidity = dht11.dht11(15)#传入引脚号
            #print(temperature,Humidity)
            c.publish(b"$sys/449990/pc_esp32/dp/post/json", "{ 'id': 123,  'dp': { 'temperatrue': [{ 'v':" + str(temperature)+ "}],'humidity': [{ 'v':" + str(Humidity) +", }]}}")#发送数据
        except OSError:
            print(OSError)
        # Non-blocking wait for message
        c.check_msg()
        # Then need to sleep to avoid 100% CPU usage (in a real
        # app other useful actions would be performed instead)
        time.sleep(6)

    c.disconnect()

if __name__ == "__main__":
    main() 

运行后,看onenet控制台/设备/数据流,可以看到消息已经发送到了

下发开灯命令测试:

Esp32收到消息:

发送关灯命令:

Ok,本次测试完成。

补充:

Import dht11 是带入这个文件dht11.py,里面的内容是:

from machine import Pin
import dht

def dht11(pin):
    d = dht.DHT11(Pin(pin,Pin.IN))
    d.measure()
    #print(d.temperature(),d.humidity())
    return d,d.temperature(),d.humidity()

Tags:

最近发表
标签列表