Post your best Lua script examples here

User avatar
By tuanpm
#7429 UPDATE: 2015-Jan-17: while waiting NodeMcu published, you can try to play with it here: https://github.com/tuanpmt/nodemcu-firmware
UPDATE: 2015-Jan-18: New source/api more reliable: https://github.com/nodemcu/nodemcu-firmware/tree/mqtt
UPDATE: 2015-Jan-17: Official support now on github repo, this topic closed

Hello,
Here are the results of my attempt to add mqtt stack to net module of nodemcu:
Port from Native MQTT client for ESP8266:
viewtopic.php?f=6&t=1031

Firmware:
(252.74 KiB) Downloaded 824 times


Code for test:

Code: Select all-- init mqtt client with keepalive timer 120sec
m = mqtt.Client("clientid", 120, "user", "password")

-- setup Last Will and Testament (optional)
-- Broker will publish a message with qos = 0, retain = 0, data = "offline"
-- to topic "/lwt" if client don't send keepalive packet
m:lwt("/lwt", "offline", 0, 0)

m:on("connect", function(con) print ("connected") end)
m:on("offline", function(con) print ("offline") end)

-- on publish message receive event
m:on("message", function(conn, topic, data)
  print(topic .. ":" )
  if data ~= nil then
    print(data)
  end
end)

-- for secure: m:connect("192.168.11.118", 1880, 1)
m:connect("192.168.11.118", 1880, 0, function(conn) print("connected") end)

-- subscribe topic with qos = 0
m:subscribe("/topic",0, function(conn) print("subscribe success") end)

-- publish a message with data = hello, QoS = 0, retain = 0
m:publish("/topic","hello",0,0, function(conn) print("sent") end)

m:close();
-- you can call m:connect again


Example application
Code: Select allm = mqtt.Client(wifi.sta.getmac(), 120, "user", "password")
m:lwt("/lwt", wifi.sta.getmac(), 0, 0)

m:on("offline", function(con)
     print ("reconnecting...")
     print(node.heap())
     tmr.alarm(1, 10000, 0, function()
          m:connect("192.168.11.102", 1880, 0)
     end)
end)

-- on publish message receive event
m:on("message", function(conn, topic, data)
  print(topic .. ":" )
  if data ~= nil then
    print(data)
  end
end)

tmr.alarm(0, 1000, 1, function()
 if wifi.sta.status() == 5 then
     tmr.stop(0)
     m:connect("192.168.11.102", 1880, 0, function(conn)
          print("connected")
          m:subscribe("/topic",0, function(conn)
               m:publish("/topic","hello",0,0, function(conn) print("sent") end)
          end)
     end)
 end
end)

Regards
Last edited by tuanpm on Fri Jun 05, 2015 1:47 am, edited 8 times in total.
User avatar
By scargill
#7435 Hi installed..

But could you please give that same example again - using an MQTT server NAME rather than an IP address - many of us will be using external servers or external test servers... can't QUITE get my head around how to fit the DNS lookup in there... I wish the Lua interpreter would handle this automatically...