RE:Lua中的回调函数

时间:2017-08-02 05:26:34

标签: lua

我是LUA的初学者(2天大)。我有一个要实现的功能,其用户指南中的定义如下

mqtt_id = mqtt.create(config)

config: Lua table containing mqtt client connection parameters
“host” MQTT broker domain or IP address
“port” optional; MQTT broker connection port; default: 1883
“user” optional; user name
“onmessage” optional; Lua callback function to be executed on new message
                      function cb_func(len, topic, msg)

并且表中还有一些其他值,但是是可选的

我想创建一个回调函数,这就是我在mqtt.create()函数的声明中所做的

我在这里添加完整的代码

function sleep (a) 
    local sec = tonumber(os.clock() + a); 
    while (os.clock() < sec) do 
    end 
end

function cb_func(len, topic, msg)
    print('in on message')
    print(msg)
end

sleep(10000)

--configure GPRS APN 
sms_apn = net.setapn({apn = "airtelgprs.com"})
if sms_apn == 0 then
    print('gprs enabled')
else
    print('gprs not enabled')
    while true do
    end
end

--creating new mqtt client connections
mqtt_id = mqtt.create({host = "abc.xyz.com", port = 1883, qos = 2, onmessage = cb_func})
if mqtt_id ~= nil then
    print('configuring mqtt clint completed')
else
    print('configuring mqtt clint failed')
    while true do
    end
end

--connect to mqtt broker
status = mqtt.connect(mqtt_id,5,600)
if status == 0 then
    print('connected to mqtt broker')
else
    print('coonnection failed with mqtt broker')
    while true do
    end
end

--adding topic
mqtt.addtopic(mqtt_id, "Osm1", 2)
mqtt.addtopic(mqtt_id, "GW", 2)

--subscribing to the topics
mqtt.subscribe(mqtt_id)

mqtt.publish(mqtt_id, "GW", "ACTIVE")

while true do
    -- print('in infinite loop')

    --active
    --mqtt.publish(mqtt_id, "GW", "ACTIVE")
    --sleep(10000)

end

我做得对吗?请帮忙

打印消息永远不会发生在回调函数

0 个答案:

没有答案