mqtt2cloud.lua 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. -- test with cloudmqtt.com
  2. local m_dis = {}
  3. local function dispatch(m,t,pl)
  4. if pl~=nil and m_dis[t] then
  5. m_dis[t](m,pl)
  6. end
  7. end
  8. local function topic1func(_,pl)
  9. print("get1: "..pl)
  10. end
  11. local function topic2func(_,pl)
  12. print("get2: "..pl)
  13. end
  14. do
  15. m_dis["/topic1"] = topic1func
  16. m_dis["/topic2"] = topic2func
  17. -- Lua: mqtt.Client(clientid, keepalive, user, pass)
  18. local m = mqtt.Client("nodemcu1", 60, "test", "test123")
  19. m:on("connect",function(client)
  20. print("connection "..node.heap())
  21. client:subscribe("/topic1",0,function() print("sub done") end)
  22. client:subscribe("/topic2",0,function() print("sub done") end)
  23. client:publish("/topic1","hello",0,0)
  24. client:publish("/topic2","world",0,0)
  25. end)
  26. m:on("offline", function()
  27. print("disconnect to broker...")
  28. print(node.heap())
  29. end)
  30. m:on("message",dispatch )
  31. -- Lua: mqtt:connect( host, port, secure, function(client) )
  32. m:connect("m11.cloudmqtt.com",11214,0)
  33. tmr.create():alarm(10000, tmr.ALARM_AUTO, function()
  34. local pl = "time: "..tmr.time()
  35. m:publish("/topic1",pl,0,0)
  36. end)
  37. end