0
0
mirror of https://github.com/Doodle3D/doodle3d-firmware.git synced 2024-12-22 11:03:48 +01:00

Add logging module/facility support.

Change log message format to match with that in print3d logger.
This commit is contained in:
Wouter R 2014-04-25 14:51:29 +02:00
parent 2459cda0ac
commit 5f59e5e2c9
17 changed files with 196 additions and 151 deletions

View File

@ -30,6 +30,7 @@ local updater = require('script.d3d-updater')
arg = argStash arg = argStash
local postData = nil local postData = nil
local MOD_ABBR = "ENTR"
--- Switches to wifi client mode or to access point mode based on availability of known wifi networks. --- Switches to wifi client mode or to access point mode based on availability of known wifi networks.
@ -48,11 +49,11 @@ local function setupAutoWifiMode()
local wifiState = wifi.getDeviceState() local wifiState = wifi.getDeviceState()
local netName, netMode = wifiState.ssid, wifiState.mode local netName, netMode = wifiState.ssid, wifiState.mode
log:info("current wifi name: " .. (netName or "<nil>") .. ", mode: " .. netMode) log:info(MOD_ABBR, "current wifi name: " .. (netName or "<nil>") .. ", mode: " .. netMode)
local apSsid = wifi.getSubstitutedSsid(settings.get('network.ap.ssid')) local apSsid = wifi.getSubstitutedSsid(settings.get('network.ap.ssid'))
local apMode = (apSsid == netName) and (netMode == 'ap') local apMode = (apSsid == netName) and (netMode == 'ap')
log:info("ssid of self: " .. apSsid) log:info(MOD_ABBR, "ssid of self: " .. apSsid)
local scanList,msg = wifi.getScanInfo() local scanList,msg = wifi.getScanInfo()
if not scanList then if not scanList then
@ -60,7 +61,7 @@ local function setupAutoWifiMode()
end end
local knownSsids = wifi.getConfigs() local knownSsids = wifi.getConfigs()
-- log:info("current wifi name: " .. (netName or "<nil>") .. ", mode: " .. netMode .. ", ssid of self: " .. apSsid) -- log:info(MOD_ABBR, "current wifi name: " .. (netName or "<nil>") .. ", mode: " .. netMode .. ", ssid of self: " .. apSsid)
local visNet, knownNet = {}, {} local visNet, knownNet = {}, {}
for _,sn in ipairs(scanList) do for _,sn in ipairs(scanList) do
table.insert(visNet, sn.ssid) table.insert(visNet, sn.ssid)
@ -68,8 +69,8 @@ local function setupAutoWifiMode()
for _,kn in ipairs(knownSsids) do for _,kn in ipairs(knownSsids) do
table.insert(knownNet, kn.ssid .. "/" .. kn.mode) table.insert(knownNet, kn.ssid .. "/" .. kn.mode)
end end
log:info("visible networks: " .. table.concat(visNet, ", ")) log:info(MOD_ABBR, "visible networks: " .. table.concat(visNet, ", "))
log:info("known networks: " .. table.concat(knownNet, ", ")) log:info(MOD_ABBR, "known networks: " .. table.concat(knownNet, ", "))
-- if the currently active network is client mode and is also visible, do nothing since it will connect automatically further along the boot process -- if the currently active network is client mode and is also visible, do nothing since it will connect automatically further along the boot process
if netMode == 'sta' and netName ~= nil and netName ~= "" and findSsidInList(scanList, netName) then if netMode == 'sta' and netName ~= nil and netName ~= "" and findSsidInList(scanList, netName) then
@ -173,12 +174,12 @@ local function setupLogger()
local rv = true local rv = true
if logTargetError then if logTargetError then
log:error("could not open logfile '" .. logTargetSetting .. "', using stderr as fallback (" .. logTargetError .. ")") log:error(MOD_ABBR, "could not open logfile '" .. logTargetSetting .. "', using stderr as fallback (" .. logTargetError .. ")")
rv = false rv = false
end end
if logLevelError then if logLevelError then
log:error("uci config specifies invalid log level '" .. logLevelSetting .. "', using verbose level as fallback") log:error(MOD_ABBR, "uci config specifies invalid log level '" .. logLevelSetting .. "', using verbose level as fallback")
rv = false rv = false
end end
@ -198,7 +199,7 @@ local function init(environment)
end end
if dbgText ~= "" then dbgText = " (" .. dbgText .. " debugging)" end if dbgText ~= "" then dbgText = " (" .. dbgText .. " debugging)" end
log:info("=======rest api" .. dbgText .. "=======") log:info(MOD_ABBR, "=======rest api" .. dbgText .. "=======")
if (environment['REQUEST_METHOD'] == 'POST') then if (environment['REQUEST_METHOD'] == 'POST') then
local n = tonumber(environment['CONTENT_LENGTH']) local n = tonumber(environment['CONTENT_LENGTH'])
@ -224,48 +225,48 @@ local function main(environment)
if rq:getRequestMethod() == 'CMDLINE' and rq:get('autowifi') ~= nil then if rq:getRequestMethod() == 'CMDLINE' and rq:get('autowifi') ~= nil then
local version = updater.formatVersion(updater.getCurrentVersion()); local version = updater.formatVersion(updater.getCurrentVersion());
log:info("Doodle3D version: "..util.dump(version)) log:info(MOD_ABBR, "Doodle3D version: "..util.dump(version))
log:info("running in autowifi mode") log:info(MOD_ABBR, "running in autowifi mode")
local rv,msg = setupAutoWifiMode() local rv,msg = setupAutoWifiMode()
if rv then if rv then
log:info("autowifi setup done (" .. msg .. ")") log:info(MOD_ABBR, "autowifi setup done (" .. msg .. ")")
else else
log:error("autowifi setup failed (" .. msg .. ")") log:error(MOD_ABBR, "autowifi setup failed (" .. msg .. ")")
end end
elseif rq:getRequestMethod() == 'CMDLINE' and rq:get('signin') ~= nil then elseif rq:getRequestMethod() == 'CMDLINE' and rq:get('signin') ~= nil then
log:info("running in signin mode") log:info(MOD_ABBR, "running in signin mode")
local ds = wifi.getDeviceState() local ds = wifi.getDeviceState()
log:info(" ds.mode: "..util.dump(ds.mode)) log:info(MOD_ABBR, " ds.mode: "..util.dump(ds.mode))
if ds.mode == "sta" then if ds.mode == "sta" then
log:info(" attempting signin") log:info(MOD_ABBR, " attempting signin")
local success,msg = Signin.signin() local success,msg = Signin.signin()
if success then if success then
log:info("Signin successful") log:info(MOD_ABBR, "Signin successful")
else else
log:info("Signin failed: "..util.dump(msg)) log:info(MOD_ABBR, "Signin failed: "..util.dump(msg))
end end
end end
elseif rq:getRequestMethod() ~= 'CMDLINE' or confDefaults.DEBUG_API then elseif rq:getRequestMethod() ~= 'CMDLINE' or confDefaults.DEBUG_API then
-- log:info("received request of type " .. rq:getRequestMethod() .. " for " .. (rq:getRequestedApiModule() or "<unknown>") -- log:info(MOD_ABBR, "received request of type " .. rq:getRequestMethod() .. " for " .. (rq:getRequestedApiModule() or "<unknown>")
-- .. "/" .. (rq:getRealApiFunctionName() or "<unknown>") .. " with arguments: " .. util.dump(rq:getAll())) -- .. "/" .. (rq:getRealApiFunctionName() or "<unknown>") .. " with arguments: " .. util.dump(rq:getAll()))
log:info("received request of type " .. rq:getRequestMethod() .. " for " .. (rq:getRequestedApiModule() or "<unknown>") log:info(MOD_ABBR, "received request of type " .. rq:getRequestMethod() .. " for " .. (rq:getRequestedApiModule() or "<unknown>")
.. "/" .. (rq:getRealApiFunctionName() or "<unknown>")) .. "/" .. (rq:getRealApiFunctionName() or "<unknown>"))
if rq:getRequestMethod() ~= 'CMDLINE' then if rq:getRequestMethod() ~= 'CMDLINE' then
log:info("remote IP/port: " .. rq:getRemoteHost() .. "/" .. rq:getRemotePort()) log:info(MOD_ABBR, "remote IP/port: " .. rq:getRemoteHost() .. "/" .. rq:getRemotePort())
--log:verbose("user agent: " .. rq:getUserAgent()) --log:verbose(MOD_ABBR, "user agent: " .. rq:getUserAgent())
end end
local response, err = rq:handle() local response, err = rq:handle()
if err ~= nil then log:error(err) end if err ~= nil then log:error(MOD_ABBR, err) end
response:send() response:send()
response:executePostResponseQueue() response:executePostResponseQueue()
else else
log:info("Nothing to do...bye.\n") log:info(MOD_ABBR, "Nothing to do...bye.\n")
end end
end end
@ -286,7 +287,7 @@ function handle_request(env)
resp:setError("initialization failed" .. errSuffix) resp:setError("initialization failed" .. errSuffix)
resp:send() resp:send()
log:error("initialization failed" .. errSuffix) --NOTE: this assumes the logger has been initialized properly, despite init() having failed log:error(MOD_ABBR, "initialization failed" .. errSuffix) --NOTE: this assumes the logger has been initialized properly, despite init() having failed
return 1 return 1
else else

