我无法在Lua上为ESP8266订阅MQTT代理

问题描述 投票:0回答:1

首先,我正在使用以下内容:

  • ESP8266(ESP12E)
  • Git的默认固件(根据nodemcu文档,它是使用所有相关配置由Linux内置的)
  • ESPlorer IDE

我的特定问题(我认为)是我无法将MQTT客户端连接到adafruit.io代理。我想我已经成功连接到WiFi(由两个单独的SSID确认)。创建MQTT客户端并将其连接到其代理时,问题就来了。

-- INITIAL DEFINES
-- defines
station_cfg={}
station_cfg.ssid        = "<my wifi>"    -- my personal ssid
station_cfg.pwd         = "<wifi pwd>"   -- my wifi pwd
--station_cfg.ssid        = "IoT"        -- campus' ssid
--station_cfg.pwd         = "<wifi pwd>" -- campus' wifi pwd, I tried this first, then my home's. It 
                                            worked as it should
station_cfg.auto        = false
station_cfg.save        = false

mqtt_client_cfg = {}
mqtt_client_cfg.clientid    = "alro"          -- any ID
mqtt_client_cfg.keepalive   = 120             -- went for the example's value
mqtt_client_cfg.username    = "AlvaRocha"     -- obviously a paranoic Ctrl+C/V from adafruit
mqtt_client_cfg.password    = "aio_KO<safety edit>sXwbgtWCboCal" -- obviously a paranoic Ctrl+C/V 
                                                                 -- from adafruit

wifi.setmode(wifi.STATION)
wifi.sta.config(station_cfg)
wifi.sta.connect(connect)         -- so far so good

iot_test = mqtt.Client(mqtt_client_cfg) -- open client, apparently OK
--iot_test:lwt("/lwt", "offline", 0, 0) -- this line is on examples, doesn't affect outputs

iot_test:on("connect", function(client) print("client connected") end)
iot_test:on("offline", function(client) print("client offline") end) -- this event is called
                                                                     -- always (line 27)

function connect(params)
    print('Connected to:', params.SSID) -- I understant from documentation that this is called IF 
                                        -- successfull wifi connection. Double checked with 
                                        -- campus' and home wifi
end

function disconnect(params)
    print('Disconnected from:', params.SSID) -- ignore this function
end

function get_broker(mqtt_client)
    mqtt_client:connect("io.adafruit.com", 1883, false, false, --Found this double 'false' on 
                                                   --https://www.electronicwings.com/nodemcu/nodemcu- 
                                                   --mqtt-client-with-esplorer-ide 
           function(client) -- CONNECTED CALLBACK
            print('connected to broker') 
            --break
            -- continue
            client:subscribe("/Test", 0, function(client) print("Succesfull sub.") end) -- (LINE 42)
            --break
      --- continue
      end,
      function(_reason) -- OFFLINE CALLBACK not called (called if I don't write the 'double false' 
                        -- from the example)
            print('connection failed', reason) 
      end)
 end

 get_broker(iot_test) -- connect to broker

问题:即使调用了第27行,也会调用CONNECTED CALLBACK。那里没有一致性。

问题:42行输出:PANIC:调用Lua API时出现未保护的错误(init.lua:42:未连接)

希望评论是有帮助的,我想指出明显的内容:

  • 这是我第一次使用ESP8266,LUA和MQTT
  • 我阅读了尽可能多的内容(您永远无法读够)
  • 我不喜欢Arduino IDE(但我会尝试的,因为这会得到答复)

我怀疑以下情况:

  • 我搞砸了固件配置。
  • WiFi并未真正连接。
  • 我缺少明显的东西。

最诚挚的问候,Alvaro R。

lua mqtt iot esp8266 broker
1个回答
0
投票
您的脚本有几处错误;一些基本的,特定的。

基本原理

NodeMCU是异步的

NodeMCU编程模型与Node.js相似,仅在a它是异步的并且是事件驱动的。因此,许多功能具有回调函数的参数。

-> https://nodemcu.readthedocs.io/en/latest/#programming-model

这意味着一旦执行继续到N + 1行,您就不能假定N行的语句已经完成。就是这种情况@darius在注释中提示的wifi.sta.connect()。您可以注册一个回调,一旦设备从DHCP获得IP,该回调便会触发。我们在文档中维护一个template for one possible way to handle this

仅信任官方文档

您显然是从互联网资源中获取了一些错误或过时的代码段。通常最好参考官方的API文档。我们努力使它有用并保持最新。

Specifics

MQTT客户端初始化

wifi.sta.config()相反,它期望单个Lua表参数mqtt.Client()需要单个参数。因此,mqtt.Client(mqtt_client_cfg)是错误的。

-> https://nodemcu.readthedocs.io/en/latest/modules/mqtt/#mqttclient

MQTT客户端连接

mqtt.client:connect()的签名错误。它是connect(host[, port[, secure]][, function(client),其中secure是一个布尔值,而不是您传递的两个布尔值。

-> https://nodemcu.readthedocs.io/en/latest/modules/mqtt/#mqttclientconnect

可能的解决方案>>

这里是修复脚本的一种方法:

station_cfg = {} station_cfg.ssid = "***" station_cfg.pwd = "***" station_cfg.auto = false station_cfg.save = false mqtt_cfg = {} mqtt_cfg.host = "io.adafruit.com" mqtt_cfg.port = 1883 mqtt_cfg.clientid = "alro" mqtt_cfg.keepalive = 120 mqtt_cfg.username = "AlvaRocha" mqtt_cfg.password = "aio_KO<safety edit>sXwbgtWCboCal" wifi.setmode(wifi.STATION) wifi.sta.config(station_cfg) iot_test = mqtt.Client(mqtt_cfg.clientid, mqtt_cfg.keepalive, mqtt_cfg.username, mqtt_cfg.password) iot_test:on("offline", function(client) print("client offline") end) iot_test:on("message", function(client, topic, data) print("MQTT msg received on '" .. topic .. "':") if data ~= nil then print("\t" .. data) end end) function get_broker(mqtt_client) mqtt_client:connect(mqtt_cfg.host, mqtt_cfg.port, false, function(client) client:subscribe("/topic", 0, function(client) print("subscribe success") end) client:publish("/topic", "hello", 0, 0, function(client) print("sent") end) end, function(client, reason) print('connection failed', reason) end) end function startup() if file.open("init.lua") == nil then print("init.lua deleted or renamed") else print("Running") file.close("init.lua") get_broker(iot_test) end end wifi_connect_event = function(T) print("Connection to AP(" .. T.SSID .. ") established!") print("Waiting for IP address...") if disconnect_ct ~= nil then disconnect_ct = nil end end wifi_got_ip_event = function(T) -- Note: Having an IP address does not mean there is internet access! -- Internet connectivity can be determined with net.dns.resolve(). print("Wifi connection is ready! IP address is: " .. T.IP) print("Startup will resume momentarily, you have 3 seconds to abort.") print("Waiting...") tmr.create():alarm(3000, tmr.ALARM_SINGLE, startup) end wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, wifi_connect_event) wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, wifi_got_ip_event) wifi.sta.connect()

© www.soinside.com 2019 - 2024. All rights reserved.