gossip_example.lua 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. -- need a wifi connection
  2. -- enter your wifi credentials
  3. local credentials = {SSID = "SSID", PASS = "PASS"};
  4. -- push a message onto the network
  5. -- this can also be done by changing gossip.networkState[gossip.ip].data = {temperature = 78};
  6. local function sendAlarmingData()
  7. Gossip.pushGossip({temperature = 78});
  8. print('Pushed alarming data');
  9. end
  10. local function removeAlarmingData()
  11. Gossip.pushGossip(nil);
  12. print('Removed alarming data from the network.');
  13. end
  14. -- callback function for when gossip receives an update
  15. local function treatAlarmingData(updateData)
  16. for k in pairs(updateData) do
  17. if updateData[k].data then
  18. if updateData[k].data.temperature and updateData[k].data.temperature > 30 then
  19. print('Warning, the temp is above 30 degrees at ' .. k);
  20. end
  21. end
  22. end
  23. end
  24. local function Startup()
  25. -- initialize all nodes with the seed except for the seed itself
  26. -- eventually they will all know about each other
  27. -- enter at least one ip that will be a start seed
  28. local startingSeed = '192.168.0.73';
  29. -- luacheck: push allow defined
  30. Gossip = require('gossip');
  31. -- luacheck: pop
  32. local config = {debug = true, seedList = {}};
  33. if wifi.sta.getip() ~= startingSeed then
  34. table.insert(config.seedList, startingSeed);
  35. end
  36. Gossip.setConfig(config);
  37. -- add the update callback
  38. Gossip.updateCallback = treatAlarmingData;
  39. -- start gossiping
  40. Gossip.start();
  41. -- send some alarming data timer
  42. if wifi.sta.getip() == startingSeed then
  43. tmr.create():alarm(50000, tmr.ALARM_SINGLE, sendAlarmingData);
  44. tmr.create():alarm(50000*3, tmr.ALARM_SINGLE, removeAlarmingData);
  45. end
  46. end
  47. local function startExample()
  48. wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED,
  49. function() print('Diconnected') end);
  50. print("Connecting to WiFi access point...");
  51. if wifi.sta.getip() == nil then
  52. wifi.setmode(wifi.STATION);
  53. wifi.sta.config({ssid = credentials.SSID, pwd = credentials.PASS});
  54. end
  55. print('Ip: ' .. wifi.sta.getip() .. '. Starting in 5s ..');
  56. tmr.create():alarm(5000, tmr.ALARM_SINGLE, Startup);
  57. end
  58. startExample();