【问题标题】:nodemcu lua dofile - how to invoke another lua file?nodemcu lua dofile - 如何调用另一个lua文件?
【发布时间】:2017-07-16 22:55:00
【问题描述】:

我的 nodemcu esp8266 上有一个可用的 init.lua:

-- load credentials, 'SSID' and 'PASSWORD' declared and initialize in there
dofile("credentials.lua")

function startup()
    if file.open("init.lua") == nil then
        print("init.lua deleted or renamed")
    else
        print("Running")
        file.close("init.lua")
        -- the actual application is stored in 'application.lua'
        -- dofile("application.lua")
    end
end

print("Connecting to WiFi access point...")
wifi.setmode(wifi.STATION)
wifi.sta.config(SSID, PASSWORD)
-- wifi.sta.connect() not necessary because config() uses auto-connect=true by default
tmr.create():alarm(1000, tmr.ALARM_AUTO, function(cb_timer)
    if wifi.sta.getip() == nil then
        print("Waiting for IP address...")
    else
        cb_timer:unregister()
        print("WiFi connection established, IP address: " .. wifi.sta.getip())
        print("You have 3 seconds to abort")
        print("Waiting...")
        tmr.create():alarm(3000, tmr.ALARM_SINGLE, startup)
    end
end)

它运行没有错误,无线连接已建立。

现在我已经编写了第二个我想自动运行的 bme280_mqtt.lua:

alt=45 -- altitude of the measurement place

bme280.init(3, 4)

P, T = bme280.baro()
-- convert measure air pressure to sea level pressure
QNH = bme280.qfe2qnh(P, alt)
ldk=string.format("Ld=%d.%03d ", QNH/1000, QNH%1000)

H, T = bme280.humi()
if T<0 then    
  temp=string.format("T=-%d.%02d°C ", -T/100, -T%100)
else
  temp=string.format("T=%d.%02d°C ", T/100, T%100)
end
luftf=string.format("Lf=%d%% ", H/1000, H%1000)
D = bme280.dewpoint(H, T)
if D<0 then
  taupu=string.format("Tp=-%d.%02d°C ", -D/100, -D%100)
else
  taupu=string.format("Tp=%d.%02d°C ", D/100, D%100)
end
m = mqtt.Client("wetterstation", 120)
m:connect("192.168.1.116", 1883)
m:publish("wetterstation",temp .. taupu .. luftf .. ldk,0,0)
node.dsleep(10*1000000)

通过发送到 ESP 按钮在 ESPlorer 中手动调用一切正常。

但是有

dofile(bme280_mqtt.lua)

我明白了:

dofile('bme280_mqtt.lua')
bme280_mqtt.lua:25: not connected
stack traceback:
    [C]: in function 'publish'
    bme280_mqtt.lua:25: in main chunk
    [C]: in function 'dofile'
    stdin:1: in main chunk

这里有什么错误?以及如何正确调用 init.lua 中的 bme280_mqtt.lua?

亲切的问候

【问题讨论】:

  • 这个问题解决了吗,还是需要更多反馈?

标签: lua esp8266 nodemcu


【解决方案1】:

如何正确调用 init.lua 中的 bme280_mqtt.lua?

确实正确调用了它。

bme280_mqtt.lua:25: not connected

表示bme280_mqtt.lua 的第 25 行/从第 25 行出现错误。

我没有数线,但问题就在这里

m:connect("192.168.1.116", 1883)
m:publish("wetterstation",temp .. taupu .. luftf .. ldk,0,0)

您只能在与代理的连接建立后发布。查看http://nodemcu.readthedocs.io/en/latest/en/modules/mqtt/#example 的示例。您可以使用connect 函数中的回调函数来发布或注册连接事件处理程序您调用connect 之前,如下所示:

m:on("connect", function(client) 
  -- publish here
 end)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-19
    • 2015-02-09
    • 2019-05-21
    • 1970-01-01
    • 2015-07-14
    • 2012-07-14
    • 2021-09-20
    • 1970-01-01
    相关资源
    最近更新 更多