Browse Source

Merge branch 'develop'

Conflicts:
	README.md
pull/64/head 0.10.10
peteruithoven 6 years ago
parent
commit
89748e11aa
  1. 14
      Makefile
  2. 17
      README.md
  3. 39
      ReleaseNotes.md
  4. 2
      extra/openwrt-build/openwrt-diffconfig-extramini
  5. 2
      extra/openwrt-build/openwrt-diffconfig-mini
  6. 2
      extra/openwrt-build/openwrt-diffconfig-regular
  7. 10
      extra/scripts/publish-wifibox-release.lua
  8. 2
      license-spec.lua
  9. 44
      post-install.sh
  10. 2
      src/FIRMWARE-VERSION
  11. 8
      src/conf_defaults.lua
  12. 159
      src/main.lua
  13. 124
      src/network/netconfig.lua
  14. 45
      src/network/signin.lua
  15. 38
      src/network/wlanconfig.lua
  16. 16
      src/rest/api/api_config.lua
  17. 77
      src/rest/api/api_info.lua
  18. 11
      src/rest/api/api_network.lua
  19. 124
      src/rest/api/api_printer.lua
  20. 6
      src/rest/api/api_sketch.lua
  21. 4
      src/rest/api/api_update.lua
  22. 7
      src/rest/request.lua
  23. 19
      src/rest/response.lua
  24. 92
      src/script/README-loglite.md
  25. 12
      src/script/d3d-updater.lua
  26. 5
      src/script/d3dapi
  27. 63
      src/script/loglite-filters.lua
  28. 275
      src/script/loglite.lua
  29. 36
      src/script/logrotate-wifibox.conf
  30. 9
      src/script/wifibox.uci.config
  31. 6
      src/script/wifibox_init
  32. 16
      src/util/access.lua
  33. 81
      src/util/logger.lua
  34. 21
      src/util/printer.lua
  35. 40
      src/util/settings.lua
  36. 8
      src/util/status.lua

14
Makefile

@ -66,6 +66,13 @@ define Build/Compile directives
# no compilation necessary (although possible with luac?)
endef
# This information is contained within the ipk file and (at least) used by
# sysupgrade to determine which files to keep (see `opkg list-changed-conffiles`).
define Package/wifibox/conffiles
/etc/config/wifibox
/etc/logrotate.d/wifibox.conf
endef
# The $(1) variable represents the root directory on the router running
# OpenWrt. The $(INSTALL_DIR) variable contains a command to prepare the install
# directory if it does not already exist. Likewise $(INSTALL_BIN) contains the
@ -88,6 +95,9 @@ define Package/wifibox/install
#$(INSTALL_DIR) $(1)/etc
$(INSTALL_DIR) $(1)/etc/init.d
$(INSTALL_DIR) $(1)/etc/config
$(INSTALL_DIR) $(1)/etc/logrotate.d
$(INSTALL_DIR) $(1)/root/
$(INSTALL_DIR) $(1)/root/sketches
#$(INSTALL_DIR) $(1)/www
$(INSTALL_DIR) $(1)/www/cgi-bin
@ -102,10 +112,14 @@ define Package/wifibox/install
$(INSTALL_BIN) $(WIFIBOX_BASE_DIR)/script/d3d-updater.lua $(1)/$(TGT_LUA_DIR_SUFFIX)/script
$(LN) -s /$(TGT_LUA_DIR_SUFFIX)/script/d3d-updater.lua $(1)/bin/d3d-updater
$(CP) $(WIFIBOX_BASE_DIR)/script/loglite-filters.lua $(1)/root/
$(INSTALL_BIN) $(WIFIBOX_BASE_DIR)/script/loglite.lua $(1)/$(TGT_LUA_DIR_SUFFIX)/script
$(LN) -s /$(TGT_LUA_DIR_SUFFIX)/script/loglite.lua $(1)/bin/loglite
$(INSTALL_BIN) $(WIFIBOX_BASE_DIR)/script/wifibox_init $(1)/etc/init.d/wifibox
$(INSTALL_BIN) $(WIFIBOX_BASE_DIR)/script/dhcpcheck_init $(1)/etc/init.d/dhcpcheck
$(INSTALL_BIN) $(WIFIBOX_BASE_DIR)/script/d3dapi $(1)/$(TGT_LUA_DIR_SUFFIX)/script
$(INSTALL_BIN) $(WIFIBOX_BASE_DIR)/script/signin.sh $(1)/$(TGT_LUA_DIR_SUFFIX)/script
$(CP) $(WIFIBOX_BASE_DIR)/script/logrotate-wifibox.conf $(1)/etc/logrotate.d/wifibox.conf
$(CP) $(WIFIBOX_BASE_DIR)/script/wifibox.uci.config $(1)/etc/config/wifibox # copy base configuration to uci config dir
$(CP) $(WIFIBOX_BASE_DIR)/FIRMWARE-VERSION $(1)/etc/wifibox-version

17
README.md

