mqtt_file.lua 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. -- test transfer files over mqtt.
  2. m_dis={}
  3. 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. 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. 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. m_dis["/topic1"]=topic1func
  32. -- Lua: mqtt.Client(clientid, keepalive, user, pass)
  33. m=mqtt.Client()
  34. m:on("connect",function(m)
  35. print("connection "..node.heap())
  36. m:subscribe("/topic1",0,function(m) print("sub done") end)
  37. end )
  38. m:on("offline", function(conn)
  39. print("disconnect to broker...")
  40. print(node.heap())
  41. end)
  42. m:on("message",dispatch )
  43. -- Lua: mqtt:connect( host, port, secure, auto_reconnect, function(client) )
  44. m:connect(192.168.18.88,1883,0,1)
  45. -- usage:
  46. -- another client(pc) subscribe to /topic2, will receive the test.lua content.
  47. -- and publish below message to /topic1
  48. -- {"cmd":"open","content":"test.lua"}
  49. -- {"cmd":"write","content":"print([[hello world]])\n"}
  50. -- {"cmd":"write","content":"print(\"hello2 world2\")\n"}
  51. -- {"cmd":"write","content":"test.lua"}
  52. -- {"cmd":"run","content":"test.lua"}
  53. -- {"cmd":"read","content":"test.lua"}