View File

@ -18,6 +18,8 @@ local reconf = {}
local wifi local wifi
local reloadSilent local reloadSilent
local MOD_ABBR = "NTCF"
M.WWW_CAPTIVE_PATH = '/usr/share/lua/wifibox/www' M.WWW_CAPTIVE_PATH = '/usr/share/lua/wifibox/www'
M.WWW_CAPTIVE_INDICATOR = '/www/.wifibox-inplace' M.WWW_CAPTIVE_INDICATOR = '/www/.wifibox-inplace'
M.WWW_RENAME_NAME = '/www-regular' M.WWW_RENAME_NAME = '/www-regular'
@ -62,10 +64,10 @@ function M.switchConfiguration(components)
for k,v in pairs(components) do for k,v in pairs(components) do
local fname = k .. '_' .. v local fname = k .. '_' .. v
if type(reconf[fname]) == 'function' then if type(reconf[fname]) == 'function' then
log:verbose("reconfiguring component '" .. k .. "' (" .. v .. ")") log:verbose(MOD_ABBR, "reconfiguring component '" .. k .. "' (" .. v .. ")")
reconf[fname](dirtyList) reconf[fname](dirtyList)
else else
log:warning("unknown component or action '" .. fname .. "' skipped") log:warning(MOD_ABBR, "unknown component or action '" .. fname .. "' skipped")
end end
end end
@ -79,12 +81,12 @@ function M.switchConfiguration(components)
end end
function M.commitComponent(c) function M.commitComponent(c)
log:info("committing component '" .. c .. "'") log:info(MOD_ABBR, "committing component '" .. c .. "'")
uci:commit(c) uci:commit(c)
end end
function M.reloadComponent(c, silent) function M.reloadComponent(c, silent)
log:info("reloading component '" .. c .. "'") log:info(MOD_ABBR, "reloading component '" .. c .. "'")
local command = 'reload' local command = 'reload'
local cmd = '/etc/init.d/' .. c .. ' '..command local cmd = '/etc/init.d/' .. c .. ' '..command
if silent ~= nil and silent then if silent ~= nil and silent then
@ -92,7 +94,7 @@ function M.reloadComponent(c, silent)
os.execute(cmd) os.execute(cmd)
else else
rv = utils.captureCommandOutput(cmd) rv = utils.captureCommandOutput(cmd)
log:verbose(" result reloading component '" .. c .. "' (cmd: '"..cmd.."'): \n"..utils.dump(rv)) log:verbose(MOD_ABBR, " result reloading component '" .. c .. "' (cmd: '"..cmd.."'): \n"..utils.dump(rv))
end end
end end
@ -147,7 +149,7 @@ function reconf.apnet_rm(dirtyList)
uci:foreach('wireless', 'wifi-iface', function(s) uci:foreach('wireless', 'wifi-iface', function(s)
if s.ssid == wifi.getSubstitutedSsid(settings.get('network.ap.ssid')) then sname = s['.name']; return false end if s.ssid == wifi.getSubstitutedSsid(settings.get('network.ap.ssid')) then sname = s['.name']; return false end
end) end)
if sname == nil then return log:info("AP network configuration does not exist, nothing to remove") end if sname == nil then return log:info(MOD_ABBR, "AP network configuration does not exist, nothing to remove") end
uci:delete('wireless', sname) uci:delete('wireless', sname)
reloadBit(dirtyList, 'network'); commitBit(dirtyList, 'wireless') reloadBit(dirtyList, 'network'); commitBit(dirtyList, 'wireless')
end end
@ -212,15 +214,15 @@ end
function reconf.dnsredir_add(dirtyList) function reconf.dnsredir_add(dirtyList)
local redirText = '/#/' .. settings.get('network.ap.address') local redirText = '/#/' .. settings.get('network.ap.address')
local sname = utils.getUciSectionName('dhcp', 'dnsmasq') local sname = utils.getUciSectionName('dhcp', 'dnsmasq')
if sname == nil then return log:error("dhcp config does not contain a dnsmasq section") end if sname == nil then return log:error(MOD_ABBR, "dhcp config does not contain a dnsmasq section") end
if uci:get('dhcp', sname, 'address') ~= nil then return log:verbose("DNS address redirection already in place, not re-adding", false) end if uci:get('dhcp', sname, 'address') ~= nil then return log:verbose(MOD_ABBR, "DNS address redirection already in place, not re-adding", false) end
uci:set('dhcp', sname, 'address', {redirText}) uci:set('dhcp', sname, 'address', {redirText})
commitBit(dirtyList, 'dhcp'); reloadBit(dirtyList, 'dnsmasq') commitBit(dirtyList, 'dhcp'); reloadBit(dirtyList, 'dnsmasq')
end end
function reconf.dnsredir_rm(dirtyList) function reconf.dnsredir_rm(dirtyList)
local sname = utils.getUciSectionName('dhcp', 'dnsmasq') local sname = utils.getUciSectionName('dhcp', 'dnsmasq')
if sname == nil then return log:error("dhcp config does not contain a dnsmasq section") end if sname == nil then return log:error(MOD_ABBR, "dhcp config does not contain a dnsmasq section") end
uci:delete('dhcp', sname, 'address') uci:delete('dhcp', sname, 'address')
commitBit(dirtyList, 'dhcp'); reloadBit(dirtyList, 'dnsmasq') commitBit(dirtyList, 'dhcp'); reloadBit(dirtyList, 'dnsmasq')
@ -230,21 +232,21 @@ end
--TODO: handle os.rename() return values (nil+msg on error) --TODO: handle os.rename() return values (nil+msg on error)
function reconf.wwwcaptive_add(dirtyList) function reconf.wwwcaptive_add(dirtyList)
if utils.exists(M.WWW_CAPTIVE_INDICATOR) then if utils.exists(M.WWW_CAPTIVE_INDICATOR) then
return log:verbose("WWW captive directory already in place, not redoing", false) return log:verbose(MOD_ABBR, "WWW captive directory already in place, not redoing", false)
end end
local rv,reason = os.rename('/www', M.WWW_RENAME_NAME) local rv,reason = os.rename('/www', M.WWW_RENAME_NAME)
if rv == true then if rv == true then
utils.symlink(M.WWW_CAPTIVE_PATH, '/www') utils.symlink(M.WWW_CAPTIVE_PATH, '/www')
return true return true
else else
return log:error("Could not rename /www to " .. M.WWW_RENAME_NAME .. "(" .. reason .. ")") return log:error(MOD_ABBR, "Could not rename /www to " .. M.WWW_RENAME_NAME .. "(" .. reason .. ")")
end end
end end
function reconf.wwwcaptive_rm(dirtyList) function reconf.wwwcaptive_rm(dirtyList)
if not utils.exists(M.WWW_CAPTIVE_INDICATOR) then return log:verbose("WWW captive directory not in place, not undoing", false) end if not utils.exists(M.WWW_CAPTIVE_INDICATOR) then return log:verbose(MOD_ABBR, "WWW captive directory not in place, not undoing", false) end
os.remove('/www') os.remove('/www')
if os.rename(M.WWW_RENAME_NAME, '/www') ~= true then if os.rename(M.WWW_RENAME_NAME, '/www') ~= true then
return log:error("Could not rename " .. M.WWW_RENAME_NAME .. " to /www") return log:error(MOD_ABBR, "Could not rename " .. M.WWW_RENAME_NAME .. " to /www")
end end
return true return true
end end
@ -286,21 +288,21 @@ function M.setupAccessPoint(ssid)
M.setStatus(M.CREATED,"Access point created"); M.setStatus(M.CREATED,"Access point created");
local ds = wifi.getDeviceState() local ds = wifi.getDeviceState()
--log:info(" network/status: ") --log:info(MOD_ABBR, " network/status: ")
log:info(" ssid: ".. utils.dump(ds.ssid)) log:info(MOD_ABBR, " ssid: ".. utils.dump(ds.ssid))
--[[log:info(" bssid: ".. utils.dump(ds.bssid)) --[[log:info(MOD_ABBR, " bssid: ".. utils.dump(ds.bssid))
log:info(" channel: ".. utils.dump(ds.channel)) log:info(MOD_ABBR, " channel: ".. utils.dump(ds.channel))
log:info(" mode: ".. utils.dump(ds.mode)) log:info(MOD_ABBR, " mode: ".. utils.dump(ds.mode))
log:info(" encryption: ".. utils.dump(ds.encryption)) log:info(MOD_ABBR, " encryption: ".. utils.dump(ds.encryption))
log:info(" quality: ".. utils.dump(ds.quality)) log:info(MOD_ABBR, " quality: ".. utils.dump(ds.quality))
log:info(" quality_max: ".. utils.dump(ds.quality_max)) log:info(MOD_ABBR, " quality_max: ".. utils.dump(ds.quality_max))
log:info(" txpower: ".. utils.dump(ds.txpower)) log:info(MOD_ABBR, " txpower: ".. utils.dump(ds.txpower))
log:info(" signal: ".. utils.dump(ds.signal)) log:info(MOD_ABBR, " signal: ".. utils.dump(ds.signal))
log:info(" noise: ".. utils.dump(ds.noise)) log:info(MOD_ABBR, " noise: ".. utils.dump(ds.noise))
log:info(" raw: ".. utils.dump(ds)) log:info(MOD_ABBR, " raw: ".. utils.dump(ds))
local localip = wifi.getLocalIP() local localip = wifi.getLocalIP()
log:info(" localip: "..utils.dump(localip))]]-- log:info(MOD_ABBR, " localip: "..utils.dump(localip))]]--
return true return true
end end
@ -311,13 +313,13 @@ end
-- @tparam string ssid The SSID to use for the access point. -- @tparam string ssid The SSID to use for the access point.
-- @return True on success or nil+msg on error. -- @return True on success or nil+msg on error.
function M.enableAccessPoint(ssid) function M.enableAccessPoint(ssid)
log:verbose("enableAccessPoint ssid: ".. utils.dump(ssid)) log:verbose(MOD_ABBR, "enableAccessPoint ssid: ".. utils.dump(ssid))
M.switchConfiguration{apnet="add_noreload"} M.switchConfiguration{apnet="add_noreload"}
wifi.activateConfig(ssid) wifi.activateConfig(ssid)
local ds = wifi.getDeviceState() local ds = wifi.getDeviceState()
log:verbose(" ssid: ".. utils.dump(ds.ssid)) log:verbose(MOD_ABBR, " ssid: ".. utils.dump(ds.ssid))
return true return true
end end
@ -330,7 +332,7 @@ end
-- @tparam boolean recreate If true, a new UCI configuration based on scan data will always be created, otherwise an attempt will be made to use an existing configuration. -- @tparam boolean recreate If true, a new UCI configuration based on scan data will always be created, otherwise an attempt will be made to use an existing configuration.
-- @return True on success or nil+msg on error. -- @return True on success or nil+msg on error.
function M.associateSsid(ssid, passphrase, recreate) function M.associateSsid(ssid, passphrase, recreate)
log:info("netconfig:associateSsid: "..(ssid or "<nil>")..", "..(recreate or "<nil>")) log:info(MOD_ABBR, "netconfig:associateSsid: "..(ssid or "<nil>")..", "..(recreate or "<nil>"))
M.setStatus(M.CONNECTING,"Connecting..."); M.setStatus(M.CONNECTING,"Connecting...");
-- see if previously configured network for given ssid exists -- see if previously configured network for given ssid exists
@ -374,7 +376,7 @@ function M.associateSsid(ssid, passphrase, recreate)
local nextAttemptTime = os.time() local nextAttemptTime = os.time()
while true do while true do
if os.time() > nextAttemptTime then if os.time() > nextAttemptTime then
log:verbose("associated check "..utils.dump(attempt).."/"..utils.dump(maxAttempts)) log:verbose(MOD_ABBR, "associated check "..utils.dump(attempt).."/"..utils.dump(maxAttempts))
if wifi.getLocalIP() ~= nil and wifi.getDeviceState().ssid == ssid then if wifi.getLocalIP() ~= nil and wifi.getDeviceState().ssid == ssid then
break break
else else
@ -394,9 +396,9 @@ function M.associateSsid(ssid, passphrase, recreate)
-- signin to connect.doodle3d.com -- signin to connect.doodle3d.com
local success, output = signin.signin() local success, output = signin.signin()
if success then if success then
log:info("Signed in") log:info(MOD_ABBR, "Signed in")
else else
log:info("Signing in failed") log:info(MOD_ABBR, "Signing in failed")
end end
-- report we are connected after signin attempt -- report we are connected after signin attempt
@ -417,24 +419,24 @@ function M.disassociate()
end end
function M.getStatus() function M.getStatus()
log:info("network:getStatus") log:info(MOD_ABBR, "network:getStatus")
local file, error = io.open('/tmp/networkstatus.txt','r') local file, error = io.open('/tmp/networkstatus.txt','r')
if file == nil then if file == nil then
--log:error("Util:Access:Can't read controller file. Error: "..error) --log:error(MOD_ABBR, "Util:Access:Can't read controller file. Error: "..error)
return "","" return "",""
else else
local status = file:read('*a') local status = file:read('*a')
--log:info(" status: "..utils.dump(status)) --log:info(MOD_ABBR, " status: "..utils.dump(status))
file:close() file:close()
local code, msg = string.match(status, '([^|]+)|+(.*)') local code, msg = string.match(status, '([^|]+)|+(.*)')
--log:info(" code: "..utils.dump(code)) --log:info(MOD_ABBR, " code: "..utils.dump(code))
--log:info(" msg: "..utils.dump(msg)) --log:info(MOD_ABBR, " msg: "..utils.dump(msg))
return code,msg return code,msg
end end
end end
function M.setStatus(code,msg) function M.setStatus(code,msg)
log:info("network:setStatus: "..code.." | "..msg) log:info(MOD_ABBR, "network:setStatus: "..code.." | "..msg)
local file = io.open('/tmp/networkstatus.txt','w') local file = io.open('/tmp/networkstatus.txt','w')
file:write(code.."|"..msg) file:write(code.."|"..msg)
file:flush() file:flush()

