#!/usr/bin/lua local socket = require "socket" local lfs = require "lfs" local uci = require "uci" local posix = require "posix" function startswith(String,Start) if String then return string.sub(String,1,string.len(Start))==Start else return False end end function trim(s) return (s:gsub("^%s*(.-)%s*$", "%1")) end function url_decode(str) if not str then return nil end str = string.gsub (str, "+", " ") str = string.gsub (str, "%%(%x%x)", function(h) return string.char(tonumber(h,16)) end) str = string.gsub (str, "\r\n", "\n") return str end function url_encode(str) if (str) then str = string.gsub (str, "\n", "\r\n") str = string.gsub (str, "([^%w %-%_%.%~])", function (c) return string.format ("%%%02X", string.byte(c)) end) str = string.gsub (str, " ", "+") end return str end function capture(cmd, raw) local f = assert(io.popen(cmd, 'r')) local s = assert(f:read('*a')) f:close() if raw then return s end s = string.gsub(s, '^%s+', '') s = string.gsub(s, '%s+$', '') s = string.gsub(s, '[\n\r]+', ' ') return s end function mqtt_encode(str) if (str) then str = string.gsub (str, "\n", "") str = string.gsub (str, "/", "-") end return str end function touch(name) local file = io.open(name, 'a') file:close() end function write_file(name,data) pcall(function () local f = io.open(name,"w") io.output(f) io.write(data) io.close(f) end) end function file_exists(name) local f=io.open(name,"r") if f~=nil then io.close(f) return true else return false end end function get_file_content(name) local f = io.open(name,"r") if f ~= nil then local content = trim(f:read("*all")) io.close(f) return content else return false end end function sleep(sec) socket.sleep(sec) end function split(s, delimiter) local result = {}; for match in (s..delimiter):gmatch("(.-)"..delimiter) do result[#result+1] = match end return result; end function list_dir(name) local result = {} for name in lfs.dir(name) do if not startswith(name,".") then result[#result+1] = name end end return result end function get_devid(config) local web_devid = uci.get(config,"web","devid") if web_devid then return web_devid end web_iface = uci.get(config,"web","iface") if not web_iface then web_iface = list_dir('/sys/class/net/')[1] end io.input("/sys/class/net/"..web_iface.."/address") local web_devid = io.read("*line") return web_devid:gsub(":",""):upper() end function get_children() local pid = posix.getpid() local pidlist = list_dir('/proc') local pids = {} for k,v in pairs(pidlist) do pcall( function () local stats = get_file_content('/proc/'..v..'/stat') local ppid = tonumber(split(stats,' ')[4]) if pid == ppid then pids[#pids+1] = tonumber(v) end end) end return pids end