首页 文章

nodemcu(esp8266)的mqtt上的Keepalive定时器没有响应

提问于
浏览
1

亲爱的,我正在尝试在nodemcu上的esp8266构建上使用mqtt . 我目前正在使用自定义构建(https://nodemcu-build.com/index.php

使用的模块:adc,enduser_setup,文件,gpio,http,mqtt,net,node,ow,pwm,tmr,uart,wifi

版本:由SDK 1.5.1上的Lua 5.1.4提供支持(e67da894)

function connect_to_mqtt_broker()


    print("Connecting to broker...")
    m:connect(BROKER, PORT, 0, 1, function(client) 
                                    print("connected") 
                                    print("["..tmr.time().."(s)] - Client connected to broker: "..BROKER)
                                    m:subscribe(SUB_TOPIC,0, function(conn) 
                                        print("Subscribed to "..SUB_TOPIC.." topic")
                                        led(0,204,0,150) 
                                    end)
                                    m:publish(PUB_TOPIC,"Hello from: "..node.chipid()..RESTART_REASON,0,0, function(conn) 
                                        print("sent")
                                    end)
                                  end, 
                                  function(client, reason) 
                                    print("failed reason: "..reason)
                                  end)

end

---MQTT client---
print("--------------> Create mqtt clinet")
--set up MQTT client
-- init mqtt client with keepalive timer 120sec
m = mqtt.Client("ESP"..node.chipid(), KEEP_ALIVE_TMR, USER, PASSWORD)
m:lwt(PUB_TOPIC, "offline", 0, 0)
m:on("offline", function(conn) 
        print("["..tmr.time().."(s)] - Mqtt client gone offline")

end)
m:on("message", function(conn, topic, data) 
        --receive_data(data, topic)
        print("Data received: "..data) 
        led(200,50,50,30)
        receive_data(data, topic)
        led(0,204,0,150)
end)

所以在程序的初始化时我调用的是 connect_to_mqtt_broker() ,它工作正常,我可以订阅并发布到主题 .

问题是keepalive计时器不正确 . 让我用一个例子解释一下 . 我设置了KEEP_ALIVE_TMR = 120s,并且在esp8266成功连接到mqtt代理后,我在路由器上禁用了wifi并开始计数秒 . 根据KEEP_ALIVE_TMR离线事件:

m:on("offline", function(conn) 
        print("["..tmr.time().."(s)] - Mqtt client gone offline")

end)

应该从我禁用WiFi的那一刻开始正好发射120秒,但由于某些未知原因,这种情况不会发生 . 通常事件会在10-15分钟后爆发 . 我正在努力理解这种延迟的原因并没有成功 . 你知道为什么会发生这种奇怪的事吗?

2 回答

  • 0

    设置 autoreconnect 标志时,我也遇到了同样的问题 . 此标志会中断代理之间连接的脱机事件的运行 .

    尝试不设置 autoreconnect ,其默认值为0:

    m:connect(BROKER, PORT, 0, function(client)
    
  • 0

    如果您通过打开/关闭mqtt代理来进行测试,那么它可以工作 . 但不是通过切换你的wifi连接,那么它是nodemcu的mqtt库问题 .

    我相信在断开连接时没有这样的mqtt离线/断开事件 . 这是添加连接的看门狗的解决方法 .

    tmr.alarm(1, 3000, 1, function()
      if wifi.sta.getip() == nil then
       --mark as mqtt restart needed
       restart = true
     else
       -- wifi reconnect detected then restart mqtt connections
       if restart == true then
         --reset flag, clean object, init for a new one
         restart = false
         m = nil
         mqtt_init()
         connect()
       end
     end
    end)
    

    Here it is the full code example

相关问题