View File

@ -20,6 +20,7 @@ local status = require('util.status')
local M = {} local M = {}
local STATUS_FILE = "signinstatus" local STATUS_FILE = "signinstatus"
local MOD_ABBR = "NTSI"
local IDLE_STATUS = 1 local IDLE_STATUS = 1
local SIGNING_IN_STATUS = 2 local SIGNING_IN_STATUS = 2
@ -28,14 +29,14 @@ local SIGNING_IN_STATUS = 2
-- --
function M.signin() function M.signin()
--log:verbose("signin:signin"); --log:verbose(MOD_ABBR, "signin:signin");
local code, msg = M.getStatus() local code, msg = M.getStatus()
--log:verbose(" status: "..utils.dump(code).." "..utils.dump(msg)); --log:verbose(MOD_ABBR, " status: "..utils.dump(code).." "..utils.dump(msg));
-- if we are already signin in, skip -- if we are already signin in, skip
if(code == SIGNING_IN_STATUS) then if(code == SIGNING_IN_STATUS) then
log:verbose(" skipping signin") log:verbose(MOD_ABBR, " skipping signin")
return return
end end
@ -53,10 +54,10 @@ function M.signin()
local signinResponse = "" local signinResponse = ""
while true do while true do
if os.time() > nextAttemptTime then if os.time() > nextAttemptTime then
log:verbose("signin attempt "..utils.dump(attempt).."/"..utils.dump(maxAttempts)) log:verbose(MOD_ABBR, "signin attempt "..utils.dump(attempt).."/"..utils.dump(maxAttempts))
local signedin = false local signedin = false
local localip = wifi.getLocalIP(); local localip = wifi.getLocalIP();
--log:verbose(" localip: "..utils.dump(localip)) --log:verbose(MOD_ABBR, " localip: "..utils.dump(localip))
if localip ~= nil then if localip ~= nil then
local wifiboxid = wifi.getSubstitutedSsid(settings.get('network.cl.wifiboxid')) local wifiboxid = wifi.getSubstitutedSsid(settings.get('network.cl.wifiboxid'))
@ -64,16 +65,16 @@ function M.signin()
local cmd = "wget -q -T 2 -t 1 -O - "..baseurl.."?wifiboxid="..wifiboxid.."\\&localip="..localip; local cmd = "wget -q -T 2 -t 1 -O - "..baseurl.."?wifiboxid="..wifiboxid.."\\&localip="..localip;
signinResponse = utils.captureCommandOutput(cmd); signinResponse = utils.captureCommandOutput(cmd);
log:verbose(" signin response: \n"..utils.dump(signinResponse)) log:verbose(MOD_ABBR, " signin response: \n"..utils.dump(signinResponse))
local success = signinResponse:match('"status":"success"') local success = signinResponse:match('"status":"success"')
log:verbose(" success: "..utils.dump(success)) log:verbose(MOD_ABBR, " success: "..utils.dump(success))
if success ~= nil then if success ~= nil then
signedin = true signedin = true
else else
log:warning("signin failed request failed (response: "..utils.dump(signinResponse)..")") log:warning(MOD_ABBR, "signin failed request failed (response: "..utils.dump(signinResponse)..")")
end end
else else
log:warning("signin failed no local ip found (attempt: "..utils.dump(attempt).."/"..utils.dump(maxAttempts)..")") log:warning(MOD_ABBR, "signin failed no local ip found (attempt: "..utils.dump(attempt).."/"..utils.dump(maxAttempts)..")")
end end
if signedin then if signedin then
@ -100,7 +101,7 @@ function M.getStatus()
end end
function M.setStatus(code,msg) function M.setStatus(code,msg)
log:info("signin:setStatus: "..code.." | "..msg) log:info(MOD_ABBR, "signin:setStatus: "..code.." | "..msg)
status.set(STATUS_FILE,code,msg); status.set(STATUS_FILE,code,msg);
end end

