check.lua 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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, file, json, net, node, table, tmr, wifi =
  11. crypto, file, sjson, net, node, table, tmr, wifi
  12. local error, pcall = error, pcall
  13. local loadfile, gc = loadfile, collectgarbage
  14. local concat, unpack = table.concat, unpack or table.unpack
  15. local self = {post = node.task.post, prefix = "luaOTA/", conf = {}}
  16. self.log = (DEBUG == true) and print or function() end
  17. self.modname = ...
  18. --------------------------------------------------------------------------------------
  19. -- Utility Functions
  20. setmetatable( self, {__index=function(self, func) --upval: loadfile
  21. -- The only __index calls in in LuaOTA are dynamically loaded functions.
  22. -- The convention is that functions starting with "_" are treated as
  23. -- call-once / ephemeral; the rest are registered in self
  24. func = self.prefix .. func
  25. local f,msg = loadfile( func..".lc")
  26. if msg then f, msg = loadfile(func..".lua") end
  27. if msg then error (msg,2) end
  28. if func:sub(8,8) ~= "_" then self[func] = f end
  29. return f
  30. end} )
  31. function self.sign(arg) --upval: crypto, json, self
  32. arg = json.encode(arg)
  33. return arg .. crypto.toHex(crypto.hmac("MD5", arg, self.secret):sub(-3)) .. '\n'
  34. end
  35. function self.startApp(arg) --upval: gc, self, tmr, wifi
  36. gc();gc()
  37. tmr.unregister(0)
  38. self.socket = nil
  39. if not self.config.leave then wifi.setmode(wifi.NULLMODE,false) end
  40. local appMod = self.config.app or "luaOTA.default"
  41. local appMethod = self.config.entry or "entry"
  42. if not arg then arg = "General timeout on provisioning" end
  43. self.post(function() --upval: appMod, appMethod, arg
  44. require(appMod)[appMethod](arg)
  45. end)
  46. end
  47. function self.socket_send(socket, rec, opt_buffer)
  48. return socket:send(self.sign(rec) .. (opt_buffer or ''))
  49. end
  50. self.post(function() -- upval: self
  51. -- This config check is to prevent a double execution if the
  52. -- user invokes with "require 'luaOTA/check':_init( etc>)" form
  53. if not rawget(self, "config") then self:_init() end
  54. end)
  55. return self