@ -3,6 +3,7 @@ WiFi box OpenWRT firmware package
General documentation can be found on the wiki: <http://doodle3d.com/help/wiki>. Source code documentation can be generated, see below.
Documentation
-------------
@ -11,10 +12,9 @@ Make sure the 'ldoc' program is installed on your machine and the LDOC variable
On OSX, this can be accomplished by installing it through luarocks (run `sudo luarocks install ldoc`). Luarocks can be installed using [MacPorts](http://www.macports.org/). After installing that, the command would be `sudo port install luarocks`.
Command line interface
----------------------
The Doodle3D API can be called using a terminal:
The Doodle3D API can be called using a terminal:
```d3dapi p=/network/scan r=GET```
@ -24,3 +24,16 @@ Post request can be send using the same method:
```d3dapi p=/printer/print r=POST```
Parameters: TODO
Debugging Lua
-------------
Syntax errors in Lua can lead to tricky issues since they might only surface when the faulty code is actually being run.
One countermeasure for this is to use [pcall](http://www.lua.org/pil/8.4.html) instead of regular calls in many cases. To let the error 'happen' (which in turn gives information in the form of stack traces), tell the code to use regular calls by setting 'M.DEBUG_PCALLS' to 'true' in `conf_defaults.lua`.
Additionally, when the pcall setting is not enough, a second way of debugging is to take uhttpd out of the loop and invoke the Lua code from command-line. To do this, set 'M.DEBUG_API' to 'true' in `conf_defaults.lua`. Then invoke the API using the command `d3dapi p=/mod/func r=POST` where `p=` is followed by the API path and `r=` followed by either 'GET' or 'POST'.
Note that because stack traces are sent to `stderr`, this script redirects output streams to a separate log file: `/tmp/wifibox.stdout.log`; apart from these traces, the file should not contain any data.
Finally, the `CGI` gateway of uhttpd also uses this script, so the API can also be used to obtain stack traces by calling it as `<wifibox-ip>/cgi-bin/d3dapi/<endpoint>` (note the extra `cgi-bin`).

39
ReleaseNotes.md

@ -1,4 +1,43 @@
Changelog
# 0.10.10 (11 may 2016)
- Logging client version info to console.
- Logging less when printing to makerbot/wanhao
- Logging API time info
- Included version number file in logfiles
- Fixed stopping while sending
# 0.10.10-e (21 apr 2016)
- Fixed Makerbot end gcode that prevented prints or stopping prints to finish.
# 0.10.10-d (20 apr 2016)
- Allow print part sequence numbers to be retrieved
- Sequence numbers are send back when sending print parts
- When WiFi-Box responds that print part was already received the client will send the next part.
# 0.10.10-c (1 apr 2016)
- Quicker log rotation
# 0.10.10-b (21 mrt 2016)
- Logrotation (making sure older logs are removed)
- Improved logging.
- Always log initial printer communication
- loglite improvements, added readme
# 0.10.10-a (24 feb 2016)
- Max buffer size check: the WiFi-Box can now indicate through the API that its buffer is full and it won't accept new gcode.
- Buffer information is communicated through the API so all clients can handle this properly. The Doodle3D client will stop sending and waits until it drops below 75%. It will check this every 30 seconds.
- Improved progress indication: when sending a print the total number of lines can be added, causing the total lines reported through the API to be correct, instead of being approximated to be total lines in buffer, which keeps increasing while a print is still being sent.
- When sending print parts, sequence numbers can be added which will be checked for correctness.
- The stop button now stays enabled while still sending a print.
- Made firmware log format consistent with print3d's.
- Fixed local IP parsing pattern in firmware.
- Improved log messages and log messages formatting.
- Added loglite utility which enables filtering and coloring of logs.
- Won't attempt sign-in when in access point mode.
- More consistent error reporting from API.
- API d3dapi/printer/print's 'first' parameter has been deprecated in favor of a more descriptive 'clear' parameter.
- Support for CraftBot PLUS printer.
# 0.10.9 (11 jan 2016)
# 0.10.8 (11 jan 2016)
# 0.10.8-b (7 jan 2016)

2
extra/openwrt-build/openwrt-diffconfig-extramini

@ -22,8 +22,10 @@ CONFIG_PACKAGE_kmod-usb-serial-ftdi=y
# CONFIG_PACKAGE_libip6tc is not set
CONFIG_PACKAGE_libiwinfo=y
CONFIG_PACKAGE_libiwinfo-lua=y
CONFIG_PACKAGE_libpopt=y
CONFIG_PACKAGE_liblua=y
CONFIG_PACKAGE_libuci-lua=y
CONFIG_PACKAGE_logrotate=y
CONFIG_PACKAGE_lua=y
CONFIG_PACKAGE_luafilesystem=y
# CONFIG_PACKAGE_odhcp6c is not set

2
extra/openwrt-build/openwrt-diffconfig-mini

@ -20,8 +20,10 @@ CONFIG_PACKAGE_kmod-usb-serial-ftdi=y
# CONFIG_PACKAGE_libip6tc is not set
CONFIG_PACKAGE_libiwinfo=y
CONFIG_PACKAGE_libiwinfo-lua=y
CONFIG_PACKAGE_libpopt=y
CONFIG_PACKAGE_liblua=y
CONFIG_PACKAGE_libuci-lua=y
CONFIG_PACKAGE_logrotate=y
CONFIG_PACKAGE_lua=y
CONFIG_PACKAGE_luafilesystem=y
# CONFIG_PACKAGE_odhcp6c is not set

2
extra/openwrt-build/openwrt-diffconfig-regular

@ -9,8 +9,10 @@ CONFIG_PACKAGE_kmod-usb-serial=y
CONFIG_PACKAGE_kmod-usb-serial-ftdi=y
CONFIG_PACKAGE_libiwinfo=y
CONFIG_PACKAGE_libiwinfo-lua=y
CONFIG_PACKAGE_libpopt=y
CONFIG_PACKAGE_liblua=y
CONFIG_PACKAGE_libuci-lua=y
CONFIG_PACKAGE_logrotate=y
CONFIG_PACKAGE_lua=y
CONFIG_PACKAGE_luafilesystem=y
CONFIG_PACKAGE_print3d=y

10
extra/scripts/publish-wifibox-release.lua

@ -129,9 +129,15 @@ local function quit(ev)
end
local function md5sum(file)
-- try OS X specific md5 utility
local rv,_,sum = pl.utils.executeex('md5 -q "' .. file .. '"')
return rv and sum:sub(1, -2) or nil
if rv then
return rv and sum:sub(1, -2) or nil
end
-- try Linux md5sum utility
local rv,_,output = pl.utils.executeex('md5sum "' .. file .. '"')
local md5 = string.match(output, "[^%s]+")
return md5
end
local function getYesNo(question)

2
license-spec.lua

@ -1,6 +1,6 @@
local M = {
BASE_PATH = 'src',
EXCLUDE_FILES = { 'src/util/JSON.lua', 'src/util/urlcode.lua' },
EXCLUDE_FILES = { 'src/util/JSON.lua', 'src/util/urlcode.lua', 'src/script/loglite%-filters.lua' },
PROCESS_FILES = {
['src/[^/]*%.lua'] = 'lua',
['src/network/[^/]*%.lua'] = 'lua',

44
post-install.sh

@ -36,9 +36,9 @@ addFirewallNet() {
### Replace the banner with a custom one
if [ ! -f $IPKG_INSTROOT/etc/banner.default ]; then
mv $IPKG_INSTROOT/etc/banner $IPKG_INSTROOT/etc/banner.default
cat <<-'EOM' > $IPKG_INSTROOT/etc/banner
cat <<-\EOM > $IPKG_INSTROOT/etc/banner
........D o o d l e 3 D
.......________ _____ _____ v \$(PACKAGE_VERSION)
.......________ _____ _____
....../ / / |__ / __/ / - /___ __
...../ / / /--// _|-// --| . /v /
..../________/__//__/__//____/___/_^_\
@ -52,17 +52,23 @@ fi
mkdir -p $IPKG_INSTROOT/root
grep '^# DO NOT MODIFY.*wifibox package.$' $IPKG_INSTROOT/root/.profile >/dev/null 2>&1
if [ $? -gt 0 ]; then
cat <<-EOM >> $IPKG_INSTROOT/root/.profile
cat <<-\EOM >> $IPKG_INSTROOT/root/.profile
# DO NOT MODIFY - this block of lines has been added by the wifibox package.
alias d='ls -la'
alias d3dapi='/usr/share/lua/wifibox/script/d3dapi'
alias encore='ulimit -c unlimited'
alias wopkg='opkg -f /usr/share/lua/wifibox/opkg.conf'
alias tailfw='loglite /tmp/wifibox.log firmware'
tailp3d() {
logfile=/tmp/print3d-ttyACM0.log
if [ $# -gt 0 ]; then logfile=$1; fi
loglite "$logfile" print3d
}
loop() {
if [ \$# -lt 2 ]; then echo "Please supply a delay and a command."; return 1; fi
DELAY=\$1; shift; while true; do \$@; sleep \$DELAY; done
if [ $# -lt 2 ]; then echo "Please supply a delay and a command."; return 1; fi
DELAY=$1; shift; while true; do $@; sleep $DELAY; done
}
EOM
fi
@ -70,11 +76,11 @@ fi
#preserve saved sketches during firmware update
echo "/root/sketches" >> $IPKG_INSTROOT/etc/sysupgrade.conf
### Finally make sure basic configuration is set correctly
$IPKG_INSTROOT/etc/init.d/wifibox enable
$IPKG_INSTROOT/etc/init.d/wifibox start
$IPKG_INSTROOT/etc/init.d/dhcpcheck enable
LOGROTATE_CRON_LINE="*/2 * * * * /usr/sbin/logrotate /etc/logrotate.conf"
if [ -z "$IPKG_INSTROOT" ]; then
# No installation root, we are being installed on a live box so run uci commands directly.
@ -99,6 +105,13 @@ if [ -z "$IPKG_INSTROOT" ]; then
uci -q delete wifibox.system.loglevel # remove key used in older versions (<=0.10.8a) if it exists
uci commit wifibox
crontab -l 2> /dev/null | grep logrotate\.conf > /dev/null
if [ $? -ne 0 ]; then
# add line, method from http://askubuntu.com/a/58582
# Note: `crontab -l` will throw an error to stderr because the file does not exist, but that does not matter
(crontab -l 2> /dev/null; echo "$LOGROTATE_CRON_LINE" ) | crontab -
fi
else
# Create a script to setup the system as wifibox, it will be deleted after it has been run, except if it returns > 0.
@ -121,10 +134,23 @@ else
uci set wifibox.general.system_log_level='info'
uci -q delete wifibox.system.loglevel # remove key used in older versions (<=0.10.8a) if it exists
crontab -l 2> /dev/null | grep logrotate\.conf > /dev/null
if [ $? -ne 0 ]; then
# add line, method from http://askubuntu.com/a/58582
# Note: `crontab -l` will throw an error to stderr because the file does not exist, but that does not matter
(crontab -l 2> /dev/null; echo "$LOGROTATE_CRON_LINE" ) | crontab -
fi
exit 0
EOM
echo "WARNING: WiFiBox network configuration can only be fully prepared when installing on real device"
fi
$IPKG_INSTROOT/etc/init.d/wifibox enable
$IPKG_INSTROOT/etc/init.d/wifibox start
$IPKG_INSTROOT/etc/init.d/dhcpcheck enable
$IPKG_INSTROOT/etc/init.d/cron enable
$IPKG_INSTROOT/etc/init.d/cron start
exit 0

2
src/FIRMWARE-VERSION

@ -1 +1 @@
0.10.9
0.10.10

8
src/conf_defaults.lua

@ -36,6 +36,8 @@ M.DEBUG_PCALLS = false
--- This constant enables debugging of the REST API from the command-line by emulating GET/POST requests.
-- Specify the path and optionally the request method as follows: `d3dapi p=/mod/func r=POST`.
-- Note that the command-line script redirects the output streams to '/tmp/wifibox.stdout.log',
-- meaning that any stack traces can be found there.
M.DEBUG_API = true
--- If enabled, REST responses will contain 'module' and 'function' keys describing what was requested.
@ -131,6 +133,7 @@ M.printer_dimensions_x = {
default_colido_2_0_plus = 230,
default_colido_x3045 = 300,
default_colido_compact = 130,
default_craftbot_plus = 250,
subSection = 'printer_type',
type = 'int',
description = '',
@ -182,6 +185,7 @@ M.printer_heatedbed = {
default_colido_2_0_plus = true,
default_colido_m2020 = true,
default_colido_x3045 = true,
default_craftbot_plus = true,
subSection = 'printer_type',
type = 'bool',
description = 'Printer has heated bed',
@ -190,6 +194,7 @@ M.printer_filamentThickness = {
default = 2.89,
default_doodle_dream = 1.75,
default_wanhao_duplicator4 = 1.75,
default_craftbot_plus = 1.75,
type = 'float',
description = '',
min = 0.0,
@ -217,7 +222,7 @@ M.printer_startcode = {
description = ''
}
local default_makerbot_endcode = 'M73 P100\nG92 A0 B0 ;reset extruder position to prevent retraction\nM18 A B(Turn off A and B Steppers)\nG162 Z F900\nG162 X Y F2000\nM18 X Y Z(Turn off steppers after a build)\n{if heatedBed}M140 S{preheatBedTemp} T0\nM104 S{preheatTemp} T0\nM73 P100 (end build progress )\nM72 P1 ( Play Ta-Da song )\nM137 (build end notification)'
local default_makerbot_endcode = 'G92 A0 B0 ;reset extruder position to prevent retraction\nM18 A B(Turn off A and B Steppers)\nG162 Z F900\nG162 X Y F2000\nM18 X Y Z(Turn off steppers after a build)\n{if heatedBed}M140 S{preheatBedTemp} T0\nM104 S{preheatTemp} T0\nM72 P1 ( Play Ta-Da song )\nM137 (build end notification)'
local default_deltabot_endcode = 'M107 ;fan offG91 ;relative positioningG1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressureG1 Z+0.5 E-5 X-20 Y-20 F9000 ;move Z up a bit and retract filament even moreG28 ;move to homeM84 ;disable axes / steppersG90 ;absolute positioningM109 S0 ; hot end off{if heatedBed}M140 S{preheatBedTemp}M117 Done ;display message (20 characters to clear whole screen)'
local default_ultimaker2_endcode = 'M107 ;fan off\nG91 ;relative positioning\nG1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure\nG1 Z+5.5 E-5 X-20 Y-20 F9000 ;move Z up a bit and retract filament even more\nG28 ;home the printer\nM84 ;disable axes / steppers\nG90 ;absolute positioning\nM104 S{preheatTemp}\n{if heatedBed}M140 S{preheatBedTemp}\nM117 Done ;display message (20 characters to clear whole screen)'
M.printer_endcode = {
@ -233,6 +238,7 @@ M.printer_endcode = {
default_delta_rostockmax = default_deltabot_endcode,
default_deltamaker = default_deltabot_endcode,
default_kossel = default_deltabot_endcode,
default_craftbot_plus = 'M107 ;fan off\nG91 ;relative positioning\nG1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure\nG1 Z+0.5 E-5 X-20 Y-20 F9000 ;move Z up a bit and retract filament even more\nG28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way\nM84 ;disable axes / steppers\nG90 ;absolute positioning\nM109 S{preheatTemp}\n{if heatedBed}M140 S{preheatBedTemp}\nM117 Done ;display message (20 characters to clear whole screen)',
type = 'string',
subSection = 'printer_type',
description = ''

159
src/main.lua

@ -22,6 +22,8 @@ local netconf = require('network.netconfig')
local RequestClass = require('rest.request')
local ResponseClass = require('rest.response')
local Signin = require('network.signin')
local osUtils = require('os_utils')
-- NOTE: the updater module 'detects' command-line invocation by existence of 'arg', so we have to make sure it is not defined.
argStash = arg
@ -30,6 +32,7 @@ local updater = require('script.d3d-updater')
arg = argStash
local postData = nil
local MOD_ABBR = "ENTR"
--- Switches to wifi client mode or to access point mode based on availability of known wifi networks.
@ -48,11 +51,11 @@ local function setupAutoWifiMode()
local wifiState = wifi.getDeviceState()
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 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()
if not scanList then
@ -60,7 +63,7 @@ local function setupAutoWifiMode()
end
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 = {}, {}
for _,sn in ipairs(scanList) do
table.insert(visNet, sn.ssid)
@ -68,17 +71,17 @@ local function setupAutoWifiMode()
for _,kn in ipairs(knownSsids) do
table.insert(knownNet, kn.ssid .. "/" .. kn.mode)
end
log:info("visible networks: " .. table.concat(visNet, ", "))
log:info("known networks: " .. table.concat(knownNet, ", "))
log:info(MOD_ABBR, "visible networks: " .. table.concat(visNet, ", "))
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 netMode == 'sta' and netName ~= nil and netName ~= "" and findSsidInList(scanList, netName) then
-- signin to connect.doodle3d.com
local success, output = Signin.signin()
if success then
log:info("Signed in")
log:info(MOD_ABBR, "Signed in")
else
log:info("Signing in failed")
log:info(MOD_ABBR, "Signing in failed")
end
-- report we are connected after signin attempt
netconf.setStatus(netconf.CONNECTED,"Connected");
@ -119,41 +122,57 @@ local function setupAutoWifiMode()
end
--- Initializes the logging system to use the file and level defined in the system settings.
-- The settings used are `logfile` and `loglevel`. The former may either be a
-- reular file path, or `<stdout>` or `<stderr>`.
-- The settings used are `log_path`, `api_log_filename` from the system section and
-- `system_log_level` from the general section. The filename may either be a regular filename
-- (with an absolute log_path), or `<stdout>` or `<stderr>`.
-- TODO: also support backticks (see Logger.cpp in print3d)--
-- @see util.settings.getSystemKey
-- @treturn bool True on success, false on error.
local function setupLogger()
local logStream = io.stderr -- use stderr as hard-coded default target
local logLevel = log.LEVEL.debug -- use debug logging as hard-coded default level
local logLevel = log.LEVEL.verbose -- use verbose logging as hard-coded default level
local logTargetSetting = settings.getSystemKey('logfile')
local logLevelSetting = settings.get('system.log.level')
local logPathSetting = settings.getSystemKey('log_path')
local logTargetSetting = settings.getSystemKey('api_log_filename')
local logLevelSetting = settings.get('system_log_level')
local logTargetError, logLevelError = nil, nil
-- TEMP: for now, translate print3d log level to firmware level, these will be unfiied in the future
-- we get (print3d): quiet,error,warning,info,verbose,bulk -- and we need (firmware): debug,info,warn,error,fatal
logLevelMapping = { quiet='fatal', error='error', warning='warn', info='warn', verbose='info', bulk='debug' }
logLevelSetting = logLevelMapping[logLevelSetting]
if type(logTargetSetting) == 'string' then
local specialTarget = logTargetSetting:match('^<(.*)>$')
if specialTarget then
if specialTarget == 'stdout' then logStream = io.stdout
elseif specialTarget == 'stderr' then logStream = io.stderr
local streamTarget = logTargetSetting:match('^<(.*)>$')
local popenTarget = logTargetSetting:match('^`(.*)`$')
if streamTarget then
if streamTarget:lower() == 'stdout' then logStream = io.stdout
elseif streamTarget:lower() == 'stderr' then logStream = io.stderr
end
elseif logTargetSetting:sub(1, 1) == '/' then
local f,msg = io.open(logTargetSetting, 'a+')
elseif popenTarget then
local f,msg = io.popen(popenTarget, 'w')
if f then logStream = f
else logTargetError = msg
end
elseif logPathSetting:sub(1, 1) == '/' then
local path = logPathSetting .. '/' .. logTargetSetting
local f,msg = io.open(path, 'a+')
if f then
logStream = f
log:setLogFilePath(path)
else
logTargetError = msg
end
else
logTargetError = "log file path is not absolute"
end
else
-- if uci config not available, fallback to /tmp/wifibox.log
local f,msg = io.open('/tmp/wifibox.log', 'a+')
if f then logStream = f
else logTargetError = msg
local path = '/tmp/wifibox.log'
local f,msg = io.open(path, 'a+')
if f then
logStream = f
log:setLogFilePath(path)
else
logTargetError = msg
end
end
@ -173,12 +192,12 @@ local function setupLogger()
local rv = true
if logTargetError then
log:error("could not open logfile '" .. logTargetSetting .. "', using stderr as fallback (" .. logTargetError .. ")")
log:error(MOD_ABBR, "could not open logfile '" .. logPathSetting .. '/' .. logTargetSetting .. "', using stderr as fallback (" .. logTargetError .. ")")
rv = false
end
if logLevelError then
log:error("uci config specifies invalid log level '" .. logLevelSetting .. "', using debug level as fallback")
log:error(MOD_ABBR, "uci config specifies invalid log level '" .. logLevelSetting .. "', using verbose level as fallback")
rv = false
end
@ -189,17 +208,6 @@ end
-- The logger is set up, any POST data is read and several other subsystems are initialized.
-- @tparam table environment The 'shell' environment containing all CGI variables. Note that @{cmdmain} simulates this.
local function init(environment)
setupLogger()
local dbgText = ""
if confDefaults.DEBUG_API and confDefaults.DEBUG_PCALLS then dbgText = "pcall+api"
elseif confDefaults.DEBUG_API then dbgText = "api"
elseif confDefaults.DEBUG_PCALL then dbgText = "pcall"
end
if dbgText ~= "" then dbgText = " (" .. dbgText .. " debugging)" end
log:info("=======rest api" .. dbgText .. "=======")
if (environment['REQUEST_METHOD'] == 'POST') then
local n = tonumber(environment['CONTENT_LENGTH'])
postData = io.read(n)
@ -222,50 +230,47 @@ local function main(environment)
local rq = RequestClass.new(environment, postData, confDefaults.DEBUG_API)
if rq:getRequestMethod() == 'CMDLINE' and rq:get('autowifi') ~= nil then
local version = updater.formatVersion(updater.getCurrentVersion());
log:info("Doodle3D version: "..util.dump(version))
log:info("running in autowifi mode")
log:info(MOD_ABBR, "Doodle3D version: "..util.dump(version))
log:info(MOD_ABBR, "Running in autowifi mode")
local rv,msg = setupAutoWifiMode()
if rv then
log:info("autowifi setup done (" .. msg .. ")")
log:info(MOD_ABBR, "Autowifi setup done (" .. msg .. ")")
else
log:error("autowifi setup failed (" .. msg .. ")")
log:error(MOD_ABBR, "Autowifi setup failed (" .. msg .. ")")
end
elseif rq:getRequestMethod() == 'CMDLINE' and rq:get('signin') ~= nil then
log:info("running in signin mode")
local ds = wifi.getDeviceState()
log:info(" ds.mode: "..util.dump(ds.mode))
if ds.mode == "sta" then
log:info(" attempting signin")
local success,msg = Signin.signin()
if success then
log:info("Signin successful")
else
log:info("Signin failed: "..util.dump(msg))
end
log:info(MOD_ABBR, "Running in signin mode")
log:info(MOD_ABBR, " attempting signin")
local success,msg = Signin.signin()
if success then
log:info(MOD_ABBR, "Signin successful")
else
log:warning(MOD_ABBR, "Signin failed: "..util.dump(msg))
end
elseif rq:getRequestMethod() ~= 'CMDLINE' or confDefaults.DEBUG_API then
-- log:info("received request of type " .. rq:getRequestMethod() .. " for " .. (rq:getRequestedApiModule() or "<unknown>")
-- .. "/" .. (rq:getRealApiFunctionName() or "<unknown>") .. " with arguments: " .. util.dump(rq:getAll()))
log:info("received request of type " .. rq:getRequestMethod() .. " for " .. (rq:getRequestedApiModule() or "<unknown>")
.. "/" .. (rq:getRealApiFunctionName() or "<unknown>"))
-- Note: the commented log message will print too many data if it's for instance dumping a gcode add request
--logMessage = "received request of type " .. rq:getRequestMethod() .. " for " .. (rq:getRequestedApiModule() or "<unknown>")
-- .. "/" .. (rq:getRealApiFunctionName() or "<unknown>") .. " with arguments: " .. util.dump(rq:getAll())
logMessage = rq:getRequestMethod() .. " request for " .. (rq:getRequestedApiModule() or "<unknown>")
.. "/" .. (rq:getRealApiFunctionName() or "<unknown>")
if rq:getRequestMethod() ~= 'CMDLINE' then
log:info("remote IP/port: " .. rq:getRemoteHost() .. "/" .. rq:getRemotePort())
--log:debug("user agent: " .. rq:getUserAgent())
logMessage = logMessage .. " (remote IP/port: " .. rq:getRemoteHost() .. "/" .. rq:getRemotePort() .. ")"
--logMessage = logMessage .. " (user agent: " .. rq:getUserAgent() .. ")"
end
log:info(MOD_ABBR, logMessage)
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:executePostResponseQueue()
response:executePostResponseQueue()
else
log:info("Nothing to do...bye.\n")
log:info(MOD_ABBR, "Nothing to do...bye.\n")
end
end
@ -278,6 +283,22 @@ end
-- @tparam table env The CGI environment table.
-- @treturn number A Z+ return value suitable to return from wrapper script. Note that this value is ignored by uhttpd-mod-lua.
function handle_request(env)
local function constructDebugText()
local dbgText = ""
if confDefaults.DEBUG_API and confDefaults.DEBUG_PCALLS then dbgText = "pcall+api"
elseif confDefaults.DEBUG_API then dbgText = "api"
elseif confDefaults.DEBUG_PCALL then dbgText = "pcall"
end
if dbgText ~= "" then dbgText = " (" .. dbgText .. " debugging)" end
return dbgText
end
setupLogger()
local pid = osUtils.getPID()
local beginSecs, beginUSecs = osUtils.getTime()
log:verbose(MOD_ABBR, "START-RQ with PID=" .. pid .. constructDebugText())
local s, msg = init(env)
if s == false then
@ -286,11 +307,13 @@ function handle_request(env)
resp:setError("initialization failed" .. errSuffix)
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)
return 1
else
main(env)
local elapsed,msg = osUtils.getElapsedTime(beginSecs, beginUSecs)
log:bulk(MOD_ABBR, "END-RQ with PID=" .. pid .. " completed in " .. elapsed .. " msec")
return 0
end
end

124
src/network/netconfig.lua

@ -18,6 +18,8 @@ local reconf = {}
local wifi
local reloadSilent
local MOD_ABBR = "NTCF"
M.WWW_CAPTIVE_PATH = '/usr/share/lua/wifibox/www'
M.WWW_CAPTIVE_INDICATOR = '/www/.wifibox-inplace'
M.WWW_RENAME_NAME = '/www-regular'
@ -25,9 +27,9 @@ M.WWW_RENAME_NAME = '/www-regular'
M.CONNECTING_FAILED = -1
M.NOT_CONNECTED = 0
M.CONNECTING = 1
M.CONNECTED = 2
M.CREATING = 3
M.CREATED = 4
M.CONNECTED = 2
M.CREATING = 3
M.CREATED = 4
local function reloadBit(dlist, itemname)
if dlist[itemname] == nil then dlist[itemname] = '' end
@ -62,10 +64,10 @@ function M.switchConfiguration(components)
for k,v in pairs(components) do
local fname = k .. '_' .. v
if type(reconf[fname]) == 'function' then
log:debug("reconfiguring component '" .. k .. "' (" .. v .. ")")
log:verbose(MOD_ABBR, "reconfiguring component '" .. k .. "' (" .. v .. ")")
reconf[fname](dirtyList)
else
log:warn("unknown component or action '" .. fname .. "' skipped")
log:warning(MOD_ABBR, "unknown component or action '" .. fname .. "' skipped")
end
end
@ -79,20 +81,20 @@ function M.switchConfiguration(components)
end
function M.commitComponent(c)
log:info("committing component '" .. c .. "'")
log:verbose(MOD_ABBR, "committing component '" .. c .. "'")
uci:commit(c)
end
function M.reloadComponent(c, silent)
log:info("reloading component '" .. c .. "'")
log:verbose(MOD_ABBR, "reloading component '" .. c .. "'")
local command = 'reload'
local cmd = '/etc/init.d/' .. c .. ' '..command
if silent ~= nil and silent then
if silent ~= nil and silent then
cmd = cmd .. ' &> /dev/null'
os.execute(cmd)
else
rv = utils.captureCommandOutput(cmd)
log:debug(" 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
@ -147,7 +149,7 @@ function reconf.apnet_rm(dirtyList)
uci:foreach('wireless', 'wifi-iface', function(s)
if s.ssid == wifi.getSubstitutedSsid(settings.get('network.ap.ssid')) then sname = s['.name']; return false 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)
reloadBit(dirtyList, 'network'); commitBit(dirtyList, 'wireless')
end
@ -212,15 +214,15 @@ end
function reconf.dnsredir_add(dirtyList)
local redirText = '/#/' .. settings.get('network.ap.address')
local sname = utils.getUciSectionName('dhcp', 'dnsmasq')
if sname == nil then return log:error("dhcp config does not contain a dnsmasq section") end
if uci:get('dhcp', sname, 'address') ~= nil then return log:debug("DNS address redirection already in place, not re-adding", false) 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:info(MOD_ABBR, "DNS address redirection already in place, not re-adding", false) end
uci:set('dhcp', sname, 'address', {redirText})
commitBit(dirtyList, 'dhcp'); reloadBit(dirtyList, 'dnsmasq')
end
function reconf.dnsredir_rm(dirtyList)
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')
commitBit(dirtyList, 'dhcp'); reloadBit(dirtyList, 'dnsmasq')
@ -230,21 +232,21 @@ end
--TODO: handle os.rename() return values (nil+msg on error)
function reconf.wwwcaptive_add(dirtyList)
if utils.exists(M.WWW_CAPTIVE_INDICATOR) then
return log:debug("WWW captive directory already in place, not redoing", false)
return log:info(MOD_ABBR, "WWW captive directory already in place, not redoing", false)
end
local rv,reason = os.rename('/www', M.WWW_RENAME_NAME)
if rv == true then
utils.symlink(M.WWW_CAPTIVE_PATH, '/www')
return true
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
function reconf.wwwcaptive_rm(dirtyList)
if not utils.exists(M.WWW_CAPTIVE_INDICATOR) then return log:debug("WWW captive directory not in place, not undoing", false) end
if not utils.exists(M.WWW_CAPTIVE_INDICATOR) then return log:info(MOD_ABBR, "WWW captive directory not in place, not undoing", false) end
os.remove('/www')
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
return true
end
@ -275,33 +277,35 @@ end
-- @return True on success or nil+msg on error.
function M.setupAccessPoint(ssid)
M.setStatus(M.CREATING,"Creating access point '"..ssid.."'...");
-- add access point configuration
-- add access point configuration
M.switchConfiguration({apnet="add_noreload"})
wifi.activateConfig(ssid)
-- NOTE: dnsmasq must be reloaded after network or it will be unable to serve IP addresses
M.switchConfiguration({ wifiiface="add", network="reload", staticaddr="add", dhcppool="add_noreload", wwwredir="add", dnsredir="add" })
M.switchConfiguration({dhcp="reload"})
M.setStatus(M.CREATED,"Access point created");
local ds = wifi.getDeviceState()
--log:info(" network/status: ")
log:info(" ssid: ".. utils.dump(ds.ssid))
--[[log:info(" bssid: ".. utils.dump(ds.bssid))
log:info(" channel: ".. utils.dump(ds.channel))
log:info(" mode: ".. utils.dump(ds.mode))
log:info(" encryption: ".. utils.dump(ds.encryption))
log:info(" quality: ".. utils.dump(ds.quality))
log:info(" quality_max: ".. utils.dump(ds.quality_max))
log:info(" txpower: ".. utils.dump(ds.txpower))
log:info(" signal: ".. utils.dump(ds.signal))
log:info(" noise: ".. utils.dump(ds.noise))
log:info(" raw: ".. utils.dump(ds))
--log:info(MOD_ABBR, " network/status: ")
log:info(MOD_ABBR, " ssid: ".. utils.dump(ds.ssid))
--[[
log:info(MOD_ABBR, " bssid: ".. utils.dump(ds.bssid))
log:info(MOD_ABBR, " channel: ".. utils.dump(ds.channel))
log:info(MOD_ABBR, " mode: ".. utils.dump(ds.mode))
log:info(MOD_ABBR, " encryption: ".. utils.dump(ds.encryption))
log:info(MOD_ABBR, " quality: ".. utils.dump(ds.quality))
log:info(MOD_ABBR, " quality_max: ".. utils.dump(ds.quality_max))
log:info(MOD_ABBR, " txpower: ".. utils.dump(ds.txpower))
log:info(MOD_ABBR, " signal: ".. utils.dump(ds.signal))
log:info(MOD_ABBR, " noise: ".. utils.dump(ds.noise))
log:info(MOD_ABBR, " raw: ".. utils.dump(ds))
local localip = wifi.getLocalIP()
log:info(" localip: "..utils.dump(localip))]]--
log:info(MOD_ABBR, " localip: "..utils.dump(localip))
--]]
return true
end
@ -311,14 +315,14 @@ end
-- @tparam string ssid The SSID to use for the access point.
-- @return True on success or nil+msg on error.
function M.enableAccessPoint(ssid)
log:debug("enableAccessPoint ssid: ".. utils.dump(ssid))
log:info(MOD_ABBR, "enableAccessPoint ssid: ".. utils.dump(ssid))
M.switchConfiguration{apnet="add_noreload"}
wifi.activateConfig(ssid)
local ds = wifi.getDeviceState()
log:debug(" ssid: ".. utils.dump(ds.ssid))
log:info(MOD_ABBR, " deviceState.ssid: ".. utils.dump(ds.ssid))
return true
end
@ -330,9 +334,9 @@ 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.
-- @return True on success or nil+msg on error.
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...");
-- see if previously configured network for given ssid exists
local cfg = nil
for _, net in ipairs(wifi.getConfigs()) do
@ -341,7 +345,7 @@ function M.associateSsid(ssid, passphrase, recreate)
break
end
end
-- if not, or if newly created configuration is requested, create a new configuration
if cfg == nil or recreate ~= nil then
local scanResult, msg = wifi.getScanInfo(ssid)
@ -365,16 +369,16 @@ function M.associateSsid(ssid, passphrase, recreate)
--M.switchConfiguration{ wifiiface="add", apnet="rm", staticaddr="rm", dhcppool="rm", wwwredir="rm", dnsredir="rm", wireless="reload" }
--M.switchConfiguration{ wifiiface="add", staticaddr="rm", dhcppool="rm", wwwredir="rm", dnsredir="rm", wireless="reload" }
M.switchConfiguration({ wifiiface="add", staticaddr="rm", dhcppool="rm", wwwredir="rm", dnsredir="rm" })
-- we check if we get a ssid and ip in max 5 seconds
-- if not there is probably a issue
-- if not there is probably a issue
local attemptInterval = 1
local maxAttempts = 5
local attempt = 0
local nextAttemptTime = os.time()
while true do
if os.time() > nextAttemptTime then
log:debug("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
break
else
@ -390,20 +394,22 @@ function M.associateSsid(ssid, passphrase, recreate)
end
end
end
log:info(MOD_ABBR, "Network associated")
-- signin to connect.doodle3d.com
local success, output = signin.signin()
if success then
log:info("Signed in")
else
log:info("Signing in failed")
log:info(MOD_ABBR, "Signed in")
else
log:info(MOD_ABBR, "Signing in failed")
end
-- report we are connected after signin attempt
M.setStatus(M.CONNECTED,"Connected");
return true
end
--- Disassociate wlan device as client from all SSID's.
-- Note: this function might belong in the wlanconfig module but that would introduce
-- a circular dependency, easiest solution is to place the function here.
@ -411,30 +417,28 @@ end
function M.disassociate()
M.setStatus(M.NOT_CONNECTED,"Not connected");
wifi.activateConfig()
return wifi.restart()
end
function M.getStatus()
log:info("network:getStatus")
log:verbose(MOD_ABBR, "network:getStatus")
local file, error = io.open('/tmp/networkstatus.txt','r')
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 "",""
else
local status = file:read('*a')
--log:info(" status: "..utils.dump(status))
file:close()
local code, msg = string.match(status, '([^|]+)|+(.*)')
--log:info(" code: "..utils.dump(code))
--log:info(" msg: "..utils.dump(msg))
log:verbose(MOD_ABBR, " raw status: "..utils.dump(status).." (code: "..utils.dump(code)..", msg: "..utils.dump(msg)..")")
return code,msg
end
end
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')
file:write(code.."|"..msg)
file:flush()

45
src/network/signin.lua

@ -20,6 +20,7 @@ local status = require('util.status')
local M = {}
local STATUS_FILE = "signinstatus"
local MOD_ABBR = "NTSI"
local IDLE_STATUS = 1
local SIGNING_IN_STATUS = 2
@ -27,55 +28,61 @@ local SIGNING_IN_STATUS = 2
--- Signin to connect.doodle3d.com server
--
function M.signin()
--log:debug("signin:signin");
log:verbose(MOD_ABBR, "signin:signin");
local code, msg = M.getStatus()
--log:debug(" 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(code == SIGNING_IN_STATUS) then
log:debug(" skipping signin")
log:verbose(MOD_ABBR, " already signing in, skipping")
return
end
local ds = wifi.getDeviceState()
log:verbose(MOD_ABBR, " wifi deviceState.mode: "..utils.dump(ds.mode))
if ds.mode ~= "sta" then
log:verbose(MOD_ABBR, " wifi not in station mode, skipping signin")
return
end
M.setStatus(SIGNING_IN_STATUS,"signing in")
local baseurl = "http://connect.doodle3d.com/api/signin.php"
local attemptInterval = 1
local maxAttempts = 20
local attempt = 0
local nextAttemptTime = os.time()
local localip = ""
local signinResponse = ""
while true do
if os.time() > nextAttemptTime then
log:debug("signin attempt "..utils.dump(attempt).."/"..utils.dump(maxAttempts))
log:verbose(MOD_ABBR, " signin attempt "..utils.dump(attempt).."/"..utils.dump(maxAttempts))
local signedin = false
local localip = wifi.getLocalIP();
--log:debug(" localip: "..utils.dump(localip))
--log:verbose(MOD_ABBR, " localip: "..utils.dump(localip))
if localip ~= nil then
local wifiboxid = wifi.getSubstitutedSsid(settings.get('network.cl.wifiboxid'))
wifiboxid = urlcode.escape(wifiboxid)
local cmd = "wget -q -T 2 -t 1 -O - "..baseurl.."?wifiboxid="..wifiboxid.."\\&localip="..localip;
signinResponse = utils.captureCommandOutput(cmd);
log:debug(" signin response: \n"..utils.dump(signinResponse))
log:verbose(MOD_ABBR, " signin response: \n"..utils.dump(signinResponse))
local success = signinResponse:match('"status":"success"')
log:debug(" success: "..utils.dump(success))
log:verbose(MOD_ABBR, " success: "..utils.dump(success))
if success ~= nil then
signedin = true
else
log:warn("signin failed request failed (response: "..utils.dump(signinResponse)..")")
log:warning(MOD_ABBR, "signin failed, request failed (response: "..utils.dump(signinResponse)..")")
end
else
log:warn("signin failed no local ip found (attempt: "..utils.dump(attempt).."/"..utils.dump(maxAttempts)..")")
else
log:warning(MOD_ABBR, "signin failed, no local ip found (attempt: "..utils.dump(attempt).."/"..utils.dump(maxAttempts)..")")
end
if signedin then
break
else
@ -90,7 +97,7 @@ function M.signin()
end
end
end
M.setStatus(IDLE_STATUS,"idle")
return string.len(signinResponse) > 0, signinResponse
end
@ -100,7 +107,7 @@ function M.getStatus()
end
function M.setStatus(code,msg)
log:info("signin:setStatus: "..code.." | "..msg)
log:verbose(MOD_ABBR, "signin:setStatus: " .. code .. " (" .. msg .. ")")
status.set(STATUS_FILE,code,msg);
end

38
src/network/wlanconfig.lua

@ -13,6 +13,8 @@ local iwinfo = require('iwinfo')
local M = {}
local MOD_ABBR = "NTWL"
-- NOTE: fallback device 'radio0' is required because sometimes the wlan0 device disappears
M.DFL_DEVICE = 'wlan0'
M.DFL_DEVICE_FALLBACK = 'radio0'
@ -25,12 +27,12 @@ local deviceName, deviceApi
local cachedApSsid, baseApSsid = nil, nil
function M.getSubstitutedSsid(unformattedSsid)
log:debug("getSubstitutedSsid unformattedSsid:'" .. (unformattedSsid or "nil") .. "' baseApSsid:'" .. (baseApSsid or "nil") .. "' cachedApSsid:'" .. (cachedApSsid or "nil"))
log:verbose(MOD_ABBR, "getSubstitutedSsid unformattedSsid:'" .. (unformattedSsid or "nil") .. "' baseApSsid:'" .. (baseApSsid or "nil") .. "' cachedApSsid:'" .. (cachedApSsid or "nil"))
if unformattedSsid == baseApSsid and cachedApSsid ~= nil then return cachedApSsid end
if not unformattedSsid or type(unformattedSsid) ~= 'string' then return nil end
local macTail = M.getMacAddress():sub(7)
log:debug(" macTail:'" .. macTail)
log:verbose(MOD_ABBR, " macTail:'" .. macTail)
baseApSsid = unformattedSsid
cachedApSsid = unformattedSsid:gsub('%%%%MAC_ADDR_TAIL%%%%', macTail)
return cachedApSsid
@ -75,7 +77,7 @@ function M.init(device)
deviceName = M.DFL_DEVICE_FALLBACK
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
return false, "No such wireless device: '" .. devInitial .. "' (and fallback '" .. deviceName .. "' does not exist either)"
@ -107,9 +109,9 @@ end
--returns the wireless device's MAC address (as string, without colons)
--(lua numbers on openWrt seem to be 32bit so they cannot represent a MAC address as one number)
function M.getMacAddress()
log:debug("getMacAddress")
log:verbose(MOD_ABBR, "getMacAddress")
local macText = utils.readFile('/sys/class/net/' .. deviceName .. '/address')
log:debug(" macText: '" .. (macText or "nil") .. "'")
log:verbose(MOD_ABBR, " macText: '" .. (macText or "nil") .. "'")
local out = ''
-- Hack to prevent failure in case the MAC address could not be obtained.
@ -126,9 +128,10 @@ end
--returns the wireless local ip address
function M.getLocalIP()
local ifconfig, rv = utils.captureCommandOutput("ifconfig wlan0");
--log:debug(" ifconfig: \n"..utils.dump(ifconfig));
local localip = ifconfig:match('inet addr:([%d\.]+)')
return localip;
log:bulk(MOD_ABBR, " ifconfig: \n"..utils.dump(ifconfig));
local localip = ifconfig:match('inet addr:([%d%.]+)')
return localip
end
function M.getDeviceName()
@ -140,9 +143,9 @@ end
-- @return data for all or requested network; false+error on failure or nil when requested network not found
function M.getScanInfo(ssid)
local iw = iwinfo[deviceApi]
log:info("start wifi scan")
log:info(MOD_ABBR, "start wifi scan")
local sr = iw.scanlist(deviceName)
log:info("wifi scan done")
log:info(MOD_ABBR, "wifi scan done")
local si, se
if ssid == nil then
@ -186,12 +189,12 @@ end
--- Activate wireless section for given SSID and disable all others
-- @param ssid SSID of config to enable, or nil to disable all network configs
function M.activateConfig(ssid)
--log:info("wlanconfig.activateConfig: "..ssid);
log:verbose(MOD_ABBR, "wlanconfig.activateConfig: "..ssid);
-- make sure only one is enabled
uci:foreach('wireless', 'wifi-iface', function(s)
local disabled = s.ssid ~= ssid and '1' or '0'
--log:info(" "..utils.dump(s.ssid).." disable: "..utils.dump(disabled))
log:verbose(MOD_ABBR, " ssid: "..utils.dump(s.ssid).." disabled: "..utils.dump(disabled))
uci:set('wireless', s['.name'], 'disabled', disabled)
end)
@ -209,11 +212,14 @@ function M.activateConfig(ssid)
return false
end
end)
--[[log:info(" result:");
--[[
log:verbose(MOD_ABBR, " wifi reorder result:");
uci:foreach('wireless', 'wifi-iface', function(s)
local disabled = s.ssid ~= ssid and '1' or '0'
log:info(" "..utils.dump(s.ssid).." disable: "..utils.dump(disabled))
end)]]--
log:verbose(MOD_ABBR, " ssid: "..utils.dump(s.ssid).." disabled: "..utils.dump(disabled))
end)
--]]
uci:commit('wireless')
end
@ -241,7 +247,7 @@ function M.createConfigFromScanInfo(info, passphrase, disabled)
uci:foreach('wireless', 'wifi-iface', function(s)
--if s.bssid == info.bssid then
if s.ssid == info.ssid then
log:debug("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'])
-- return false --keep looking, just in case multiple entries with this bssid exist
end

16
src/rest/api/api_config.lua

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

77
src/rest/api/api_info.lua

@ -16,11 +16,19 @@ local printerAPI = require('rest.api.api_printer')
local wifi = require('network.wlanconfig')
local settings = require('util.settings')
local MOD_ABBR = "AINF"
local TMP_DIR = '/tmp'
local LOG_COLLECT_DIRNAME = 'wifibox-logs'
local LOG_COLLECT_DIR = TMP_DIR .. '/' .. LOG_COLLECT_DIRNAME
local WIFIBOX_LOG_FILENAME = 'wifibox.log'
local WIFIBOX_LOG_FILE = TMP_DIR .. '/' .. WIFIBOX_LOG_FILENAME
local DEFAULT_WIFIBOX_LOG_FILENAME = 'wifibox.log'
local DEFAULT_WIFIBOX_LOG_FILE = TMP_DIR .. '/' .. DEFAULT_WIFIBOX_LOG_FILENAME
local WIFIBOX_STDOUT_LOG_FILENAME = 'wifibox.stdout.log'
local WIFIBOX_STDOUT_LOG_FILE = TMP_DIR .. '/' .. WIFIBOX_STDOUT_LOG_FILENAME
local WIFIBOX_VERSION_FILENAME = 'wifibox-version'
local WIFIBOX_VERSION_FILE = '/etc/' .. WIFIBOX_VERSION_FILENAME
local ROTATED_LOGS_DIRNAME = 'wifibox-rotated'
local ROTATED_LOGS_DIR = TMP_DIR .. '/' .. ROTATED_LOGS_DIRNAME
local SYSLOG_FILENAME = 'syslog'
local PROCESS_LIST_FILENAME = 'processes'
@ -34,7 +42,7 @@ local USB_DIRTREE_COMMAND = "ls -R /sys/devices/platform/ehci-platform/usb1 | gr
local USB_DIRTREE_FILENAME = 'sys_devices_platform_ehci-platform_usb1.tree'
local PRINT3D_BASEPATH = '/tmp'
local PRINT3D_LOG_FILENAME_PREFIX = 'print3d-'
local PRINT3D_LOG_FILENAME_PREFIX = 'print3d.'
local PRINT3D_LOG_FILENAME_SUFFIX = '.log'
local LOG_COLLECT_ARCHIVE_FILENAME = LOG_COLLECT_DIRNAME .. '.tgz'
local LOG_COLLECT_ARCHIVE_FILE = TMP_DIR .. '/' .. LOG_COLLECT_ARCHIVE_FILENAME
@ -50,10 +58,10 @@ local M = {
-- returns wifiboxid (since version 0.10.2)
function M._global(request, response)
response:setSuccess()
local wifiboxid = wifi.getSubstitutedSsid(settings.get('network.cl.wifiboxid'))
response:addData('wifiboxid', wifiboxid)
end
-- TODO: redirect stdout+stderr; handle errors
@ -63,11 +71,34 @@ function M.logfiles(request, response)
rv,msg = lfs.mkdir(LOG_COLLECT_DIR)
rv,msg = lfs.chdir(TMP_DIR)
local wifiboxLogFilePath = log:getLogFilePath()
local wifiboxLogFileName = wifiboxLogFilePath and wifiboxLogFilePath:match('.*/(.*)')
--[[ create temporary files ]]--
-- copy wifibox API-script log
rv,sig,code = redirectedExecute('cp ' .. WIFIBOX_LOG_FILE .. ' ' .. LOG_COLLECT_DIR)
-- copy wifibox API-script (firmware) log
lfs.link(wifiboxLogFilePath, LOG_COLLECT_DIR .. '/' .. wifiboxLogFileName)
-- copy d3dapi script stdout/stderr (fallback) log
lfs.link(WIFIBOX_STDOUT_LOG_FILE, LOG_COLLECT_DIR .. '/' .. WIFIBOX_STDOUT_LOG_FILENAME)
-- collect and copy print3d server logs
for file in lfs.dir(PRINT3D_BASEPATH) do
if file:find(PRINT3D_LOG_FILENAME_PREFIX) == 1 and file:find(PRINT3D_LOG_FILENAME_SUFFIX) ~= nil then
local srcLogFile = PRINT3D_BASEPATH .. '/' .. file
local tgtLogFile = LOG_COLLECT_DIR .. '/' .. file
lfs.link(srcLogFile, tgtLogFile)
end
end
-- copy rotated firmware and print3d logs
rv,msg = lfs.mkdir(LOG_COLLECT_DIR .. '/' .. ROTATED_LOGS_DIRNAME)
for file in lfs.dir(ROTATED_LOGS_DIR) do
local srcLogFile = ROTATED_LOGS_DIR .. '/' .. file
local tgtLogFile = LOG_COLLECT_DIR .. '/' .. ROTATED_LOGS_DIRNAME .. '/' .. file
lfs.link(srcLogFile, tgtLogFile)
end
-- capture syslog
rv,sig,code = os.execute('logread > ' .. LOG_COLLECT_DIR .. '/' .. SYSLOG_FILENAME)
@ -87,7 +118,10 @@ function M.logfiles(request, response)
-- list directory structure for primary USB controller
rv,sig,code = os.execute(USB_DIRTREE_COMMAND .. ' > ' .. LOG_COLLECT_DIR .. '/' .. USB_DIRTREE_FILENAME)
rv,sig,code = redirectedExecute('cp ' .. WIFIBOX_VERSION_FILE .. ' ' .. LOG_COLLECT_DIR)
-- copy relevant openwrt configuration files
-- Note: we cannot link them because that would require the link to span over filesystems
rv,msg = lfs.mkdir(LOG_COLLECT_DIR .. '/config')
for _,v in pairs(UCI_CONFIG_FILES_TO_SAVE) do
local srcFile = '/etc/config/' .. v
@ -95,19 +129,12 @@ function M.logfiles(request, response)
if v ~= 'wireless' then
rv,sig,code = redirectedExecute('cp ' .. srcFile .. ' ' .. tgtFile)
else
-- replace WiFi passwords with '...'
rv,sig,code = os.execute("sed \"s/option key '.*'/option key '...'/g\" " .. srcFile .. " > " .. tgtFile)
end
end
-- collect and copy print3d server logs
for file in lfs.dir(PRINT3D_BASEPATH) do
if file:find(PRINT3D_LOG_FILENAME_PREFIX) == 1 and file:find(PRINT3D_LOG_FILENAME_SUFFIX) ~= nil then
local srcLogFile = PRINT3D_BASEPATH .. '/' .. file
local tgtLogFile = LOG_COLLECT_DIR .. '/' .. file
rv,sig,code = redirectedExecute('cp ' .. srcLogFile .. ' ' .. tgtLogFile)
end
end
-- create tar.gz archive of the files/data we collected
rv,sig,code = redirectedExecute('tar czf ' .. LOG_COLLECT_ARCHIVE_FILE .. ' ' .. LOG_COLLECT_DIRNAME) --returns 0 success, 1 error
@ -133,13 +160,19 @@ function M.logfiles(request, response)
rv,sig,code = redirectedExecute('rm ' .. LOG_COLLECT_DIR .. '/config/*')
rv,msg = lfs.rmdir(LOG_COLLECT_DIR .. '/config'