check.lua 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. --SAFETRIM
  2. --------------------------------------------------------------------------------
  3. -- LuaOTA provisioning system for ESPs using NodeMCU Lua
  4. -- LICENCE: http://opensource.org/licenses/MIT
  5. -- TerryE 15 Jul 2017
  6. --
  7. -- See luaOTA.md for description and implementation notes
  8. --------------------------------------------------------------------------------
  9. -- upvals
  10. local crypto, json, node, wifi =
  11. crypto, sjson, node, wifi
  12. local error = error
  13. local loadfile, gc = loadfile, collectgarbage
  14. local self = {post = node.task.post, prefix = "luaOTA/", conf = {}}
  15. -- luacheck: globals DEBUG
  16. self.log = (DEBUG == true) and print or function() end
  17. self.modname = ...
  18. self.timer = tmr.create()
  19. _G["stopOTA"] = function()
  20. self.timer:stop()
  21. end
  22. --------------------------------------------------------------------------------------
  23. -- Utility Functions
  24. setmetatable( self, {__index=function(obj, func) --upval: loadfile
  25. -- The only __index calls in in LuaOTA are dynamically loaded functions.
  26. -- The convention is that functions starting with "_" are treated as
  27. -- call-once / ephemeral; the rest are registered in self
  28. func = obj.prefix .. func
  29. local f,msg = loadfile( func..".lc")
  30. if msg then f, msg = loadfile(func..".lua") end
  31. if msg then error (msg,2) end
  32. if func:sub(8,8) ~= "_" then obj[func] = f end
  33. return f
  34. end} )
  35. function self.sign(arg) --upval: crypto, json, self
  36. arg = json.encode(arg)
  37. return arg .. crypto.toHex(crypto.hmac("MD5", arg, self.secret):sub(-3)) .. '\n'
  38. end
  39. function self.startApp(arg) --upval: gc, self, wifi
  40. gc();gc()
  41. self.timer.unregister()
  42. self.socket = nil
  43. if not self.config.leave then wifi.setmode(wifi.NULLMODE,false) end
  44. local appMod = self.config.app or "luaOTA.default"
  45. local appMethod = self.config.entry or "entry"
  46. if not arg then arg = "General timeout on provisioning" end
  47. self.post(function() --upval: appMod, appMethod, arg
  48. require(appMod)[appMethod](arg)
  49. end)
  50. end
  51. function self.socket_send(socket, rec, opt_buffer)
  52. return socket:send(self.sign(rec) .. (opt_buffer or ''))
  53. end
  54. self.post(function() -- upval: self
  55. -- This config check is to prevent a double execution if the
  56. -- user invokes with "require 'luaOTA/check':_init( etc>)" form
  57. if not rawget(self, "config") then self:_init() end
  58. end)
  59. return self