mqtt_file.lua 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. -- test transfer files over mqtt.
  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 pubfile(m,filename)
  9. file.close()
  10. file.open(filename)
  11. repeat
  12. local pl = file.read(1024)
  13. if pl then m:publish("/topic2", pl, 0, 0) end
  14. until not pl
  15. file.close()
  16. end
  17. -- payload(json): {"cmd":xxx,"content":xxx}
  18. local function topic1func(m,pl)
  19. print("get1: "..pl)
  20. local pack = sjson.decode(pl)
  21. if pack.content then
  22. if pack.cmd == "open" then file.open(pack.content,"w+")
  23. elseif pack.cmd == "write" then file.write(pack.content)
  24. elseif pack.cmd == "close" then file.close()
  25. elseif pack.cmd == "remove" then file.remove(pack.content)
  26. elseif pack.cmd == "run" then dofile(pack.content)
  27. elseif pack.cmd == "read" then pubfile(m, pack.content)
  28. end
  29. end
  30. end
  31. do
  32. m_dis["/topic1"]=topic1func
  33. -- Lua: mqtt.Client(clientid, keepalive, user, pass)
  34. local m = mqtt.Client()
  35. m:on("connect",function(client)
  36. print("connection "..node.heap())
  37. client:subscribe("/topic1", 0, function() print("sub done") end)
  38. end)
  39. m:on("offline", function()
  40. print("disconnect to broker...")
  41. print(node.heap())
  42. end)
  43. m:on("message",dispatch )
  44. -- Lua: mqtt:connect( host, port, secure, function(client) )
  45. m:connect("192.168.18.88",1883,0)
  46. end
  47. -- usage:
  48. -- another client(pc) subscribe to /topic2, will receive the test.lua content.
  49. -- and publish below message to /topic1
  50. -- {"cmd":"open","content":"test.lua"}
  51. -- {"cmd":"write","content":"print([[hello world]])\n"}
  52. -- {"cmd":"write","content":"print(\"hello2 world2\")\n"}
  53. -- {"cmd":"write","content":"test.lua"}
  54. -- {"cmd":"run","content":"test.lua"}
  55. -- {"cmd":"read","content":"test.lua"}