View File

@ -13,6 +13,8 @@ local iwinfo = require('iwinfo')
local M = {} local M = {}
local MOD_ABBR = "NTWL"
-- NOTE: fallback device 'radio0' is required because sometimes the wlan0 device disappears -- NOTE: fallback device 'radio0' is required because sometimes the wlan0 device disappears
M.DFL_DEVICE = 'wlan0' M.DFL_DEVICE = 'wlan0'
M.DFL_DEVICE_FALLBACK = 'radio0' M.DFL_DEVICE_FALLBACK = 'radio0'
@ -75,7 +77,7 @@ function M.init(device)
deviceName = M.DFL_DEVICE_FALLBACK deviceName = M.DFL_DEVICE_FALLBACK
deviceApi = iwinfo.type(deviceName) deviceApi = iwinfo.type(deviceName)
log:info("wireless device '" .. devInitial .. "' not found, trying fallback '" .. deviceName .. "'") log:info(MOD_ABBR, "wireless device '" .. devInitial .. "' not found, trying fallback '" .. deviceName .. "'")
if not deviceApi then if not deviceApi then
return false, "No such wireless device: '" .. devInitial .. "' (and fallback '" .. deviceName .. "' does not exist either)" return false, "No such wireless device: '" .. devInitial .. "' (and fallback '" .. deviceName .. "' does not exist either)"
@ -126,7 +128,7 @@ end
--returns the wireless local ip address --returns the wireless local ip address
function M.getLocalIP() function M.getLocalIP()
local ifconfig, rv = utils.captureCommandOutput("ifconfig wlan0"); local ifconfig, rv = utils.captureCommandOutput("ifconfig wlan0");
--log:verbose(" ifconfig: \n"..utils.dump(ifconfig)); --log:verbose(MOD_ABBR, " ifconfig: \n"..utils.dump(ifconfig));
local localip = ifconfig:match('inet addr:([%d%.]+)') local localip = ifconfig:match('inet addr:([%d%.]+)')
return localip return localip
@ -187,12 +189,12 @@ end
--- Activate wireless section for given SSID and disable all others --- Activate wireless section for given SSID and disable all others
-- @param ssid SSID of config to enable, or nil to disable all network configs -- @param ssid SSID of config to enable, or nil to disable all network configs
function M.activateConfig(ssid) function M.activateConfig(ssid)
--log:info("wlanconfig.activateConfig: "..ssid); --log:info(MOD_ABBR, "wlanconfig.activateConfig: "..ssid);
-- make sure only one is enabled -- make sure only one is enabled
uci:foreach('wireless', 'wifi-iface', function(s) uci:foreach('wireless', 'wifi-iface', function(s)
local disabled = s.ssid ~= ssid and '1' or '0' local disabled = s.ssid ~= ssid and '1' or '0'
--log:info(" "..utils.dump(s.ssid).." disable: "..utils.dump(disabled)) --log:info(MOD_ABBR, " "..utils.dump(s.ssid).." disable: "..utils.dump(disabled))
uci:set('wireless', s['.name'], 'disabled', disabled) uci:set('wireless', s['.name'], 'disabled', disabled)
end) end)
@ -210,10 +212,10 @@ function M.activateConfig(ssid)
return false return false
end end
end) end)
--[[log:info(" result:"); --[[log:info(MOD_ABBR, " result:");
uci:foreach('wireless', 'wifi-iface', function(s) uci:foreach('wireless', 'wifi-iface', function(s)
local disabled = s.ssid ~= ssid and '1' or '0' local disabled = s.ssid ~= ssid and '1' or '0'
log:info(" "..utils.dump(s.ssid).." disable: "..utils.dump(disabled)) log:info(MOD_ABBR, " "..utils.dump(s.ssid).." disable: "..utils.dump(disabled))
end)]]-- end)]]--
uci:commit('wireless') uci:commit('wireless')
@ -242,7 +244,7 @@ function M.createConfigFromScanInfo(info, passphrase, disabled)
uci:foreach('wireless', 'wifi-iface', function(s) uci:foreach('wireless', 'wifi-iface', function(s)
--if s.bssid == info.bssid then --if s.bssid == info.bssid then
if s.ssid == info.ssid then if s.ssid == info.ssid then
log:verbose("removing old wireless config for net '" .. s.ssid .. "'") log:verbose(MOD_ABBR, "removing old wireless config for net '" .. s.ssid .. "'")
uci:delete('wireless', s['.name']) uci:delete('wireless', s['.name'])
-- return false --keep looking, just in case multiple entries with this bssid exist -- return false --keep looking, just in case multiple entries with this bssid exist
end end

View File

@ -15,6 +15,8 @@ local wifi = require('network.wlanconfig')
local accessManager = require('util.access') local accessManager = require('util.access')
local printerAPI = require('rest.api.api_printer') local printerAPI = require('rest.api.api_printer')
local MOD_ABBR = "ACFG"
local M = { local M = {
isApi = true isApi = true
} }
@ -57,7 +59,7 @@ end
-- returns substituted_wifiboxid (since version 0.10.2) -- returns substituted_wifiboxid (since version 0.10.2)
-- returns substituted_ssid (since version 0.9.1) -- returns substituted_ssid (since version 0.9.1)
function M._global_POST(request, response) function M._global_POST(request, response)
--log:info("API:config:set") --log:info(MOD_ABBR, "API:config:set")
if not operationsAccessOrFail(request, response) then return end if not operationsAccessOrFail(request, response) then return end
@ -65,14 +67,14 @@ function M._global_POST(request, response)
local validation = {} local validation = {}
for k,v in pairs(request:getAll()) do for k,v in pairs(request:getAll()) do
--log:info(" "..k..": "..v); --log:info(MOD_ABBR, " "..k..": "..v);
local r,m = settings.set(k, v, true) local r,m = settings.set(k, v, true)
if r then if r then
validation[k] = "ok" validation[k] = "ok"
elseif r == false then elseif r == false then
validation[k] = "could not save setting ('" .. m .. "')" validation[k] = "could not save setting ('" .. m .. "')"
log:info(" m: "..utils.dump(m)) log:info(MOD_ABBR, " m: "..utils.dump(m))
elseif r == nil then elseif r == nil then
settings.commit() settings.commit()
response:setError(m) response:setError(m)
@ -109,12 +111,12 @@ end
-- and printer.type is set to 'ultimaker' then -- and printer.type is set to 'ultimaker' then
-- only the printer.startcode under the ultimaker subsection is removed. -- only the printer.startcode under the ultimaker subsection is removed.
function M.reset_POST(request, response) function M.reset_POST(request, response)
--log:info("API:reset"); --log:info(MOD_ABBR, "API:reset");
if not operationsAccessOrFail(request, response) then return end if not operationsAccessOrFail(request, response) then return end
response:setSuccess() response:setSuccess()
for k,v in pairs(request:getAll()) do for k,v in pairs(request:getAll()) do
--log:info(" "..k..": "..v); --log:info(MOD_ABBR, " "..k..": "..v);
local r,m = settings.reset(k); local r,m = settings.reset(k);
if r ~= nil then if r ~= nil then
response:addData(k, "ok") response:addData(k, "ok")

View File

@ -21,6 +21,7 @@ local LOG_COLLECT_DIRNAME = 'wifibox-logs'
local LOG_COLLECT_DIR = TMP_DIR .. '/' .. LOG_COLLECT_DIRNAME local LOG_COLLECT_DIR = TMP_DIR .. '/' .. LOG_COLLECT_DIRNAME
local WIFIBOX_LOG_FILENAME = 'wifibox.log' local WIFIBOX_LOG_FILENAME = 'wifibox.log'
local WIFIBOX_LOG_FILE = TMP_DIR .. '/' .. WIFIBOX_LOG_FILENAME local WIFIBOX_LOG_FILE = TMP_DIR .. '/' .. WIFIBOX_LOG_FILENAME
local MOD_ABBR = "AINF"
local SYSLOG_FILENAME = 'syslog' local SYSLOG_FILENAME = 'syslog'
local PROCESS_LIST_FILENAME = 'processes' local PROCESS_LIST_FILENAME = 'processes'
@ -147,12 +148,12 @@ function M.logfiles(request, response)
end end
function M.access(request, response) function M.access(request, response)
--log:info(" remoteAddress: |"..utils.dump(request.remoteAddress).."|"); --log:info(MOD_ABBR, " remoteAddress: |"..utils.dump(request.remoteAddress).."|");
--log:info(" controller: |"..utils.dump(accessManager.getController()).."|"); --log:info(MOD_ABBR, " controller: |"..utils.dump(accessManager.getController()).."|");
local hasControl = accessManager.hasControl(request.remoteAddress) local hasControl = accessManager.hasControl(request.remoteAddress)
-- if hasControl then log:info(" hasControl: true") -- if hasControl then log:info(MOD_ABBR, " hasControl: true")
-- else log:info(" hasControl: false") end -- else log:info(MOD_ABBR, " hasControl: false") end
response:setSuccess() response:setSuccess()
response:addData('has_control', hasControl) response:addData('has_control', hasControl)

View File

@ -16,6 +16,8 @@ local signin = require('network.signin')
local accessManager = require('util.access') local accessManager = require('util.access')
local printerAPI = require('rest.api.api_printer') local printerAPI = require('rest.api.api_printer')
local MOD_ABBR = "ANET"
local M = { local M = {
isApi = true isApi = true
} }
@ -149,9 +151,9 @@ function M.associate_POST(request, response)
local rv,msg = netconf.associateSsid(argSsid, argPhrase, argRecreate) local rv,msg = netconf.associateSsid(argSsid, argPhrase, argRecreate)
if rv then if rv then
log:info("associated to wifi: "..utils.dump(argSsid)) log:info(MOD_ABBR, "associated to wifi: "..utils.dump(argSsid))
else else
log:info("failed to associate to wifi: "..utils.dump(argSsid).." ("..utils.dump(msg)..")") log:info(MOD_ABBR, "failed to associate to wifi: "..utils.dump(argSsid).." ("..utils.dump(msg)..")")
end end
end end
@ -201,14 +203,14 @@ function M.remove_POST(request, response)
end end
function M.signin(request, response) function M.signin(request, response)
log:info("API:Network:signin") log:info(MOD_ABBR, "API:Network:signin")
local success, output = signin.signin() local success, output = signin.signin()
if success then if success then
log:info("API:Network:signed in") log:info(MOD_ABBR, "API:Network:signed in")
response:setSuccess("API:Network:signed in") response:setSuccess("API:Network:signed in")
response:addData("response", output) response:addData("response", output)
else else
log:info("API:Network:Signing in failed") log:info(MOD_ABBR, "API:Network:Signing in failed")
response:setError("Signing in failed") response:setError("Signing in failed")
end end
end end

View File

@ -14,6 +14,8 @@ local printDriver = require('print3d')
local printerUtils = require('util.printer') local printerUtils = require('util.printer')
local accessManager = require('util.access') local accessManager = require('util.access')
local MOD_ABBR = "APRN"
local M = { local M = {
isApi = true isApi = true
} }
@ -68,7 +70,7 @@ function M.progress(request, response)
return true; return true;
end end
-- NOTE: onlyReturnState is optional and prevents response from being modified -- NOTE: onlyReturnState is optional and prevents response from being modified, used when calling from within other api call
function M.state(request, response, onlyReturnState) function M.state(request, response, onlyReturnState)
local argId = request:get("id") local argId = request:get("id")
if not onlyReturnState then response:addData('id', argId) end if not onlyReturnState then response:addData('id', argId) end
@ -136,7 +138,7 @@ end
function M.stop_POST(request, response) function M.stop_POST(request, response)
log:info("API:printer/stop") log:info(MOD_ABBR, "API:printer/stop")
if not accessManager.hasControl(request.remoteAddress) then if not accessManager.hasControl(request.remoteAddress) then
response:setFail("No control access") response:setFail("No control access")
@ -159,6 +161,8 @@ function M.stop_POST(request, response)
end end
end end
--requires: gcode(string) (the gcode to be appended)
--accepts: id(string) (the printer ID to append to)
--accepts: first(bool) (chunks will be concatenated but output file will be cleared first if this argument is true) --accepts: first(bool) (chunks will be concatenated but output file will be cleared first if this argument is true)
--accepts: start(bool) (only when this argument is true will printing be started) --accepts: start(bool) (only when this argument is true will printing be started)
function M.print_POST(request, response) function M.print_POST(request, response)
@ -172,7 +176,7 @@ function M.print_POST(request, response)
hasControl = true hasControl = true
end end
log:info(" hasControl: "..utils.dump(hasControl)) log:info(MOD_ABBR, " hasControl: "..utils.dump(hasControl))
if not hasControl then if not hasControl then
response:setFail("No control access") response:setFail("No control access")
return return
@ -194,7 +198,7 @@ function M.print_POST(request, response)
end end
if argIsFirst == true then if argIsFirst == true then
log:verbose("clearing all gcode for " .. printer:getId()) log:verbose(MOD_ABBR, "clearing all gcode for " .. printer:getId())
response:addData('gcode_clear',true) response:addData('gcode_clear',true)
local rv,msg = printer:clearGcode() local rv,msg = printer:clearGcode()

View File

@ -16,6 +16,8 @@ local lfs = require('lfs')
local log = require('util.logger') local log = require('util.logger')
local utils = require('util.utils') local utils = require('util.utils')
local MOD_ABBR = "ASKE"
local M = { local M = {
isApi = true, isApi = true,
SKETCH_DIR = '/root/sketches', SKETCH_DIR = '/root/sketches',
@ -29,7 +31,7 @@ local SKETCH_FILE_EXTENSION = 'svg'
-- creates sketch directory, and sets response to error state on failure -- creates sketch directory, and sets response to error state on failure
local function createSketchDirectory() local function createSketchDirectory()
if os.execute('mkdir -p ' .. M.SKETCH_DIR) ~= 0 then if os.execute('mkdir -p ' .. M.SKETCH_DIR) ~= 0 then
log:error("Error: could not create sketch directory '" .. M.SKETCH_DIR .. "'") log:error(MOD_ABBR, "Error: could not create sketch directory '" .. M.SKETCH_DIR .. "'")
response:setError("could not create sketch directory") response:setError("could not create sketch directory")
return false return false
end end
@ -133,7 +135,7 @@ function M._global_POST(request, response)
local sketchIdx = listSize > 0 and sketches[listSize] + 1 or 1 local sketchIdx = listSize > 0 and sketches[listSize] + 1 or 1
local sketchFile = M.SKETCH_DIR .. '/' .. constructSketchFilename(sketchIdx) local sketchFile = M.SKETCH_DIR .. '/' .. constructSketchFilename(sketchIdx)
log:verbose("saving sketch #" .. sketchIdx .. " (" .. argData:len() .. " bytes)") log:verbose(MOD_ABBR, "saving sketch #" .. sketchIdx .. " (" .. argData:len() .. " bytes)")
local saveFile,msg = io.open(sketchFile, 'w') local saveFile,msg = io.open(sketchFile, 'w')
if not saveFile then if not saveFile then

View File

@ -10,6 +10,8 @@ local wifi = require('network.wlanconfig')
local netconf = require('network.netconfig') local netconf = require('network.netconfig')
local settings = require('util.settings') local settings = require('util.settings')
local MOD_ABBR = "AUPD"
-- NOTE: the updater module 'detects' command-line invocation by existence of 'arg', so we have to make sure it is not defined. -- NOTE: the updater module 'detects' command-line invocation by existence of 'arg', so we have to make sure it is not defined.
argStash = arg argStash = arg
arg = nil arg = nil
@ -158,7 +160,7 @@ end
function M.install_POST(request, response) function M.install_POST(request, response)
local argVersion = request:get("version") local argVersion = request:get("version")
local argNoRetain = request:get("no_retain") local argNoRetain = request:get("no_retain")
log:info("API:update/install (noRetain: "..utils.dump(argNoRetain)..")") log:info(MOD_ABBR, "API:update/install (noRetain: "..utils.dump(argNoRetain)..")")
local noRetain = argNoRetain == 'true' local noRetain = argNoRetain == 'true'
if not operationsAccessOrFail(request, response) then return end if not operationsAccessOrFail(request, response) then return end

View File

@ -20,6 +20,7 @@ local M = {}
M.__index = M M.__index = M
local REQUEST_ID_ARGUMENT = 'rq_id' local REQUEST_ID_ARGUMENT = 'rq_id'
local MOD_ABBR = "HRSP"
M.httpStatusCode, M.httpStatusText, M.contentType = nil, nil, nil M.httpStatusCode, M.httpStatusText, M.contentType = nil, nil, nil
M.binaryData, M.binarySavename = nil, nil M.binaryData, M.binarySavename = nil, nil
@ -131,7 +132,7 @@ end
--- Call all function on the post-response queue, see @{M:addPostResponseFunction} for details and a side-note. --- Call all function on the post-response queue, see @{M:addPostResponseFunction} for details and a side-note.
function M:executePostResponseQueue() function M:executePostResponseQueue()
--log:info("Response:executePostResponseQueue: " .. utils.dump(self.postResponseQueue)) --log:info(MOD_ABBR, "Response:executePostResponseQueue: " .. utils.dump(self.postResponseQueue))
for i,fn in ipairs(self.postResponseQueue) do fn() end for i,fn in ipairs(self.postResponseQueue) do fn() end
end end
@ -169,7 +170,7 @@ function M:send()
end end
if self.body.status ~= "success" then if self.body.status ~= "success" then
log:verbose("Response:"..utils.dump(self.body.status).." ("..utils.dump(self.body.msg)..")") log:verbose(MOD_ABBR, "Response:"..utils.dump(self.body.status).." ("..utils.dump(self.body.msg)..")")
end end
end end

View File

@ -24,6 +24,8 @@
-- note: take care not to print any text in module functions, as this breaks http responses -- note: take care not to print any text in module functions, as this breaks http responses
-- change representation of sysupgrade/factory info in versionInfo? (and also in image index?) <- create api call to get all info on all versions? -- change representation of sysupgrade/factory info in versionInfo? (and also in image index?) <- create api call to get all info on all versions?
local MOD_ABBR = "UPDA"
local M = {} local M = {}
--- Possible states the updater can be in, they are stored in @{STATE_FILE}. --- Possible states the updater can be in, they are stored in @{STATE_FILE}.
@ -82,8 +84,8 @@ local baseUrl = M.DEFAULT_BASE_URL -- default, can be overwritten by M.setBaseUr
-- @string msg The message to log. -- @string msg The message to log.
local function P(lvl, msg) local function P(lvl, msg)
if log then if log then
if lvl == -1 then log:verbose(msg) if lvl == -1 then log:verbose(MOD_ABBR, msg)
elseif lvl == 0 or lvl == 1 then log:info(msg) elseif lvl == 0 or lvl == 1 then log:info(MOD_ABBR, msg)
end end
else else
if (-lvl <= verbosity) then print(msg) end if (-lvl <= verbosity) then print(msg) end
@ -99,7 +101,7 @@ local function D(msg) P(-1, (log and msg or "(DBG) " .. msg)) end
-- Messages will be written to [stderr](http://www.cplusplus.com/reference/cstdio/stderr/), or logged using the logger set with @{setLogger}. -- Messages will be written to [stderr](http://www.cplusplus.com/reference/cstdio/stderr/), or logged using the logger set with @{setLogger}.
-- @string msg The message to log. -- @string msg The message to log.
local function E(msg) local function E(msg)
if log then log:error(msg) if log then log:error(MOD_ABBR, msg)
else io.stderr:write(msg .. '\n') else io.stderr:write(msg .. '\n')
end end
end end
@ -792,7 +794,7 @@ end
-- @treturn bool|nil True on success (with the 'exception' as noted above) or nil on error. -- @treturn bool|nil True on success (with the 'exception' as noted above) or nil on error.
-- @treturn ?string|number (optional) Descriptive message or sysupgrade exit status on error. -- @treturn ?string|number (optional) Descriptive message or sysupgrade exit status on error.
function M.flashImageVersion(versionEntry, noRetain, devType, isFactory) function M.flashImageVersion(versionEntry, noRetain, devType, isFactory)
if log then log:info("flashImageVersion") end if log then log:info(MOD_ABBR, "flashImageVersion") end
local imgName = M.constructImageFilename(versionEntry.version, devType, isFactory) local imgName = M.constructImageFilename(versionEntry.version, devType, isFactory)
local cmd = noRetain and 'sysupgrade -n ' or 'sysupgrade ' local cmd = noRetain and 'sysupgrade -n ' or 'sysupgrade '
cmd = cmd .. cachePath .. '/' .. imgName cmd = cmd .. cachePath .. '/' .. imgName

View File

@ -10,6 +10,8 @@ local log = require('util.logger')
local utils = require('util.utils') local utils = require('util.utils')
local printerUtils = require('util.printer') local printerUtils = require('util.printer')
local MOD_ABBR = "UACS"
local M = {} local M = {}
function M.hasControl(ip) function M.hasControl(ip)
@ -41,7 +43,7 @@ end
function M.getController() function M.getController()
local file, error = io.open('/tmp/controller.txt','r') local file, error = io.open('/tmp/controller.txt','r')
if file == nil then if file == nil then
--log:error("Util:Access:Can't read controller file. Error: "..error) --log:error(MOD_ABBR, "Util:Access:Can't read controller file. Error: "..error)
return "" return ""
else else
controllerIP = file:read('*a') controllerIP = file:read('*a')

View File

@ -32,7 +32,7 @@ for i,v in ipairs(M.LEVEL) do
end end
local function log(level, msg, verboseFmt) local function log(level, module, msg, verboseFmt)
if level <= logLevel then if level <= logLevel then
local now = os.date('%m-%d %H:%M:%S') local now = os.date('%m-%d %H:%M:%S')
local i = debug.getinfo(3) --the stack frame just above the logger call local i = debug.getinfo(3) --the stack frame just above the logger call
@ -41,9 +41,10 @@ local function log(level, msg, verboseFmt)
local name = i.name or "(nil)" local name = i.name or "(nil)"
local vVal = 'nil' local vVal = 'nil'
local m = (type(msg) == 'string') and msg or utils.dump(msg) local m = (type(msg) == 'string') and msg or utils.dump(msg)
if module == nil then module = "LUA " end
if v then logStream:write(now .. " (" .. M.LEVEL[level] .. ") " .. m .. " [" .. name .. "@" .. i.short_src .. ":" .. i.linedefined .. "]\n") if v then logStream:write(now .. " [" .. module .. "] (" .. M.LEVEL[level] .. "): " .. m .. " [" .. name .. "@" .. i.short_src .. ":" .. i.linedefined .. "]\n")
else logStream:write(now .. " (" .. M.LEVEL[level] .. ") " .. m .. "\n") end else logStream:write(now .. " [" .. module .. "] (" .. M.LEVEL[level] .. "): " .. m .. "\n") end
logStream:flush() logStream:flush()
end end
@ -52,11 +53,11 @@ end
--- Initializes the logger. --- Initializes the logger.
-- @tparam @{util.logger.LEVEL} level Minimum level of messages to log. -- @tparam @{util.logger.LEVEL} level Minimum level of messages to log.
-- @tparam bool verbose Write verbose log messages (include file/line inforomation). -- @tparam bool verbose Write verbose log messages (include file/line information).
function M:init(level, verboseFmt) function M:init(level, verboseFmt)
logLevel = level or M.LEVEL.warning logLevel = level or M.LEVEL.warning
logVerboseFmt = verboseFmt or false logVerboseFmt = verboseFmt or false
logStream = stream or io.stdout --logStream = stream or io.stdout
end end
function M:setLevel(level, verboseFmt) function M:setLevel(level, verboseFmt)
@ -73,10 +74,14 @@ function M:getLevel()
return logLevel, logVerboseFmt return logLevel, logVerboseFmt
end end
function M:error(msg, verboseFmt) log(M.LEVEL.error, msg, verboseFmt); return false end function M:getStream()
function M:warning(msg, verboseFmt) log(M.LEVEL.warning, msg, verboseFmt); return true end return logStream
function M:info(msg, verboseFmt) log(M.LEVEL.info, msg, verboseFmt); return true end end
function M:verbose(msg, verboseFmt) log(M.LEVEL.verbose, msg, verboseFmt); return true end
function M:bulk(msg, verboseFmt) log(M.LEVEL.bulk, msg, verboseFmt); return true end function M:error(module, msg, verboseFmt) log(M.LEVEL.error, module, msg, verboseFmt); return false end
function M:warning(module, msg, verboseFmt) log(M.LEVEL.warning, module, msg, verboseFmt); return true end
function M:info(module, msg, verboseFmt) log(M.LEVEL.info, module, msg, verboseFmt); return true end
function M:verbose(module, msg, verboseFmt) log(M.LEVEL.verbose, module, msg, verboseFmt); return true end
function M:bulk(module, msg, verboseFmt) log(M.LEVEL.bulk, module, msg, verboseFmt); return true end
return M return M

View File

@ -10,6 +10,8 @@ local log = require('util.logger')
local utils = require('util.utils') local utils = require('util.utils')
local printDriver = require('print3d') local printDriver = require('print3d')
local MOD_ABBR = "UPRN"
local SUPPORTED_PRINTERS = { local SUPPORTED_PRINTERS = {
rigidbot = "Rigidbot", rigidbot = "Rigidbot",
ultimaker = "Ultimaker", ultimaker = "Ultimaker",
@ -81,8 +83,8 @@ end
--returns a printer instance or nil (and sets error state on response in the latter case) --returns a printer instance or nil (and sets error state on response in the latter case)
function M.createPrinterOrFail(deviceId, response) function M.createPrinterOrFail(deviceId, response)
--log:verbose("API:printer:createPrinterOrFail: "..utils.dump(deviceId)) --log:verbose(MOD_ABBR, "API:printer:createPrinterOrFail: "..utils.dump(deviceId))
local msg,printer = nil, nil local rv,msg,printer = nil, nil, nil
if deviceId == nil or deviceId == "" then if deviceId == nil or deviceId == "" then
printer,msg = printDriver.getPrinter() printer,msg = printDriver.getPrinter()
@ -98,7 +100,17 @@ function M.createPrinterOrFail(deviceId, response)
return nil return nil
end end
printer:setLocalLogLevel(log:getLevel()) -- only log these log setup errors, do not let them prevent further request handling
rv,msg = printer:setLocalLogStream(log:getStream())
if not rv then
log:error(MOD_ABBR, "could not set log stream in Lua binding (" .. msg .. ")")
end
rv,msg = printer:setLocalLogLevel(log:getLevel())
if not rv then
log:error(MOD_ABBR, "could not set log level '" .. log:getLevel() .. "' in Lua binding (" .. msg .. ")")
end
return printer return printer
end end

View File

@ -19,6 +19,8 @@ local baseconfig = require('conf_defaults')
local utils = require('util.utils') local utils = require('util.utils')
local log = require('util.logger') local log = require('util.logger')
local MOD_ABBR = "USET"
local M = {} local M = {}
--- UCI config name (i.e., file under `/etc/config`) --- UCI config name (i.e., file under `/etc/config`)
@ -159,7 +161,7 @@ end]]--
-- @return The associated value, beware (!) that this may be boolean false for keys of 'bool' type, or nil if the key could not be read because of a UCI error. -- @return The associated value, beware (!) that this may be boolean false for keys of 'bool' type, or nil if the key could not be read because of a UCI error.
-- @treturn string Message in case of error. -- @treturn string Message in case of error.
function M.get(key) function M.get(key)
--log:info("settings:get: "..utils.dump(key)) --log:info(MOD_ABBR, "settings:get: "..utils.dump(key))
key = replaceDots(key) key = replaceDots(key)
-- retrieve settings's base settings from conf_defaults.lua -- retrieve settings's base settings from conf_defaults.lua
@ -177,7 +179,7 @@ function M.get(key)
local uciV,msg = uci:get(UCI_CONFIG_NAME, section, key) local uciV,msg = uci:get(UCI_CONFIG_NAME, section, key)
if not uciV and msg ~= nil then if not uciV and msg ~= nil then
local errorMSG = "Issue reading setting '"..utils.dump(key).."': "..utils.dump(msg); local errorMSG = "Issue reading setting '"..utils.dump(key).."': "..utils.dump(msg);
log:info(errorMSG) log:info(MOD_ABBR, errorMSG)
return nil, errorMSG; return nil, errorMSG;
end end
@ -244,21 +246,21 @@ end
-- @treturn bool|nil True if everything went well, false if validation error, nil in case of error. -- @treturn bool|nil True if everything went well, false if validation error, nil in case of error.
-- @treturn ?string Error message in case first return value is nil (invalid key). -- @treturn ?string Error message in case first return value is nil (invalid key).
function M.set(key, value, noCommit) function M.set(key, value, noCommit)
log:info("settings:set: "..utils.dump(key).." to: "..utils.dump(value)) log:info(MOD_ABBR, "settings:set: "..utils.dump(key).." to: "..utils.dump(value))
key = replaceDots(key) key = replaceDots(key)
local r = utils.create(UCI_CONFIG_FILE) local r = utils.create(UCI_CONFIG_FILE)
local rv, msg = uci:set(UCI_CONFIG_NAME, UCI_CONFIG_SECTION, UCI_CONFIG_TYPE) local rv, msg = uci:set(UCI_CONFIG_NAME, UCI_CONFIG_SECTION, UCI_CONFIG_TYPE)
if not rv and msg ~= nil then if not rv and msg ~= nil then
local errorMSG = "Issue creating section '"..utils.dump(UCI_CONFIG_SECTION).."': "..utils.dump(msg); local errorMSG = "Issue creating section '"..utils.dump(UCI_CONFIG_SECTION).."': "..utils.dump(msg);
log:info(errorMSG) log:info(MOD_ABBR, errorMSG)
return nil, errorMSG; return nil, errorMSG;
end end
local base = getBaseKeyTable(key) local base = getBaseKeyTable(key)
if not base then return false,ERR_NO_SUCH_KEY end if not base then return false,ERR_NO_SUCH_KEY end
--log:info(" base.type: "..utils.dump(base.type)) --log:info(MOD_ABBR, " base.type: "..utils.dump(base.type))
if base.type == 'bool' then if base.type == 'bool' then
if value ~= "" then if value ~= "" then
value = utils.toboolean(value) value = utils.toboolean(value)
@ -283,7 +285,7 @@ function M.set(key, value, noCommit)
local rv, msg = uci:set(UCI_CONFIG_NAME, section, UCI_CONFIG_TYPE) local rv, msg = uci:set(UCI_CONFIG_NAME, section, UCI_CONFIG_TYPE)
if not rv and msg ~= nil then if not rv and msg ~= nil then
local errorMSG = "Issue getting subsection '"..utils.dump(base.subSection).."': "..utils.dump(msg); local errorMSG = "Issue getting subsection '"..utils.dump(base.subSection).."': "..utils.dump(msg);
log:info(errorMSG) log:info(MOD_ABBR, errorMSG)
return nil, errorMSG; return nil, errorMSG;
end end
end end
@ -292,14 +294,14 @@ function M.set(key, value, noCommit)
local rv, msg = uci:set(UCI_CONFIG_NAME, section, key, toUciValue(value, base.type)) local rv, msg = uci:set(UCI_CONFIG_NAME, section, key, toUciValue(value, base.type))
if not rv and msg ~= nil then if not rv and msg ~= nil then
local errorMSG = "Issue setting setting '"..utils.dump(key).."' in section '"..utils.dump(section).."': "..utils.dump(msg); local errorMSG = "Issue setting setting '"..utils.dump(key).."' in section '"..utils.dump(section).."': "..utils.dump(msg);
log:info(errorMSG) log:info(MOD_ABBR, errorMSG)
return nil, errorMSG; return nil, errorMSG;
end end
else else
local rv, msg = uci:delete(UCI_CONFIG_NAME, section, key) local rv, msg = uci:delete(UCI_CONFIG_NAME, section, key)
if not rv and msg ~= nil then if not rv and msg ~= nil then
local errorMSG = "Issue deleting setting '"..utils.dump(key).."' in section '"..utils.dump(section).."': "..utils.dump(msg); local errorMSG = "Issue deleting setting '"..utils.dump(key).."' in section '"..utils.dump(section).."': "..utils.dump(msg);
log:info(errorMSG) log:info(MOD_ABBR, errorMSG)
return nil, errorMSG; return nil, errorMSG;
end end
end end
@ -318,13 +320,13 @@ end
-- @string key The key to set. -- @string key The key to set.
-- @treturn bool|nil True if everything went well, nil in case of error. -- @treturn bool|nil True if everything went well, nil in case of error.
function M.resetAll() function M.resetAll()
log:info("settings:resetAll") log:info(MOD_ABBR, "settings:resetAll")
-- find all sections -- find all sections
local allSections, msg = uci:get_all(UCI_CONFIG_NAME) local allSections, msg = uci:get_all(UCI_CONFIG_NAME)
if not allSections and msg ~= nil then if not allSections and msg ~= nil then
local errorMSG = "Issue reading all settings: "..utils.dump(msg); local errorMSG = "Issue reading all settings: "..utils.dump(msg);
log:info(errorMSG) log:info(MOD_ABBR, errorMSG)
return nil, errorMSG; return nil, errorMSG;
end end
@ -334,7 +336,7 @@ function M.resetAll()
local rv, msg = uci:delete(UCI_CONFIG_NAME,key) local rv, msg = uci:delete(UCI_CONFIG_NAME,key)
if not rv and msg ~= nil then if not rv and msg ~= nil then
local errorMSG = "Issue deleting setting '"..utils.dump(key).."': "..utils.dump(msg); local errorMSG = "Issue deleting setting '"..utils.dump(key).."': "..utils.dump(msg);
log:info(errorMSG) log:info(MOD_ABBR, errorMSG)
return nil, errorMSG; return nil, errorMSG;
end end
end end
@ -356,7 +358,7 @@ end
-- @p[opt=nil] noCommit If true, do not commit the uci configuration; this is more efficient when resetting multiple values -- @p[opt=nil] noCommit If true, do not commit the uci configuration; this is more efficient when resetting multiple values
-- @treturn bool|nil True if everything went well, nil in case of error. -- @treturn bool|nil True if everything went well, nil in case of error.
function M.reset(key, noCommit) function M.reset(key, noCommit)
log:info("settings:reset: "..utils.dump(key)) log:info(MOD_ABBR, "settings:reset: "..utils.dump(key))
-- delete -- delete
key = replaceDots(key) key = replaceDots(key)
@ -371,7 +373,7 @@ function M.reset(key, noCommit)
-- (which always happens when reset is used in resetall) it will also generate a error -- (which always happens when reset is used in resetall) it will also generate a error
--if not rv and msg ~= nil then --if not rv and msg ~= nil then
-- local errorMSG = "Issue deleting setting '"..utils.dump(key).."' in section '"..section.."': "..utils.dump(msg); -- local errorMSG = "Issue deleting setting '"..utils.dump(key).."' in section '"..section.."': "..utils.dump(msg);
-- log:info(errorMSG) -- log:info(MOD_ABBR, errorMSG)
-- return nil, errorMSG; -- return nil, errorMSG;
--end --end

View File

@ -9,6 +9,8 @@
local log = require('util.logger') local log = require('util.logger')
local utils = require('util.utils') local utils = require('util.utils')
local MOD_ABBR = "USTS"
local M = {} local M = {}
local FOLDER = "/tmp/" local FOLDER = "/tmp/"
@ -23,7 +25,7 @@ function M.get(fileName)
local path = getPath(fileName) local path = getPath(fileName)
local file, error = io.open(path,'r') local file, error = io.open(path,'r')
if file == nil then if file == nil then
--log:error("Util:Access:Can't read controller file. Error: "..error) --log:error(MOD_ABBR, "Util:Access:Can't read controller file. Error: "..error)
return "","" return "",""
else else
local status = file:read('*a') local status = file:read('*a')
@ -35,7 +37,7 @@ function M.get(fileName)
end end
function M.set(fileName,code,msg) function M.set(fileName,code,msg)
--log:info("setStatus: "..code.." | "..msg) --log:info(MOD_ABBR, "setStatus: "..code.." | "..msg)
local path = getPath(fileName) local path = getPath(fileName)
local file = io.open(path,'w') local file = io.open(path,'w')
file:write(code.."|"..msg) file:write(code.."|"..msg)