nodeMCU Lua ESP8266第四课 MQTT的使用

本文是关于使用nodeMCU和ESP8266进行MQTT通信的教程,通过实例介绍了如何配置MQTT客户端,连接免费broker,并使用mqtt-spy进行测试。教程详细解释了工作流程,包括创建客户端、连接broker、监听事件、发布和接收消息,以及关闭连接的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第四课 MQTT的使用

   写在前面的话:个人学习笔记,抛砖引玉,希望有兴趣的人加入QQ群415469069一起讨论,欢迎有共同爱好的人。 

本教程以ESP-12N,CP2102开发板为例进行讲解。

分为两个文件:mqtt_test.lua和close_mqtt.lua。群文件可以下载。

--mqtt_test.lua

myClient = mqtt.Client("test_mqqt_20180123_mcu",120)

myClient:connect("iot.eclipse.org",

    function(client)

        print("connected")

    end)

myClient:lwt("mcu_to_pc_topic20180123","mcu is closed")

myClient:on("connect",

    function(clinet)

        if(myClient:publish("mcu_to_pc_topic20180123","online",0,0))then

            print("pc connected mcu")

        end

        if(myClient:subscribe("pc_to_mcu_topic20180123",0))then

            print("subscribe is success.")

        end

    end)

myClient:on("offline",

    function(client)

        myClient:publish("mcu_to_pc_topic20180123","offline",0,0)

    end)

myClient:on("message",

function(client , topic , message)

    print(“get a message.\n”)

        print(topic..":"..message)

    end)        

--mqtt_close.lua

if(myClient:close()) then

    print("mqtt is closed.")

else

    print("closed is failed.")

end


  • 工作流程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值