Post your best Lua script examples here

User avatar
By helix
#8369 Hello all,

Is there a good way to subscribe to multiple topics?

If I parse multiple subscribe commands I either get a sending in process panic :

Code: Select allm:connect("192.168.11.10", 1883, 0, function(conn)
     print("connected")
     m:subscribe("test",0, function(conn) print("subscribe test")
     end)
     m:subscribe("test2",0, function(conn) print("subscribe test2")
     end)
end)


response :
> dofile('mqtt_test.lua')
> connected
PANIC: unprotected error in call to Lua API (mqtt_test.lua:21: sending in process)

of if I nest the subscriptions, they are repeated :
Code: Select allm:connect("192.168.11.10", 1883, 0, function(conn)
     print("connected")
     m:subscribe("test",0, function(conn) print("subscribe test")
          m:subscribe("test2",0, function(conn) print("subscribe test2")
          end)
     end)
end)


Response :
> dofile('mqtt_test.lua')
> connected
subscribe test
subscribe test2
subscribe test2

Helix
User avatar
By helix
#8482 No, I am still testing. I am looking at using timers but I have no results to share yet...

For now I have the moudule subscribe to the base topic e.g test/# but this means every module recieves every message and must process it. It is not very effcient.

When I have done some more testing I will report back, unless someone can propose a better solution....
User avatar
By helix
#8493 ok, so the below code works for me :
Code: Select alltopics = {"test1","test2","test3","test4","test5","test6"} --array of topics
current_topic = 1 -- variable for one currently being subscribed to
alarm_delay = 50 -- microseconds between subscription attempts, worked for me (local network) down to 5...YMMV

--connect to the broker
m:connect("192.168.11.10", 1883, 0, function(conn)
     print("connected")
     mqtt_sub() --run the subscription function
end)

function mqtt_sub()

     -- if we have subscribed to all topics in the array, run the main prog
     if table.getn(topics) < current_topic then
     
          run_main_prog()
         
     else
          --subscribe to the topic
          m:subscribe(topics[current_topic],0, function(conn)
               print("subscribe")
          end)
          -- increment the variable of the current topic for next loop     
          current_topic = current_topic + 1
          --set the timer to rerun the loop
          tmr.alarm(0, alarm_delay, 0, function()
               mqtt_sub()
          end)
     end
end

--main program to run after the subscriptions are done
function run_main_prog()
     print("Hello World")
end


It does seem a bit hackish though... as mentioned in a previous comment, some form of queue would be ideal....