diff --git a/.github/ci/install-esp8266.sh b/.github/ci/install-esp8266.sh index 15112737..431d0a4d 100644 --- a/.github/ci/install-esp8266.sh +++ b/.github/ci/install-esp8266.sh @@ -7,7 +7,7 @@ shopt -s globstar cd $HOME/arduino_ide/hardware mkdir esp8266com cd esp8266com -git clone -b 3.0.2 https://github.com/esp8266/Arduino.git esp8266 +git clone -b 3.1.1 https://github.com/esp8266/Arduino.git esp8266 cd esp8266 git submodule update --init cd tools diff --git a/docs/Commands.md b/docs/Commands.md index ae5bbb3c..339b52c0 100644 --- a/docs/Commands.md +++ b/docs/Commands.md @@ -74,7 +74,7 @@ The json format is `[ESP131] json= pwd=` * Sync / Set / Get current time - `[ESP140] json= pwd=` + `[ESP140] json= pwd=` * Get/Set display/set boot delay in ms / Verbose boot `[ESP150]pwd=` @@ -183,7 +183,7 @@ label can be: light/framesize/quality/contrast/brightness/saturation/gainceiling ESP_NOTIFICATION_TOKEN2 396 //64 bytes 63+1 = string ; warning does not support multibyte char like chinese ESP_SENSOR_TYPE 460 //1 bytes = flag ESP_TARGET_FW 461 //1 bytes = flag - ESP_TIMEZONE 462 //1 bytes = flag + ESP_FREE 462 //1 bytes = flag ESP_TIME_IS_DST 463 //1 bytes = flag ESP_TIME_SERVER1 464 //129 bytes 128+1 = string ; warning does not support multibyte char like chinese ESP_TIME_SERVER2 593 //129 bytes 128+1 = string ; warning does not support multibyte char like chinese @@ -216,6 +216,7 @@ label can be: light/framesize/quality/contrast/brightness/saturation/gainceiling ESP_SERIAL_BRIDGE_ON 1036 //1 byte = flag ESP_SERIAL_BRIDGE_FLAG 1037 //1 byte = flag ESP_SERIAL_BRIDGE_BAUD 1038 //4 bytes= int + ESP_TIME_ZONE 1042 //7 bytes= string ``` * Get/Set Check update at boot state which can be ON, OFF @@ -287,7 +288,7 @@ label can be: light/framesize/quality/contrast/brightness/saturation/gainceiling `[ESP790]= json= pwd=` * FW Informations - `[ESP800]json= pwd= ` + `[ESP800]json= pwd= ` * Get state / Set Enable / Disable Serial Communication `[ESP900] json= pwd=` diff --git a/docs/esp3dcnf.ini b/docs/esp3dcnf.ini index 5fec3b16..644a4c6a 100644 --- a/docs/esp3dcnf.ini +++ b/docs/esp3dcnf.ini @@ -119,8 +119,8 @@ Time_server1 = 1.pool.ntp.org Time_server2 = 2.pool.ntp.org Time_server3 = 3.pool.ntp.org -#time zone -12~12 -Time_zone = 2 +#time zone -12~14 +Time_zone = +00:00 #is DST Yes/No Time_DST = No diff --git a/docs/espXXX.md b/docs/espXXX.md new file mode 100644 index 00000000..94537c32 --- /dev/null +++ b/docs/espXXX.md @@ -0,0 +1,1683 @@ ++++ +archetype = "section" +title = "[ESP100]" +weight = 800 ++++ + +Set / Display Station SSID + +## Input +`[ESP100] json= pwd=` +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* SSID + * if SSID is empty, it will display current SSID + * if SSID is not empty, it will set the SSID + +## Output + +- In json format + +```json +{ + "cmd":"100", + "status":"ok", + "data":"esp3d" +} +``` +* `cmd` Id of requested command, should be `100` +* `status` status of command, should be `ok` +* `data` content of response, here the SSID + + ++++ +archetype = "section" +title = "[ESP101]" +weight = 800 ++++ +Set Station Password + +## Input +`[ESP101] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* password + * if password is not empty, it will set the password + +* NOPASSWORD + * if NOPASSWORD is present, it will remove the password + +* if password is empty and NOPASSWORD is not present, it will raise error: `Password not displayable`` + +## Output + +- In json format + +```json +{ + "cmd":"101", + "status":"ok", + "data":"ok" +} +``` + +* `cmd` Id of requested command, should be `101` +* `status` status of command, should be `ok` +* `data` content of response, here `ok` + +if error : + + json format : + +```json +{ +"cmd":"101", +"status":"error", +"data":"Password not displayable" +} +``` + + plain text : `error: Password not displayable` + + ++++ +archetype = "section" +title = "[ESP102]" +weight = 800 ++++ +Set / Display Station IP mode + +## Input +`[ESP102] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* mode + * if mode is empty, it will display current mode + * if mode is not empty, it will set the setting mode: `DHCP` or `STATIC` + +## Output + +- In json format + +```json +{ + "cmd":"102", + "status":"ok", + "data":"DHCP" +} +``` + +* `cmd` Id of requested command, should be `102` +* `status` status of command, should be `ok` +* `data` content of response, here the mode + ++++ +archetype = "section" +title = "[ESP103]" +weight = 800 ++++ +Set / Display Station IP address + +## Input +`[ESP103]IP= MSK= GW= DNS= json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* IP + * if IP is empty, it will display defined IP + * if IP is not empty, it will set the IP + +* MSK + * if MSK is empty, it will display defined Network Mask + * if MSK is not empty, it will set the Network Mask + +* GW + * if GW is empty, it will display defined Gateway + * if GW is not empty, it will set the Gateway + +* DNS + * if DNS is empty, it will display defined DNS + * if DNS is not empty, it will set the DNS + +## Output + +- In json format + +```json +{ + "cmd": "103", + "status": "ok", + "data": { + "ip": "192.168.0.1", + "gw": "192.168.0.1", + "msk": "255.255.255.0", + "dns": "192.168.0.1" + } +} +``` + +* `cmd` Id of requested command, should be `103` +* `status` status of command, should be `ok` +* `data` content of response, here the IP, GW, MSK and DNS + ++++ +archetype = "section" +title = "[ESP104]" +weight = 800 ++++ +Set station fallback mode state at boot which can be BT, WIFI-AP, OFF + +## Input +`[ESP104] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= + +the admin password if authentication is enabled + +* mode + * if mode is empty, it will display current mode + * if mode is not empty, it will set the setting mode: `BT`, `WIFI-AP` or `OFF` + +## Output + +- In json format + +```json +{ + "cmd":"104", + "status":"ok", + "data":"OFF" +} +``` + +* `cmd` Id of requested command, should be `104` +* `status` status of command, should be `ok` +* `data` content of response, here the mode + ++++ +archetype = "section" +title = "[ESP104]" +weight = 800 ++++ +Set station fallback mode state at boot which can be BT, WIFI-SETUP, OFF + +## Input +`[ESP104] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* mode + * if mode is empty, it will display current mode + * if mode is not empty, it will set the setting mode: `BT`, `WIFI-SETUP` or `OFF` + +## Output + +- In json format + +```json +{ + "cmd":"104", + "status":"ok", + "data":"OFF" +} +``` + ++++ +archetype = "section" +title = "[ESP105]" +weight = 800 ++++ +Set / Display Access point SSID + +## Input +`[ESP105] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* SSID + * if SSID is empty, it will display current SSID + * if SSID is not empty, it will set the SSID + +## Output + +- In json format + +```json +{ + "cmd":"105", + "status":"ok", + "data":"esp3d" +} +``` + +* `cmd` Id of requested command, should be `105` +* `status` status of command, should be `ok` +* `data` content of response, here the SSID + + + ++++ +archetype = "section" +title = "[ESP106]" +weight = 800 ++++ +Set Access point password + +## Input +`[ESP106] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* password + * if password is not empty, it will set the password + +* NOPASSWORD + * if NOPASSWORD is present, it will remove the password + +* if password is empty and NOPASSWORD is not present, it will raise error: `Password not displayable`` + +## Output + +- In json format + +```json +{ + "cmd":"106", + "status":"ok", + "data":"ok" +} +``` + +* `cmd` Id of requested command, should be `106` +* `status` status of command, should be `ok` +* `data` content of response, here `ok` + + ++++ +archetype = "section" +title = "[ESP107]" +weight = 800 ++++ +Set / Display Access point IP value + +## Input +`[ESP107] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* IP + * if IP is empty, it will display defined IP + * if IP is not empty, it will set the IP + +## Output + +- In json format + +```json +{ + "cmd":"107", + "status":"ok", + "data":"192.168.0.1" +} +``` + +* `cmd` Id of requested command, should be `107` +* `status` status of command, should be `ok` +* `data` content of response, here the IP + + ++++ +archetype = "section" +title = "[ESP108]" +weight = 800 ++++ +Set / Display Access point channel value + +## Input +`[ESP108] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* channel + * if channel is empty, it will display defined channel + * if channel is not empty, it will set the channel + +## Output + +- In json format + +```json +{ + "cmd":"108", + "status":"ok", + "data":"1" +} +``` + +* `cmd` Id of requested command, should be `108` +* `status` status of command, should be `ok` +* `data` content of response, here the channel + ++++ +archetype = "section" +title = "[ESP110]" +weight = 800 ++++ +Set radio state at boot which can be BT, WIFI-STA, WIFI-AP, ETH-STA, OFF + +## Input +`[ESP110] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* mode + * if mode is empty, it will display current mode + * if mode is not empty, it will set the setting mode: `BT`, `WIFI-STA`, `WIFI-AP`, `ETH-STA` or `OFF` + +## Output + +- In json format + +```json +{ + "cmd":"110", + "status":"ok", + "data":"OFF" +} +``` + +* `cmd` Id of requested command, should be `110` +* `status` status of command, should be `ok` +* `data` content of response, here the mode + + ++++ +archetype = "section" +title = "[ESP111]" +weight = 800 ++++ +Display current IP + +## Input +`[ESP111] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* OUTPUT + * if OUTPUT is empty, it will display current IP as text `192.168.0.1` + * if OUTPUT is `PRINTER`, it will display current IP in printer format `M117 192.168.0.1` + +## Output + +- In json format + +```json +{ + "cmd":"111", + "status":"ok", + "data":"192.168.0.1" +} +``` + +* `cmd` Id of requested command, should be `111` +* `status` status of command, should be `ok` +* `data` content of response, here the IP + + ++++ +archetype = "section" +title = "[ESP112]" +weight = 800 ++++ +Set / Display Hostname + +## Input +`[ESP112] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* hostname + * if hostname is empty, it will display current hostname + * if hostname is not empty, it will set the hostname + +## Output + +- In json format + +```json +{ + "cmd":"112", + "status":"ok", + "data":"esp3d" +} +``` + +* `cmd` Id of requested command, should be `112` +* `status` status of command, should be `ok` +* `data` content of response, here the hostname + + ++++ +archetype = "section" +title = "[ESP114]" +weight = 800 ++++ +Get/Set Boot radio state which can be ON, OFF + +## Input +`[ESP114] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* mode + * if mode is empty, it will display current mode + * if mode is not empty, it will set the setting mode: `ON` or `OFF` + + +## Output + +- In json format + +```json +{ + "cmd":"114", + "status":"ok", + "data":"OFF" +} +``` + +* `cmd` Id of requested command, should be `114` +* `status` status of command, should be `ok` +* `data` content of response, here the mode + ++++ +archetype = "section" +title = "[ESP115]" +weight = 800 ++++ +Get/Set immediate Network (WiFi/BT/Ethernet) state which can be ON, OFF + +## Input +`[ESP115] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* mode + * if mode is empty, it will display current mode + * if mode is not empty, it will set the setting mode: `ON` or `OFF` + +## Output + +- In json format + +```json +{ + "cmd":"115", + "status":"ok", + "data":"OFF" +} +``` + +* `cmd` Id of requested command, should be `115` +* `status` status of command, should be `ok` +* `data` content of response, here the mode + ++++ +archetype = "section" +title = "[ESP120]" +weight = 800 ++++ +Get/Set HTTP state which can be ON, OFF + +## Input +`[ESP120] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* mode + * if mode is empty, it will display current mode + * if mode is not empty, it will set the setting mode: `ON` or `OFF` + +## Output + +- In json format + +```json +{ + "cmd":"120", + "status":"ok", + "data":"OFF" +} +``` + +* `cmd` Id of requested command, should be `120` +* `status` status of command, should be `ok` +* `data` content of response, here the mode + + ++++ +archetype = "section" +title = "[ESP121]" +weight = 800 ++++ +Get/Set HTTP port + +## Input +`[ESP121] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* port + * if port is empty, it will display current port + * if port is not empty, it will set the port + +## Output + +- In json format + +```json +{ + "cmd":"121", + "status":"ok", + "data":"80" +} +``` + +* `cmd` Id of requested command, should be `121` +* `status` status of command, should be `ok` +* `data` content of response, here the port + + ++++ +archetype = "section" +title = "[ESP130]" +weight = 800 ++++ + Get/Set TELNET state which can be ON, OFF, CLOSE + +## Input +`[ESP130] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* mode + * if mode is empty, it will display current mode + * if mode is not empty, it will set the setting mode: `ON`, `OFF` or `CLOSE` + +## Output + +- In json format + +```json +{ + "cmd":"130", + "status":"ok", + "data":"OFF" +} +``` + +* `cmd` Id of requested command, should be `130` +* `status` status of command, should be `ok` +* `data` content of response, here the mode + + ++++ +archetype = "section" +title = "[ESP131]" +weight = 800 ++++ +Get/Set TELNET port + +## Input +`[ESP131] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* port + * if port is empty, it will display current port + * if port is not empty, it will set the port + +## Output + +- In json format + +```json +{ + "cmd":"131", + "status":"ok", + "data":"23" +} +``` + +* `cmd` Id of requested command, should be `131` +* `status` status of command, should be `ok` +* `data` content of response, here the port + + ++++ +archetype = "section" +title = "[ESP140]" +weight = 800 ++++ +Sync / Set / Get current time + +## Input +`[ESP140] NOW json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + + * srv1 / srv2 / srv3 + * if srv1 / srv2 / srv3 are empty, it will display current NTP servers + * if srv1 / srv2 / srv3 are not empty, it will set the NTP servers + +* tzone + * if tzone is empty, it will display current time zone + * if tzone is not empty, it will set the time zone + +* time + * if time is empty, it will display current time + * if time is not empty, it will set the time + +* ntp + * if ntp is empty, it will display current NTP state + * if ntp is not empty, it will set the NTP state + +* SYNC + * if SYNC, it will restart NTP service to sync time + +* NOW + * if NOW, it will display current time in ISO 8601 format with time zone + +## Output + +- In json format + +```json +{ + "cmd":"140", + "status":"ok", + "data":"2020-01-01T00:00:00 (+08:00)" +} +``` + +* `cmd` Id of requested command, should be `140` +* `status` status of command, should be `ok` +* `data` content of response, here the time + + ++++ +archetype = "section" +title = "[ESP150]" +weight = 800 ++++ + Get/Set display/set boot delay in ms / Verbose boot + +## Input +`[ESP150] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + + * delay + * if delay is empty, it will display current delay + * if delay is not empty, it will set the delay + +* verbose + * if verbose is empty, it will display current verbose state + * if verbose is not empty, it will set the verbose state + +## Output + +- In json format + +```json +{ + "cmd":"150", + "status":"ok", + "data": { + "delay": "100", + "verbose": "OFF" + } +} +``` + +* `cmd` Id of requested command, should be `150` +* `status` status of command, should be `ok` +* `data` content of response, here the delay and verbose state + + + ++++ +archetype = "section" +title = "[ESP160]" +weight = 800 ++++ +Get/Set WebSocket state which can be ON, OFF, CLOSE + +## Input +`[ESP160] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* mode + * if mode is empty, it will display current mode + * if mode is not empty, it will set the setting mode: `ON`, `OFF` or `CLOSE` + +## Output + +- In json format + +```json +{ + "cmd":"160", + "status":"ok", + "data":"OFF" +} +``` + +* `cmd` Id of requested command, should be `160` +* `status` status of command, should be `ok` +* `data` content of response, here the mode + + ++++ +archetype = "section" +title = "[ESP161]" +weight = 800 ++++ +Get/Set WebSocket port + +## Input +`[ESP161] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* port + * if port is empty, it will display current port + * if port is not empty, it will set the port + +## Output + +- In json format + +```json +{ + "cmd":"161", + "status":"ok", + "data":"81" +} +``` + +* `cmd` Id of requested command, should be `161` +* `status` status of command, should be `ok` +* `data` content of response, here the port + ++++ +archetype = "section" +title = "[ESP170]" +weight = 800 ++++ +Set Camera command value / list all values in JSON/plain text + +## Input +`[ESP170] pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + + * label + * if label is empty, it will display current value + * if label is not empty, it will set the value + + label can be: light/framesize/quality/contrast/brightness/saturation/gainceiling/colorbar/awb/agc/aec/hmirror/vflip/awb_gain/agc_gain/aec_value/aec2/cw/bpc/wpc/raw_gma/lenc/special_effect/wb_mode/ae_level + value depend on label + +## Output + +- In json format + +```json +{ + "cmd":"170", + "status":"ok", + "data":"ok" +} +``` + +* `cmd` Id of requested command, should be `170` +* `status` status of command, should be `ok` +* `data` content of response, here `ok` + + ++++ +archetype = "section" +title = "[ESP171]" +weight = 800 ++++ +Save frame to target path and filename (default target = today date, default name=timestamp.jpg) + +## Input +`[ESP171] path= filename= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* path + * if path is not empty, it will set the path + +* filename + * if filename is not empty, it will set the filename + +## Output + +- In json format + +```json +{ + "cmd":"171", + "status":"ok", + "data":"Snapshot taken" +} +``` + +* `cmd` Id of requested command, should be `171` +* `status` status of command, should be `ok` +* `data` content of response, here `Snapshot taken` + ++++ +archetype = "section" +title = "[ESP180]" +weight = 800 ++++ +Get/Set Ftp state which can be ON, OFF, CLOSE + +## Input +`[ESP180] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + + * state + * if state is empty, it will display current state + * if state is not empty, it will set the state ON, OFF, CLOSE + +## Output + +- In json format + +```json +{ + "cmd":"180", + "status":"ok", + "data":"OFF" +} +``` + +* `cmd` Id of requested command, should be `180` +* `status` status of command, should be `ok` +* `data` content of response, here the state + ++++ +archetype = "section" +title = "[ESP181]" +weight = 800 ++++ +Get/Set Ftp ports + +## Input +`ESP181]ctrl= active= passive= json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* ctrl + * if ctrl is empty, it will display current ctrl port + * if ctrl is not empty, it will set the ctrl port + +* active + * if active is empty, it will display current active port + * if active is not empty, it will set the active port + +* passive + * if passive is empty, it will display current passive port + * if passive is not empty, it will set the passive port + ++++ +archetype = "section" +title = "[ESP190]" +weight = 800 ++++ +Set WebDav state which can be ON, OFF, CLOSE + +## Input +`[ESP190] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + + * state + * if state is empty, it will display current state + * if state is not empty, it will set the state ON, OFF, CLOSE + +## Output + +- In json format + +```json +{ + "cmd":"190", + "status":"ok", + "data":"OFF" +} +``` + +* `cmd` Id of requested command, should be `190` +* `status` status of command, should be `ok` +* `data` content of response, here the state + + ++++ +archetype = "section" +title = "[ESP191]" +weight = 800 ++++ +Get/Set WebDav port + +## Input +`[ESP191] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + + * port + * if port is empty, it will display current port + * if port is not empty, it will set the port + +## Output + +- In json format + +```json +{ + "cmd":"191", + "status":"ok", + "data":"80" +} +``` + +* `cmd` Id of requested command, should be `191` +* `status` status of command, should be `ok` +* `data` content of response, here the port + + ++++ +archetype = "section" +title = "[ESP200]" +weight = 800 ++++ +Get/Set SD state + +## Input +`[ESP200] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + + * RELEASESD + * if RELEASESD is present, it will release SD card + + * REFRESH + * if REFRESH is present, it will refresh SD card + +## Output + +- In json format + +```json +{ + "cmd":"200", + "status":"ok", + "data":"ok" +} +``` + +states can be : `Busy`. `"Not available`, `ok`, `No SD card` + +* `cmd` Id of requested command, should be `200` +* `status` status of command, should be `ok` +* `data` content of response, here `ok` + + ++++ +archetype = "section" +title = "[ESP201]" +weight = 800 ++++ +Get/Set pin value + +## Input +`[ESP201]P= V= pwd= Range can be 255 / 1024 / 2047 / 4095 / 8191` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + + * P + * if P is not empty, it will use the pin value + + * V + * if V is empty, it will display current pin value + * if V is not empty, it will set the pin value + * RAW + * if RAW is present, it will not set the pin mode + + * PULLUP + * if PULLUP is present, it will set the pin mode to pullup + + + * ANALOG + * if ANALOG is present, it will set the pin ANALOG + + * ANALOG_RANGE + * if ANALOG_RANGE is not empty, it will set the ANALOG_RANGE + +## Output + +- In json format + +```json +{ + "cmd":"201", + "status":"ok", + "data":"1" +} +``` + +* `cmd` Id of requested command, should be `201` +* `status` status of command, should be `ok` +* `data` content of response, here the pin value is 1 or High + + ++++ +archetype = "section" +title = "[ESP202]" +weight = 800 ++++ + Get/Set SD card Speed factor 1 2 4 6 8 16 32 + +## Input +`[ESP202]SPEED= json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* SPEED= + * if factor is empty, it will display current factor + * if factor is not empty, it will set the factor + +## Output + +- In json format + +```json +{ + "cmd":"202", + "status":"ok", + "data":"1" +} +``` + +* `cmd` Id of requested command, should be `202` +* `status` status of command, should be `ok` +* `data` content of response, here the current SPI factor + + + ++++ +archetype = "section" +title = "[ESP210]" +weight = 800 ++++ +Get Sensor Value / type/Set Sensor type + +## Input +`[ESP210] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + + * type + * if type is empty, it will display current type + * if type is not empty, it will set the type + + * interval + * if interval is empty, it will display current interval + * if interval is not empty, it will set the interval + +## Output + +- In json format + +```json +{ + "cmd":"210", + "status":"ok", + "data":"ok" +} +``` + +* `cmd` Id of requested command, should be `210` +* `status` status of command, should be `ok` +* `data` content of response, here `ok` + ++++ +archetype = "section" +title = "[ESP214]" +weight = 800 ++++ +Output to esp screen status + +## Input +`[ESP214] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* Text + * if Text is not empty, it will set the Text + * if Text is empty, it will clear current Text + +## Output + +- In json format + +```json +{ + "cmd":"214", + "status":"ok", + "data":"ok" +} +``` + +* `cmd` Id of requested command, should be `214` +* `status` status of command, should be `ok` +* `data` content of response, here `ok` + + ++++ +archetype = "section" +title = "[ESP215]" +weight = 800 ++++ +Start a Touch Calibration + +## Input +`[ESP215] json= pwd=` + +* json=no +the output format + +* pwd= +the admin password if authentication is enabled + +* CALIBRATE + * if CALIBRATE is present, it will start the calibration + +## Output + +- In json format + +```json +{ + "cmd":"215", + "status":"ok", + "data":"ok" +} +``` + +* `cmd` Id of requested command, should be `215` +* `status` status of command, should be `ok` +* `data` content of response, here `ok` + + ++++ +archetype = "section" +title = "[ESP220]" +weight = 800 ++++ +Get ESP pins definition + +## Input +`[ESP220] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +## Output + +- In json format +```json +{ + "cmd": "220", + "status": "ok", + "data": [ + { + "id": "SD CS", + "value": "13" + }, + { + "id": "SD MOSI", + "value": "15" + }, + { + "id": "SD MISO", + "value": "2" + }, + { + "id": "SD SCK", + "value": "14" + }, + { + "id": "SD DETECT", + "value": "-1" + }, + { + "id": "SD SWITCH", + "value": "26" + } + ] +} +``` + +* `cmd` Id of requested command, should be `220` +* `status` status of command, should be `ok` +* `data` content of response, here the pins definitions + + - plain text format + +```text +SD CS: 13 +SD MOSI: 15 +SD MISO: 2 +SD SCK: 14 +SD DETECT: -1 +SD SWITCH: 26 +``` + + ++++ +archetype = "section" +title = "[ESP250]" +weight = 800 ++++ +Play sound + +## Input +`[ESP250]F= D= json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* F + * if F is empty, it will use current frequency + * if F is not empty, it will use the frequency + +* D + * if D is empty, it will use current duration + * if D is not empty, it will use the duration + +## Output + +- In json format + +```json +{ + "cmd":"250", + "status":"ok", + "data":"ok" +} +``` + +* `cmd` Id of requested command, should be `250` +* `status` status of command, should be `ok` +* `data` content of response, here `ok` + ++++ +archetype = "section" +title = "[ESP290]" +weight = 800 ++++ +Delay/Pause command + +## Input +`[ESP290] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* delay + * if delay is empty, it will use 0 delay + * if delay is not empty, it will use the delay + +## Output + +- In json format + +```json +{ + "cmd":"290", + "status":"ok", + "data":"ok" +} +``` + +* `cmd` Id of requested command, should be `290` +* `status` status of command, should be `ok` +* `data` content of response, here `ok` + + + + + + ++++ +archetype = "section" +title = "[ESP800]" +weight = 800 ++++ +Get FW capabilities + +## Input + +`[ESP800] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* time= +to set ESP3D time using ISO 8601 format : `YYYY`-`MM`-`DD`T`HH`:`minutes`:`seconds` + +* tzone= +to set ESP3D time zone using ISO 8601 format : `+`/`-` `HH`:`minutes` + +* pwd= +the admin password if authentication is enabled + +* version +version of webUI +* setup flag +Enable / Disable the setup flag + +## Output + +- In json format + +```json +{ + "cmd":"800", + "status":"ok", + "data":{ + "FWVersion":"bugfix-2.0.x-3.0.0.a200", + "FWTarget":"marlin", + "FWTargetID":"30", + "Setup":"Enabled", + "SDConnection":"shared", + "SerialProtocol":"Socket", + "Authentication":"Disabled", + "WebCommunication":"Synchronous", + "WebSocketIP":"192.168.2.117", + "WebSocketPort":"81", + "Hostname":"esp3d", + "WiFiMode":"STA", + "WebUpdate":"Enabled", + "FlashFileSystem":"LittleFS", + "HostPath":"www", + "Time":"none" + } +} +``` + +* `cmd` +Id of requested command, should be `800` + +* `status` +status of command, should be `ok` + +* `data` +content of response: +* `FWVersion` +Version of ESP3D firmware or targeted FW (Marlin with ESP3DLib / grblHal) +* `FWTarget` +name of targeted Firmware +* `FWTargetID` +numerical ID of targeted FW as same name can have several Ids +* `Setup` +Should be `Enabled` or `Disabled` according flag in EEPROM/Preferences, this allows to WedUI to start wizard automaticaly (or not) + +* `SDConnection` +This is SD capability, SD can be + * `shared` + ESP does share access to SD card reader with main board or Firmware (Marlin with ESP3Dlib, ESP3D with hardware SD share solution) + * `direct` + ESP does have direct access to SD card reader (e.g: ESP3D, grblHal) + * `none` + ESP does not have direct access to SD card reader, (e.g: ESP3D with only serial connection) +* `SerialProtocol` +It define how ESP3D FW communicate with main FW + * `Socket` + ESP and main FW use same FW (e.g: Marlin with ESP3DLib, grblHal) + * `Raw` + Classic serial connection + * `MKS` + Serial connection using MKS protocol +* `Authentication` +Can be `Enabled` or `Disabled` +* `WebCommunication` + currently only `Synchronous`, because `Asychronous` has been put in hold +* `WebSocketIP` +Ip address for the websocket terminal `192.168.2.117` +* `WebSocketPort` +Port for the web socket terminal `81` +* `Hostname` + Hostname of ESP3D or main Baord `esp3d` +* `WiFiMode` +Current wiFi mode in use can be `AP` or `STA` +* `WebUpdate` +Inform webUI the feature is available or not, can be `Enabled` or `Disabled` +* `FlashFileSystem` (currently `FileSystem`, to be updated soon ) +The file system used by ESP board can be `LittleFS`, `SPIFFS`, `Fat`, `none` +* `HostPath` +Path where the preferences.json and index.html.gz are stored and can be updated (e.g: `www`) +* `Time` +Type of time support + * `none` + Time is not supported + * `Auto` + Board use internet to sync time and it is successful + * `Failed to set` + Board use internet to sync time and it is failed + * `Manual` + Board use time of ESP800 to set the time and it is successful + * `Not set` + Board use time of ESP800 to set the time and command did not sent it (time may have been set by previous command) +* `CameraID` +if ESP has camera it contain the camera ID +* `CameraName` +if ESP has camera it contain the camera name +* `Axisletters` +Currently only used for grbHAL +can be : + - XYZABC + - XYZUVZ (supported soon) + - XYZABCUVZ (supported soon) diff --git a/esp3d/configuration.h b/esp3d/configuration.h index d9fd4ced..782768bf 100644 --- a/esp3d/configuration.h +++ b/esp3d/configuration.h @@ -250,7 +250,7 @@ /* Enable date/time on files * Set date/time on files using SNTP or last webui connection */ -// #define FILESYSTEM_TIMESTAMP_FEATURE +#define FILESYSTEM_TIMESTAMP_FEATURE /************************************ * diff --git a/esp3d/src/core/esp3d_string.cpp b/esp3d/src/core/esp3d_string.cpp new file mode 100644 index 00000000..46eb1655 --- /dev/null +++ b/esp3d/src/core/esp3d_string.cpp @@ -0,0 +1,150 @@ +/* + esp3d_string.cpp - esp3d strings helpers + + Copyright (c) 2023 Luc Lebosse. All rights reserved. + + This code is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This code is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with This code; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ +#include "esp3d_string.h" + +#include + +#include "../include/esp3d_config.h" + +#if defined(TIMESTAMP_FEATURE) +#include "../modules/time/time_service.h" +#endif // TIMESTAMP_FEATURE + +const char* esp3d_string::getTimeString(time_t time, bool isGMT) { + static char buffer[40]; + memset(buffer, 0, sizeof(buffer)); + struct tm* tm_info; + struct tm tmstruct; + + if (isGMT) { + // convert to GMT time + tm_info = gmtime_r(&time, &tmstruct); + strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S GMT", tm_info); + } else { + // convert to local time + tm_info = localtime_r(&time, &tmstruct); + strftime(buffer, sizeof(buffer), "%Y-%m-%dT%H:%M:%S", tm_info); + } + if (!isGMT) { +#if defined(TIMESTAMP_FEATURE) + // if time zone is set add it + strcat(buffer, timeService.getTimeZone()); +#else + // add Z to indicate UTC time because no time zone is set + strcat(buffer, "Z"); +#endif // TIMESTAMP_FEATURE + } + return buffer; +} + +// Update hash function used by generateUUID +void update_hash(uint8_t* data, size_t len, uint8_t* hash_buffer, + uint8_t hash_size) { + static bool reverse = false; + reverse = !reverse; + int start_index = reverse ? hash_size : 0; + for (int i = 0; i < hash_size; i++) { + int idx = + reverse ? (start_index - i) % hash_size : (start_index + i) % hash_size; + if (i >= len) { + hash_buffer[idx] ^= random(1, 254); + } else { + hash_buffer[idx] ^= data[i]; + } + } +} + +const char* esp3d_string::generateUUID(const char* seed) { + static String token; + String tmp; + uint8_t hash_buffer[16]; + memset(hash_buffer, 0, 16); + if (!seed) { + tmp = "ESP3D ecosystem"; + } else { + tmp = seed; + } + // init random seed + randomSeed(time(NULL)); + // Use seed + update_hash((uint8_t*)tmp.c_str(), tmp.length(), hash_buffer, 16); + + // use epoch time + uint64_t millisec = millis(); + update_hash((uint8_t*)&millisec, sizeof(millisec), hash_buffer, 16); + + // use current time + time_t now; + time(&now); + update_hash((uint8_t*)&now, sizeof(now), hash_buffer, 16); + + tmp = ""; + // now hash all the buffer + for (int i = 0; i < 16; i++) { + char hex[3]; + sprintf(hex, "%02x", hash_buffer[i]); + tmp += hex; + } + + // format the uuid on 36 chars + token = tmp.substring(0, 7) + "-"; + token += tmp.substring(8, 8 + 3) + "-"; + token += tmp.substring(12, 12 + 3) + "-"; + token += tmp.substring(16, 16 + 3) + "-"; + token += &tmp[20]; + + return token.c_str(); +} + +const char* esp3d_string::getContentType(const char* filename) { + String file_name = filename; + file_name.toLowerCase(); + if (file_name.endsWith(".htm")) { + return "text/html"; + } else if (file_name.endsWith(".html")) { + return "text/html"; + } else if (file_name.endsWith(".css")) { + return "text/css"; + } else if (file_name.endsWith(".js")) { + return "application/javascript"; + } else if (file_name.endsWith(".png")) { + return "image/png"; + } else if (file_name.endsWith(".gif")) { + return "image/gif"; + } else if (file_name.endsWith(".jpeg")) { + return "image/jpeg"; + } else if (file_name.endsWith(".jpg")) { + return "image/jpeg"; + } else if (file_name.endsWith(".ico")) { + return "image/x-icon"; + } else if (file_name.endsWith(".xml")) { + return "text/xml"; + } else if (file_name.endsWith(".pdf")) { + return "application/x-pdf"; + } else if (file_name.endsWith(".zip")) { + return "application/x-zip"; + } else if (file_name.endsWith(".gz")) { + return "application/x-gzip"; + } else if (file_name.endsWith(".txt") || file_name.endsWith(".gcode") || + file_name.endsWith(".gco") || file_name.endsWith(".g")) { + return "text/plain"; + } + return "application/octet-stream"; +} \ No newline at end of file diff --git a/esp3d/src/modules/time/time_server.h b/esp3d/src/core/esp3d_string.h similarity index 57% rename from esp3d/src/modules/time/time_server.h rename to esp3d/src/core/esp3d_string.h index b719afa6..fdfd9dda 100644 --- a/esp3d/src/modules/time/time_server.h +++ b/esp3d/src/core/esp3d_string.h @@ -1,7 +1,7 @@ /* - time_server.h - time server functions class + esp3d_string.h - esp3d strings helpers - Copyright (c) 2014 Luc Lebosse. All rights reserved. + Copyright (c) 2023 Luc Lebosse. All rights reserved. This code is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -18,31 +18,13 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - -#ifndef _TIME_SERVER_H -#define _TIME_SERVER_H - +#ifndef _ESP3D_STRING_H +#define _ESP3D_STRING_H #include +namespace esp3d_string { +const char* getTimeString(time_t time, bool isGMT); +const char* generateUUID(const char* seed); +const char* getContentType(const char* filename); +} // namespace esp3d_string -class TimeServer -{ -public: - TimeServer(); - ~TimeServer(); - bool begin(); - void end(); - void handle(); - const char * current_time(time_t t = 0); - bool setTime(const char* stime); - bool started(); - bool is_internet_time(bool readfromsettings = false); -private: - bool _started; - bool _is_internet_time; -}; - -extern TimeServer timeserver; - -#endif //_TIME_SERVER_H - +#endif //_ESP3D_STRING_H diff --git a/esp3d/src/core/esp3doutput.cpp b/esp3d/src/core/esp3doutput.cpp index 1205498a..e1e1ec30 100644 --- a/esp3d/src/core/esp3doutput.cpp +++ b/esp3d/src/core/esp3doutput.cpp @@ -70,6 +70,7 @@ uint8_t ESP3DOutput::_BToutputflags = DEFAULT_BT_FLAG; uint8_t ESP3DOutput::_serialBridgeoutputflags = DEFAULT_SERIAL_BRIDGE_FLAG; #endif // ESP_SERIAL_BRIDGE_OUTPUT #if defined(HTTP_FEATURE) +#include "../modules/http/http_server.h" #if defined(ARDUINO_ARCH_ESP32) #include #endif // ARDUINO_ARCH_ESP32 @@ -453,6 +454,7 @@ size_t ESP3DOutput::printMSGLine(const char *s) { _webserver->setContentLength(CONTENT_LENGTH_UNKNOWN); _webserver->sendHeader("Content-Type", "text/html"); _webserver->sendHeader("Cache-Control", "no-cache"); + HTTP_Server::set_http_headers(); _webserver->send(_code); _headerSent = true; } @@ -529,6 +531,7 @@ size_t ESP3DOutput::printMSG(const char *s, bool withNL) { if (_webserver) { if (!_headerSent && !_footerSent) { _webserver->sendHeader("Cache-Control", "no-cache"); + HTTP_Server::set_http_headers(); #ifdef ESP_ACCESS_CONTROL_ALLOW_ORIGIN _webserver->sendHeader("Access-Control-Allow-Origin", "*"); #endif // ESP_ACCESS_CONTROL_ALLOw_ORIGIN @@ -606,6 +609,7 @@ size_t ESP3DOutput::printERROR(const char *s, int code_error) { if (_webserver) { if (!_headerSent && !_footerSent) { _webserver->sendHeader("Cache-Control", "no-cache"); + HTTP_Server::set_http_headers(); if (s[0] != '{') { display = "error: "; } else { @@ -750,6 +754,7 @@ size_t ESP3DOutput::write(const uint8_t *buffer, size_t size) { _webserver->setContentLength(CONTENT_LENGTH_UNKNOWN); _webserver->sendHeader("Content-Type", "text/html"); _webserver->sendHeader("Cache-Control", "no-cache"); + HTTP_Server::set_http_headers(); _webserver->send(_code); _headerSent = true; } diff --git a/esp3d/src/core/espcmd/ESP0.cpp b/esp3d/src/core/espcmd/ESP0.cpp index 074cfb41..75e537cc 100644 --- a/esp3d/src/core/espcmd/ESP0.cpp +++ b/esp3d/src/core/espcmd/ESP0.cpp @@ -21,362 +21,355 @@ #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -const char * help[]= {"[ESP] (id) - display this help", -#if defined (WIFI_FEATURE) - "[ESP100](SSID) - display/set STA SSID", - "[ESP101](Password) - set STA password", -#endif //WIFI_FEATURE -#if defined (WIFI_FEATURE) || defined (ETH_FEATURE) - "[ESP102](Mode) - display/set STA IP mode (DHCP/STATIC)", - "[ESP103](IP=xxxx MSK=xxxx GW=xxxx) - display/set STA IP/Mask/GW", -#endif //WIFI_FEATURE || ETH_FEATURE -#if defined( WIFI_FEATURE) || defined( BLUETOOTH_FEATURE) || defined (ETH_FEATURE) - "[ESP104](State) - display/set sta fallback mode which can be BT, SETUP, OFF", -#endif // WIFI_FEATURE || BLUETOOTH_FEATURE || ETH_FEATURE -#if defined (WIFI_FEATURE) - "[ESP105](SSID) - display/set AP SSID", - "[ESP106](Password) - set AP password", - "[ESP107](IP) - display/set AP IP", - "[ESP108](Chanel) - display/set AP chanel", -#endif //WIFI_FEATURE -#if defined( WIFI_FEATURE) || defined( BLUETOOTH_FEATURE) || defined (ETH_FEATURE) - "[ESP110](State) - display/set radio state which can be BT, WIFI-STA, WIFI-AP, WIFI-SETUP, ETH-STA, OFF", -#endif // WIFI_FEATURE || BLUETOOTH_FEATURE || ETH_FEATURE -#if defined( WIFI_FEATURE) || defined (ETH_FEATURE) - "[ESP111](header)display current IP", -#endif //WIFI_FEATURE || ETH_FEATURE +const char* help[] = { + "[ESP] (id) - display this help", +#if defined(WIFI_FEATURE) + "[ESP100](SSID) - display/set STA SSID", + "[ESP101](Password) - set STA password", +#endif // WIFI_FEATURE +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) + "[ESP102](Mode) - display/set STA IP mode (DHCP/STATIC)", + "[ESP103](IP=xxxx MSK=xxxx GW=xxxx) - display/set STA IP/Mask/GW", +#endif // WIFI_FEATURE || ETH_FEATURE +#if defined(WIFI_FEATURE) || defined(BLUETOOTH_FEATURE) || defined(ETH_FEATURE) + "[ESP104](State) - display/set sta fallback mode which can be BT, SETUP, " + "OFF", +#endif // WIFI_FEATURE || BLUETOOTH_FEATURE || ETH_FEATURE +#if defined(WIFI_FEATURE) + "[ESP105](SSID) - display/set AP SSID", + "[ESP106](Password) - set AP password", + "[ESP107](IP) - display/set AP IP", + "[ESP108](Chanel) - display/set AP chanel", +#endif // WIFI_FEATURE +#if defined(WIFI_FEATURE) || defined(BLUETOOTH_FEATURE) || defined(ETH_FEATURE) + "[ESP110](State) - display/set radio state which can be BT, WIFI-STA, " + "WIFI-AP, WIFI-SETUP, ETH-STA, OFF", +#endif // WIFI_FEATURE || BLUETOOTH_FEATURE || ETH_FEATURE +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) + "[ESP111](header)display current IP", +#endif // WIFI_FEATURE || ETH_FEATURE #if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BT_FEATURE) - "[ESP112](Hostname) - display/set Hostname", - "[ESP114](State) - display/set boot Network state which can be ON, OFF", - "[ESP115](State) - display/set immediate Network state which can be ON, OFF", -#endif //WIFI_FEATURE || ETH_FEATURE || BT_FEATURE + "[ESP112](Hostname) - display/set Hostname", + "[ESP114](State) - display/set boot Network state which can be ON, OFF", + "[ESP115](State) - display/set immediate Network state which can be ON, " + "OFF", +#endif // WIFI_FEATURE || ETH_FEATURE || BT_FEATURE #if defined(HTTP_FEATURE) - "[ESP120](State) - display/set HTTP state which can be ON, OFF", - "[ESP121](Port) - display/set HTTP port ", -#endif //HTTP_FEATURE + "[ESP120](State) - display/set HTTP state which can be ON, OFF", + "[ESP121](Port) - display/set HTTP port ", +#endif // HTTP_FEATURE #if defined(TELNET_FEATURE) - "[ESP130](State) - display/set Telnet state which can be ON, OFF", - "[ESP131](Port) - display/set Telnet port", -#endif //TELNET_FEATURE + "[ESP130](State) - display/set Telnet state which can be ON, OFF", + "[ESP131](Port) - display/set Telnet port", +#endif // TELNET_FEATURE #if defined(TIMESTAMP_FEATURE) - "[ESP140](SYNC) (srv1=xxxx) (srv2=xxxx) (srv3=xxxx) (zone=xxx) (dst=YES/NO) (time=YYYY-MM-DDTHH:mm:ss) (SYNC) (NOW)- sync/display/set current time/time servers", -#endif //TIMESTAMP_FEATURE - "[ESP150](delay=time) (verbose=ON/OFF)- display/set boot delay in ms / Verbose boot", + "[ESP140](SYNC) (srv1=xxxx) (srv2=xxxx) (srv3=xxxx) (tzone=xxx) " + "(time=YYYY-MM-DDTHH:mm:ss)(ntp=YES/NO) (SYNC) (NOW)- sync/display/set " + "current time/time servers", +#endif // TIMESTAMP_FEATURE + "[ESP150](delay=time) (verbose=ON/OFF)- display/set boot delay in ms / " + "Verbose boot", #if defined(WS_DATA_FEATURE) - "[ESP160](State) - display/set WebSocket state which can be ON, OFF, CLOSE", - "[ESP161](Port) - display/set WebSocket port", -#endif //WS_DATA_FEATURE + "[ESP160](State) - display/set WebSocket state which can be ON, OFF, CLOSE", + "[ESP161](Port) - display/set WebSocket port", +#endif // WS_DATA_FEATURE #if defined(CAMERA_DEVICE) - "[ESP170](json) (label=value) - display/set Camera commands", - "[ESP171] (path=) (filename=) Save frame to target path and filename", -#endif //CAMERA_DEVICE + "[ESP170](json) (label=value) - display/set Camera commands", + "[ESP171] (path=) (filename=) Save frame to " + "target path and filename", +#endif // CAMERA_DEVICE #if defined(FTP_FEATURE) - "[ESP180](State) - display/set FTP state which can be ON, OFF", - "[ESP181](ctrl=xxxx) (active=xxxx) (passive=xxxx) - display/set FTP ports", -#endif //FTP_FEATURE + "[ESP180](State) - display/set FTP state which can be ON, OFF", + "[ESP181](ctrl=xxxx) (active=xxxx) (passive=xxxx) - display/set FTP ports", +#endif // FTP_FEATURE #if defined(WEBDAV_FEATURE) - "[ESP190](State) - display/set WebDav state which can be ON, OFF", - "[ESP191](Port) - display/set WebDav port", -#endif //WEBDAV_FEATURE -#if defined (SD_DEVICE) - "[ESP200] (json) (RELEASE) (REFRESH)- display/set SD Card Status", -#endif //SD_DEVICE + "[ESP190](State) - display/set WebDav state which can be ON, OFF", + "[ESP191](Port) - display/set WebDav port", +#endif // WEBDAV_FEATURE +#if defined(SD_DEVICE) + "[ESP200] (json) (RELEASE) (REFRESH)- display/set SD Card Status", +#endif // SD_DEVICE #ifdef DIRECT_PIN_FEATURE - "[ESP201](P=xxx) (V=xxx) (PULLUP=YES RAW=YES ANALOG=NO ANALOG_RANGE=255) - read / set pin value", -#endif //DIRECT_PIN_FEATURE -#if defined (SD_DEVICE) + "[ESP201](P=xxx) (V=xxx) (PULLUP=YES RAW=YES ANALOG=NO ANALOG_RANGE=255) - " + "read / set pin value", +#endif // DIRECT_PIN_FEATURE +#if defined(SD_DEVICE) #if SD_DEVICE != ESP_SDIO - "[ESP202] SPEED=(factor) - display / set SD Card SD card Speed factor (1 2 4 6 8 16 32)", -#endif //SD_DEVICE != ESP_SDIO -#endif //SD_DEVICE + "[ESP202] SPEED=(factor) - display / set SD Card SD card Speed factor (1 " + "2 4 6 8 16 32)", +#endif // SD_DEVICE != ESP_SDIO +#endif // SD_DEVICE #ifdef SENSOR_DEVICE - "[ESP210](type=NONE/xxx) (interval=xxxx) - display and read/set SENSOR info", -#endif //SENSOR_DEVICE -#if defined (DISPLAY_DEVICE) - "[ESP214](text) - display (text) to ESP screen status", + "[ESP210](type=NONE/xxx) (interval=xxxx) - display and read/set SENSOR " + "info", +#endif // SENSOR_DEVICE +#if defined(DISPLAY_DEVICE) + "[ESP214](text) - display (text) to ESP screen status", #if defined(DISPLAY_TOUCH_DRIVER) - "[ESP215](CALIBRATE) - display state / start touch calibration", -#endif //DISPLAY_TOUCH_DRIVER -#endif //DISPLAY_DEVICE - "[ESP220] - Show used pins", + "[ESP215](CALIBRATE) - display state / start touch calibration", +#endif // DISPLAY_TOUCH_DRIVER +#endif // DISPLAY_DEVICE + "[ESP220] - Show used pins", #ifdef BUZZER_DEVICE - "[ESP250]F=(frequency) D=(duration) - play sound on buzzer", -#endif //BUZZER_DEVICE - "[ESP290](delay in ms) - do a pause", - "[ESP400] - display ESP3D settings in JSON", - "[ESP401]P=(position) T=(type) V=(value) - Set specific setting", + "[ESP250]F=(frequency) D=(duration) - play sound on buzzer", +#endif // BUZZER_DEVICE + "[ESP290](delay in ms) - do a pause", + "[ESP400] - display ESP3D settings in JSON", + "[ESP401]P=(position) T=(type) V=(value) - Set specific setting", #ifdef SD_UPDATE_FEATURE - "[ESP402](State) - display/set check update at boot from SD which can be ON, OFF", -#endif //SD_UPDATE_FEATURE -#if defined (WIFI_FEATURE) - "[ESP410]display available AP list (limited to 30) in plain/JSON", -#endif //WIFI_FEATURE - "[ESP420]display ESP3D current status in plain/JSON", - "[ESP444](Cmd) - set ESP3D state (RESET/RESTART)", + "[ESP402](State) - display/set check update at boot from SD which can be " + "ON, OFF", +#endif // SD_UPDATE_FEATURE +#if defined(WIFI_FEATURE) + "[ESP410]display available AP list (limited to 30) in plain/JSON", +#endif // WIFI_FEATURE + "[ESP420]display ESP3D current status in plain/JSON", + "[ESP444](Cmd) - set ESP3D state (RESET/RESTART)", #ifdef MDNS_FEATURE - "[ESP450]display ESP3D list on network", -#endif //MDNS_FEATURE -#if defined (AUTHENTICATION_FEATURE) - "[ESP550](password) - change admin password", - "[ESP555](password) - change user password", -#endif //AUTHENTICATION_FEATURE + "[ESP450]display ESP3D list on network", +#endif // MDNS_FEATURE +#if defined(AUTHENTICATION_FEATURE) + "[ESP550](password) - change admin password", + "[ESP555](password) - change user password", +#endif // AUTHENTICATION_FEATURE #if defined(NOTIFICATION_FEATURE) - "[ESP600](message) - send notification", - "[ESP610]type=(NONE/PUSHOVER/EMAIL/LINE/TELEGRAM/IFTTT) (T1=xxx) (T2=xxx) (TS=xxx) - display/set Notification settings", - "[ESP620]URL=http://XXXXXX - send GET notification", -#endif //NOTIFICATION_FEATURE + "[ESP600](message) - send notification", + "[ESP610]type=(NONE/PUSHOVER/EMAIL/LINE/TELEGRAM/IFTTT) (T1=xxx) (T2=xxx) " + "(TS=xxx) - display/set Notification settings", + "[ESP620]URL=http://XXXXXX - send GET notification", +#endif // NOTIFICATION_FEATURE #if defined(GCODE_HOST_FEATURE) - "[ESP700](filename) - read ESP Filesystem file", - "[ESP701]action=(PAUSE/RESUME/ABORT) - query and control ESP700 stream", -#endif //GCODE_HOST_FEATURE + "[ESP700](filename) - read ESP Filesystem file", + "[ESP701]action=(PAUSE/RESUME/ABORT) - query and control ESP700 stream", +#endif // GCODE_HOST_FEATURE #if defined(FILESYSTEM_FEATURE) - "[ESP710]FORMATFS - Format ESP Filesystem", -#endif //FILESYSTEM_FEATURE -#if defined (SD_DEVICE) - "[ESP715]FORMATSD - Format SD Filesystem", -#endif //SD_DEVICE + "[ESP710]FORMATFS - Format ESP Filesystem", +#endif // FILESYSTEM_FEATURE +#if defined(SD_DEVICE) + "[ESP715]FORMATSD - Format SD Filesystem", +#endif // SD_DEVICE #if defined(FILESYSTEM_FEATURE) - "[ESP720](path) - List ESP Filesystem", - "[ESP730](Action)=(path) - rmdir / remove / mkdir / exists / create on ESP FileSystem (path)", -#endif //FILESYSTEM_FEATURE -#if defined (SD_DEVICE) - "[ESP740](path) - List SD Filesystem", - "[ESP750](Action)=(path) - rmdir / remove / mkdir / exists / create on SD (path)", -#endif //SD_DEVICE -#if defined (GLOBAL_FILESYSTEM_FEATURE) - "[ESP780](path) - List Global Filesystem", - "[ESP790](Action)=(path) - rmdir / remove / mkdir / exists / create on Global Filesystem (path)", -#endif //GLOBAL_FILESYSTEM_FEATURE - "[ESP800](time=YYYY-MM-DDTHH:mm:ss)(version=3.0.0-a11)(setup=0/1) - display FW Informations /set time", + "[ESP720](path) - List ESP Filesystem", + "[ESP730](Action)=(path) - rmdir / remove / mkdir / exists / create on ESP " + "FileSystem (path)", +#endif // FILESYSTEM_FEATURE +#if defined(SD_DEVICE) + "[ESP740](path) - List SD Filesystem", + "[ESP750](Action)=(path) - rmdir / remove / mkdir / exists / create on SD " + "(path)", +#endif // SD_DEVICE +#if defined(GLOBAL_FILESYSTEM_FEATURE) + "[ESP780](path) - List Global Filesystem", + "[ESP790](Action)=(path) - rmdir / remove / mkdir / exists / create on " + "Global Filesystem (path)", +#endif // GLOBAL_FILESYSTEM_FEATURE + "[ESP800](time=YYYY-MM-DDTHH:mm:ss)(version=3.0.0-a11)(setup=0/1) - " + "display FW Informations /set time", #if COMMUNICATION_PROTOCOL != SOCKET_SERIAL - "[ESP900](ENABLE/DISABLE) - display/set serial state", - "[ESP901] - display/set serial baud rate", -#endif //COMMUNICATION_PROTOCOL != SOCKET_SERIAL + "[ESP900](ENABLE/DISABLE) - display/set serial state", + "[ESP901] - display/set serial baud rate", +#endif // COMMUNICATION_PROTOCOL != SOCKET_SERIAL #ifdef BUZZER_DEVICE - "[ESP910](ENABLE/DISABLE) - display/set buzzer state", -#endif //BUZZER_DEVICE - "[ESP920](client)=(ON/OFF) - display/set SERIAL / SCREEN / REMOTE_SCREEN / WEBSOCKET / TELNET /BT / ALL client state if available", + "[ESP910](ENABLE/DISABLE) - display/set buzzer state", +#endif // BUZZER_DEVICE + "[ESP920](client)=(ON/OFF) - display/set SERIAL / SCREEN / REMOTE_SCREEN / " + "WEBSOCKET / TELNET /BT / ALL client state if available", #if defined(ESP_SERIAL_BRIDGE_OUTPUT) - "[ESP930](ON/OFF/CLOSE) - display/set serial bridge state", - "[ESP931] - display/set serial bridge baud rate", -#endif //defined(ESP_SERIAL_BRIDGE_OUTPUT) -#if defined(ARDUINO_ARCH_ESP32) && (CONFIG_IDF_TARGET_ESP32S3 || CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3) - "[ESP999](QUIETBOOT) [pwd=] - set quiet boot mode", -#endif //ARDUINO_ARCH_ESP32 - "" - }; -const uint cmdlist[]= {0, -#if defined (WIFI_FEATURE) - 100, - 101, -#endif //WIFI_FEATURE -#if defined (WIFI_FEATURE) || defined (ETH_FEATURE) - 102, - 103, -#endif //WIFI_FEATURE || ETH_FEATURE -#if defined( WIFI_FEATURE) || defined( BLUETOOTH_FEATURE) || defined (ETH_FEATURE) - 104, -#endif // WIFI_FEATURE || BLUETOOTH_FEATURE || ETH_FEATURE -#if defined (WIFI_FEATURE) - 105, - 106, - 107, - 108, -#endif //WIFI_FEATURE -#if defined( WIFI_FEATURE) || defined( BLUETOOTH_FEATURE) || defined (ETH_FEATURE) - 110, -#endif // WIFI_FEATURE || BLUETOOTH_FEATURE || ETH_FEATURE -#if defined( WIFI_FEATURE) || defined (ETH_FEATURE) - 111, -#endif //WIFI_FEATURE || ETH_FEATURE + "[ESP930](ON/OFF/CLOSE) - display/set serial bridge state", + "[ESP931] - display/set serial bridge baud rate", +#endif // defined(ESP_SERIAL_BRIDGE_OUTPUT) +#if defined(ARDUINO_ARCH_ESP32) && \ + (CONFIG_IDF_TARGET_ESP32S3 || CONFIG_IDF_TARGET_ESP32S2 || \ + CONFIG_IDF_TARGET_ESP32C3) + "[ESP999](QUIETBOOT) [pwd=] - set quiet boot mode", +#endif // ARDUINO_ARCH_ESP32 + ""}; +const uint cmdlist[] = {0, +#if defined(WIFI_FEATURE) + 100, 101, +#endif // WIFI_FEATURE +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) + 102, 103, +#endif // WIFI_FEATURE || ETH_FEATURE +#if defined(WIFI_FEATURE) || defined(BLUETOOTH_FEATURE) || defined(ETH_FEATURE) + 104, +#endif // WIFI_FEATURE || BLUETOOTH_FEATURE || ETH_FEATURE +#if defined(WIFI_FEATURE) + 105, 106, 107, 108, +#endif // WIFI_FEATURE +#if defined(WIFI_FEATURE) || defined(BLUETOOTH_FEATURE) || defined(ETH_FEATURE) + 110, +#endif // WIFI_FEATURE || BLUETOOTH_FEATURE || ETH_FEATURE +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) + 111, +#endif // WIFI_FEATURE || ETH_FEATURE #if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BT_FEATURE) - 112, - 114, - 115, -#endif //WIFI_FEATURE || ETH_FEATURE || BT_FEATURE + 112, 114, 115, +#endif // WIFI_FEATURE || ETH_FEATURE || BT_FEATURE #if defined(HTTP_FEATURE) - 120, - 121, -#endif //HTTP_FEATURE + 120, 121, +#endif // HTTP_FEATURE #if defined(TELNET_FEATURE) - 130, - 131, -#endif //TELNET_FEATURE + 130, 131, +#endif // TELNET_FEATURE #if defined(TIMESTAMP_FEATURE) - 140, -#endif //TIMESTAMP_FEATURE - 150, + 140, +#endif // TIMESTAMP_FEATURE + 150, #if defined(WS_DATA_FEATURE) - 160, - 161, -#endif //WS_DATA_FEATURE + 160, 161, +#endif // WS_DATA_FEATURE #if defined(CAMERA_DEVICE) - 170, - 171, -#endif //CAMERA_DEVICE + 170, 171, +#endif // CAMERA_DEVICE #if defined(FTP_FEATURE) - 180, - 181, -#endif //FTP_FEATURE + 180, 181, +#endif // FTP_FEATURE #if defined(WEBDAV_FEATURE) - 190, - 191, -#endif //WEBDAV_FEATURE -#if defined (SD_DEVICE) - 200, -#endif //SD_DEVICE + 190, 191, +#endif // WEBDAV_FEATURE +#if defined(SD_DEVICE) + 200, +#endif // SD_DEVICE #ifdef DIRECT_PIN_FEATURE - 201, -#endif //DIRECT_PIN_FEATURE -#if defined (SD_DEVICE) && SD_DEVICE != ESP_SDIO - 202, -#endif //SD_DEVICE + 201, +#endif // DIRECT_PIN_FEATURE +#if defined(SD_DEVICE) && SD_DEVICE != ESP_SDIO + 202, +#endif // SD_DEVICE #ifdef SENSOR_DEVICE - 210, -#endif //SENSOR_DEVICE -#if defined (DISPLAY_DEVICE) - 214, + 210, +#endif // SENSOR_DEVICE +#if defined(DISPLAY_DEVICE) + 214, #if defined(DISPLAY_TOUCH_DRIVER) - 215, -#endif //DISPLAY_TOUCH_DRIVER -#endif //DISPLAY_DEVICE - 220, + 215, +#endif // DISPLAY_TOUCH_DRIVER +#endif // DISPLAY_DEVICE + 220, #ifdef BUZZER_DEVICE - 250, -#endif //BUZZER_DEVICE - 290, - 400, - 401, -#if defined (WIFI_FEATURE) - 410, -#endif //WIFI_FEATURE - 420, - 444, + 250, +#endif // BUZZER_DEVICE + 290, 400, 401, +#if defined(WIFI_FEATURE) + 410, +#endif // WIFI_FEATURE + 420, 444, #ifdef MDNS_FEATURE - 450, -#endif //MDNS_FEATURE -#if defined (AUTHENTICATION_FEATURE) - 550, - 555, -#endif //AUTHENTICATION_FEATURE + 450, +#endif // MDNS_FEATURE +#if defined(AUTHENTICATION_FEATURE) + 550, 555, +#endif // AUTHENTICATION_FEATURE #if defined(NOTIFICATION_FEATURE) - 600, - 610, - 620, -#endif //NOTIFICATION_FEATURE + 600, 610, 620, +#endif // NOTIFICATION_FEATURE #if defined(GCODE_HOST_FEATURE) - 700, - 701, -#endif //GCODE_HOST_FEATURE + 700, 701, +#endif // GCODE_HOST_FEATURE #if defined(FILESYSTEM_FEATURE) - 710, -#endif //FILESYSTEM_FEATURE -#if defined (SD_DEVICE) - 715, -#endif //SD_DEVICE + 710, +#endif // FILESYSTEM_FEATURE +#if defined(SD_DEVICE) + 715, +#endif // SD_DEVICE #if defined(FILESYSTEM_FEATURE) - 720, - 730, -#endif //FILESYSTEM_FEATURE -#if defined (SD_DEVICE) - 740, - 750, -#endif //SD_DEVICE -#if defined (GLOBAL_FILESYSTEM_FEATURE) - 780, - 790, -#endif //GLOBAL_FILESYSTEM_FEATURE - 800, + 720, 730, +#endif // FILESYSTEM_FEATURE +#if defined(SD_DEVICE) + 740, 750, +#endif // SD_DEVICE +#if defined(GLOBAL_FILESYSTEM_FEATURE) + 780, 790, +#endif // GLOBAL_FILESYSTEM_FEATURE + 800, #if COMMUNICATION_PROTOCOL != SOCKET_SERIAL - 900, - 901, -#endif //COMMUNICATION_PROTOCOL != SOCKET_SERIAL + 900, 901, +#endif // COMMUNICATION_PROTOCOL != SOCKET_SERIAL #ifdef BUZZER_DEVICE - 910, + 910, -#endif //BUZZER_DEVICE - 920, +#endif // BUZZER_DEVICE + 920, #if defined(ESP_SERIAL_BRIDGE_OUTPUT) - 930, - 935, -#endif //defined(ESP_SERIAL_BRIDGE_OUTPUT) -#if defined(ARDUINO_ARCH_ESP32) && (CONFIG_IDF_TARGET_ESP32S3 || CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3) - 999, -#endif //ARDUINO_ARCH_ESP32 && CONFIG_IDF_TARGET_ESP32S3 || CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3 - 0 - }; + 930, 935, +#endif // defined(ESP_SERIAL_BRIDGE_OUTPUT) +#if defined(ARDUINO_ARCH_ESP32) && \ + (CONFIG_IDF_TARGET_ESP32S3 || CONFIG_IDF_TARGET_ESP32S2 || \ + CONFIG_IDF_TARGET_ESP32C3) + 999, +#endif // ARDUINO_ARCH_ESP32 && CONFIG_IDF_TARGET_ESP32S3 || + // CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3 + 0}; - -//ESP3D Help +// ESP3D Help //[ESP0] or [ESP] -bool Commands::ESP0(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - String parameter; - const uint cmdNb = sizeof(help)/sizeof(char*); - (void)auth_type; - bool json=has_tag(cmd_params,"json"); - parameter = clean_param(get_param (cmd_params, "")); - if (parameter.length() == 0) { - - if (json) { - output->print("{\"cmd\":\"0\",\"status\":\"ok\",\"data\":["); - } else { - output->printMSGLine("[List of ESP3D commands]"); - } - - for (uint i = 0; i < cmdNb -1; i++) { - if (json) { - output->print("{\"id\":\""); - output->print(String(cmdlist[i]).c_str()); - output->print("\",\"help\":\""); - output->print(String(help[i]).c_str()); - output->print("\"}"); - if (i < cmdNb - 2) { - output->print(","); - } - } else { - output->printMSGLine(help[i]); - - } - - } - if (json) { - output->printLN("]}"); - } +bool Commands::ESP0(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + String parameter; + const uint cmdNb = sizeof(help) / sizeof(char*); + (void)auth_type; + bool json = has_tag(cmd_params, "json"); + parameter = clean_param(get_param(cmd_params, "")); + if (parameter.length() == 0) { + if (json) { + output->print("{\"cmd\":\"0\",\"status\":\"ok\",\"data\":["); } else { - bool found = false; - uint cmdval = parameter.toInt(); - if (sizeof(help)/sizeof(char*) != sizeof(cmdlist)/sizeof(uint)) { - String s = "Error in code:" + String(sizeof(help)/sizeof(char*)) + "entries vs " + String(sizeof(cmdlist)/sizeof(uint)); - output->printLN(s.c_str()); - return false; - } - for (uint i = 0; i < cmdNb-1; i++) { - if (cmdlist[i] == cmdval) { - if (json) { - output->print("{\"cmd\":\"0\",\"status\":\"ok\",\"data\":{\"id\":\""); - output->print(String(cmdval).c_str()); - output->print("\",\"help\":\""); - output->print(help[i]); - output->printLN("\"}}"); - } else { - output->printMSGLine(help[i]); - } - found = true; - } - } - if (!found) { - String msg = "This command is not supported: "; - msg+= parameter; - noError=false; - String response = format_response(0, json, noError, msg.c_str()); - if (json) { - output->printLN (response.c_str() ); - } else { - output->printERROR (response.c_str() ); - } - } + output->printMSGLine("[List of ESP3D commands]"); } - return noError; + + for (uint i = 0; i < cmdNb - 1; i++) { + if (json) { + output->print("{\"id\":\""); + output->print(String(cmdlist[i]).c_str()); + output->print("\",\"help\":\""); + output->print(String(help[i]).c_str()); + output->print("\"}"); + if (i < cmdNb - 2) { + output->print(","); + } + } else { + output->printMSGLine(help[i]); + } + } + if (json) { + output->printLN("]}"); + } + } else { + bool found = false; + uint cmdval = parameter.toInt(); + if (sizeof(help) / sizeof(char*) != sizeof(cmdlist) / sizeof(uint)) { + String s = "Error in code:" + String(sizeof(help) / sizeof(char*)) + + "entries vs " + String(sizeof(cmdlist) / sizeof(uint)); + output->printLN(s.c_str()); + return false; + } + for (uint i = 0; i < cmdNb - 1; i++) { + if (cmdlist[i] == cmdval) { + if (json) { + output->print("{\"cmd\":\"0\",\"status\":\"ok\",\"data\":{\"id\":\""); + output->print(String(cmdval).c_str()); + output->print("\",\"help\":\""); + output->print(help[i]); + output->printLN("\"}}"); + } else { + output->printMSGLine(help[i]); + } + found = true; + } + } + if (!found) { + String msg = "This command is not supported: "; + msg += parameter; + noError = false; + String response = format_response(0, json, noError, msg.c_str()); + if (json) { + output->printLN(response.c_str()); + } else { + output->printERROR(response.c_str()); + } + } + } + return noError; } diff --git a/esp3d/src/core/espcmd/ESP100.cpp b/esp3d/src/core/espcmd/ESP100.cpp index 7536e117..ad94b3e6 100644 --- a/esp3d/src/core/espcmd/ESP100.cpp +++ b/esp3d/src/core/espcmd/ESP100.cpp @@ -18,70 +18,75 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (WIFI_FEATURE) +#if defined(WIFI_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/wifi/wificonfig.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/wifi/wificonfig.h" -#include "../../modules/authentication/authentication_service.h" -#define COMMANDID 100 -//STA SSID -//[ESP100][json=no] [pwd= -bool Commands::ESP100(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead + +#define COMMANDID 100 +// STA SSID +//[ESP100][json=no] [pwd=] +bool Commands::ESP100(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + response = format_response(COMMANDID, json, true, + Settings_ESP3D::read_string(ESP_STA_SSID)); + } else { // set +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = format_response(COMMANDID, json, false, + "Wrong authentication level"); noError = false; errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - response = format_response(COMMANDID, json, true, Settings_ESP3D::read_string(ESP_STA_SSID)); - } else { //set -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } -#endif //AUTHENTICATION_FEATURE - if (noError) { - if (!WiFiConfig::isSSIDValid (parameter.c_str() ) ) { - response = format_response(COMMANDID, json, false, "Incorrect SSID"); - noError = false; - } else { - if(!Settings_ESP3D::write_string(ESP_STA_SSID, parameter.c_str())) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } else { - response = format_response(COMMANDID, json, true, "ok"); - } - } - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); + } +#endif // AUTHENTICATION_FEATURE + if (noError) { + if (!WiFiConfig::isSSIDValid(parameter.c_str())) { + response = format_response(COMMANDID, json, false, "Incorrect SSID"); + noError = false; } else { - output->printMSG (response.c_str() ); + if (!Settings_ESP3D::write_string(ESP_STA_SSID, parameter.c_str())) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } else { + response = format_response(COMMANDID, json, true, "ok"); + } } - } else { - output->printERROR(response.c_str(), errorCode); + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //WIFI_FEATURE +#endif // WIFI_FEATURE diff --git a/esp3d/src/core/espcmd/ESP101.cpp b/esp3d/src/core/espcmd/ESP101.cpp index 257dcfed..b6d04e8d 100644 --- a/esp3d/src/core/espcmd/ESP101.cpp +++ b/esp3d/src/core/espcmd/ESP101.cpp @@ -18,64 +18,71 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (WIFI_FEATURE) +#if defined(WIFI_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/wifi/wificonfig.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/wifi/wificonfig.h" -#include "../../modules/authentication/authentication_service.h" -#define COMMANDID 101 -//STA Password -//[ESP101] [json=no] [pwd=] -bool Commands::ESP101(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - bool clearSetting = has_tag (cmd_params,"NOPASSWORD"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - if (parameter.length() == 0) { - response = format_response(COMMANDID, json, false, "Password not displayable"); - noError = false; - } else { - if (clearSetting) { - parameter=""; - } - if (!WiFiConfig::isPasswordValid (parameter.c_str() ) ) { - response = format_response(COMMANDID, json, false, "Incorrect password"); - noError = false; - } else { - if(!Settings_ESP3D::write_string(ESP_STA_PASSWORD, parameter.c_str())) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } else { - response = format_response(COMMANDID, json, true, "ok"); - } - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); - } +#define COMMANDID 101 +// STA Password +//[ESP101] [json=no] [pwd=] +bool Commands::ESP101(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + bool clearSetting = has_tag(cmd_params, "NOPASSWORD"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = + format_response(COMMANDID, json, false, "Wrong authentication level"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + if (parameter.length() == 0) { + response = + format_response(COMMANDID, json, false, "Password not displayable"); + noError = false; } else { - output->printERROR(response.c_str(), errorCode); + if (clearSetting) { + parameter = ""; + } + if (!WiFiConfig::isPasswordValid(parameter.c_str())) { + response = + format_response(COMMANDID, json, false, "Incorrect password"); + noError = false; + } else { + if (!Settings_ESP3D::write_string(ESP_STA_PASSWORD, + parameter.c_str())) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + + } else { + response = format_response(COMMANDID, json, true, "ok"); + } + } } - return noError; + } + + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //WIFI_FEATURE +#endif // WIFI_FEATURE diff --git a/esp3d/src/core/espcmd/ESP102.cpp b/esp3d/src/core/espcmd/ESP102.cpp index d2b8f6c0..366c89c9 100644 --- a/esp3d/src/core/espcmd/ESP102.cpp +++ b/esp3d/src/core/espcmd/ESP102.cpp @@ -18,85 +18,90 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (WIFI_FEATURE) || defined (ETH_FEATURE) +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) +#include "../../modules/network/netconfig.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/network/netconfig.h" -#if defined (WIFI_FEATURE) + +#if defined(WIFI_FEATURE) #include "../../modules/wifi/wificonfig.h" -#endif //WIFI_FEATURE -#if defined (ETH_FEATURE) +#endif // WIFI_FEATURE +#if defined(ETH_FEATURE) #include "../../modules/ethernet/ethconfig.h" -#endif //ETH_FEATURE +#endif // ETH_FEATURE #include "../../modules/authentication/authentication_service.h" -#define COMMANDID 102 -//Change STA IP mode (DHCP/STATIC) +#define COMMANDID 102 +// Change STA IP mode (DHCP/STATIC) //[ESP102][json=no] [pwd=] -bool Commands::ESP102(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP102(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + int8_t resp = Settings_ESP3D::read_byte(ESP_STA_IP_MODE); + if (resp == DHCP_MODE) { + response = format_response(COMMANDID, json, true, "DHCP"); + } else if (resp == STATIC_IP_MODE) { + response = format_response(COMMANDID, json, true, "STATIC"); + } else { + noError = false; + response = format_response(COMMANDID, json, true, "Unknow"); + } + } else { // set +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = format_response(COMMANDID, json, false, + "Wrong authentication level"); noError = false; errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - int8_t resp = Settings_ESP3D::read_byte(ESP_STA_IP_MODE); - if (resp == DHCP_MODE) { - response = format_response(COMMANDID, json, true, "DHCP"); - } else if (resp == STATIC_IP_MODE) { - response = format_response(COMMANDID, json, true, "STATIC"); - } else { - noError = false; - response = format_response(COMMANDID, json, true, "Unknow"); - } - } else { //set -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter.toUpperCase(); - if (!((parameter == "STATIC") || (parameter == "DHCP"))) { - response = format_response(COMMANDID, json, false, "only STATIC or DHCP mode supported"); - noError = false; - } else { - uint8_t bbuf = (parameter == "DHCP")?DHCP_MODE:STATIC_IP_MODE; - if (!Settings_ESP3D::write_byte(ESP_STA_IP_MODE, bbuf)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } else { - response = format_response(COMMANDID, json, true, "ok"); - } - } - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); + } +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter.toUpperCase(); + if (!((parameter == "STATIC") || (parameter == "DHCP"))) { + response = format_response(COMMANDID, json, false, + "only STATIC or DHCP mode supported"); + noError = false; } else { - output->printMSG (response.c_str() ); + uint8_t bbuf = (parameter == "DHCP") ? DHCP_MODE : STATIC_IP_MODE; + if (!Settings_ESP3D::write_byte(ESP_STA_IP_MODE, bbuf)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } else { + response = format_response(COMMANDID, json, true, "ok"); + } } - } else { - output->printERROR(response.c_str(), errorCode); + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //WIFI_FEATURE || ETH_FEATURE +#endif // WIFI_FEATURE || ETH_FEATURE diff --git a/esp3d/src/core/espcmd/ESP103.cpp b/esp3d/src/core/espcmd/ESP103.cpp index 06ab4525..d2742596 100644 --- a/esp3d/src/core/espcmd/ESP103.cpp +++ b/esp3d/src/core/espcmd/ESP103.cpp @@ -18,124 +18,132 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (WIFI_FEATURE) || defined (ETH_FEATURE) +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) +#include "../../modules/network/netconfig.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/network/netconfig.h" -#if defined (WIFI_FEATURE) + +#if defined(WIFI_FEATURE) #include "../../modules/wifi/wificonfig.h" -#endif //WIFI_FEATURE -#if defined (ETH_FEATURE) +#endif // WIFI_FEATURE +#if defined(ETH_FEATURE) #include "../../modules/ethernet/ethconfig.h" -#endif //ETH_FEATURE +#endif // ETH_FEATURE #include "../../modules/authentication/authentication_service.h" -#define COMMANDID 103 -//Change STA IP/Mask/GW -//[ESP103]IP= MSK= GW= [json=no] [pwd= -bool Commands::ESP103(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +#define COMMANDID 103 +// Change STA IP/Mask/GW +//[ESP103]IP= MSK= GW= DNS= [json=no] [pwd= +bool Commands::ESP103(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + String res; + if (json) { + res += "{\"ip\":\""; + } else { + res += "IP:"; + } + res += Settings_ESP3D::read_IP_String(ESP_STA_IP_VALUE); + if (json) { + res += "\",\"gw\":\""; + } else { + res += ", GW:"; + } + res += Settings_ESP3D::read_IP_String(ESP_STA_GATEWAY_VALUE); + if (json) { + res += "\",\"msk\":\""; + } else { + res += ", MSK:"; + } + res += Settings_ESP3D::read_IP_String(ESP_STA_MASK_VALUE); + if (json) { + res += "\",\"dns\":\""; + } else { + res += ", DNS:"; + } + res += Settings_ESP3D::read_IP_String(ESP_STA_DNS_VALUE); + if (json) { + res += "\"}"; + } + response = format_response(COMMANDID, json, true, res.c_str()); + } else { // set +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = format_response(COMMANDID, json, false, + "Wrong authentication level"); noError = false; errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - String res; - if(json) { - res+= "{\"ip\":\""; - } else { - res+= "IP:"; - } - res += Settings_ESP3D::read_IP_String(ESP_STA_IP_VALUE); - if(json) { - res+= "\",\"gw\":\""; - } else { - res += ", GW:"; - } - res += Settings_ESP3D::read_IP_String(ESP_STA_GATEWAY_VALUE); - if(json) { - res+= "\",\"msk\":\""; - } else { - res += ", MSK:"; - } - res += Settings_ESP3D::read_IP_String(ESP_STA_MASK_VALUE); - if(json) { - res+= "\",\"dns\":\""; - } else { - res += ", DNS:"; - } - res += Settings_ESP3D::read_IP_String(ESP_STA_DNS_VALUE); - if(json) { - res+= "\"}"; - } - response = format_response(COMMANDID, json, true, res.c_str()); - } else { //set -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } -#endif //AUTHENTICATION_FEATURE - if (noError) { - String IP = get_param (cmd_params, "IP="); - String GW = get_param (cmd_params, "GW="); - String MSK = get_param (cmd_params, "MSK="); - String DNS = get_param (cmd_params, "DNS="); - if ( !NetConfig::isValidIP(IP.c_str())) { - response = format_response(COMMANDID, json, false, "Incorrect IP"); - noError = false; - } - if ( !NetConfig::isValidIP(GW.c_str())) { - response = format_response(COMMANDID, json, false, "Incorrect gateway"); - noError = false; - } - if ( !NetConfig::isValidIP(MSK.c_str())) { - response = format_response(COMMANDID, json, false, "Incorrect mask"); - noError = false; - } - if ( !NetConfig::isValidIP(DNS.c_str())) { - response = format_response(COMMANDID, json, false, "Incorrect dns"); - noError = false; - } - if(noError) { - - if ( !Settings_ESP3D::write_IP_String(ESP_STA_IP_VALUE, IP.c_str()) || - !Settings_ESP3D::write_IP_String(ESP_STA_GATEWAY_VALUE, GW.c_str()) || - !Settings_ESP3D::write_IP_String(ESP_STA_DNS_VALUE, DNS.c_str()) || - !Settings_ESP3D::write_IP_String(ESP_STA_MASK_VALUE, MSK.c_str())) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } else { - response = format_response(COMMANDID, json, true, "ok"); - } - } - } + } +#endif // AUTHENTICATION_FEATURE + if (noError) { + String IP = get_param(cmd_params, "IP="); + String GW = get_param(cmd_params, "GW="); + String MSK = get_param(cmd_params, "MSK="); + String DNS = get_param(cmd_params, "DNS="); + if (!NetConfig::isValidIP(IP.c_str())) { + response = format_response(COMMANDID, json, false, "Incorrect IP"); + noError = false; } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); + if (!NetConfig::isValidIP(GW.c_str())) { + response = + format_response(COMMANDID, json, false, "Incorrect gateway"); + noError = false; } + if (!NetConfig::isValidIP(MSK.c_str())) { + response = format_response(COMMANDID, json, false, "Incorrect mask"); + noError = false; + } + if (!NetConfig::isValidIP(DNS.c_str())) { + response = format_response(COMMANDID, json, false, "Incorrect dns"); + noError = false; + } + if (noError) { + if (!Settings_ESP3D::write_IP_String(ESP_STA_IP_VALUE, IP.c_str()) || + !Settings_ESP3D::write_IP_String(ESP_STA_GATEWAY_VALUE, + GW.c_str()) || + !Settings_ESP3D::write_IP_String(ESP_STA_DNS_VALUE, + DNS.c_str()) || + !Settings_ESP3D::write_IP_String(ESP_STA_MASK_VALUE, + MSK.c_str())) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } else { + response = format_response(COMMANDID, json, true, "ok"); + } + } + } + } + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); } else { - output->printERROR(response.c_str(), errorCode); + output->printERROR(response.c_str(), errorCode); } - return noError; + } + + return noError; } -#endif //WIFI_FEATURE || ETH_FEATURE +#endif // WIFI_FEATURE || ETH_FEATURE diff --git a/esp3d/src/core/espcmd/ESP104.cpp b/esp3d/src/core/espcmd/ESP104.cpp index d2c6b334..689f969f 100644 --- a/esp3d/src/core/espcmd/ESP104.cpp +++ b/esp3d/src/core/espcmd/ESP104.cpp @@ -18,111 +18,116 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined( WIFI_FEATURE) || defined( BLUETOOTH_FEATURE) || defined (ETH_FEATURE) +#if defined(WIFI_FEATURE) || defined(BLUETOOTH_FEATURE) || defined(ETH_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/network/netconfig.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/network/netconfig.h" -#include "../../modules/authentication/authentication_service.h" -#define COMMANDID 104 -//Set STA fallback mode state at boot which can be BT, WIFI-AP, OFF + +#define COMMANDID 104 +// Set STA fallback mode state at boot which can be BT, WIFI-SETUP, OFF //[ESP104] json= pwd= -bool Commands::ESP104(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP104(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + int8_t wifiMode = Settings_ESP3D::read_byte(ESP_STA_FALLBACK_MODE); + if (wifiMode == ESP_NO_NETWORK) { + response = format_response(COMMANDID, json, true, "OFF"); + } else if (wifiMode == ESP_BT) { + response = format_response(COMMANDID, json, true, "BT"); + } else if (wifiMode == ESP_AP_SETUP) { + response = format_response(COMMANDID, json, true, "WIFI-SETUP"); + } else { + response = format_response(COMMANDID, json, true, "???"); + } + } else { // set +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = format_response(COMMANDID, json, false, + "Wrong authentication level"); noError = false; errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - int8_t wifiMode = Settings_ESP3D::read_byte(ESP_STA_FALLBACK_MODE); - if (wifiMode == ESP_NO_NETWORK) { - response = format_response(COMMANDID, json, true, "OFF"); - } else if (wifiMode == ESP_BT) { - response = format_response(COMMANDID, json, true, "BT"); - } else if (wifiMode == ESP_AP_SETUP) { - response = format_response(COMMANDID, json, true, "WIFI-SETUP"); - } else { - response = format_response(COMMANDID, json, true, "???"); - } - } else { //set -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter.toUpperCase(); - if (!( -#if defined( BLUETOOTH_FEATURE) - (parameter == "BT") || -#endif //BLUETOOTH_FEATURE -#if defined( WIFI_FEATURE) - (parameter == "WIFI-SETUP") || -#endif //WIFI_FEATURE -#if defined( ETH_FEATURE) - (parameter == "ETH-STA") || //(parameter == "ETH-SRV") || -#endif //ETH_FEATURE - (parameter == "OFF"))) { + } +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter.toUpperCase(); + if (!( +#if defined(BLUETOOTH_FEATURE) + (parameter == "BT") || +#endif // BLUETOOTH_FEATURE +#if defined(WIFI_FEATURE) + (parameter == "WIFI-SETUP") || +#endif // WIFI_FEATURE +#if defined(ETH_FEATURE) + (parameter == "ETH-STA") || //(parameter == "ETH-SRV") || +#endif // ETH_FEATURE + (parameter == "OFF"))) { - String res = "Only " + String res = + "Only " #ifdef BLUETOOTH_FEATURE - "BT or " -#endif //BLUETOOTH_FEATURE + "BT or " +#endif // BLUETOOTH_FEATURE #ifdef WIFI_FEATURE - "WIFI-SETUP or " -#endif //WIFI_FEATURE - "OFF mode supported!"; - response = format_response(COMMANDID, json, false, res.c_str()); - noError = false; - } - if (noError) { - int8_t bbuf = ESP_NO_NETWORK; + "WIFI-SETUP or " +#endif // WIFI_FEATURE + "OFF mode supported!"; + response = format_response(COMMANDID, json, false, res.c_str()); + noError = false; + } + if (noError) { + int8_t bbuf = ESP_NO_NETWORK; #ifdef WIFI_FEATURE - if(parameter == "WIFI-SETUP") { - bbuf = ESP_AP_SETUP; - } -#endif //WIFI_FEATURE + if (parameter == "WIFI-SETUP") { + bbuf = ESP_AP_SETUP; + } +#endif // WIFI_FEATURE #ifdef BLUETOOTH_FEATURE - if(parameter == "BT") { - bbuf = ESP_BT; - } -#endif //BLUETOOTH_FEATURE - if (!Settings_ESP3D::write_byte(ESP_STA_FALLBACK_MODE, bbuf)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } else { - response = format_response(COMMANDID, json, true, "ok"); - } - } - } + if (parameter == "BT") { + bbuf = ESP_BT; + } +#endif // BLUETOOTH_FEATURE + if (!Settings_ESP3D::write_byte(ESP_STA_FALLBACK_MODE, bbuf)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } else { + response = format_response(COMMANDID, json, true, "ok"); + } } + } } + } + if (json) { + output->printLN(response.c_str()); + } else { if (noError) { - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); - } + output->printMSG(response.c_str()); } else { - output->printERROR(response.c_str(), errorCode); + output->printERROR(response.c_str(), errorCode); } - return noError; + } + return noError; } -#endif //WIFI_FEATURE +#endif // WIFI_FEATURE diff --git a/esp3d/src/core/espcmd/ESP105.cpp b/esp3d/src/core/espcmd/ESP105.cpp index 3d4bc2a2..f8416c7f 100644 --- a/esp3d/src/core/espcmd/ESP105.cpp +++ b/esp3d/src/core/espcmd/ESP105.cpp @@ -18,71 +18,75 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (WIFI_FEATURE) +#if defined(WIFI_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/wifi/wificonfig.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/wifi/wificonfig.h" -#include "../../modules/authentication/authentication_service.h" -#define COMMANDID 105 -//AP SSID -//[ESP105] [json=no] [pwd=] -bool Commands::ESP105(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +#define COMMANDID 105 +// AP SSID +//[ESP105] [json=no] [pwd=] +bool Commands::ESP105(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + response = format_response(COMMANDID, json, true, + Settings_ESP3D::read_string(ESP_AP_SSID)); + } else { // set +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = format_response(COMMANDID, json, false, + "Wrong authentication level"); noError = false; errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - response = format_response(COMMANDID, json, true, Settings_ESP3D::read_string(ESP_AP_SSID)); - } else { //set -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } -#endif //AUTHENTICATION_FEATURE - if (noError) { - if (!WiFiConfig::isSSIDValid (parameter.c_str() ) ) { - response = format_response(COMMANDID, json, false, "Incorrect SSID"); - noError = false; - } else { - if(!Settings_ESP3D::write_string(ESP_AP_SSID, parameter.c_str())) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } else { - response = format_response(COMMANDID, json, true, "ok"); - } - } - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); + } +#endif // AUTHENTICATION_FEATURE + if (noError) { + if (!WiFiConfig::isSSIDValid(parameter.c_str())) { + response = format_response(COMMANDID, json, false, "Incorrect SSID"); + noError = false; } else { - output->printMSG (response.c_str() ); + if (!Settings_ESP3D::write_string(ESP_AP_SSID, parameter.c_str())) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } else { + response = format_response(COMMANDID, json, true, "ok"); + } } - } else { - output->printERROR(response.c_str(), errorCode); + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //WIFI_FEATURE +#endif // WIFI_FEATURE diff --git a/esp3d/src/core/espcmd/ESP106.cpp b/esp3d/src/core/espcmd/ESP106.cpp index e9acb1f6..be9ebf00 100644 --- a/esp3d/src/core/espcmd/ESP106.cpp +++ b/esp3d/src/core/espcmd/ESP106.cpp @@ -18,65 +18,69 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (WIFI_FEATURE) +#if defined(WIFI_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/wifi/wificonfig.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/wifi/wificonfig.h" -#include "../../modules/authentication/authentication_service.h" -#define COMMANDID 106 -//AP Password + +#define COMMANDID 106 +// AP Password //[ESP106] [json=no] [pwd=] -bool Commands::ESP106(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - bool clearSetting = has_tag (cmd_params,"NOPASSWORD"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP106(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + bool clearSetting = has_tag(cmd_params, "NOPASSWORD"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } + if (auth_type != LEVEL_ADMIN) { + response = + format_response(COMMANDID, json, false, "Wrong authentication level"); + noError = false; + errorCode = 401; + } #else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - if (parameter.length() == 0) { - response = format_response(COMMANDID, json, false, "Password not displayable"); - noError = false; - } else { - if (clearSetting) { - parameter=""; - } - if (!WiFiConfig::isPasswordValid (parameter.c_str() ) ) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } else { - if(!Settings_ESP3D::write_string(ESP_AP_PASSWORD, parameter.c_str())) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } else { - response = format_response(COMMANDID, json, true, "ok"); - } - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); - } + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + if (parameter.length() == 0) { + response = + format_response(COMMANDID, json, false, "Password not displayable"); + noError = false; } else { - output->printERROR(response.c_str(), errorCode); + if (clearSetting) { + parameter = ""; + } + if (!WiFiConfig::isPasswordValid(parameter.c_str())) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } else { + if (!Settings_ESP3D::write_string(ESP_AP_PASSWORD, parameter.c_str())) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } else { + response = format_response(COMMANDID, json, true, "ok"); + } + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //WIFI_FEATURE +#endif // WIFI_FEATURE diff --git a/esp3d/src/core/espcmd/ESP107.cpp b/esp3d/src/core/espcmd/ESP107.cpp index 11230724..279ca8fa 100644 --- a/esp3d/src/core/espcmd/ESP107.cpp +++ b/esp3d/src/core/espcmd/ESP107.cpp @@ -18,70 +18,77 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (WIFI_FEATURE) +#if defined(WIFI_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/network/netconfig.h" +#include "../../modules/wifi/wificonfig.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/wifi/wificonfig.h" -#include "../../modules/network/netconfig.h" -#include "../../modules/authentication/authentication_service.h" -#define COMMANDID 107 -//Change AP IP + +#define COMMANDID 107 +// Change AP IP //[ESP107] [json=no] pwd= -bool Commands::ESP107(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP107(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + response = format_response( + COMMANDID, json, true, + Settings_ESP3D::read_IP_String(ESP_AP_IP_VALUE).c_str()); + } else { // set +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = format_response(COMMANDID, json, false, + "Wrong authentication level"); noError = false; errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - response = format_response(COMMANDID, json, true, Settings_ESP3D::read_IP_String(ESP_AP_IP_VALUE).c_str()); - } else { //set -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } -#endif //AUTHENTICATION_FEATURE - if (noError) { - if ( !NetConfig::isValidIP(parameter.c_str())) { - response = format_response(COMMANDID, json, false, "Incorrect IP"); - noError = false; - } - if ( !Settings_ESP3D::write_IP_String(ESP_AP_IP_VALUE, parameter.c_str())) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } else { - response = format_response(COMMANDID, json, true, "ok"); - } - } + } +#endif // AUTHENTICATION_FEATURE + if (noError) { + if (!NetConfig::isValidIP(parameter.c_str())) { + response = format_response(COMMANDID, json, false, "Incorrect IP"); + noError = false; } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); + if (!Settings_ESP3D::write_IP_String(ESP_AP_IP_VALUE, + parameter.c_str())) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; } else { - output->printMSG (response.c_str() ); + response = format_response(COMMANDID, json, true, "ok"); } - } else { - output->printERROR(response.c_str(), errorCode); + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //WIFI_FEATURE +#endif // WIFI_FEATURE diff --git a/esp3d/src/core/espcmd/ESP108.cpp b/esp3d/src/core/espcmd/ESP108.cpp index fb622bd9..d10343c5 100644 --- a/esp3d/src/core/espcmd/ESP108.cpp +++ b/esp3d/src/core/espcmd/ESP108.cpp @@ -18,71 +18,79 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (WIFI_FEATURE) +#if defined(WIFI_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/wifi/wificonfig.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/wifi/wificonfig.h" -#include "../../modules/authentication/authentication_service.h" -#define COMMANDID 108 -//Change AP channel + +#define COMMANDID 108 +// Change AP channel //[ESP108] [json=no] [pwd=] -bool Commands::ESP108(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP108(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + response = format_response( + COMMANDID, json, true, + String(Settings_ESP3D::read_byte(ESP_AP_CHANNEL)).c_str()); + } else { // set +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = format_response(COMMANDID, json, false, + "Wrong authentication level"); noError = false; errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - response = format_response(COMMANDID, json, true, String(Settings_ESP3D::read_byte (ESP_AP_CHANNEL)).c_str()); - } else { //set -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } -#endif //AUTHENTICATION_FEATURE - if (noError) { - int bbuf = parameter.toInt(); - if ((bbuf > Settings_ESP3D::get_max_byte (ESP_AP_CHANNEL)) || (bbuf < Settings_ESP3D::get_min_byte (ESP_AP_CHANNEL))) { - response = format_response(COMMANDID, json, false, "Incorrect channel"); - noError = false; - } else { - if (!Settings_ESP3D::write_byte (ESP_AP_CHANNEL, (int8_t)bbuf)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } else { - response = format_response(COMMANDID, json, true, "ok"); - } - } - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); + } +#endif // AUTHENTICATION_FEATURE + if (noError) { + int bbuf = parameter.toInt(); + if ((bbuf > Settings_ESP3D::get_max_byte(ESP_AP_CHANNEL)) || + (bbuf < Settings_ESP3D::get_min_byte(ESP_AP_CHANNEL))) { + response = + format_response(COMMANDID, json, false, "Incorrect channel"); + noError = false; } else { - output->printMSG (response.c_str() ); + if (!Settings_ESP3D::write_byte(ESP_AP_CHANNEL, (int8_t)bbuf)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } else { + response = format_response(COMMANDID, json, true, "ok"); + } } - } else { - output->printERROR(response.c_str(), errorCode); + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //WIFI_FEATURE +#endif // WIFI_FEATURE diff --git a/esp3d/src/core/espcmd/ESP110.cpp b/esp3d/src/core/espcmd/ESP110.cpp index ac051b68..4ebc08d8 100644 --- a/esp3d/src/core/espcmd/ESP110.cpp +++ b/esp3d/src/core/espcmd/ESP110.cpp @@ -18,141 +18,148 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined( WIFI_FEATURE) || defined( BLUETOOTH_FEATURE) || defined (ETH_FEATURE) +#if defined(WIFI_FEATURE) || defined(BLUETOOTH_FEATURE) || defined(ETH_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/network/netconfig.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/network/netconfig.h" -#include "../../modules/authentication/authentication_service.h" -#define COMMANDID 110 -//Set radio state at boot which can be BT, WIFI-STA, WIFI-AP, ETH-STA, OFF + +#define COMMANDID 110 +// Set radio state at boot which can be BT, WIFI-STA, WIFI-AP, ETH-STA, OFF //[ESP110] json= pwd= -bool Commands::ESP110(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP110(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + int8_t wifiMode = Settings_ESP3D::read_byte(ESP_RADIO_MODE); + if (wifiMode == ESP_NO_NETWORK) { + response = format_response(COMMANDID, json, true, "OFF"); + } else if (wifiMode == ESP_BT) { + response = format_response(COMMANDID, json, true, "BT"); + } else if (wifiMode == ESP_WIFI_AP) { + response = format_response(COMMANDID, json, true, "WIFI-AP"); + } else if (wifiMode == ESP_WIFI_STA) { + response = format_response(COMMANDID, json, true, "WIFI-STA"); + // } else if (wifiMode == ESP_ETH_SRV) { + // output->printMSG("ETH-SRV"); + } else if (wifiMode == ESP_ETH_STA) { + response = format_response(COMMANDID, json, true, "ETH-STA"); + } else if (wifiMode == ESP_AP_SETUP) { + response = format_response(COMMANDID, json, true, "WIFI-SETUP"); + } else { + response = format_response(COMMANDID, json, true, "???"); + } + } else { // set +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = format_response(COMMANDID, json, false, + "Wrong authentication level"); noError = false; errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - int8_t wifiMode = Settings_ESP3D::read_byte(ESP_RADIO_MODE); - if (wifiMode == ESP_NO_NETWORK) { - response = format_response(COMMANDID, json, true, "OFF"); - } else if (wifiMode == ESP_BT) { - response = format_response(COMMANDID, json, true, "BT"); - } else if (wifiMode == ESP_WIFI_AP) { - response = format_response(COMMANDID, json, true, "WIFI-AP"); - } else if (wifiMode == ESP_WIFI_STA) { - response = format_response(COMMANDID, json, true, "WIFI-STA"); -// } else if (wifiMode == ESP_ETH_SRV) { -// output->printMSG("ETH-SRV"); - } else if (wifiMode == ESP_ETH_STA) { - response = format_response(COMMANDID, json, true, "ETH-STA"); - } else if (wifiMode == ESP_AP_SETUP) { - response = format_response(COMMANDID, json, true, "WIFI-SETUP"); - } else { - response = format_response(COMMANDID, json, true, "???"); - } - } else { //set -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter.toUpperCase(); - if (!( -#if defined( BLUETOOTH_FEATURE) - (parameter == "BT") || -#endif //BLUETOOTH_FEATURE -#if defined( WIFI_FEATURE) - (parameter == "WIFI-STA") || (parameter == "WIFI-AP") || (parameter == "WIFI-SETUP") || -#endif //WIFI_FEATURE -#if defined( ETH_FEATURE) - (parameter == "ETH-STA") || //(parameter == "ETH-SRV") || -#endif //ETH_FEATURE - (parameter == "OFF"))) { + } +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter.toUpperCase(); + if (!( +#if defined(BLUETOOTH_FEATURE) + (parameter == "BT") || +#endif // BLUETOOTH_FEATURE +#if defined(WIFI_FEATURE) + (parameter == "WIFI-STA") || (parameter == "WIFI-AP") || + (parameter == "WIFI-SETUP") || +#endif // WIFI_FEATURE +#if defined(ETH_FEATURE) + (parameter == "ETH-STA") || //(parameter == "ETH-SRV") || +#endif // ETH_FEATURE + (parameter == "OFF"))) { - String res ="Only " + String res = + "Only " #ifdef BLUETOOTH_FEATURE - "BT or " -#endif //BLUETOOTH_FEATURE + "BT or " +#endif // BLUETOOTH_FEATURE #ifdef WIFI_FEATURE - "WIFI-STA or WIFI-AP or WIFI-SETUP or " -#endif //WIFI_FEATURE + "WIFI-STA or WIFI-AP or WIFI-SETUP or " +#endif // WIFI_FEATURE #ifdef ETH_FEATURE - "ETH-STA or " -#endif //ETH_FEATURE - "OFF mode supported!"; - response = format_response(COMMANDID, json, false, res.c_str()); - noError = false; - } - if (noError) { - int8_t bbuf = ESP_NO_NETWORK; + "ETH-STA or " +#endif // ETH_FEATURE + "OFF mode supported!"; + response = format_response(COMMANDID, json, false, res.c_str()); + noError = false; + } + if (noError) { + int8_t bbuf = ESP_NO_NETWORK; #ifdef WIFI_FEATURE - if(parameter == "WIFI-STA") { - bbuf = ESP_WIFI_STA; - } - if(parameter == "WIFI-AP") { - bbuf = ESP_WIFI_AP; - } - if(parameter == "WIFI-SETUP") { - bbuf = ESP_AP_SETUP; - } -#endif //WIFI_FEATURE + if (parameter == "WIFI-STA") { + bbuf = ESP_WIFI_STA; + } + if (parameter == "WIFI-AP") { + bbuf = ESP_WIFI_AP; + } + if (parameter == "WIFI-SETUP") { + bbuf = ESP_AP_SETUP; + } +#endif // WIFI_FEATURE #ifdef ETH_FEATURE - if(parameter == "ETH-STA") { - bbuf = ESP_ETH_STA; - } + if (parameter == "ETH-STA") { + bbuf = ESP_ETH_STA; + } // if(parameter == "ETH-SRV") { // bbuf = ESP_ETH_SRV; // } -#endif //ETH_FEATURE +#endif // ETH_FEATURE #ifdef BLUETOOTH_FEATURE - if(parameter == "BT") { - bbuf = ESP_BT; - } -#endif //BLUETOOTH_FEATURE - if (!Settings_ESP3D::write_byte(ESP_RADIO_MODE, bbuf)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } else { - if (!NetConfig::begin()) { - response = format_response(COMMANDID, json, false, "Cannot setup network"); - noError = false; - } else { - response = format_response(COMMANDID, json, true, "ok"); - } - } - } + if (parameter == "BT") { + bbuf = ESP_BT; + } +#endif // BLUETOOTH_FEATURE + if (!Settings_ESP3D::write_byte(ESP_RADIO_MODE, bbuf)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } else { + if (!NetConfig::begin()) { + response = format_response(COMMANDID, json, false, + "Cannot setup network"); + noError = false; + } else { + response = format_response(COMMANDID, json, true, "ok"); } + } } + } } + } + if (json) { + output->printLN(response.c_str()); + } else { if (noError) { - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); - } + output->printMSG(response.c_str()); } else { - output->printERROR(response.c_str(), errorCode); + output->printERROR(response.c_str(), errorCode); } - return noError; + } + return noError; } -#endif //WIFI_FEATURE +#endif // WIFI_FEATURE diff --git a/esp3d/src/core/espcmd/ESP111.cpp b/esp3d/src/core/espcmd/ESP111.cpp index 8a9f4903..c97c947e 100644 --- a/esp3d/src/core/espcmd/ESP111.cpp +++ b/esp3d/src/core/espcmd/ESP111.cpp @@ -59,7 +59,11 @@ bool Commands::ESP111(const char* cmd_params, level_authenticate_type auth_type, } } } else { - output->printERROR(response.c_str(), 200); + if (json) { + output->printLN(response.c_str()); + } else { + output->printERROR(response.c_str(), 200); + } } return noError; } diff --git a/esp3d/src/core/espcmd/ESP112.cpp b/esp3d/src/core/espcmd/ESP112.cpp index f901bd4b..fa154d04 100644 --- a/esp3d/src/core/espcmd/ESP112.cpp +++ b/esp3d/src/core/espcmd/ESP112.cpp @@ -19,69 +19,75 @@ */ #include "../../include/esp3d_config.h" #if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BT_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/network/netconfig.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/network/netconfig.h" -#include "../../modules/authentication/authentication_service.h" -//Get/Set hostname + +// Get/Set hostname //[ESP112] [json=no] pwd= -#define COMMANDID 112 -bool Commands::ESP112(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +#define COMMANDID 112 +bool Commands::ESP112(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // Get hostname + if (parameter.length() == 0) { + response = format_response(COMMANDID, json, true, + Settings_ESP3D::read_string(ESP_HOSTNAME)); + } else { // set host name +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = format_response(COMMANDID, json, false, + "Wrong authentication level"); noError = false; errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //Get hostname - if (parameter.length() == 0) { - response = format_response(COMMANDID, json, true, Settings_ESP3D::read_string(ESP_HOSTNAME)); - } else { //set host name -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } -#endif //AUTHENTICATION_FEATURE - if (noError) { - if (!NetConfig::isHostnameValid (parameter.c_str())) { - response = format_response(COMMANDID, json, false, "Incorrect hostname"); - noError = false; - } else { - if (!Settings_ESP3D::write_string (ESP_HOSTNAME, parameter.c_str())) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } else { - response = format_response(COMMANDID, json, true, "ok"); - } - } - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); + } +#endif // AUTHENTICATION_FEATURE + if (noError) { + if (!NetConfig::isHostnameValid(parameter.c_str())) { + response = + format_response(COMMANDID, json, false, "Incorrect hostname"); + noError = false; } else { - output->printMSG (response.c_str() ); + if (!Settings_ESP3D::write_string(ESP_HOSTNAME, parameter.c_str())) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } else { + response = format_response(COMMANDID, json, true, "ok"); + } } - } else { - output->printERROR(response.c_str(), errorCode); + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //WIFI_FEATURE || ETH_FEATURE || BT_FEATURE +#endif // WIFI_FEATURE || ETH_FEATURE || BT_FEATURE diff --git a/esp3d/src/core/espcmd/ESP114.cpp b/esp3d/src/core/espcmd/ESP114.cpp index 7596e07d..afa55e73 100644 --- a/esp3d/src/core/espcmd/ESP114.cpp +++ b/esp3d/src/core/espcmd/ESP114.cpp @@ -19,70 +19,79 @@ */ #include "../../include/esp3d_config.h" #if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BT_FEATURE) +#include "../../modules/authentication/authentication_service.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -//Get/Set Boot radio state which can be ON, OFF + +// Get/Set Boot radio state which can be ON, OFF //[ESP114] json= pwd= -#define COMMANDID 114 -bool Commands::ESP114(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +#define COMMANDID 114 +bool Commands::ESP114(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + response = format_response( + COMMANDID, json, true, + (Settings_ESP3D::read_byte(ESP_BOOT_RADIO_STATE) == 0) ? "OFF" + : "ON"); + } else { // set +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = format_response(COMMANDID, json, false, + "Wrong authentication level"); noError = false; errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - response =format_response(COMMANDID, json, true, (Settings_ESP3D::read_byte(ESP_BOOT_RADIO_STATE) == 0)?"OFF":"ON"); - } else { //set -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter.toUpperCase(); - if (!((parameter == "ON") || (parameter == "OFF"))) { - response = format_response(COMMANDID, json, false, "Only ON or OFF mode supported"); - noError = false; - } else { - if (!Settings_ESP3D::write_byte (ESP_BOOT_RADIO_STATE, (parameter == "ON")?1:0)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } else { - response = format_response(COMMANDID, json, true, "ok"); - } - } - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); + } +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter.toUpperCase(); + if (!((parameter == "ON") || (parameter == "OFF"))) { + response = format_response(COMMANDID, json, false, + "Only ON or OFF mode supported"); + noError = false; } else { - output->printMSG (response.c_str() ); + if (!Settings_ESP3D::write_byte(ESP_BOOT_RADIO_STATE, + (parameter == "ON") ? 1 : 0)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } else { + response = format_response(COMMANDID, json, true, "ok"); + } } - } else { - output->printERROR(response.c_str(), errorCode); + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BT_FEATURE) \ No newline at end of file +#endif // defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BT_FEATURE) \ No newline at end of file diff --git a/esp3d/src/core/espcmd/ESP115.cpp b/esp3d/src/core/espcmd/ESP115.cpp index 6f7349ba..2d4129eb 100644 --- a/esp3d/src/core/espcmd/ESP115.cpp +++ b/esp3d/src/core/espcmd/ESP115.cpp @@ -19,75 +19,82 @@ */ #include "../../include/esp3d_config.h" #if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BT_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/network/netconfig.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/network/netconfig.h" -#include "../../modules/authentication/authentication_service.h" -#define COMMANDID 115 -//Get/Set immediate Network (WiFi/BT/Ethernet) state which can be ON, OFF + +#define COMMANDID 115 +// Get/Set immediate Network (WiFi/BT/Ethernet) state which can be ON, OFF //[ESP115] json= pwd= -bool Commands::ESP115(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP115(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + response = format_response(COMMANDID, json, true, + (NetConfig::started()) ? "ON" : "OFF"); + } else { // set +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = format_response(COMMANDID, json, false, + "Wrong authentication level"); noError = false; errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - response =format_response(COMMANDID, json, true, (NetConfig::started())?"ON":"OFF"); - } else { //set -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; + } +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter.toUpperCase(); + if ((parameter == "ON") || (parameter == "OFF")) { + if (parameter == "ON") { + if (!NetConfig::begin()) { + response = format_response(COMMANDID, json, false, + "Cannot setup network"); + noError = false; } -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter.toUpperCase(); - if((parameter == "ON") || (parameter == "OFF")) { - if (parameter == "ON") { - if (!NetConfig::begin()) { - response = format_response(COMMANDID, json, false, "Cannot setup network"); - noError = false; - } - } else { - NetConfig::end(); - } - if (noError) { - response = format_response(COMMANDID, json, true, "ok"); - } - } else { - response = format_response(COMMANDID, json, false, "Only mode ON and OFF are supported"); - noError = false; - } - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); + } else { + NetConfig::end(); + } + if (noError) { + response = format_response(COMMANDID, json, true, "ok"); + } } else { - output->printMSG (response.c_str() ); + response = format_response(COMMANDID, json, false, + "Only mode ON and OFF are supported"); + noError = false; } - } else { - output->printERROR(response.c_str(), errorCode); + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //WIFI_FEATURE || ETH_FEATURE || BT_FEATURE +#endif // WIFI_FEATURE || ETH_FEATURE || BT_FEATURE diff --git a/esp3d/src/core/espcmd/ESP120.cpp b/esp3d/src/core/espcmd/ESP120.cpp index faf20fe8..dd5072df 100644 --- a/esp3d/src/core/espcmd/ESP120.cpp +++ b/esp3d/src/core/espcmd/ESP120.cpp @@ -18,70 +18,78 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (HTTP_FEATURE) +#if defined(HTTP_FEATURE) +#include "../../modules/authentication/authentication_service.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#define COMMANDID 120 -//Set HTTP state which can be ON, OFF + +#define COMMANDID 120 +// Set HTTP state which can be ON, OFF //[ESP120] json= pwd= -bool Commands::ESP120(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP120(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + + // get + if (parameter.length() == 0) { + response = format_response( + COMMANDID, json, true, + (Settings_ESP3D::read_byte(ESP_HTTP_ON) == 0) ? "OFF" : "ON"); + } else { // set +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = format_response(COMMANDID, json, false, + "Wrong authentication level"); noError = false; errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - - //get - if (parameter.length() == 0) { - response = format_response(COMMANDID, json, true, (Settings_ESP3D::read_byte(ESP_HTTP_ON) == 0)?"OFF":"ON"); - } else { //set -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter.toUpperCase(); - if (!((parameter == "ON") || (parameter == "OFF"))) { - response = format_response(COMMANDID, json, false, "Only ON or OFF mode supported!"); - noError = false; - } else { - if (!Settings_ESP3D::write_byte (ESP_HTTP_ON, (parameter == "ON")?1:0)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } else { - response = format_response(COMMANDID, json, true, "ok"); - } - } - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); + } +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter.toUpperCase(); + if (!((parameter == "ON") || (parameter == "OFF"))) { + response = format_response(COMMANDID, json, false, + "Only ON or OFF mode supported!"); + noError = false; } else { - output->printMSG (response.c_str() ); + if (!Settings_ESP3D::write_byte(ESP_HTTP_ON, + (parameter == "ON") ? 1 : 0)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } else { + response = format_response(COMMANDID, json, true, "ok"); + } } - } else { - output->printERROR(response.c_str(), errorCode); + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //HTTP_FEATURE +#endif // HTTP_FEATURE diff --git a/esp3d/src/core/espcmd/ESP121.cpp b/esp3d/src/core/espcmd/ESP121.cpp index f0708e41..0b943218 100644 --- a/esp3d/src/core/espcmd/ESP121.cpp +++ b/esp3d/src/core/espcmd/ESP121.cpp @@ -18,70 +18,77 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (HTTP_FEATURE) +#if defined(HTTP_FEATURE) +#include "../../modules/authentication/authentication_service.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#define COMMANDID 121 -//Set HTTP port + +#define COMMANDID 121 +// Set HTTP port //[ESP121] json= pwd= -bool Commands::ESP121(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP121(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + response = format_response( + COMMANDID, json, true, + String(Settings_ESP3D::read_uint32(ESP_HTTP_PORT)).c_str()); + } else { // set +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = format_response(COMMANDID, json, false, + "Wrong authentication level"); noError = false; errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - response = format_response(COMMANDID, json, true,String(Settings_ESP3D::read_uint32(ESP_HTTP_PORT)).c_str()); - } else { //set -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } -#endif //AUTHENTICATION_FEATURE - if (noError) { - uint ibuf = parameter.toInt(); - if ((ibuf > Settings_ESP3D::get_max_int32_value(ESP_HTTP_PORT)) || (ibuf < Settings_ESP3D::get_min_int32_value(ESP_HTTP_PORT))) { - response = format_response(COMMANDID, json, false, "Incorrect port"); - noError = false; - } else { - if (!Settings_ESP3D::write_uint32 (ESP_HTTP_PORT, ibuf)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } else { - response = format_response(COMMANDID, json, true, "ok"); - } - } - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); + } +#endif // AUTHENTICATION_FEATURE + if (noError) { + uint ibuf = parameter.toInt(); + if ((ibuf > Settings_ESP3D::get_max_int32_value(ESP_HTTP_PORT)) || + (ibuf < Settings_ESP3D::get_min_int32_value(ESP_HTTP_PORT))) { + response = format_response(COMMANDID, json, false, "Incorrect port"); + noError = false; } else { - output->printMSG (response.c_str() ); + if (!Settings_ESP3D::write_uint32(ESP_HTTP_PORT, ibuf)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } else { + response = format_response(COMMANDID, json, true, "ok"); + } } - } else { - output->printERROR(response.c_str(), errorCode); + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //HTTP_FEATURE +#endif // HTTP_FEATURE diff --git a/esp3d/src/core/espcmd/ESP130.cpp b/esp3d/src/core/espcmd/ESP130.cpp index 4e304baf..1e620912 100644 --- a/esp3d/src/core/espcmd/ESP130.cpp +++ b/esp3d/src/core/espcmd/ESP130.cpp @@ -18,75 +18,84 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (TELNET_FEATURE) +#if defined(TELNET_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/telnet/telnet_server.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#include "../../modules/telnet/telnet_server.h" -#define COMMANDID 130 -//Set TELNET state which can be ON, OFF, CLOSE + +#define COMMANDID 130 +// Set TELNET state which can be ON, OFF, CLOSE //[ESP130] json= pwd= -bool Commands::ESP130(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP130(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + response = format_response( + COMMANDID, json, true, + (Settings_ESP3D::read_byte(ESP_HTTP_ON) == 0) ? "OFF" : "ON"); + } else { // set +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = format_response(COMMANDID, json, false, + "Wrong authentication level"); noError = false; errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - response = format_response(COMMANDID, json, true, (Settings_ESP3D::read_byte(ESP_HTTP_ON) == 0)?"OFF":"ON"); - } else { //set -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter.toUpperCase(); - if (!((parameter == "ON") || (parameter == "OFF") || (parameter == "CLOSE"))) { - response = format_response(COMMANDID, json, false, "Only ON or OFF or CLOSE mode supported!"); - noError = false; - } else { - if (parameter == "CLOSE") { - telnet_server.closeClient(); - } else { - if (!Settings_ESP3D::write_byte (ESP_TELNET_ON, (parameter == "ON")?1:0)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } - } - if (noError) { - response = format_response(COMMANDID, json, true, "ok"); - } - } - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); + } +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter.toUpperCase(); + if (!((parameter == "ON") || (parameter == "OFF") || + (parameter == "CLOSE"))) { + response = format_response(COMMANDID, json, false, + "Only ON or OFF or CLOSE mode supported!"); + noError = false; } else { - output->printMSG (response.c_str() ); + if (parameter == "CLOSE") { + telnet_server.closeClient(); + } else { + if (!Settings_ESP3D::write_byte(ESP_TELNET_ON, + (parameter == "ON") ? 1 : 0)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } + } + if (noError) { + response = format_response(COMMANDID, json, true, "ok"); + } } - } else { - output->printERROR(response.c_str(), errorCode); + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //TELNET_FEATURE +#endif // TELNET_FEATURE diff --git a/esp3d/src/core/espcmd/ESP131.cpp b/esp3d/src/core/espcmd/ESP131.cpp index 0862a646..f01e24ec 100644 --- a/esp3d/src/core/espcmd/ESP131.cpp +++ b/esp3d/src/core/espcmd/ESP131.cpp @@ -18,69 +18,76 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (TELNET_FEATURE) +#if defined(TELNET_FEATURE) +#include "../../modules/authentication/authentication_service.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#define COMMANDID 131 -//Set TELNET port + +#define COMMANDID 131 +// Set TELNET port //[ESP131] json= pwd= -bool Commands::ESP131(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP131(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + response = format_response( + COMMANDID, json, true, + String(Settings_ESP3D::read_uint32(ESP_TELNET_PORT)).c_str()); + } else { // set +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = format_response(COMMANDID, json, false, + "Wrong authentication level"); noError = false; errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - response = format_response(COMMANDID, json, true,String(Settings_ESP3D::read_uint32(ESP_TELNET_PORT)).c_str()); - } else { //set -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } -#endif //AUTHENTICATION_FEATURE - if (noError) { - uint ibuf = parameter.toInt(); - if ((ibuf > Settings_ESP3D::get_max_int32_value(ESP_TELNET_PORT)) || (ibuf < Settings_ESP3D::get_min_int32_value(ESP_TELNET_PORT))) { - response = format_response(COMMANDID, json, false, "Incorrect port"); - noError = false; - } else { - if (!Settings_ESP3D::write_uint32 (ESP_TELNET_PORT, ibuf)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } else { - response = format_response(COMMANDID, json, true, "ok"); - } - } - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); + } +#endif // AUTHENTICATION_FEATURE + if (noError) { + uint ibuf = parameter.toInt(); + if ((ibuf > Settings_ESP3D::get_max_int32_value(ESP_TELNET_PORT)) || + (ibuf < Settings_ESP3D::get_min_int32_value(ESP_TELNET_PORT))) { + response = format_response(COMMANDID, json, false, "Incorrect port"); + noError = false; } else { - output->printMSG (response.c_str() ); + if (!Settings_ESP3D::write_uint32(ESP_TELNET_PORT, ibuf)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } else { + response = format_response(COMMANDID, json, true, "ok"); + } } - } else { - output->printERROR(response.c_str(), errorCode); + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //TELNET_FEATURE +#endif // TELNET_FEATURE diff --git a/esp3d/src/core/espcmd/ESP140.cpp b/esp3d/src/core/espcmd/ESP140.cpp index 3e49a85b..51aecd33 100644 --- a/esp3d/src/core/espcmd/ESP140.cpp +++ b/esp3d/src/core/espcmd/ESP140.cpp @@ -20,15 +20,15 @@ #include "../../include/esp3d_config.h" #if defined(TIMESTAMP_FEATURE) #include "../../modules/authentication/authentication_service.h" -#include "../../modules/time/time_server.h" +#include "../../modules/time/time_service.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" #define COMMANDID 140 // Sync / Set / Get current time -//[ESP140] -// NOW json= pwd= +//[ESP140] +// NOW json= pwd= bool Commands::ESP140(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput* output) { bool noError = true; @@ -106,22 +106,48 @@ bool Commands::ESP140(const char* cmd_params, level_authenticate_type auth_type, } } if (noError) { - parameter = get_param(cmd_params, "zone="); + parameter = get_param(cmd_params, "tzone="); if (parameter.length() > 0) { hasParam = true; - if ((parameter.toInt() <= - (int8_t)Settings_ESP3D::get_max_byte(ESP_TIMEZONE)) && - (parameter.toInt() >= - (int8_t)Settings_ESP3D::get_min_byte(ESP_TIMEZONE))) { - if (!Settings_ESP3D::write_byte(ESP_TIMEZONE, parameter.toInt())) { + bool isvalid = false; + for (uint8_t i = 0; i < SupportedTimeZonesSize; i++) { + if (parameter == SupportedTimeZones[i]) { + isvalid = true; + break; + } + } + if (isvalid) { + if (!Settings_ESP3D::write_string(ESP_TIME_ZONE, + parameter.c_str())) { response = format_response(COMMANDID, json, false, "Set time zone failed"); noError = false; } + } else { + response = + format_response(COMMANDID, json, false, "Invalid time zone"); + noError = false; + } + } + } + + if (noError) { + parameter = get_param(cmd_params, "ntp="); + parameter.toUpperCase(); + if (parameter.length() > 0) { + hasParam = true; + parameter.toUpperCase(); + if (parameter.length() > 0) { + if (!Settings_ESP3D::write_byte(ESP_INTERNET_TIME, + (parameter == "NO") ? 0 : 1)) { + response = format_response(COMMANDID, json, false, + "Set internet time failed"); + noError = false; + } } } } - if (noError) { + /*if (noError) { parameter = get_param(cmd_params, "dst="); if (parameter.length() > 0) { hasParam = true; @@ -135,13 +161,13 @@ bool Commands::ESP140(const char* cmd_params, level_authenticate_type auth_type, } } } - } + }*/ if (noError) { parameter = get_param(cmd_params, "time="); parameter.toUpperCase(); if (parameter.length() > 0) { hasParam = true; - if (!timeserver.setTime(parameter.c_str())) { + if (!timeService.setTime(parameter.c_str())) { response = format_response(COMMANDID, json, false, "Set time failed"); noError = false; @@ -149,12 +175,13 @@ bool Commands::ESP140(const char* cmd_params, level_authenticate_type auth_type, } } parameter = clean_param(get_param(cmd_params, "")); + parameter.toUpperCase(); if (noError) { if (has_tag(parameter.c_str(), "SYNC")) { log_esp3d("Sync time"); hasParam = true; - if (timeserver.is_internet_time()) { - if (!timeserver.begin()) { + if (timeService.is_internet_time()) { + if (!timeService.begin()) { response = format_response(COMMANDID, json, false, "Init time failed"); noError = false; @@ -167,16 +194,19 @@ bool Commands::ESP140(const char* cmd_params, level_authenticate_type auth_type, if (noError) { log_esp3d("Get time"); response = format_response(COMMANDID, json, true, - timeserver.current_time()); + timeService.getCurrentTime()); } } } if (noError) { if (has_tag(parameter.c_str(), "NOW")) { + String tmp = timeService.getCurrentTime(); + tmp += " ("; + tmp += timeService.getTimeZone(); + tmp += ")"; hasParam = true; log_esp3d("Get time"); - response = - format_response(COMMANDID, json, true, timeserver.current_time()); + response = format_response(COMMANDID, json, true, tmp.c_str()); } } if (noError && !hasParam) { @@ -203,33 +233,33 @@ bool Commands::ESP140(const char* cmd_params, level_authenticate_type auth_type, } else { tmp += ", srv3="; } - tmp += Settings_ESP3D::read_string(ESP_TIME_SERVER3); + tmp += Settings_ESP3D::read_string(ESP_TIME_ZONE); if (json) { - tmp += "\",\"zone\":\""; + tmp += "\",\"tzone\":\""; } else { - tmp += ", zone="; + tmp += ", tzone="; } - tmp += Settings_ESP3D::read_byte(ESP_TIMEZONE); + tmp += Settings_ESP3D::read_byte(ESP_INTERNET_TIME); if (json) { - tmp += "\",\"dst\":\""; + tmp += "\",\"ntp\":\""; } else { - tmp += ", dst="; + tmp += ", ntp="; } - tmp += Settings_ESP3D::read_byte(ESP_TIME_IS_DST) ? "YES" : "NO"; + tmp += Settings_ESP3D::read_byte(ESP_INTERNET_TIME) ? "YES" : "NO"; if (json) { tmp += "\"}"; } response = format_response(COMMANDID, json, true, tmp.c_str()); } } - if (noError) { - if (json) { - output->printLN(response.c_str()); - } else { - output->printMSG(response.c_str()); - } + if (json) { + output->printLN(response.c_str()); } else { - output->printERROR(response.c_str(), errorCode); + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } } return noError; } diff --git a/esp3d/src/core/espcmd/ESP150.cpp b/esp3d/src/core/espcmd/ESP150.cpp index b3270927..1f8cd107 100644 --- a/esp3d/src/core/espcmd/ESP150.cpp +++ b/esp3d/src/core/espcmd/ESP150.cpp @@ -18,110 +18,120 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" +#include "../../modules/authentication/authentication_service.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#define COMMANDID 150 + +#define COMMANDID 150 // Get/Set display/set boot delay in ms / Verbose boot //[ESP150][pwd=] -bool Commands::ESP150(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP150(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + String s = ""; + if (json) { + s += "{\"delay\":\""; + } else { + s += "delay="; + } + s += String(Settings_ESP3D::read_uint32(ESP_BOOT_DELAY)); + if (json) { + s += "\",\"verbose\":\""; + } else { + s += ", verbose="; + } + s += Settings_ESP3D::isVerboseBoot(true) ? "ON" : "OFF"; + if (json) { + s += "\"}"; + } + response = format_response(COMMANDID, json, true, s.c_str()); + } else { +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = format_response(COMMANDID, json, false, + "Wrong authentication level"); noError = false; errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - String s =""; - if(json) { - s += "{\"delay\":\""; - } else { - s+= "delay="; + } +#endif // AUTHENTICATION_FEATURE + if (noError) { + bool hasParameter = false; + parameter = get_param(cmd_params, "delay="); + if (parameter.length() != 0) { + hasParameter = true; + uint ibuf = parameter.toInt(); + if ((ibuf > Settings_ESP3D::get_max_int32_value(ESP_BOOT_DELAY)) || + (ibuf < Settings_ESP3D::get_min_int32_value(ESP_BOOT_DELAY))) { + response = + format_response(COMMANDID, json, false, "Incorrect delay"); + noError = false; + } + if (noError) { + if (!Settings_ESP3D::write_uint32(ESP_BOOT_DELAY, ibuf)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; } - s+= String(Settings_ESP3D::read_uint32(ESP_BOOT_DELAY)); - if(json) { - s += "\",\"verbose\":\""; - } else { - s+= ", verbose="; - } - s+= Settings_ESP3D::isVerboseBoot(true)?"ON":"OFF"; - if(json) { - s += "\"}"; - } - response = format_response(COMMANDID, json, true,s.c_str()); - } else { -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); + } + } + if (noError) { + parameter = get_param(cmd_params, "verbose="); + if (parameter.length() != 0) { + hasParameter = true; + if ((parameter == "ON") || (parameter == "OFF")) { + if (!Settings_ESP3D::write_byte(ESP_VERBOSE_BOOT, + (parameter == "ON") ? 1 : 0)) { + response = + format_response(COMMANDID, json, false, "Set failed"); noError = false; - errorCode = 401; - } -#endif //AUTHENTICATION_FEATURE - if (noError) { - bool hasParameter = false; - parameter = get_param (cmd_params, "delay="); - if (parameter.length() != 0) { - hasParameter = true; - uint ibuf = parameter.toInt(); - if ((ibuf > Settings_ESP3D::get_max_int32_value(ESP_BOOT_DELAY)) || (ibuf < Settings_ESP3D::get_min_int32_value(ESP_BOOT_DELAY))) { - response = format_response(COMMANDID, json, false, "Incorrect delay"); - noError = false; - } - if (noError) { - if (!Settings_ESP3D::write_uint32 (ESP_BOOT_DELAY, ibuf)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } - } - } - if(noError) { - parameter = get_param (cmd_params, "verbose="); - if (parameter.length() != 0) { - hasParameter = true; - if ((parameter == "ON")|| (parameter == "OFF")) { - if (!Settings_ESP3D::write_byte (ESP_VERBOSE_BOOT, (parameter == "ON")?1:0)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } else { - Settings_ESP3D::isVerboseBoot(true); - } - } else { - response = format_response(COMMANDID, json, false, "Only verbose +ON/OFF is allowed"); - noError = false; - } - } - } - if (noError && !hasParameter) { - response = format_response(COMMANDID, json, false, "Incorrect command"); - noError = false; - } else if(noError) { - response = format_response(COMMANDID, json, true, "ok"); - } + } else { + Settings_ESP3D::isVerboseBoot(true); + } + } else { + response = format_response(COMMANDID, json, false, + "Only verbose +ON/OFF is allowed"); + noError = false; } + } } + if (noError && !hasParameter) { + response = + format_response(COMMANDID, json, false, "Incorrect command"); + noError = false; + } else if (noError) { + response = format_response(COMMANDID, json, true, "ok"); + } + } } + } + if (json) { + output->printLN(response.c_str()); + } else { if (noError) { - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); - } + output->printMSG(response.c_str()); } else { - output->printERROR(response.c_str(), errorCode); + output->printERROR(response.c_str(), errorCode); } - return noError; + } + return noError; } diff --git a/esp3d/src/core/espcmd/ESP160.cpp b/esp3d/src/core/espcmd/ESP160.cpp index 91f03e76..b7137cb7 100644 --- a/esp3d/src/core/espcmd/ESP160.cpp +++ b/esp3d/src/core/espcmd/ESP160.cpp @@ -18,75 +18,84 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (WS_DATA_FEATURE) +#if defined(WS_DATA_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/websocket/websocket_server.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#include "../../modules/websocket/websocket_server.h" -#define COMMANDID 160 -//Set WebSocket state which can be ON, OFF, CLOSE + +#define COMMANDID 160 +// Set WebSocket state which can be ON, OFF, CLOSE //[ESP160] json= pwd= -bool Commands::ESP160(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP160(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + response = format_response( + COMMANDID, json, true, + (Settings_ESP3D::read_byte(ESP_WEBSOCKET_ON) == 0) ? "OFF" : "ON"); + } else { // set +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = format_response(COMMANDID, json, false, + "Wrong authentication level"); noError = false; errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - response = format_response(COMMANDID, json, true, (Settings_ESP3D::read_byte(ESP_WEBSOCKET_ON) == 0)?"OFF":"ON"); - } else { //set -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter.toUpperCase(); - if (!((parameter == "ON") || (parameter == "OFF") || (parameter == "CLOSE"))) { - response = format_response(COMMANDID, json, false, "Only ON or OFF or CLOSE mode supported!"); - noError = false; - } else { - if (parameter == "CLOSE") { - websocket_data_server.closeClients(); - } else { - if (!Settings_ESP3D::write_byte (ESP_WEBSOCKET_ON, (parameter == "ON")?1:0)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } - } - if (noError) { - response = format_response(COMMANDID, json, true, "ok"); - } - } - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); + } +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter.toUpperCase(); + if (!((parameter == "ON") || (parameter == "OFF") || + (parameter == "CLOSE"))) { + response = format_response(COMMANDID, json, false, + "Only ON or OFF or CLOSE mode supported!"); + noError = false; } else { - output->printMSG (response.c_str() ); + if (parameter == "CLOSE") { + websocket_data_server.closeClients(); + } else { + if (!Settings_ESP3D::write_byte(ESP_WEBSOCKET_ON, + (parameter == "ON") ? 1 : 0)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } + } + if (noError) { + response = format_response(COMMANDID, json, true, "ok"); + } } - } else { - output->printERROR(response.c_str(), errorCode); + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //WS_DATA_FEATURE +#endif // WS_DATA_FEATURE diff --git a/esp3d/src/core/espcmd/ESP161.cpp b/esp3d/src/core/espcmd/ESP161.cpp index bfab401c..c6cfaf56 100644 --- a/esp3d/src/core/espcmd/ESP161.cpp +++ b/esp3d/src/core/espcmd/ESP161.cpp @@ -18,69 +18,76 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (WS_DATA_FEATURE) +#if defined(WS_DATA_FEATURE) +#include "../../modules/authentication/authentication_service.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#define COMMANDID 161 -//Set Websocket port + +#define COMMANDID 161 +// Set Websocket port //[ESP161] json= pwd= -bool Commands::ESP161(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP161(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + response = format_response( + COMMANDID, json, true, + String(Settings_ESP3D::read_uint32(ESP_WEBSOCKET_PORT)).c_str()); + } else { // set +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = format_response(COMMANDID, json, false, + "Wrong authentication level"); noError = false; errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - response = format_response(COMMANDID, json, true,String(Settings_ESP3D::read_uint32(ESP_WEBSOCKET_PORT)).c_str()); - } else { //set -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } -#endif //AUTHENTICATION_FEATURE - if (noError) { - uint ibuf = parameter.toInt(); - if ((ibuf > Settings_ESP3D::get_max_int32_value(ESP_WEBSOCKET_PORT)) || (ibuf < Settings_ESP3D::get_min_int32_value(ESP_WEBSOCKET_PORT))) { - response = format_response(COMMANDID, json, false, "Incorrect port"); - noError = false; - } else { - if (!Settings_ESP3D::write_uint32 (ESP_WEBSOCKET_PORT, ibuf)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } else { - response = format_response(COMMANDID, json, true, "ok"); - } - } - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); + } +#endif // AUTHENTICATION_FEATURE + if (noError) { + uint ibuf = parameter.toInt(); + if ((ibuf > Settings_ESP3D::get_max_int32_value(ESP_WEBSOCKET_PORT)) || + (ibuf < Settings_ESP3D::get_min_int32_value(ESP_WEBSOCKET_PORT))) { + response = format_response(COMMANDID, json, false, "Incorrect port"); + noError = false; } else { - output->printMSG (response.c_str() ); + if (!Settings_ESP3D::write_uint32(ESP_WEBSOCKET_PORT, ibuf)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } else { + response = format_response(COMMANDID, json, true, "ok"); + } } - } else { - output->printERROR(response.c_str(), errorCode); + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //WS_DATA_FEATURE +#endif // WS_DATA_FEATURE diff --git a/esp3d/src/core/espcmd/ESP170.cpp b/esp3d/src/core/espcmd/ESP170.cpp index 6466fcb0..afae498b 100644 --- a/esp3d/src/core/espcmd/ESP170.cpp +++ b/esp3d/src/core/espcmd/ESP170.cpp @@ -18,471 +18,482 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (CAMERA_DEVICE) -#include "../commands.h" -#include "../esp3doutput.h" -#include "esp_camera.h" -#include "../settings_esp3d.h" +#if defined(CAMERA_DEVICE) #include "../../modules/authentication/authentication_service.h" #include "../../modules/camera/camera.h" -#define COMMANDID 170 -//Set Camera command value / list all values in JSON/plain +#include "../commands.h" +#include "../esp3doutput.h" +#include "../settings_esp3d.h" +#include "esp_camera.h" + +#define COMMANDID 170 +// Set Camera command value / list all values in JSON/plain //[ESP170] pwd= -//label can be: light/framesize/quality/contrast/brightness/saturation/gainceiling/colorbar -// /awb/agc/aec/hmirror/vflip/awb_gain/agc_gain/aec_value/aec2/cw/bpc/wpc -// /raw_gma/lenc/special_effect/wb_mode/ae_level -bool Commands::ESP170(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +// label can be: +// light/framesize/quality/contrast/brightness/saturation/gainceiling/colorbar +// /awb/agc/aec/hmirror/vflip/awb_gain/agc_gain/aec_value/aec2/cw/bpc/wpc +// /raw_gma/lenc/special_effect/wb_mode/ae_level +bool Commands::ESP170(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); - noError = false; - errorCode = 401; - } + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } #else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if(noError) { - if (!esp3d_camera.started()) { - response = format_response(COMMANDID, json, false, "No camera initialized"); - noError = false; - } else { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - sensor_t * s = esp_camera_sensor_get(); - if (s == nullptr) { - response = format_response(COMMANDID, json, false, "No camera initialized"); - noError = false; - } else { - String line = ""; - if (json) { - output->print ("{\"cmd\":\"170\",\"status\":\"ok\",\"data\":\"["); - } - //framesize - if (json) { - line +="{\"id\":\"framesize\",\"value\":\""; - } else { - line +="framesize:"; - } - line +=s->status.framesize; - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //quality - if (json) { - line +="{\"id\":\"quality\",\"value\":\""; - } else { - line +="quality:"; - } - line +=s->status.quality; - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //brightness - if (json) { - line +="{\"id\":\"brightness\",\"value\":\""; - } else { - line +="brightness:"; - } - line +=s->status.brightness; - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //contrast - if (json) { - line +="{\"id\":\"contrast\",\"value\":\""; - } else { - line +="contrast:"; - } - line +=s->status.contrast; - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //saturation - if (json) { - line +="{\"id\":\"saturation\",\"value\":\""; - } else { - line +="saturation:"; - } - line +=s->status.saturation; - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //sharpness - if (json) { - line +="{\"id\":\"sharpness\",\"value\":\""; - } else { - line +="sharpness:"; - } - line +=s->status.sharpness; - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //special_effect - if (json) { - line +="{\"id\":\"special_effect\",\"value\":\""; - } else { - line +="special_effect:"; - } - line +=s->status.special_effect; - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //wb_mode - if (json) { - line +="{\"id\":\"wb_mode\",\"value\":\""; - } else { - line +="wb_mode:"; - } - line +=s->status.wb_mode; - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //awb - if (json) { - line +="{\"id\":\"awb\",\"value\":\""; - } else { - line +="awb:"; - } - line +=s->status.awb; - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //awb_gain - if (json) { - line +="{\"id\":\"awb_gain\",\"value\":\""; - } else { - line +="awb_gain:"; - } - line +=s->status.awb_gain; - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //aec - if (json) { - line +="{\"id\":\"aec\",\"value\":\""; - } else { - line +="aec:"; - } - line +=s->status.aec; - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //aec2 - if (json) { - line +="{\"id\":\"aec2\",\"value\":\""; - } else { - line +="aec2:"; - } - line +=s->status.aec2; - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //ae_level - if (json) { - line +="{\"id\":\"ae_level\",\"value\":\""; - } else { - line +="ae_level:"; - } - line +=s->status.ae_level; - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //aec_value - if (json) { - line +="{\"id\":\"aec_value\",\"value\":\""; - } else { - line +="aec_value:"; - } - line +=s->status.aec_value; - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //agc - if (json) { - line +="{\"id\":\"agc\",\"value\":\""; - } else { - line +="agc:"; - } - line +=s->status.agc; - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //agc_gain - if (json) { - line +="{\"id\":\"agc_gain\",\"value\":\""; - } else { - line +="agc_gain:"; - } - line +=s->status.agc_gain; - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //gainceiling - if (json) { - line +="{\"id\":\"gainceiling\",\"value\":\""; - } else { - line +="gainceiling:"; - } - line +=s->status.gainceiling; - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //bpc - if (json) { - line +="{\"id\":\"bpc\",\"value\":\""; - } else { - line +="bpc:"; - } - line +=s->status.bpc; - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //wpc - if (json) { - line +="{\"id\":\"wpc\",\"value\":\""; - } else { - line +="wpc:"; - } - line +=s->status.wpc; - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //raw_gma - if (json) { - line +="{\"id\":\"raw_gma\",\"value\":\""; - } else { - line +="raw_gma:"; - } - line +=s->status.raw_gma; - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //lenc - if (json) { - line +="{\"id\":\"lenc\",\"value\":\""; - } else { - line +="lenc:"; - } - line +=s->status.lenc; - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //vflip - if (json) { - line +="{\"id\":\"vflip\",\"value\":\""; - } else { - line +="vflip:"; - } - line +=s->status.vflip; - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //hmirror - if (json) { - line +="{\"id\":\"hmirror\",\"value\":\""; - } else { - line +="hmirror:"; - } - line +=s->status.hmirror; - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //dcw - if (json) { - line +="{\"id\":\"dcw\",\"value\":\""; - } else { - line +="dcw:"; - } - line +=s->status.dcw; - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //colorbar - if (json) { - line +="{\"id\":\"colorbar\",\"value\":\""; - } else { - line +="colorbar:"; - } - line +=s->status.colorbar; - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; -#if CAM_LED_PIN != -1 - //light - if (json) { - line +="{\"id\":\"light\",\"value\":\""; - } else { - line +="light:"; - } - line +=digitalRead(CAM_LED_PIN)==HIGH?1:0; - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; -#endif //CAM_LED_PIN - if (json) { - output->printLN ("]}"); - } - return true; - } - } else { //set -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } -#endif //AUTHENTICATION_FEATURE - if (noError) { - String label = get_label (parameter.c_str(), "="); - if (label.length()==0) { - response = format_response(COMMANDID, json, false, "Missing command"); - noError = false; - } else { - String labels = label+"="; - String value = get_param (cmd_params,labels.c_str()); - if (value.length()==0) { - response = format_response(COMMANDID, json, false, "Invalid value"); - noError = false; - } - if (noError) { - int r = esp3d_camera.command(label.c_str(), value.c_str()); - if (r == -1) { - response = format_response(COMMANDID, json, false, "Unknow command"); - noError = false; - } else if (r == 1) { - response = format_response(COMMANDID, json, false, "Invalid value"); - noError = false; - } else { - response = format_response(COMMANDID, json, true, "ok"); - } - } - } - } - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); - } + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + if (!esp3d_camera.started()) { + response = + format_response(COMMANDID, json, false, "No camera initialized"); + noError = false; } else { - output->printERROR(response.c_str(), errorCode); + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + sensor_t* s = esp_camera_sensor_get(); + if (s == nullptr) { + response = + format_response(COMMANDID, json, false, "No camera initialized"); + noError = false; + } else { + String line = ""; + if (json) { + output->print("{\"cmd\":\"170\",\"status\":\"ok\",\"data\":\"["); + } + // framesize + if (json) { + line += "{\"id\":\"framesize\",\"value\":\""; + } else { + line += "framesize:"; + } + line += s->status.framesize; + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // quality + if (json) { + line += "{\"id\":\"quality\",\"value\":\""; + } else { + line += "quality:"; + } + line += s->status.quality; + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // brightness + if (json) { + line += "{\"id\":\"brightness\",\"value\":\""; + } else { + line += "brightness:"; + } + line += s->status.brightness; + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // contrast + if (json) { + line += "{\"id\":\"contrast\",\"value\":\""; + } else { + line += "contrast:"; + } + line += s->status.contrast; + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // saturation + if (json) { + line += "{\"id\":\"saturation\",\"value\":\""; + } else { + line += "saturation:"; + } + line += s->status.saturation; + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // sharpness + if (json) { + line += "{\"id\":\"sharpness\",\"value\":\""; + } else { + line += "sharpness:"; + } + line += s->status.sharpness; + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // special_effect + if (json) { + line += "{\"id\":\"special_effect\",\"value\":\""; + } else { + line += "special_effect:"; + } + line += s->status.special_effect; + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // wb_mode + if (json) { + line += "{\"id\":\"wb_mode\",\"value\":\""; + } else { + line += "wb_mode:"; + } + line += s->status.wb_mode; + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // awb + if (json) { + line += "{\"id\":\"awb\",\"value\":\""; + } else { + line += "awb:"; + } + line += s->status.awb; + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // awb_gain + if (json) { + line += "{\"id\":\"awb_gain\",\"value\":\""; + } else { + line += "awb_gain:"; + } + line += s->status.awb_gain; + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // aec + if (json) { + line += "{\"id\":\"aec\",\"value\":\""; + } else { + line += "aec:"; + } + line += s->status.aec; + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // aec2 + if (json) { + line += "{\"id\":\"aec2\",\"value\":\""; + } else { + line += "aec2:"; + } + line += s->status.aec2; + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // ae_level + if (json) { + line += "{\"id\":\"ae_level\",\"value\":\""; + } else { + line += "ae_level:"; + } + line += s->status.ae_level; + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // aec_value + if (json) { + line += "{\"id\":\"aec_value\",\"value\":\""; + } else { + line += "aec_value:"; + } + line += s->status.aec_value; + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // agc + if (json) { + line += "{\"id\":\"agc\",\"value\":\""; + } else { + line += "agc:"; + } + line += s->status.agc; + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // agc_gain + if (json) { + line += "{\"id\":\"agc_gain\",\"value\":\""; + } else { + line += "agc_gain:"; + } + line += s->status.agc_gain; + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // gainceiling + if (json) { + line += "{\"id\":\"gainceiling\",\"value\":\""; + } else { + line += "gainceiling:"; + } + line += s->status.gainceiling; + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // bpc + if (json) { + line += "{\"id\":\"bpc\",\"value\":\""; + } else { + line += "bpc:"; + } + line += s->status.bpc; + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // wpc + if (json) { + line += "{\"id\":\"wpc\",\"value\":\""; + } else { + line += "wpc:"; + } + line += s->status.wpc; + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // raw_gma + if (json) { + line += "{\"id\":\"raw_gma\",\"value\":\""; + } else { + line += "raw_gma:"; + } + line += s->status.raw_gma; + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // lenc + if (json) { + line += "{\"id\":\"lenc\",\"value\":\""; + } else { + line += "lenc:"; + } + line += s->status.lenc; + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // vflip + if (json) { + line += "{\"id\":\"vflip\",\"value\":\""; + } else { + line += "vflip:"; + } + line += s->status.vflip; + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // hmirror + if (json) { + line += "{\"id\":\"hmirror\",\"value\":\""; + } else { + line += "hmirror:"; + } + line += s->status.hmirror; + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // dcw + if (json) { + line += "{\"id\":\"dcw\",\"value\":\""; + } else { + line += "dcw:"; + } + line += s->status.dcw; + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // colorbar + if (json) { + line += "{\"id\":\"colorbar\",\"value\":\""; + } else { + line += "colorbar:"; + } + line += s->status.colorbar; + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; +#if CAM_LED_PIN != -1 + // light + if (json) { + line += "{\"id\":\"light\",\"value\":\""; + } else { + line += "light:"; + } + line += digitalRead(CAM_LED_PIN) == HIGH ? 1 : 0; + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; +#endif // CAM_LED_PIN + if (json) { + output->printLN("]}"); + } + return true; + } + } else { // set +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = format_response(COMMANDID, json, false, + "Wrong authentication level"); + noError = false; + errorCode = 401; + } +#endif // AUTHENTICATION_FEATURE + if (noError) { + String label = get_label(parameter.c_str(), "="); + if (label.length() == 0) { + response = + format_response(COMMANDID, json, false, "Missing command"); + noError = false; + } else { + String labels = label + "="; + String value = get_param(cmd_params, labels.c_str()); + if (value.length() == 0) { + response = + format_response(COMMANDID, json, false, "Invalid value"); + noError = false; + } + if (noError) { + int r = esp3d_camera.command(label.c_str(), value.c_str()); + if (r == -1) { + response = + format_response(COMMANDID, json, false, "Unknow command"); + noError = false; + } else if (r == 1) { + response = + format_response(COMMANDID, json, false, "Invalid value"); + noError = false; + } else { + response = format_response(COMMANDID, json, true, "ok"); + } + } + } + } + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //CAMERA_DEVICE +#endif // CAMERA_DEVICE diff --git a/esp3d/src/core/espcmd/ESP171.cpp b/esp3d/src/core/espcmd/ESP171.cpp index 00bbf2ac..84b8dab5 100644 --- a/esp3d/src/core/espcmd/ESP171.cpp +++ b/esp3d/src/core/espcmd/ESP171.cpp @@ -18,97 +18,105 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (CAMERA_DEVICE) -#include "../commands.h" -#include "../esp3doutput.h" -#include "esp_camera.h" -#include "../settings_esp3d.h" +#if defined(CAMERA_DEVICE) +#include + #include "../../modules/authentication/authentication_service.h" #include "../../modules/camera/camera.h" -#include -#define COMMANDID 171 -//Save frame to target path and filename (default target = today date, default name=timestamp.jpg) -//[ESP171]path= filename= pwd= -bool Commands::ESP171(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead - String path; - String filename; +#include "../commands.h" +#include "../esp3doutput.h" +#include "../settings_esp3d.h" +#include "esp_camera.h" + +#define COMMANDID 171 +// Save frame to target path and filename (default target = today date, default +// name=timestamp.jpg) +//[ESP171]path= filename= pwd= +bool Commands::ESP171(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead + String path; + String filename; #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); - noError = false; - errorCode = 401; - } + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } #else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if(noError) { - if (!esp3d_camera.started()) { - response = format_response(COMMANDID, json, false, "No camera initialized"); - noError = false; - } else { - parameter = clean_param(get_param (cmd_params, "path=")); - //get path - if (parameter.length() != 0) { - - path = parameter; - } - parameter = clean_param(get_param (cmd_params, "filename=")); - //get filename - if (parameter.length() != 0) { - filename = parameter; - } - //if nothing provided, use default filename / path - if (path.length()==0) { - struct tm tmstruct; - time_t now; - path = ""; - time(&now); - localtime_r(&now, &tmstruct); - path = String((tmstruct.tm_year)+1900) + "-"; - if (((tmstruct.tm_mon)+1) < 10) { - path +="0"; - } - path += String(( tmstruct.tm_mon)+1) + "-"; - if (tmstruct.tm_mday < 10) { - path +="0"; - } - path += String(tmstruct.tm_mday); - } - if(filename.length()==0) { - struct tm tmstruct; - time_t now; - time(&now); - localtime_r(&now, &tmstruct); - filename = String(now) + ".jpg"; - } - - //now send command - if(noError) { - noError = esp3d_camera.handle_snap(nullptr,path.c_str(), filename.c_str()); - if(noError) { - response = format_response(COMMANDID, json, true, "Snapshot taken"); - } else { - response = format_response(COMMANDID, json, false, "Error taking snapshot"); - } - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); - } + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + if (!esp3d_camera.started()) { + response = + format_response(COMMANDID, json, false, "No camera initialized"); + noError = false; } else { - output->printERROR(response.c_str(), errorCode); + parameter = clean_param(get_param(cmd_params, "path=")); + // get path + if (parameter.length() != 0) { + path = parameter; + } + parameter = clean_param(get_param(cmd_params, "filename=")); + // get filename + if (parameter.length() != 0) { + filename = parameter; + } + // if nothing provided, use default filename / path + if (path.length() == 0) { + struct tm tmstruct; + time_t now; + path = ""; + time(&now); + localtime_r(&now, &tmstruct); + path = String((tmstruct.tm_year) + 1900) + "-"; + if (((tmstruct.tm_mon) + 1) < 10) { + path += "0"; + } + path += String((tmstruct.tm_mon) + 1) + "-"; + if (tmstruct.tm_mday < 10) { + path += "0"; + } + path += String(tmstruct.tm_mday); + } + if (filename.length() == 0) { + struct tm tmstruct; + time_t now; + time(&now); + localtime_r(&now, &tmstruct); + filename = String(now) + ".jpg"; + } + + // now send command + if (noError) { + noError = + esp3d_camera.handle_snap(nullptr, path.c_str(), filename.c_str()); + if (noError) { + response = format_response(COMMANDID, json, true, "Snapshot taken"); + } else { + response = + format_response(COMMANDID, json, false, "Error taking snapshot"); + } + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //CAMERA_DEVICE +#endif // CAMERA_DEVICE diff --git a/esp3d/src/core/espcmd/ESP180.cpp b/esp3d/src/core/espcmd/ESP180.cpp index b6f606f7..0b769cf7 100644 --- a/esp3d/src/core/espcmd/ESP180.cpp +++ b/esp3d/src/core/espcmd/ESP180.cpp @@ -18,78 +18,86 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (FTP_FEATURE) +#if defined(FTP_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/ftp/FtpServer.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#include "../../modules/ftp/FtpServer.h" -#define COMMANDID 180 -//Set ftp state which can be ON, OFF, CLOSE + +#define COMMANDID 180 +// Set ftp state which can be ON, OFF, CLOSE //[ESP180] json= pwd= -bool Commands::ESP180(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP180(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + response = format_response( + COMMANDID, json, true, + (Settings_ESP3D::read_byte(ESP_FTP_ON) == 0) ? "OFF" : "ON"); + } else { // set +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = format_response(COMMANDID, json, false, + "Wrong authentication level"); noError = false; errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - response = format_response(COMMANDID, json, true, (Settings_ESP3D::read_byte(ESP_FTP_ON) == 0)?"OFF":"ON"); - } else { //set -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter.toUpperCase(); - if (!((parameter == "ON") || (parameter == "OFF") || (parameter == "CLOSE"))) { - response = format_response(COMMANDID, json, false, "Only ON or OFF or CLOSE mode supported!"); - noError = false; - } else { - if (parameter == "CLOSE") { - ftp_server.closeClient(); - - } else { - if (!Settings_ESP3D::write_byte (ESP_FTP_ON, (parameter == "ON")?1:0)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } - - } - if (noError) { - response = format_response(COMMANDID, json, true, "ok"); - } - } - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); + } +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter.toUpperCase(); + if (!((parameter == "ON") || (parameter == "OFF") || + (parameter == "CLOSE"))) { + response = format_response(COMMANDID, json, false, + "Only ON or OFF or CLOSE mode supported!"); + noError = false; } else { - output->printMSG (response.c_str() ); + if (parameter == "CLOSE") { + ftp_server.closeClient(); + + } else { + if (!Settings_ESP3D::write_byte(ESP_FTP_ON, + (parameter == "ON") ? 1 : 0)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } + } + if (noError) { + response = format_response(COMMANDID, json, true, "ok"); + } } - } else { - output->printERROR(response.c_str(), errorCode); + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //FTP_FEATURE +#endif // FTP_FEATURE diff --git a/esp3d/src/core/espcmd/ESP181.cpp b/esp3d/src/core/espcmd/ESP181.cpp index 7e781bf6..01f17d69 100644 --- a/esp3d/src/core/espcmd/ESP181.cpp +++ b/esp3d/src/core/espcmd/ESP181.cpp @@ -18,136 +18,156 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (FTP_FEATURE) +#if defined(FTP_FEATURE) +#include "../../modules/authentication/authentication_service.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#define COMMANDID 181 -//Set/Get Ftp ports -//[ESP181]ctrl= active= passive= json= pwd= -bool Commands::ESP181(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead + +#define COMMANDID 181 +// Set/Get Ftp ports +//[ESP181]ctrl= active= passive= json= pwd= +bool Commands::ESP181(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + String s = ""; + if (json) { + s += "{\"ctrl\":\""; + } else { + s += "ctrl="; + } + s += String(Settings_ESP3D::read_uint32(ESP_FTP_CTRL_PORT)); + if (json) { + s += "\",\"active\":\""; + } else { + s += ", active="; + } + s += String(Settings_ESP3D::read_uint32(ESP_FTP_DATA_ACTIVE_PORT)); + if (json) { + s += "\",\"passive\":\""; + } else { + s += ", passive="; + } + s += String(Settings_ESP3D::read_uint32(ESP_FTP_DATA_PASSIVE_PORT)); + if (json) { + s += "\"}"; + } + response = format_response(COMMANDID, json, true, s.c_str()); + } else { // set +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = format_response(COMMANDID, json, false, + "Wrong authentication level"); noError = false; errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - String s = ""; - if(json) { - s += "{\"ctrl\":\""; + } +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = get_param(cmd_params, "ctrl="); + uint ibuf; + bool hasParam = false; + if (parameter.length() > 0) { + hasParam = true; + ibuf = parameter.toInt(); + if ((ibuf > Settings_ESP3D::get_max_int32_value(ESP_FTP_CTRL_PORT)) || + (ibuf < Settings_ESP3D::get_min_int32_value(ESP_FTP_CTRL_PORT))) { + response = + format_response(COMMANDID, json, false, "Incorrect ctrl port"); + noError = false; + } else { + if (!Settings_ESP3D::write_uint32(ESP_FTP_CTRL_PORT, ibuf)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } + } + } + if (noError) { + parameter = get_param(cmd_params, "active="); + if (parameter.length() > 0) { + ibuf = parameter.toInt(); + hasParam = true; + if ((ibuf > Settings_ESP3D::get_max_int32_value( + ESP_FTP_DATA_ACTIVE_PORT)) || + (ibuf < Settings_ESP3D::get_min_int32_value( + ESP_FTP_DATA_ACTIVE_PORT))) { + response = format_response(COMMANDID, json, false, + "Incorrect active port"); + noError = false; } else { - s += "ctrl="; - } - s+=String(Settings_ESP3D::read_uint32(ESP_FTP_CTRL_PORT)); - if(json) { - s += "\",\"active\":\""; - } else { - s += ", active="; - } - s+=String(Settings_ESP3D::read_uint32(ESP_FTP_DATA_ACTIVE_PORT)); - if(json) { - s += "\",\"passive\":\""; - } else { - s += ", passive="; - } - s+=String(Settings_ESP3D::read_uint32(ESP_FTP_DATA_PASSIVE_PORT)); - if(json) { - s += "\"}"; - } - response = format_response(COMMANDID, json, true,s.c_str()); - } else { //set -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); + if (!Settings_ESP3D::write_uint32(ESP_FTP_DATA_ACTIVE_PORT, + ibuf)) { + response = + format_response(COMMANDID, json, false, "Set failed"); noError = false; - errorCode = 401; - } -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = get_param (cmd_params, "ctrl="); - uint ibuf; - bool hasParam = false; - if (parameter.length() > 0) { - hasParam = true; - ibuf = parameter.toInt(); - if ((ibuf > Settings_ESP3D::get_max_int32_value(ESP_FTP_CTRL_PORT)) || (ibuf < Settings_ESP3D::get_min_int32_value(ESP_FTP_CTRL_PORT))) { - response = format_response(COMMANDID, json, false, "Incorrect ctrl port"); - noError = false; - } else { - if (!Settings_ESP3D::write_uint32 (ESP_FTP_CTRL_PORT, ibuf)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } - } - } - if(noError) { - parameter = get_param (cmd_params, "active="); - if (parameter.length() > 0) { - ibuf = parameter.toInt(); - hasParam = true; - if ((ibuf > Settings_ESP3D::get_max_int32_value(ESP_FTP_DATA_ACTIVE_PORT)) || (ibuf < Settings_ESP3D::get_min_int32_value(ESP_FTP_DATA_ACTIVE_PORT))) { - response = format_response(COMMANDID, json, false, "Incorrect active port"); - noError = false; - } else { - if (!Settings_ESP3D::write_uint32 (ESP_FTP_DATA_ACTIVE_PORT, ibuf)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } - } - } - } - if(noError) { - parameter = get_param (cmd_params, "passive="); - if (parameter.length() > 0) { - hasParam = true; - ibuf = parameter.toInt(); - if ((ibuf > Settings_ESP3D::get_max_int32_value(ESP_FTP_DATA_PASSIVE_PORT)) || (ibuf < Settings_ESP3D::get_min_int32_value(ESP_FTP_DATA_PASSIVE_PORT))) { - response = format_response(COMMANDID, json, false, "Incorrect passive port"); - noError = false; - } else {} - if (!Settings_ESP3D::write_uint32 (ESP_FTP_DATA_PASSIVE_PORT, ibuf)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } - } - } - if (noError && !hasParam) { - response = format_response(COMMANDID, json, false, "Only ctrl, active and passive settings are supported!"); - noError = false; - } else { - if(noError) { - response = format_response(COMMANDID, json, true, "ok"); - } - } - + } } + } } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); + if (noError) { + parameter = get_param(cmd_params, "passive="); + if (parameter.length() > 0) { + hasParam = true; + ibuf = parameter.toInt(); + if ((ibuf > Settings_ESP3D::get_max_int32_value( + ESP_FTP_DATA_PASSIVE_PORT)) || + (ibuf < Settings_ESP3D::get_min_int32_value( + ESP_FTP_DATA_PASSIVE_PORT))) { + response = format_response(COMMANDID, json, false, + "Incorrect passive port"); + noError = false; + } else { + } + if (!Settings_ESP3D::write_uint32(ESP_FTP_DATA_PASSIVE_PORT, + ibuf)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } + } + } + if (noError && !hasParam) { + response = format_response( + COMMANDID, json, false, + "Only ctrl, active and passive settings are supported!"); + noError = false; } else { - output->printMSG (response.c_str() ); + if (noError) { + response = format_response(COMMANDID, json, true, "ok"); + } } - } else { - output->printERROR(response.c_str(), errorCode); + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //TELNET_FEATURE +#endif // TELNET_FEATURE diff --git a/esp3d/src/core/espcmd/ESP190.cpp b/esp3d/src/core/espcmd/ESP190.cpp index cbf1d181..f21d75a4 100644 --- a/esp3d/src/core/espcmd/ESP190.cpp +++ b/esp3d/src/core/espcmd/ESP190.cpp @@ -18,78 +18,87 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (WEBDAV_FEATURE) +#if defined(WEBDAV_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/webdav/webdav_server.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#include "../../modules/webdav/webdav_server.h" -#define COMMANDID 190 -//Set WebDav state which can be ON, OFF, CLOSE + +#define COMMANDID 190 +// Set WebDav state which can be ON, OFF, CLOSE //[ESP190] json= pwd= -bool Commands::ESP190(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP190(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + + // get + if (parameter.length() == 0) { + response = format_response( + COMMANDID, json, true, + (Settings_ESP3D::read_byte(ESP_WEBDAV_ON) == 0) ? "OFF" : "ON"); + // webdav_server.dir(); + } else { // set +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = format_response(COMMANDID, json, false, + "Wrong authentication level"); noError = false; errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - - //get - if (parameter.length() == 0) { - response = format_response(COMMANDID, json, true, (Settings_ESP3D::read_byte(ESP_WEBDAV_ON) == 0)?"OFF":"ON"); - //webdav_server.dir(); - } else { //set -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter.toUpperCase(); - if (!((parameter == "ON") || (parameter == "OFF") || (parameter == "CLOSE"))) { - response = format_response(COMMANDID, json, false, "Only ON or OFF or CLOSE mode supported!"); - noError = false; - } else { - if (parameter == "CLOSE") { - webdav_server.closeClient(); - - } else { - if (!Settings_ESP3D::write_byte (ESP_WEBDAV_ON, (parameter == "ON")?1:0)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } - } - if (noError) { - response = format_response(COMMANDID, json, true, "ok"); - } - } - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); + } +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter.toUpperCase(); + if (!((parameter == "ON") || (parameter == "OFF") || + (parameter == "CLOSE"))) { + response = format_response(COMMANDID, json, false, + "Only ON or OFF or CLOSE mode supported!"); + noError = false; } else { - output->printMSG (response.c_str() ); + if (parameter == "CLOSE") { + webdav_server.closeClient(); + + } else { + if (!Settings_ESP3D::write_byte(ESP_WEBDAV_ON, + (parameter == "ON") ? 1 : 0)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } + } + if (noError) { + response = format_response(COMMANDID, json, true, "ok"); + } } - } else { - output->printERROR(response.c_str(), errorCode); + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //WEBDAV_FEATURE +#endif // WEBDAV_FEATURE diff --git a/esp3d/src/core/espcmd/ESP191.cpp b/esp3d/src/core/espcmd/ESP191.cpp index c916078b..d34c5758 100644 --- a/esp3d/src/core/espcmd/ESP191.cpp +++ b/esp3d/src/core/espcmd/ESP191.cpp @@ -18,69 +18,76 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (WEBDAV_FEATURE) +#if defined(WEBDAV_FEATURE) +#include "../../modules/authentication/authentication_service.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#define COMMANDID 191 -//Set webdav port + +#define COMMANDID 191 +// Set webdav port //[ESP191] json= pwd= -bool Commands::ESP191(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP191(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + response = format_response( + COMMANDID, json, true, + String(Settings_ESP3D::read_uint32(ESP_WEBDAV_PORT)).c_str()); + } else { // set +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = format_response(COMMANDID, json, false, + "Wrong authentication level"); noError = false; errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - response = format_response(COMMANDID, json, true,String(Settings_ESP3D::read_uint32(ESP_WEBDAV_PORT)).c_str()); - } else { //set -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } -#endif //AUTHENTICATION_FEATURE - if (noError) { - uint ibuf = parameter.toInt(); - if ((ibuf > Settings_ESP3D::get_max_int32_value(ESP_WEBDAV_PORT)) || (ibuf < Settings_ESP3D::get_min_int32_value(ESP_WEBDAV_PORT))) { - response = format_response(COMMANDID, json, false, "Incorrect port"); - noError = false; - } else { - if (!Settings_ESP3D::write_uint32 (ESP_WEBDAV_PORT, ibuf)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } else { - response = format_response(COMMANDID, json, true, "ok"); - } - } - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); + } +#endif // AUTHENTICATION_FEATURE + if (noError) { + uint ibuf = parameter.toInt(); + if ((ibuf > Settings_ESP3D::get_max_int32_value(ESP_WEBDAV_PORT)) || + (ibuf < Settings_ESP3D::get_min_int32_value(ESP_WEBDAV_PORT))) { + response = format_response(COMMANDID, json, false, "Incorrect port"); + noError = false; } else { - output->printMSG (response.c_str() ); + if (!Settings_ESP3D::write_uint32(ESP_WEBDAV_PORT, ibuf)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } else { + response = format_response(COMMANDID, json, true, "ok"); + } } - } else { - output->printERROR(response.c_str(), errorCode); + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //WEBDAV_FEATURE +#endif // WEBDAV_FEATURE diff --git a/esp3d/src/core/espcmd/ESP200.cpp b/esp3d/src/core/espcmd/ESP200.cpp index f7428c77..979e97f5 100644 --- a/esp3d/src/core/espcmd/ESP200.cpp +++ b/esp3d/src/core/espcmd/ESP200.cpp @@ -18,75 +18,83 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (SD_DEVICE) +#if defined(SD_DEVICE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/filesystem/esp_sd.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/filesystem/esp_sd.h" -#include "../../modules/authentication/authentication_service.h" -#define COMMANDID 200 -//Get SD Card Status + +#define COMMANDID 200 +// Get SD Card Status //[ESP200] json= pwd= -bool Commands::ESP200(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - bool releaseSD = has_tag (cmd_params, "RELEASE"); - bool refreshSD = has_tag (cmd_params, "REFRESH"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP200(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + bool releaseSD = has_tag(cmd_params, "RELEASE"); + bool refreshSD = has_tag(cmd_params, "REFRESH"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); - noError = false; - errorCode = 401; - } + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } #else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - if (releaseSD) { - ESP_SD::releaseFS(); - response = format_response(COMMANDID, json, true, " SD card released"); - } + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + if (releaseSD) { + ESP_SD::releaseFS(); + response = format_response(COMMANDID, json, true, " SD card released"); + } - if (!ESP_SD::accessFS()) { - if (ESP_SD::getState() == ESP_SDCARD_BUSY) { - response = format_response(COMMANDID, json, true, "Busy"); - } else { - response = format_response(COMMANDID, json, true, "Not available"); - } - } else { - int8_t state = ESP_SD::getState(true); - if (state == ESP_SDCARD_IDLE) { - response = format_response(COMMANDID, json, true, "SD card ok"); - if (refreshSD) { - ESP_SD::refreshStats(true); - } - } - ESP_SD::releaseFS(); - parameter = clean_param(get_param (cmd_params, "")); - if (parameter.length()!=0 && parameter.indexOf("REFRESH")==-1 && parameter.indexOf("RELEASE")==-1) { - response = format_response(COMMANDID, json, false, "Unknown parameter"); - noError = false; - } - } - } - if (noError) { - if (response.length() == 0) { - response = format_response(COMMANDID, json, true, "No SD card"); - } - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); - } + if (!ESP_SD::accessFS()) { + if (ESP_SD::getState() == ESP_SDCARD_BUSY) { + response = format_response(COMMANDID, json, true, "Busy"); + } else { + response = format_response(COMMANDID, json, true, "Not available"); + } } else { - output->printERROR(response.c_str(), errorCode); + int8_t state = ESP_SD::getState(true); + if (state == ESP_SDCARD_IDLE) { + response = format_response(COMMANDID, json, true, "SD card ok"); + if (refreshSD) { + ESP_SD::refreshStats(true); + } + } + ESP_SD::releaseFS(); + parameter = clean_param(get_param(cmd_params, "")); + if (parameter.length() != 0 && parameter.indexOf("REFRESH") == -1 && + parameter.indexOf("RELEASE") == -1) { + response = format_response(COMMANDID, json, false, "Unknown parameter"); + noError = false; + } } - return noError; + } + if (noError) { + if (response.length() == 0) { + response = format_response(COMMANDID, json, true, "No SD card"); + } + if (json) { + output->printLN(response.c_str()); + } else { + output->printMSG(response.c_str()); + } + } else { + if (json) { + output->printLN(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //SD_DEVICE +#endif // SD_DEVICE diff --git a/esp3d/src/core/espcmd/ESP201.cpp b/esp3d/src/core/espcmd/ESP201.cpp index a0772949..32a0c780 100644 --- a/esp3d/src/core/espcmd/ESP201.cpp +++ b/esp3d/src/core/espcmd/ESP201.cpp @@ -18,118 +18,126 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (DIRECT_PIN_FEATURE) +#if defined(DIRECT_PIN_FEATURE) +#include "../../modules/authentication/authentication_service.h" #include "../commands.h" #include "../esp3doutput.h" -#include "../settings_esp3d.h" #include "../hal.h" -#include "../../modules/authentication/authentication_service.h" -#define COMMANDID 201 -//Get/Set pin value -//[ESP201]P V [PULLUP=YES RAW=YES ANALOG=NO ANALOG_RANGE=255]pwd= -//Range can be 255 / 1024 / 2047 / 4095 / 8191 -bool Commands::ESP201(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +#include "../settings_esp3d.h" + +#define COMMANDID 201 +// Get/Set pin value +//[ESP201]P V [PULLUP=YES RAW=YES ANALOG=NO +// ANALOG_RANGE=255]pwd= Range can be 255 / 1024 / 2047 / 4095 / +// 8191 +bool Commands::ESP201(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); - noError = false; - errorCode = 401; - } + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } #else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - //check if have pin - parameter = get_param (cmd_params, "P="); - log_esp3d("Pin %s", parameter.c_str()); - if (parameter .length() == 0) { - response = format_response(COMMANDID, json, false, "Missing pin"); - noError = false; - } else { - int pin = parameter.toInt(); - //check pin is valid and not serial used pins - if ( Hal::is_pin_usable(pin)) { - bool isdigital = true; - parameter = get_param (cmd_params, "ANALOG="); - if (parameter == "YES") { - log_esp3d ("Set as analog"); - isdigital=false; - } - //check if is set or get - parameter = get_param (cmd_params, "V="); - //it is a get - if (parameter.length() == 0) { - //this is to not set pin mode - int value = 0; - if(isdigital) { - parameter = get_param (cmd_params, "RAW="); - if (parameter != "YES") { - parameter = get_param (cmd_params, "PULLUP="); - if (parameter != "YES") { - Hal::pinMode (pin, INPUT); - } else { - Hal::pinMode (pin, INPUT_PULLUP); - } - } - value = digitalRead (pin); - } else { - value = Hal::analogRead(pin); - } - response = format_response(COMMANDID, json, true, String(value).c_str()); - } else { - //it is a set - int value = parameter.toInt(); - Hal::pinMode (pin, OUTPUT); - if (isdigital) { - //verify it is a '0' or a '1' - if ( (value == 0) || (value == 1) ) { - digitalWrite (pin, (value == 0) ? LOW : HIGH); - response = format_response(COMMANDID, json, true, "ok"); - } else { - response = format_response(COMMANDID, json, false, "Invalid value"); - noError = false; - } - } else { - int analog_range= 255; - parameter = get_param (cmd_params, "ANALOG_RANGE="); - if (parameter.length() > 0) { - analog_range = parameter.toInt(); - } - if ( (value >= 0) || (value <= analog_range+1) ) { - Hal::analogRange(analog_range); - Hal::analogWriteFreq(1000); - analogWrite(pin, value); - response = format_response(COMMANDID, json, false, "Invalid value"); - noError = false; - } else { - response = format_response(COMMANDID, json, false, "Invalid parameter"); - noError = false; - } - } - } - } else { - response = format_response(COMMANDID, json, false, "Invalid pin"); - noError = false; - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); - } + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + // check if have pin + parameter = get_param(cmd_params, "P="); + log_esp3d("Pin %s", parameter.c_str()); + if (parameter.length() == 0) { + response = format_response(COMMANDID, json, false, "Missing pin"); + noError = false; } else { - output->printERROR(response.c_str(), errorCode); + int pin = parameter.toInt(); + // check pin is valid and not serial used pins + if (Hal::is_pin_usable(pin)) { + bool isdigital = true; + parameter = get_param(cmd_params, "ANALOG="); + if (parameter == "YES") { + log_esp3d("Set as analog"); + isdigital = false; + } + // check if is set or get + parameter = get_param(cmd_params, "V="); + // it is a get + if (parameter.length() == 0) { + // this is to not set pin mode + int value = 0; + if (isdigital) { + parameter = get_param(cmd_params, "RAW="); + if (parameter != "YES") { + parameter = get_param(cmd_params, "PULLUP="); + if (parameter != "YES") { + Hal::pinMode(pin, INPUT); + } else { + Hal::pinMode(pin, INPUT_PULLUP); + } + } + value = digitalRead(pin); + } else { + value = Hal::analogRead(pin); + } + response = + format_response(COMMANDID, json, true, String(value).c_str()); + } else { + // it is a set + int value = parameter.toInt(); + Hal::pinMode(pin, OUTPUT); + if (isdigital) { + // verify it is a '0' or a '1' + if ((value == 0) || (value == 1)) { + digitalWrite(pin, (value == 0) ? LOW : HIGH); + response = format_response(COMMANDID, json, true, "ok"); + } else { + response = + format_response(COMMANDID, json, false, "Invalid value"); + noError = false; + } + } else { + int analog_range = 255; + parameter = get_param(cmd_params, "ANALOG_RANGE="); + if (parameter.length() > 0) { + analog_range = parameter.toInt(); + } + if ((value >= 0) || (value <= analog_range + 1)) { + Hal::analogRange(analog_range); + Hal::analogWriteFreq(1000); + analogWrite(pin, value); + response = + format_response(COMMANDID, json, false, "Invalid value"); + noError = false; + } else { + response = + format_response(COMMANDID, json, false, "Invalid parameter"); + noError = false; + } + } + } + } else { + response = format_response(COMMANDID, json, false, "Invalid pin"); + noError = false; + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //DIRECT_PIN_FEATURE +#endif // DIRECT_PIN_FEATURE diff --git a/esp3d/src/core/espcmd/ESP202.cpp b/esp3d/src/core/espcmd/ESP202.cpp index c1bfcf8b..ee5cc456 100644 --- a/esp3d/src/core/espcmd/ESP202.cpp +++ b/esp3d/src/core/espcmd/ESP202.cpp @@ -18,63 +18,70 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (SD_DEVICE) && SD_DEVICE != ESP_SDIO +#if defined(SD_DEVICE) && SD_DEVICE != ESP_SDIO +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/filesystem/esp_sd.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/filesystem/esp_sd.h" -#include "../../modules/authentication/authentication_service.h" -#define COMMANDID 202 -//Get/Set SD card Speed factor 1 2 4 6 8 16 32 -//[ESP202]SPEED= json= pwd= -bool Commands::ESP202(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead -#ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); - noError = false; - errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - response = format_response(COMMANDID, json, true, String(Settings_ESP3D::read_byte (ESP_SD_SPEED_DIV)).c_str()); - } else { //set - parameter = get_param (cmd_params, "SPEED="); - if ((parameter == "1") || (parameter == "2") || (parameter == "4")|| (parameter == "6")|| (parameter == "8")|| (parameter == "16")|| (parameter == "32")) { - if (!Settings_ESP3D::write_byte (ESP_SD_SPEED_DIV, parameter.toInt())) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } else { - ESP_SD::setSPISpeedDivider(parameter.toInt()); - response = format_response(COMMANDID, json, true, "ok"); - } - } else { - response = format_response(COMMANDID, json, false, "Invalid parameter"); - noError = false; - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); +#define COMMANDID 202 +// Get/Set SD card Speed factor 1 2 4 6 8 16 32 +//[ESP202]SPEED= json= pwd= +bool Commands::ESP202(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead +#ifdef AUTHENTICATION_FEATURE + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + response = format_response( + COMMANDID, json, true, + String(Settings_ESP3D::read_byte(ESP_SD_SPEED_DIV)).c_str()); + } else { // set + parameter = get_param(cmd_params, "SPEED="); + if ((parameter == "1") || (parameter == "2") || (parameter == "4") || + (parameter == "6") || (parameter == "8") || (parameter == "16") || + (parameter == "32")) { + if (!Settings_ESP3D::write_byte(ESP_SD_SPEED_DIV, parameter.toInt())) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } else { - output->printMSG (response.c_str() ); + ESP_SD::setSPISpeedDivider(parameter.toInt()); + response = format_response(COMMANDID, json, true, "ok"); } - } else { - output->printERROR(response.c_str(), errorCode); + } else { + response = format_response(COMMANDID, json, false, "Invalid parameter"); + noError = false; + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //SD_DEVICE +#endif // SD_DEVICE diff --git a/esp3d/src/core/espcmd/ESP210.cpp b/esp3d/src/core/espcmd/ESP210.cpp index 1697dc7b..745155b0 100644 --- a/esp3d/src/core/espcmd/ESP210.cpp +++ b/esp3d/src/core/espcmd/ESP210.cpp @@ -18,134 +18,143 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (SENSOR_DEVICE) +#if defined(SENSOR_DEVICE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/sensor/sensor.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/sensor/sensor.h" -#include "../../modules/authentication/authentication_service.h" -#define COMMANDID 210 -//Get Sensor Value / type/Set Sensor type -//[ESP210] json= pwd= -bool Commands::ESP210(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - bool hasParam = false; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead + +#define COMMANDID 210 +// Get Sensor Value / type/Set Sensor type +//[ESP210] json= pwd= +bool Commands::ESP210(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + bool hasParam = false; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + String s; + if (json) { + s = "{\"type\":\""; + } else { + s = "type="; + } + if (esp3d_sensor.started()) { + s += esp3d_sensor.GetCurrentModelString(); + } else { + s += "NONE"; + } + if (json) { + s += ":\",\"interval\":"; + } else { + s += ", interval="; + } + s += esp3d_sensor.interval(); + if (json) { + s += ":\",\"value\":"; + } else { + s += "ms, value="; + } + s += esp3d_sensor.GetData(); + if (json) { + s += "\"}"; + } + response = format_response(COMMANDID, json, true, s.c_str()); + } else { +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = format_response(COMMANDID, json, false, + "Wrong authentication level"); noError = false; errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - String s; - if (json) { - s="{\"type\":\""; - } else { - s="type="; + } +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = get_param(cmd_params, "type="); + if (parameter.length() != 0) { + hasParam = true; + parameter.toUpperCase(); + int8_t v = -1; + if (parameter == "NONE") { + v = 0; + } else if (esp3d_sensor.isModelValid( + esp3d_sensor.getIDFromString(parameter.c_str()))) { + v = esp3d_sensor.getIDFromString(parameter.c_str()); + } else { + response = + format_response(COMMANDID, json, false, "Invalid parameter"); + noError = false; + } + if (v != -1) { + if (!Settings_ESP3D::write_byte(ESP_SENSOR_TYPE, v)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; } - if(esp3d_sensor.started()) { - s+=esp3d_sensor.GetCurrentModelString(); - } else { - s+="NONE"; - } - if (json) { - s+=":\",\"interval\":"; - } else { - s+=", interval="; - } - s += esp3d_sensor.interval(); - if (json) { - s+=":\",\"value\":"; - } else { - s+="ms, value="; - } - s += esp3d_sensor.GetData(); - if (json) { - s+="\"}"; - } - response = format_response(COMMANDID, json, true,s.c_str()); - } else { -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); + if (noError) { + if (!esp3d_sensor.begin()) { + response = + format_response(COMMANDID, json, false, "Starting failed"); noError = false; - errorCode = 401; + } } -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = get_param (cmd_params, "type="); - if (parameter.length() != 0) { - hasParam=true; - parameter.toUpperCase(); - int8_t v = -1; - if (parameter == "NONE") { - v = 0; - } else if(esp3d_sensor.isModelValid(esp3d_sensor.getIDFromString(parameter.c_str()))) { - v = esp3d_sensor.getIDFromString(parameter.c_str()); - } else { - response = format_response(COMMANDID, json, false, "Invalid parameter"); - noError = false; - } - if (v!=-1) { - if (!Settings_ESP3D::write_byte(ESP_SENSOR_TYPE,v)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } - if(noError) { - if (!esp3d_sensor.begin()) { - response = format_response(COMMANDID, json, false, "Starting failed"); - noError = false; - } - } - } else { - response = format_response(COMMANDID, json, false, "Invalid type"); - noError = false; - } - } - } - if (noError) { - parameter = get_param (cmd_params, "interval="); - if (parameter.length() != 0) { - hasParam = true; - if (!Settings_ESP3D::write_uint32(ESP_SENSOR_INTERVAL,parameter.toInt())) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } - esp3d_sensor.setInterval(parameter.toInt()); - } - } - if (noError) { - if (hasParam) { - response = format_response(COMMANDID, json, true, "ok"); - } else { - response = format_response(COMMANDID, json, false, "No parameter"); - noError = false; - } - } + } else { + response = format_response(COMMANDID, json, false, "Invalid type"); + noError = false; + } } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); + } + if (noError) { + parameter = get_param(cmd_params, "interval="); + if (parameter.length() != 0) { + hasParam = true; + if (!Settings_ESP3D::write_uint32(ESP_SENSOR_INTERVAL, + parameter.toInt())) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } + esp3d_sensor.setInterval(parameter.toInt()); + } + } + if (noError) { + if (hasParam) { + response = format_response(COMMANDID, json, true, "ok"); } else { - output->printMSG (response.c_str() ); + response = format_response(COMMANDID, json, false, "No parameter"); + noError = false; } - } else { - output->printERROR(response.c_str(), errorCode); + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //SENSOR_DEVICE +#endif // SENSOR_DEVICE diff --git a/esp3d/src/core/espcmd/ESP214.cpp b/esp3d/src/core/espcmd/ESP214.cpp index 020f7a97..f12cb6df 100644 --- a/esp3d/src/core/espcmd/ESP214.cpp +++ b/esp3d/src/core/espcmd/ESP214.cpp @@ -18,46 +18,49 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (DISPLAY_DEVICE) +#if defined(DISPLAY_DEVICE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/display/display.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/display/display.h" -#include "../../modules/authentication/authentication_service.h" -#define COMMANDID 214 -//Output to esp screen status + +#define COMMANDID 214 +// Output to esp screen status //[ESP214]json= pwd= -bool Commands::ESP214(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP214(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); - noError = false; - errorCode = 401; - } + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } #else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + esp3d_display.setStatus(parameter.c_str()); + response = format_response(COMMANDID, json, true, "ok"); + } + if (json) { + output->printLN(response.c_str()); + } else { if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - esp3d_display.setStatus(parameter.c_str()); - response = format_response(COMMANDID, json, true, "ok"); - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); - } + output->printMSG(response.c_str()); } else { - output->printERROR(response.c_str(), errorCode); + output->printERROR(response.c_str(), errorCode); } - return noError; + } + return noError; } -#endif //DISPLAY_DEVICE +#endif // DISPLAY_DEVICE diff --git a/esp3d/src/core/espcmd/ESP215.cpp b/esp3d/src/core/espcmd/ESP215.cpp index 2be24a79..e15a3520 100644 --- a/esp3d/src/core/espcmd/ESP215.cpp +++ b/esp3d/src/core/espcmd/ESP215.cpp @@ -19,61 +19,68 @@ */ #include "../../include/esp3d_config.h" #if defined(DISPLAY_DEVICE) && defined(DISPLAY_TOUCH_DRIVER) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/display/display.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#include "../../modules/display/display.h" -#define COMMANDID 215 -//Touch Calibration + +#define COMMANDID 215 +// Touch Calibration //[ESP215] json= [pwd=] -bool Commands::ESP215(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP215(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); - noError = false; - errorCode = 401; - } + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } #else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - response = format_response(COMMANDID, json, true, (Settings_ESP3D::read_byte(ESP_CALIBRATION)==1)?"Done":"Not done"); - } else { //set - parameter.toUpperCase(); + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + response = format_response( + COMMANDID, json, true, + (Settings_ESP3D::read_byte(ESP_CALIBRATION) == 1) ? "Done" + : "Not done"); + } else { // set + parameter.toUpperCase(); if (has_tag (cmd_params, "CALIBRATE") { - if (!json) { - output->printMSG("Please follow screen instructions"); - } - response = format_response(COMMANDID, json, true, ok); - esp3d_display.startCalibration(); + if (!json) { + output->printMSG("Please follow screen instructions"); + } + response = format_response(COMMANDID, json, true, ok); + esp3d_display.startCalibration(); } else { - if (parameter.indexOf("CALIBRATE") == -1) { - response = format_response(COMMANDID, json, false, "Invalid parameter"); - noError = false; - } + if (parameter.indexOf("CALIBRATE") == -1) { + response = + format_response(COMMANDID, json, false, "Invalid parameter"); + noError = false; + } } - } } + } + if (json) { + output->printLN(response.c_str()); + } else { if (noError) { - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); - } + output->printMSG(response.c_str()); } else { - output->printERROR(response.c_str(), errorCode); + output->printERROR(response.c_str(), errorCode); } - return noError; + } + return noError; } -#endif //DISPLAY_DEVICE && DISPLAY_TOUCH_DRIVER +#endif // DISPLAY_DEVICE && DISPLAY_TOUCH_DRIVER diff --git a/esp3d/src/core/espcmd/ESP220.cpp b/esp3d/src/core/espcmd/ESP220.cpp index 431d85c3..454589a6 100644 --- a/esp3d/src/core/espcmd/ESP220.cpp +++ b/esp3d/src/core/espcmd/ESP220.cpp @@ -18,300 +18,307 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" +#include "../../modules/authentication/authentication_service.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#define COMMANDID 220 -//Get ESP pins definition -//output is JSON or plain text according parameter +#define COMMANDID 220 + +// Get ESP pins definition +// output is JSON or plain text according parameter //[ESP220]json= -bool Commands::ESP220(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP220(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); - noError = false; - errorCode = 401; - } + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } #else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - if (parameter.length() == 0) { - String line = ""; - if(json) { - line = "{\"cmd\":\"220\",\"status\":\"ok\",\"data\":["; - } - bool hasPin = false; + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + if (parameter.length() == 0) { + String line = ""; + if (json) { + line = "{\"cmd\":\"220\",\"status\":\"ok\",\"data\":["; + } + bool hasPin = false; #ifdef SD_DEVICE - hasPin = true; - if (json) { - line += "{\"id\":\""; - } - line +="SD CS"; - if (json) { - line +="\",\"value\":\""; - } else { - line +=": "; - } - line +=String(ESP_SD_CS_PIN==-1?SS:ESP_SD_CS_PIN); - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - if (json) { - line += "{\"id\":\""; - } - line +="SD MOSI"; - if (json) { - line +="\",\"value\":\""; - } else { - line +=": "; - } - line +=String(ESP_SD_MOSI_PIN==-1?MOSI:ESP_SD_MOSI_PIN); - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - if (json) { - line += "{\"id\":\""; - } - line +="SD MISO"; - if (json) { - line +="\",\"value\":\""; - } else { - line +=": "; - } - line +=String(ESP_SD_MISO_PIN==-1?MISO:ESP_SD_MISO_PIN); - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - if (json) { - line += "{\"id\":\""; - } - line +="SD SCK"; - if (json) { - line +="\",\"value\":\""; - } else { - line +=": "; - } - line +=String(ESP_SD_SCK_PIN==-1?SCK:ESP_SD_SCK_PIN); - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - if (json) { - line += "{\"id\":\""; - } - line +="SD DETECT"; - if (json) { - line +="\",\"value\":\""; - } else { - line +=": "; - } - line +=String(ESP_SD_DETECT_PIN); - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; -#if ESP_SD_DETECT_PIN !=-1 - if (json) { - line += "{\"id\":\""; - } - line +="SD DETECT STATE"; - if (json) { - line +="\",\"value\":\""; - } else { - line +=": "; - } - line +=String(ESP_SD_DETECT_VALUE); - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; -#endif //ESP_SD_DETECT_PIN !=-1 + hasPin = true; + if (json) { + line += "{\"id\":\""; + } + line += "SD CS"; + if (json) { + line += "\",\"value\":\""; + } else { + line += ": "; + } + line += String(ESP_SD_CS_PIN == -1 ? SS : ESP_SD_CS_PIN); + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + if (json) { + line += ",{\"id\":\""; + } + line += "SD MOSI"; + if (json) { + line += "\",\"value\":\""; + } else { + line += ": "; + } + line += String(ESP_SD_MOSI_PIN == -1 ? MOSI : ESP_SD_MOSI_PIN); + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + if (json) { + line += ",{\"id\":\""; + } + line += "SD MISO"; + if (json) { + line += "\",\"value\":\""; + } else { + line += ": "; + } + line += String(ESP_SD_MISO_PIN == -1 ? MISO : ESP_SD_MISO_PIN); + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + if (json) { + line += ",{\"id\":\""; + } + line += "SD SCK"; + if (json) { + line += "\",\"value\":\""; + } else { + line += ": "; + } + line += String(ESP_SD_SCK_PIN == -1 ? SCK : ESP_SD_SCK_PIN); + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + if (json) { + line += ",{\"id\":\""; + } + line += "SD DETECT"; + if (json) { + line += "\",\"value\":\""; + } else { + line += ": "; + } + line += String(ESP_SD_DETECT_PIN); + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; +#if ESP_SD_DETECT_PIN != -1 + if (json) { + line += ",{\"id\":\""; + } + line += "SD DETECT STATE"; + if (json) { + line += "\",\"value\":\""; + } else { + line += ": "; + } + line += String(ESP_SD_DETECT_VALUE); + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; +#endif // ESP_SD_DETECT_PIN !=-1 #if SD_DEVICE_CONNECTION == ESP_SHARED_SD && defined(ESP_FLAG_SHARED_SD_PIN) - if (json) { - line += "{\"id\":\""; - } - line +="SD SWITCH"; - if (json) { - line +="\",\"value\":\""; - } else { - line +=": "; - } - line +=String(ESP_FLAG_SHARED_SD_PIN); - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; -#endif //SD_DEVICE_CONNECTION == ESP_SHARED_SD -#endif //SD_DEVICE + if (json) { + line += ",{\"id\":\""; + } + line += "SD SWITCH"; + if (json) { + line += "\",\"value\":\""; + } else { + line += ": "; + } + line += String(ESP_FLAG_SHARED_SD_PIN); + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; +#endif // SD_DEVICE_CONNECTION == ESP_SHARED_SD +#endif // SD_DEVICE #ifdef BUZZER_DEVICE - hasPin = true; - if (json) { - line += "{\"id\":\""; - } - line +="BUZZER"; - if (json) { - line +="\",\"value\":\""; - } else { - line +=": "; - } - line +=String(ESP3D_BUZZER_PIN); - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; -#endif //BUZZER_DEVICE -#if defined(PIN_RESET_FEATURE) && defined(ESP3D_RESET_PIN) && ESP3D_RESET_PIN !=-1 - hasPin = true; - if (json) { - line += "{\"id\":\""; - } - line +="RESET"; - if (json) { - line +="\",\"value\":\""; - } else { - line +=": "; - } - line +=String(ESP3D_RESET_PIN); - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; -#endif //PIN_RESET_FEATURE + hasPin = true; + if (json) { + line += ",{\"id\":\""; + } + line += "BUZZER"; + if (json) { + line += "\",\"value\":\""; + } else { + line += ": "; + } + line += String(ESP3D_BUZZER_PIN); + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; +#endif // BUZZER_DEVICE +#if defined(PIN_RESET_FEATURE) && defined(ESP3D_RESET_PIN) && \ + ESP3D_RESET_PIN != -1 + hasPin = true; + if (json) { + line += ",{\"id\":\""; + } + line += "RESET"; + if (json) { + line += "\",\"value\":\""; + } else { + line += ": "; + } + line += String(ESP3D_RESET_PIN); + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; +#endif // PIN_RESET_FEATURE #ifdef SENSOR_DEVICE - hasPin = true; - if (json) { - line += "{\"id\":\""; - } - line +="SENSOR"; - if (json) { - line +="\",\"value\":\""; - } else { - line +=": "; - } - line +=String(ESP3D_SENSOR_PIN); - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; -#endif //SENSOR_DEVICE + hasPin = true; + if (json) { + line += ",{\"id\":\""; + } + line += "SENSOR"; + if (json) { + line += "\",\"value\":\""; + } else { + line += ": "; + } + line += String(ESP3D_SENSOR_PIN); + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; +#endif // SENSOR_DEVICE #ifdef DISPLAY_DEVICE -#if (DISPLAY_DEVICE == OLED_I2C_SSD1306) || (DISPLAY_DEVICE == OLED_I2C_SSDSH1106) - hasPin = true; - if (json) { - line += "{\"id\":\""; - } - line +="SDA"; - if (json) { - line +="\",\"value\":\""; - } else { - line +=": "; - } - line +=String(ESP_SDA_PIN); - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - if (json) { - line += "{\"id\":\""; - } - line +="SCL"; - if (json) { - line +="\",\"value\":\""; - } else { - line +=": "; - } - line +=String(ESP_SCL_PIN); - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; -#endif //(DISPLAY_DEVICE == OLED_I2C_SSD1306) || (DISPLAY_DEVICE == OLED_I2C_SSDSH1106) -#endif //DISPLAY_DEVICE - if (!hasPin) { - if (json) { - line += "{\"id\":\""; - } - line +="NO PIN"; - if (json) { - line +="\",\"value\":\""; - } else { - line +=": "; - } - line +="-"; - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - } - if (json) { - output->printLN ("]}"); - } - return true; - } else { - response = format_response(COMMANDID, json, false, "This command doesn't take parameters"); - noError = false; - } - } - if (noError) { +#if (DISPLAY_DEVICE == OLED_I2C_SSD1306) || \ + (DISPLAY_DEVICE == OLED_I2C_SSDSH1106) + hasPin = true; + if (json) { + line += ",{\"id\":\""; + } + line += "SDA"; + if (json) { + line += "\",\"value\":\""; + } else { + line += ": "; + } + line += String(ESP_SDA_PIN); + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + if (json) { + line += ",{\"id\":\""; + } + line += "SCL"; + if (json) { + line += "\",\"value\":\""; + } else { + line += ": "; + } + line += String(ESP_SCL_PIN); + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; +#endif //(DISPLAY_DEVICE == OLED_I2C_SSD1306) || (DISPLAY_DEVICE == + // OLED_I2C_SSDSH1106) +#endif // DISPLAY_DEVICE + if (!hasPin) { if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); + line += ",{\"id\":\""; } + line += "NO PIN"; + if (json) { + line += "\",\"value\":\""; + } else { + line += ": "; + } + line += "-"; + if (json) { + line += "\"}"; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + } + if (json) { + output->printLN("]}"); + } + return true; } else { - output->printERROR(response.c_str(), errorCode); + response = format_response(COMMANDID, json, false, + "This command doesn't take parameters"); + noError = false; } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } diff --git a/esp3d/src/core/espcmd/ESP250.cpp b/esp3d/src/core/espcmd/ESP250.cpp index 0267ef3e..2501a2be 100644 --- a/esp3d/src/core/espcmd/ESP250.cpp +++ b/esp3d/src/core/espcmd/ESP250.cpp @@ -18,74 +18,77 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (BUZZER_DEVICE) +#if defined(BUZZER_DEVICE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/buzzer/buzzer.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#include "../../modules/buzzer/buzzer.h" -#define COMMANDID 250 -//Play sound + +#define COMMANDID 250 +// Play sound //[ESP250]F= D= json= [pwd=] -bool Commands::ESP250(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP250(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); - noError = false; - errorCode = 401; - } + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } #else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - if (!esp3d_buzzer.started()) { - response = format_response(COMMANDID, json, false, "Buzzer disabled"); - noError = false; - } else { - parameter = get_param (cmd_params, ""); - //get - if (parameter.length() == 0) { - esp3d_buzzer.beep(); - } else { - int f,d; - //frequency - parameter = get_param (cmd_params, "F="); - if (parameter.length() == 0) { - response = format_response(COMMANDID, json, false, "No frequency"); - noError = false; - } else { - f = parameter.toInt(); - parameter = get_param (cmd_params, "D="); - if (parameter.length() == 0) { - response = format_response(COMMANDID, json, false, "No duration"); - noError = false; - } else { - d = parameter.toInt(); - esp3d_buzzer.beep(f,d); - } - } - } - if(noError) { - response = format_response(COMMANDID, json, true, "ok"); - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); - } + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + if (!esp3d_buzzer.started()) { + response = format_response(COMMANDID, json, false, "Buzzer disabled"); + noError = false; } else { - output->printERROR(response.c_str(), errorCode); + parameter = get_param(cmd_params, ""); + // get + if (parameter.length() == 0) { + esp3d_buzzer.beep(); + } else { + int f, d; + // frequency + parameter = get_param(cmd_params, "F="); + if (parameter.length() == 0) { + response = format_response(COMMANDID, json, false, "No frequency"); + noError = false; + } else { + f = parameter.toInt(); + parameter = get_param(cmd_params, "D="); + if (parameter.length() == 0) { + response = format_response(COMMANDID, json, false, "No duration"); + noError = false; + } else { + d = parameter.toInt(); + esp3d_buzzer.beep(f, d); + } + } + } + if (noError) { + response = format_response(COMMANDID, json, true, "ok"); + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //BUZZER_DEVICE +#endif // BUZZER_DEVICE diff --git a/esp3d/src/core/espcmd/ESP290.cpp b/esp3d/src/core/espcmd/ESP290.cpp index c1391c63..4c6077d4 100644 --- a/esp3d/src/core/espcmd/ESP290.cpp +++ b/esp3d/src/core/espcmd/ESP290.cpp @@ -18,51 +18,53 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#include "../commands.h" #include "../../modules/authentication/authentication_service.h" +#include "../commands.h" #include "../esp3doutput.h" -//Delay command -//[ESP290] json= [pwd=] -#define COMMANDID 290 -bool Commands::ESP290(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead -#ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); - noError = false; - errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = get_param (cmd_params, ""); - //get time - if (parameter.length() != 0) { - if(!json) { - output->printMSG ("Pause"); - } - Hal::wait(parameter.toInt()); - response = format_response(COMMANDID, json, true, "ok"); - } else { - response = format_response(COMMANDID, json, false, "Missing parameter"); - noError = false; - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); - } +// Delay command +//[ESP290] json= [pwd=] +#define COMMANDID 290 +bool Commands::ESP290(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead +#ifdef AUTHENTICATION_FEATURE + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = get_param(cmd_params, ""); + // get time + if (parameter.length() != 0) { + if (!json) { + output->printMSG("Pause"); + } + Hal::wait(parameter.toInt()); + response = format_response(COMMANDID, json, true, "ok"); } else { - output->printERROR(response.c_str(), errorCode); + response = format_response(COMMANDID, json, false, "Missing parameter"); + noError = false; } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } diff --git a/esp3d/src/core/espcmd/ESP400.cpp b/esp3d/src/core/espcmd/ESP400.cpp index 7911fb24..f3854cff 100644 --- a/esp3d/src/core/espcmd/ESP400.cpp +++ b/esp3d/src/core/espcmd/ESP400.cpp @@ -28,6 +28,9 @@ #if defined(SENSOR_DEVICE) #include "../../modules/sensor/sensor.h" #endif // SENSOR_DEVICE +#ifdef TIMESTAMP_FEATURE +#include "../../modules/time/time_service.h" +#endif // TIMESTAMP_FEATURE #define COMMANDID 400 // Get full ESP3D settings //[ESP400] @@ -427,26 +430,25 @@ bool Commands::ESP400(const char* cmd_params, level_authenticate_type auth_type, // Time zone output->print(",{\"F\":\"service/time\",\"P\":\""); - output->print(ESP_TIMEZONE); - output->print("\",\"T\":\"B\",\"R\":\"1\",\"V\":\""); - output->print( - String((int8_t)Settings_ESP3D::read_byte(ESP_TIMEZONE)).c_str()); + output->print(ESP_TIME_ZONE); + output->print("\",\"T\":\"S\",\"R\":\"1\",\"V\":\""); + output->print(Settings_ESP3D::read_string(ESP_TIME_ZONE)); output->print("\",\"H\":\"tzone\",\"O\":["); - for (int8_t i = Settings_ESP3D::get_min_byte(ESP_TIMEZONE); - i <= Settings_ESP3D::get_max_byte(ESP_TIMEZONE); i++) { - if (i > Settings_ESP3D::get_min_byte(ESP_TIMEZONE)) { + for (int8_t i = 0; i < SupportedTimeZonesSize; i++) { + if (i > 0) { output->print(","); } - output->printf("{\"%d\":\"%d\"}", i, i); + output->printf("{\"%s\":\"%s\"}", SupportedTimeZones[i], + SupportedTimeZones[i]); } output->print("]}"); - // DST - output->print(",{\"F\":\"service/time\",\"P\":\""); - output->print(ESP_TIME_IS_DST); - output->print("\",\"T\":\"B\",\"R\":\"1\",\"V\":\""); - output->print(Settings_ESP3D::read_byte(ESP_TIME_IS_DST)); - output->print("\",\"H\":\"dst\",\"O\":[{\"no\":\"0\"},{\"yes\":\"1\"}]}"); + // DST which is currently not supported automaticatly + /* output->print(",{\"F\":\"service/time\",\"P\":\""); + output->print(ESP_TIME_IS_DST); + output->print("\",\"T\":\"B\",\"R\":\"1\",\"V\":\""); + output->print(Settings_ESP3D::read_byte(ESP_TIME_IS_DST)); + output->print("\",\"H\":\"dst\",\"O\":[{\"no\":\"0\"},{\"yes\":\"1\"}]}");*/ // Time Server1 output->print(",{\"F\":\"service/time\",\"P\":\""); @@ -735,14 +737,14 @@ bool Commands::ESP400(const char* cmd_params, level_authenticate_type auth_type, noError = false; } } - if (noError) { - if (json) { - output->printLN(response.c_str()); - } else { - output->printMSG(response.c_str()); - } + if (json) { + output->printLN(response.c_str()); } else { - output->printERROR(response.c_str(), errorCode); + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } } return noError; } diff --git a/esp3d/src/core/espcmd/ESP401.cpp b/esp3d/src/core/espcmd/ESP401.cpp index 10c69608..8fd96141 100644 --- a/esp3d/src/core/espcmd/ESP401.cpp +++ b/esp3d/src/core/espcmd/ESP401.cpp @@ -34,7 +34,7 @@ #include "../../modules/buzzer/buzzer.h" #endif // BUZZER_DEVICE #ifdef TIMESTAMP_FEATURE -#include "../../modules/time/time_server.h" +#include "../../modules/time/time_service.h" #endif // TIMESTAMP_FEATURE #ifdef NOTIFICATION_FEATURE #include "../../modules/notifications/notifications_service.h" @@ -133,7 +133,7 @@ bool Commands::ESP401(const char* cmd_params, level_authenticate_type auth_type, #endif // SD_DEVICE #ifdef TIMESTAMP_FEATURE case ESP_INTERNET_TIME: - timeserver.begin(); + timeService.begin(); break; #endif // TIMESTAMP_FEATURE #ifdef NOTIFICATION_FEATURE @@ -248,7 +248,11 @@ bool Commands::ESP401(const char* cmd_params, level_authenticate_type auth_type, response += spos.length() > 0 ? " for P=" + spos : ""; } response = format_response(COMMANDID, json, false, response.c_str()); - output->printERROR(response.c_str(), errorCode); + if (json) { + output->printLN(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } } return noError; } diff --git a/esp3d/src/core/espcmd/ESP402.cpp b/esp3d/src/core/espcmd/ESP402.cpp index 641ca948..27715675 100644 --- a/esp3d/src/core/espcmd/ESP402.cpp +++ b/esp3d/src/core/espcmd/ESP402.cpp @@ -18,69 +18,78 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (SD_UPDATE_FEATURE) +#if defined(SD_UPDATE_FEATURE) +#include "../../modules/authentication/authentication_service.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -//Set SD Check at boot state which can be ON, OFF + +// Set SD Check at boot state which can be ON, OFF //[ESP402] json= pwd= -#define COMMANDID 402 -bool Commands::ESP402(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +#define COMMANDID 402 +bool Commands::ESP402(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + if (parameter.length() == 0) { + response = format_response( + COMMANDID, json, true, + (Settings_ESP3D::read_byte(ESP_SD_CHECK_UPDATE_AT_BOOT) == 0) ? "OFF" + : "ON"); + } else { // set +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = format_response(COMMANDID, json, false, + "Wrong authentication level"); noError = false; errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - if (parameter.length() == 0) { - response = format_response(COMMANDID, json, true, (Settings_ESP3D::read_byte(ESP_SD_CHECK_UPDATE_AT_BOOT) == 0)?"OFF":"ON"); - } else { //set -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter.toUpperCase(); - if (!((parameter == "ON") || (parameter == "OFF"))) { - response = format_response(COMMANDID, json, false, "Only ON or OFF mode supported"); - noError = false; - } else { - if (!Settings_ESP3D::write_byte (ESP_SD_CHECK_UPDATE_AT_BOOT, (parameter == "ON")?1:0)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } else { - response = format_response(COMMANDID, json, true, "ok"); - } - } - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); + } +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter.toUpperCase(); + if (!((parameter == "ON") || (parameter == "OFF"))) { + response = format_response(COMMANDID, json, false, + "Only ON or OFF mode supported"); + noError = false; } else { - output->printMSG (response.c_str() ); + if (!Settings_ESP3D::write_byte(ESP_SD_CHECK_UPDATE_AT_BOOT, + (parameter == "ON") ? 1 : 0)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } else { + response = format_response(COMMANDID, json, true, "ok"); + } } - } else { - output->printERROR(response.c_str(), errorCode); + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //SD_UPDATE_FEATURE +#endif // SD_UPDATE_FEATURE diff --git a/esp3d/src/core/espcmd/ESP410.cpp b/esp3d/src/core/espcmd/ESP410.cpp index 84eedd11..ef105f59 100644 --- a/esp3d/src/core/espcmd/ESP410.cpp +++ b/esp3d/src/core/espcmd/ESP410.cpp @@ -18,126 +18,130 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (WIFI_FEATURE) +#if defined(WIFI_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/wifi/wificonfig.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/wifi/wificonfig.h" -#include "../../modules/authentication/authentication_service.h" -//Get available AP list (limited to 30) -//output is JSON or plain text according parameter + +// Get available AP list (limited to 30) +// output is JSON or plain text according parameter //[ESP410]json= -#define COMMANDID 410 -bool Commands::ESP410(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +#define COMMANDID 410 +bool Commands::ESP410(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); - noError = false; - errorCode = 401; - } + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } #else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - if (parameter.length() == 0) { - //Backup current mode - uint8_t currentmode = WiFi.getMode(); - int n = 0; - uint8_t total = 0; - if (!json) { - output->printMSGLine ("Start Scan"); - } - if(currentmode==WIFI_AP) { - WiFi.mode(WIFI_AP_STA); - } - n = WiFi.scanNetworks (); - if(currentmode==WIFI_AP) { - WiFi.mode((WiFiMode_t)currentmode); - } + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + if (parameter.length() == 0) { + // Backup current mode + uint8_t currentmode = WiFi.getMode(); + int n = 0; + uint8_t total = 0; + if (!json) { + output->printMSGLine("Start Scan"); + } + if (currentmode == WIFI_AP) { + WiFi.mode(WIFI_AP_STA); + } + n = WiFi.scanNetworks(); + if (currentmode == WIFI_AP) { + WiFi.mode((WiFiMode_t)currentmode); + } + if (json) { + output->print("{\"cmd\":\"410\",\"status\":\"ok\",\"data\":["); + } + String line; + for (int i = 0; i < n; ++i) { + line = ""; + if (WiFi.RSSI(i) >= MIN_RSSI) { + if (total > 0) { if (json) { - output->print ("{\"cmd\":\"410\",\"status\":\"ok\",\"data\":["); + line += ","; } - String line; - for (int i = 0; i < n; ++i) { - line = ""; - if (WiFi.RSSI (i)>= MIN_RSSI) { - if (total > 0) { - if (json) { - line+=","; - } - } - total++; - if (json) { - line += "{\"SSID\":\""; - line +=ESP3DOutput::encodeString(WiFi.SSID (i).c_str()); - } else { - line +=WiFi.SSID (i).c_str(); - } - if (json) { - line +="\",\"SIGNAL\":\""; - } else { - line +="\t"; - } - line += String(WiFiConfig::getSignal (WiFi.RSSI (i) )); - if (!json) { - line +="%"; - } - if (json) { - line +="\",\"IS_PROTECTED\":\""; - } - if (WiFi.encryptionType (i) == ENC_TYPE_NONE) { - if (json) { - line +="0"; - } else { - line +="\tOpen"; - } - } else { - if (json) { - line +="1"; - } else { - line +="\tSecure"; - } - } - if (json) { - line +="\"}"; - } - if (json) { - output->print (line.c_str()); - } else { - output->printMSGLine (line.c_str()); - } - } - } - WiFi.scanDelete(); + } + total++; + if (json) { + line += "{\"SSID\":\""; + line += ESP3DOutput::encodeString(WiFi.SSID(i).c_str()); + } else { + line += WiFi.SSID(i).c_str(); + } + if (json) { + line += "\",\"SIGNAL\":\""; + } else { + line += "\t"; + } + line += String(WiFiConfig::getSignal(WiFi.RSSI(i))); + if (!json) { + line += "%"; + } + if (json) { + line += "\",\"IS_PROTECTED\":\""; + } + if (WiFi.encryptionType(i) == ENC_TYPE_NONE) { if (json) { - output->printLN ("]}"); + line += "0"; } else { - output->printMSGLine ("End Scan"); + line += "\tOpen"; } - return true; - } else { - response = format_response(COMMANDID, json, false, "This command doesn't take parameters"); - noError = false; - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); + } else { + if (json) { + line += "1"; + } else { + line += "\tSecure"; + } + } + if (json) { + line += "\"}"; + } + if (json) { + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } } + } + WiFi.scanDelete(); + if (json) { + output->printLN("]}"); + } else { + output->printMSGLine("End Scan"); + } + return true; } else { - output->printERROR(response.c_str(), errorCode); + response = format_response(COMMANDID, json, false, + "This command doesn't take parameters"); + noError = false; } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //WIFI_FEATURE +#endif // WIFI_FEATURE diff --git a/esp3d/src/core/espcmd/ESP420.cpp b/esp3d/src/core/espcmd/ESP420.cpp index 81d34caf..88b59c34 100644 --- a/esp3d/src/core/espcmd/ESP420.cpp +++ b/esp3d/src/core/espcmd/ESP420.cpp @@ -57,7 +57,7 @@ #include "../../modules/webdav/webdav_server.h" #endif // WEBDAV_FEATURE #if defined(TIMESTAMP_FEATURE) -#include "../../modules/time/time_server.h" +#include "../../modules/time/time_service.h" #endif // TIMESTAMP_FEATURE #if defined(SENSOR_DEVICE) #include "../../modules/sensor/sensor.h" @@ -1317,7 +1317,7 @@ bool Commands::ESP420(const char* cmd_params, level_authenticate_type auth_type, } else { line += ": "; } - line += timeserver.started() ? "ON" : "OFF"; + line += timeService.started() ? "ON" : "OFF"; if (json) { line += "\"}"; output->print(line.c_str()); @@ -1660,14 +1660,14 @@ bool Commands::ESP420(const char* cmd_params, level_authenticate_type auth_type, noError = false; } } - if (noError) { - if (json) { - output->printLN(response.c_str()); - } else { - output->printMSG(response.c_str()); - } + if (json) { + output->printLN(response.c_str()); } else { - output->printERROR(response.c_str(), errorCode); + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } } return noError; } diff --git a/esp3d/src/core/espcmd/ESP444.cpp b/esp3d/src/core/espcmd/ESP444.cpp index df9ccb63..ad3564e0 100644 --- a/esp3d/src/core/espcmd/ESP444.cpp +++ b/esp3d/src/core/espcmd/ESP444.cpp @@ -18,63 +18,67 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#include "../esp3d.h" -#include "../commands.h" -#include "../esp3doutput.h" #include "../../modules/authentication/authentication_service.h" -//Set ESP State -//cmd are RESTART / RESET +#include "../commands.h" +#include "../esp3d.h" +#include "../esp3doutput.h" + +// Set ESP State +// cmd are RESTART / RESET //[ESP444] json= -#define COMMANDID 444 -bool Commands::ESP444(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +#define COMMANDID 444 +bool Commands::ESP444(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } + if (auth_type != LEVEL_ADMIN) { + response = + format_response(COMMANDID, json, false, "Wrong authentication level"); + noError = false; + errorCode = 401; + } #else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - if (has_tag(cmd_params,"RESET")) { - if (Esp3D::reset()) { - response = format_response(COMMANDID, json, true, "ok"); - } else { - response = format_response(COMMANDID, json, false, "Reset failed"); - noError = false; - } - } - if (noError && has_tag(cmd_params,"RESTART")) { - if (!json) { - output->printMSG ("Restart ongoing"); - } else { - response = format_response(COMMANDID, json, true, "Restart ongoing"); - output->printLN (response.c_str()); - } - output->flush(); - Hal::wait(100); - Esp3D::restart_esp(); - } - if (noError && !has_tag(cmd_params,"RESTART") && !has_tag(cmd_params,"RESET")) { - response = format_response(COMMANDID, json, false, "Invalid parameter"); - noError = false; - } + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + if (has_tag(cmd_params, "RESET")) { + if (Esp3D::reset()) { + response = format_response(COMMANDID, json, true, "ok"); + } else { + response = format_response(COMMANDID, json, false, "Reset failed"); + noError = false; + } } + if (noError && has_tag(cmd_params, "RESTART")) { + if (!json) { + output->printMSG("Restart ongoing"); + } else { + response = format_response(COMMANDID, json, true, "Restart ongoing"); + output->printLN(response.c_str()); + } + output->flush(); + Hal::wait(100); + Esp3D::restart_esp(); + } + if (noError && !has_tag(cmd_params, "RESTART") && + !has_tag(cmd_params, "RESET")) { + response = format_response(COMMANDID, json, false, "Invalid parameter"); + noError = false; + } + } + if (json) { + output->printLN(response.c_str()); + } else { if (noError) { - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); - } + output->printMSG(response.c_str()); } else { - output->printERROR(response.c_str(), errorCode); + output->printERROR(response.c_str(), errorCode); } - return noError; + } + return noError; } diff --git a/esp3d/src/core/espcmd/ESP450.cpp b/esp3d/src/core/espcmd/ESP450.cpp index 6dac369a..87b65ee5 100644 --- a/esp3d/src/core/espcmd/ESP450.cpp +++ b/esp3d/src/core/espcmd/ESP450.cpp @@ -18,137 +18,136 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (MDNS_FEATURE) +#if defined(MDNS_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/mDNS/mDNS.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/mDNS/mDNS.h" -#include "../../modules/authentication/authentication_service.h" -//Get available ESP3D list -//output is JSON or plain text according parameter + +// Get available ESP3D list +// output is JSON or plain text according parameter //[ESP4\50]json= -#define COMMANDID 450 -bool Commands::ESP450(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +#define COMMANDID 450 +bool Commands::ESP450(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); - noError = false; - errorCode = 401; - } + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } #else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - if (parameter.length() == 0) { - - uint16_t n = 0; - if (!json) { - output->printMSGLine ("Start Scan"); - } - - n = esp3d_mDNS.servicesCount (); - if (json) { - output->print ("{\"cmd\":\"450\",\"status\":\"ok\",\"data\":["); - } - String line; - - for (uint16_t i = 0; i < n; i++) { - line = ""; - if (strlen(esp3d_mDNS.answerHostname(i)) == 0) { - continue; - } - if (i > 0) { - if (json) { - line+=","; - } - } - if (json) { - line += "{\"Hostname\":\""; - line +=ESP3DOutput::encodeString(esp3d_mDNS.answerHostname(i)); - } else { - line +=esp3d_mDNS.answerHostname(i); - } - if (json) { - line +="\",\"IP\":\""; - } else { - line +=" ("; - } - line += esp3d_mDNS.answerIP(i); - if (!json) { - line +=":"; - } - if (json) { - line +="\",\"port\":\""; - } - line += String(esp3d_mDNS.answerPort(i)); - if (json) { - line +="\",\"TxT\":["; - } else { - line +=") "; - } - uint16_t nbtxt = esp3d_mDNS.answerTxtCount(i); - for (uint16_t j = 0; j < nbtxt; ++j) { - if (j>0) { - line += ","; - } - if (json) { - line += "{\"key\":\""; - } - line+=esp3d_mDNS.answerTxtKey(i, j); - if (json) { - line +="\",\"value\":\""; - } else { - line +="="; - } - line+=esp3d_mDNS.answerTxt(i, j); - if (json) { - line +="\"}"; - } - - } - if (json) { - line +="]}"; - } - if (json) { - output->print (line.c_str()); - } else { - output->printMSGLine (line.c_str()); - } - } - + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + if (parameter.length() == 0) { + uint16_t n = 0; + if (!json) { + output->printMSGLine("Start Scan"); + } + n = esp3d_mDNS.servicesCount(); + if (json) { + output->print("{\"cmd\":\"450\",\"status\":\"ok\",\"data\":["); + } + String line; + for (uint16_t i = 0; i < n; i++) { + line = ""; + if (strlen(esp3d_mDNS.answerHostname(i)) == 0) { + continue; + } + if (i > 0) { + if (json) { + line += ","; + } } - if (json) { - output->printLN ("]}"); + line += "{\"Hostname\":\""; + line += ESP3DOutput::encodeString(esp3d_mDNS.answerHostname(i)); } else { - output->printMSGLine ("End Scan"); + line += esp3d_mDNS.answerHostname(i); } - return true; - } else { - response = format_response(COMMANDID, json, false, "This command doesn't take parameters"); - noError = false; + if (json) { + line += "\",\"IP\":\""; + } else { + line += " ("; + } + line += esp3d_mDNS.answerIP(i); + if (!json) { + line += ":"; + } + if (json) { + line += "\",\"port\":\""; + } + line += String(esp3d_mDNS.answerPort(i)); + if (json) { + line += "\",\"TxT\":["; + } else { + line += ") "; + } + uint16_t nbtxt = esp3d_mDNS.answerTxtCount(i); + for (uint16_t j = 0; j < nbtxt; ++j) { + if (j > 0) { + line += ","; + } + if (json) { + line += "{\"key\":\""; + } + line += esp3d_mDNS.answerTxtKey(i, j); + if (json) { + line += "\",\"value\":\""; + } else { + line += "="; + } + line += esp3d_mDNS.answerTxt(i, j); + if (json) { + line += "\"}"; + } + } + if (json) { + line += "]}"; + } + if (json) { + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + } } - if (noError) { - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); - } + if (json) { + output->printLN("]}"); } else { - output->printERROR(response.c_str(), errorCode); + output->printMSGLine("End Scan"); } - return noError; + return true; + } else { + response = format_response(COMMANDID, json, false, + "This command doesn't take parameters"); + noError = false; + } + + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //MDNS_FEATURE +#endif // MDNS_FEATURE diff --git a/esp3d/src/core/espcmd/ESP550.cpp b/esp3d/src/core/espcmd/ESP550.cpp index ae8ad892..5b6b216c 100644 --- a/esp3d/src/core/espcmd/ESP550.cpp +++ b/esp3d/src/core/espcmd/ESP550.cpp @@ -18,54 +18,57 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (AUTHENTICATION_FEATURE) +#if defined(AUTHENTICATION_FEATURE) +#include "../../modules/authentication/authentication_service.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#define COMMANDID 550 -//Change admin password + +#define COMMANDID 550 +// Change admin password //[ESP550] json= pwd= -bool Commands::ESP550(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead - if (auth_type == LEVEL_ADMIN) { - parameter = clean_param(get_param (cmd_params, "")); - if (parameter.length() != 0) { - if (Settings_ESP3D::isLocalPasswordValid (parameter.c_str() ) ) { - if (!Settings_ESP3D::write_string (ESP_ADMIN_PWD, parameter.c_str())) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } else { - response = format_response(COMMANDID, json, true, "ok"); - } - } else { - response = format_response(COMMANDID, json, false, "Invalid parameter"); - noError = false; - } +bool Commands::ESP550(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead + if (auth_type == LEVEL_ADMIN) { + parameter = clean_param(get_param(cmd_params, "")); + if (parameter.length() != 0) { + if (Settings_ESP3D::isLocalPasswordValid(parameter.c_str())) { + if (!Settings_ESP3D::write_string(ESP_ADMIN_PWD, parameter.c_str())) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; } else { - response = format_response(COMMANDID, json, false, "Missing parameter"); - noError = false; + response = format_response(COMMANDID, json, true, "ok"); } - } else { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); + } else { + response = format_response(COMMANDID, json, false, "Invalid parameter"); noError = false; - errorCode = 401; - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); - } + } } else { - output->printERROR(response.c_str(), errorCode); + response = format_response(COMMANDID, json, false, "Missing parameter"); + noError = false; } - return noError; + } else { + response = + format_response(COMMANDID, json, false, "Wrong authentication level"); + noError = false; + errorCode = 401; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //AUTHENTICATION_FEATURE +#endif // AUTHENTICATION_FEATURE diff --git a/esp3d/src/core/espcmd/ESP555.cpp b/esp3d/src/core/espcmd/ESP555.cpp index bd9d88ff..8aa530e5 100644 --- a/esp3d/src/core/espcmd/ESP555.cpp +++ b/esp3d/src/core/espcmd/ESP555.cpp @@ -18,54 +18,57 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (AUTHENTICATION_FEATURE) +#if defined(AUTHENTICATION_FEATURE) +#include "../../modules/authentication/authentication_service.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -//Change user password + +// Change user password //[ESP555] json= pwd= -#define COMMANDID 555 -bool Commands::ESP555(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead - if (auth_type != LEVEL_GUEST) { - parameter = clean_param(get_param (cmd_params, "")); - if (parameter.length() != 0) { - if (Settings_ESP3D::isLocalPasswordValid (parameter.c_str() ) ) { - if (!Settings_ESP3D::write_string (ESP_USER_PWD, parameter.c_str())) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } else { - response = format_response(COMMANDID, json, true, "ok"); - } - } else { - response = format_response(COMMANDID, json, false, "Invalid parameter"); - noError = false; - } +#define COMMANDID 555 +bool Commands::ESP555(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead + if (auth_type != LEVEL_GUEST) { + parameter = clean_param(get_param(cmd_params, "")); + if (parameter.length() != 0) { + if (Settings_ESP3D::isLocalPasswordValid(parameter.c_str())) { + if (!Settings_ESP3D::write_string(ESP_USER_PWD, parameter.c_str())) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; } else { - response = format_response(COMMANDID, json, false, "Missing parameter"); - noError = false; + response = format_response(COMMANDID, json, true, "ok"); } - } else { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); + } else { + response = format_response(COMMANDID, json, false, "Invalid parameter"); noError = false; - errorCode = 401; - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); - } + } } else { - output->printERROR(response.c_str(), errorCode); + response = format_response(COMMANDID, json, false, "Missing parameter"); + noError = false; } - return noError; + } else { + response = + format_response(COMMANDID, json, false, "Wrong authentication level"); + noError = false; + errorCode = 401; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //AUTHENTICATION_FEATURE +#endif // AUTHENTICATION_FEATURE diff --git a/esp3d/src/core/espcmd/ESP600.cpp b/esp3d/src/core/espcmd/ESP600.cpp index fa566577..5fa49cb9 100644 --- a/esp3d/src/core/espcmd/ESP600.cpp +++ b/esp3d/src/core/espcmd/ESP600.cpp @@ -18,57 +18,62 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (NOTIFICATION_FEATURE) +#if defined(NOTIFICATION_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/notifications/notifications_service.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#include "../../modules/notifications/notifications_service.h" -#define COMMANDID 600 -//Send Notification + +#define COMMANDID 600 +// Send Notification //[ESP600]msg json= [pwd=] -bool Commands::ESP600(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP600(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); - noError = false; - errorCode = 401; - } + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } #else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - response = format_response(COMMANDID, json, false, "Message is missing"); - noError = false; - } else { - parameter = get_param (cmd_params, ""); - if (notificationsservice.sendMSG(ESP_NOTIFICATION_TITLE, parameter.c_str())) { - response = format_response(COMMANDID, json, true, "ok"); - } else { - response = format_response(COMMANDID, json, false, "Send notification failed"); - noError = false; - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); - } + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + response = format_response(COMMANDID, json, false, "Message is missing"); + noError = false; } else { - output->printERROR(response.c_str(), errorCode); + parameter = get_param(cmd_params, ""); + if (notificationsservice.sendMSG(ESP_NOTIFICATION_TITLE, + parameter.c_str())) { + response = format_response(COMMANDID, json, true, "ok"); + } else { + response = + format_response(COMMANDID, json, false, "Send notification failed"); + noError = false; + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //NOTIFICATION_FEATURE +#endif // NOTIFICATION_FEATURE diff --git a/esp3d/src/core/espcmd/ESP610.cpp b/esp3d/src/core/espcmd/ESP610.cpp index e8d7bffe..f2a31f5d 100644 --- a/esp3d/src/core/espcmd/ESP610.cpp +++ b/esp3d/src/core/espcmd/ESP610.cpp @@ -18,169 +18,180 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (NOTIFICATION_FEATURE) +#if defined(NOTIFICATION_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/notifications/notifications_service.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#include "../../modules/notifications/notifications_service.h" -#define COMMANDID 610 -//Set/Get Notification settings -//[ESP610]type= T1= T2= TS= json= [pwd=] -//Get will give type and settings only not the protected T1/T2 -bool Commands::ESP610(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - bool hasParam = false; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead + +#define COMMANDID 610 +// Set/Get Notification settings +//[ESP610]type= T1= T2= +//TS= json= [pwd=] Get will give type and settings +// only not the protected T1/T2 +bool Commands::ESP610(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + bool hasParam = false; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); - noError = false; - errorCode = 401; - } + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } #else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - uint8_t Ntype = Settings_ESP3D::read_byte(ESP_NOTIFICATION_TYPE); - String tmp; - if (json) { - tmp = "{\"type\":\""; - } else { - tmp = "type="; - } - switch(Ntype) { - case ESP_PUSHOVER_NOTIFICATION: - tmp += "PUSHOVER"; - break; - case ESP_EMAIL_NOTIFICATION: - tmp += "EMAIL"; - break; - case ESP_LINE_NOTIFICATION: - tmp += "LINE"; - break; - case ESP_TELEGRAM_NOTIFICATION: - tmp += "TELEGRAM"; - break; - case ESP_IFTTT_NOTIFICATION: - tmp += "IFTTT"; - break; - default: - tmp+= "NONE"; - } - if (json) { - tmp +="\""; - } - String ts = Settings_ESP3D::read_string(ESP_NOTIFICATION_SETTINGS); - if (ts.length() > 0 && ts!="NONE") { - if (json) { - tmp += ",\"TS\":\""; - } else { - tmp += ", TS="; - } - tmp+= ts; - if (json) { - tmp += "\"}"; - } - } - if (json) { - tmp += "}"; - } - response = format_response(COMMANDID, json, true, tmp.c_str()); - } else { - //type - parameter = get_param (cmd_params, "type="); - if (parameter.length() > 0) { - hasParam = true; - uint8_t Ntype; - parameter.toUpperCase(); - if (parameter == "NONE") { - Ntype = 0; - } else if (parameter == "PUSHOVER") { - Ntype = ESP_PUSHOVER_NOTIFICATION; - } else if (parameter == "EMAIL") { - Ntype = ESP_EMAIL_NOTIFICATION; - } else if (parameter == "LINE") { - Ntype = ESP_LINE_NOTIFICATION; - } else if (parameter == "TELEGRAM") { - Ntype = ESP_TELEGRAM_NOTIFICATION; - } else if (parameter == "IFTTT") { - Ntype = ESP_IFTTT_NOTIFICATION; - } else { - response = format_response(COMMANDID, json, false, "Only NONE, PUSHOVER, EMAIL, LINE, IFTTT are supported"); - noError = false; - } - if (noError) { - if(!Settings_ESP3D::write_byte(ESP_NOTIFICATION_TYPE, Ntype)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } - } - } - //Settings - if (noError) { - parameter = get_param (cmd_params, "TS="); - if (parameter.length() > 0) { - hasParam = true; - if(!Settings_ESP3D::write_string(ESP_NOTIFICATION_SETTINGS, parameter.c_str())) { - response = format_response(COMMANDID, json, false, "Set TS failed"); - noError = false; - } - } - } - //Token1 - if (noError) { - parameter = get_param (cmd_params, "T1="); - if (parameter.length() > 0) { - hasParam = true; - if(!Settings_ESP3D::write_string(ESP_NOTIFICATION_TOKEN1, parameter.c_str())) { - response = format_response(COMMANDID, json, false, "Set T1 failed"); - noError = false; - } - } - } - //Token2 - if (noError) { - parameter = get_param (cmd_params, "T2="); - if (parameter.length() > 0) { - hasParam = true; - if(!Settings_ESP3D::write_string(ESP_NOTIFICATION_TOKEN2, parameter.c_str())) { - response = format_response(COMMANDID, json, false, "Set T2 failed"); - noError = false; - } else { - response = true; - } - } - } - if (noError) { - if (hasParam) { - //Restart service - notificationsservice.begin(); - response = format_response(COMMANDID, json, true, "ok"); - } else { - response = format_response(COMMANDID, json, false, "Only type, T1, T2 and TS not empty are supported"); - noError = false; - } - } - } - } - if (noError) { + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + uint8_t Ntype = Settings_ESP3D::read_byte(ESP_NOTIFICATION_TYPE); + String tmp; + if (json) { + tmp = "{\"type\":\""; + } else { + tmp = "type="; + } + switch (Ntype) { + case ESP_PUSHOVER_NOTIFICATION: + tmp += "PUSHOVER"; + break; + case ESP_EMAIL_NOTIFICATION: + tmp += "EMAIL"; + break; + case ESP_LINE_NOTIFICATION: + tmp += "LINE"; + break; + case ESP_TELEGRAM_NOTIFICATION: + tmp += "TELEGRAM"; + break; + case ESP_IFTTT_NOTIFICATION: + tmp += "IFTTT"; + break; + default: + tmp += "NONE"; + } + if (json) { + tmp += "\""; + } + String ts = Settings_ESP3D::read_string(ESP_NOTIFICATION_SETTINGS); + if (ts.length() > 0 && ts != "NONE") { if (json) { - output->printLN (response.c_str() ); + tmp += ",\"TS\":\""; } else { - output->printMSG (response.c_str() ); + tmp += ", TS="; } + tmp += ts; + if (json) { + tmp += "\"}"; + } + } + if (json) { + tmp += "}"; + } + response = format_response(COMMANDID, json, true, tmp.c_str()); } else { - output->printERROR(response.c_str(), errorCode); + // type + parameter = get_param(cmd_params, "type="); + if (parameter.length() > 0) { + hasParam = true; + uint8_t Ntype; + parameter.toUpperCase(); + if (parameter == "NONE") { + Ntype = 0; + } else if (parameter == "PUSHOVER") { + Ntype = ESP_PUSHOVER_NOTIFICATION; + } else if (parameter == "EMAIL") { + Ntype = ESP_EMAIL_NOTIFICATION; + } else if (parameter == "LINE") { + Ntype = ESP_LINE_NOTIFICATION; + } else if (parameter == "TELEGRAM") { + Ntype = ESP_TELEGRAM_NOTIFICATION; + } else if (parameter == "IFTTT") { + Ntype = ESP_IFTTT_NOTIFICATION; + } else { + response = format_response( + COMMANDID, json, false, + "Only NONE, PUSHOVER, EMAIL, LINE, IFTTT are supported"); + noError = false; + } + if (noError) { + if (!Settings_ESP3D::write_byte(ESP_NOTIFICATION_TYPE, Ntype)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } + } + } + // Settings + if (noError) { + parameter = get_param(cmd_params, "TS="); + if (parameter.length() > 0) { + hasParam = true; + if (!Settings_ESP3D::write_string(ESP_NOTIFICATION_SETTINGS, + parameter.c_str())) { + response = format_response(COMMANDID, json, false, "Set TS failed"); + noError = false; + } + } + } + // Token1 + if (noError) { + parameter = get_param(cmd_params, "T1="); + if (parameter.length() > 0) { + hasParam = true; + if (!Settings_ESP3D::write_string(ESP_NOTIFICATION_TOKEN1, + parameter.c_str())) { + response = format_response(COMMANDID, json, false, "Set T1 failed"); + noError = false; + } + } + } + // Token2 + if (noError) { + parameter = get_param(cmd_params, "T2="); + if (parameter.length() > 0) { + hasParam = true; + if (!Settings_ESP3D::write_string(ESP_NOTIFICATION_TOKEN2, + parameter.c_str())) { + response = format_response(COMMANDID, json, false, "Set T2 failed"); + noError = false; + } else { + response = true; + } + } + } + if (noError) { + if (hasParam) { + // Restart service + notificationsservice.begin(); + response = format_response(COMMANDID, json, true, "ok"); + } else { + response = format_response( + COMMANDID, json, false, + "Only type, T1, T2 and TS not empty are supported"); + noError = false; + } + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //NOTIFICATION_FEATURE +#endif // NOTIFICATION_FEATURE diff --git a/esp3d/src/core/espcmd/ESP620.cpp b/esp3d/src/core/espcmd/ESP620.cpp index 5ac198d6..3afa4470 100644 --- a/esp3d/src/core/espcmd/ESP620.cpp +++ b/esp3d/src/core/espcmd/ESP620.cpp @@ -18,57 +18,61 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (NOTIFICATION_FEATURE) +#if defined(NOTIFICATION_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/notifications/notifications_service.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#include "../../modules/notifications/notifications_service.h" -#define COMMANDID 620 -//Send Notification using URL + +#define COMMANDID 620 +// Send Notification using URL //[ESP620]URL= json=[pwd=] -bool Commands::ESP620(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP620(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); - noError = false; - errorCode = 401; - } + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } #else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = get_param (cmd_params, ""); - //get - if (parameter.length() == 0) { - response = format_response(COMMANDID, json, false, "Message is missing"); - noError = false; - } else { - parameter = get_param (cmd_params, "URL="); - if (notificationsservice.GET(parameter.c_str())) { - response = format_response(COMMANDID, json, true, "ok"); - } else { - response = format_response(COMMANDID, json, false, "Send notification failed"); - noError = false; - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); - } + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = get_param(cmd_params, ""); + // get + if (parameter.length() == 0) { + response = format_response(COMMANDID, json, false, "Message is missing"); + noError = false; } else { - output->printERROR(response.c_str(), errorCode); + parameter = get_param(cmd_params, "URL="); + if (notificationsservice.GET(parameter.c_str())) { + response = format_response(COMMANDID, json, true, "ok"); + } else { + response = + format_response(COMMANDID, json, false, "Send notification failed"); + noError = false; + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //NOTIFICATION_FEATURE +#endif // NOTIFICATION_FEATURE diff --git a/esp3d/src/core/espcmd/ESP700.cpp b/esp3d/src/core/espcmd/ESP700.cpp index de919c81..a3561aa1 100644 --- a/esp3d/src/core/espcmd/ESP700.cpp +++ b/esp3d/src/core/espcmd/ESP700.cpp @@ -18,64 +18,72 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined(GCODE_HOST_FEATURE) +#if defined(GCODE_HOST_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/gcode_host/gcode_host.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#include "../../modules/gcode_host/gcode_host.h" -#define COMMANDID 700 -//TODO : -// - on ESP3DLib or GRBL_ESP32 the file/line must be processed like a SD gcode file -// - on ESP3D the file/line must be processed and/or streamed like a SD gcode file -//read local file +#define COMMANDID 700 +// TODO : +// - on ESP3DLib or GRBL_ESP32 the file/line must be processed like a SD gcode +// file +// - on ESP3D the file/line must be processed and/or streamed like a SD gcode +// file + +// read local file //[ESP700] -bool Commands::ESP700(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP700(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } + if (auth_type != LEVEL_ADMIN) { + response = + format_response(COMMANDID, json, false, "Wrong authentication level"); + noError = false; + errorCode = 401; + } #else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - if (parameter.length() != 0) { - if (esp3d_gcode_host.getStatus()==HOST_NO_STREAM) { - if (esp3d_gcode_host.processFile(parameter.c_str(), auth_type, output)) { - response = format_response(COMMANDID, json, true, "ok"); - } else { - response = format_response(COMMANDID, json, false, "Error processing file"); - noError = false; - } - } else { - response = format_response(COMMANDID, json, false, "Streaming already in progress"); - noError = false; - } + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + if (parameter.length() != 0) { + if (esp3d_gcode_host.getStatus() == HOST_NO_STREAM) { + if (esp3d_gcode_host.processFile(parameter.c_str(), auth_type, + output)) { + response = format_response(COMMANDID, json, true, "ok"); } else { - response = format_response(COMMANDID, json, false, "Missing parameter"); - noError = false; - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); + response = + format_response(COMMANDID, json, false, "Error processing file"); + noError = false; } + } else { + response = format_response(COMMANDID, json, false, + "Streaming already in progress"); + noError = false; + } } else { - output->printERROR(response.c_str(), errorCode); + response = format_response(COMMANDID, json, false, "Missing parameter"); + noError = false; } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //GCODE_HOST_FEATURE +#endif // GCODE_HOST_FEATURE diff --git a/esp3d/src/core/espcmd/ESP701.cpp b/esp3d/src/core/espcmd/ESP701.cpp index 62f2821e..71f8114a 100644 --- a/esp3d/src/core/espcmd/ESP701.cpp +++ b/esp3d/src/core/espcmd/ESP701.cpp @@ -140,14 +140,14 @@ bool Commands::ESP701(const char* cmd_params, level_authenticate_type auth_type, } } } - if (noError) { - if (json) { - output->printLN(response.c_str()); - } else { - output->printMSG(response.c_str()); - } + if (json) { + output->printLN(response.c_str()); } else { - output->printERROR(response.c_str(), errorCode); + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } } return noError; } diff --git a/esp3d/src/core/espcmd/ESP710.cpp b/esp3d/src/core/espcmd/ESP710.cpp index deb5350f..d84cad90 100644 --- a/esp3d/src/core/espcmd/ESP710.cpp +++ b/esp3d/src/core/espcmd/ESP710.cpp @@ -18,53 +18,56 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (FILESYSTEM_FEATURE) +#if defined(FILESYSTEM_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/filesystem/esp_filesystem.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#include "../../modules/filesystem/esp_filesystem.h" -#define COMMANDID 710 -//Format ESP Filesystem + +#define COMMANDID 710 +// Format ESP Filesystem //[ESP710]FORMATFS json= pwd= -bool Commands::ESP710(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP710(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } + if (auth_type != LEVEL_ADMIN) { + response = + format_response(COMMANDID, json, false, "Wrong authentication level"); + noError = false; + errorCode = 401; + } #else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - if (has_tag (cmd_params, "FORMATFS")) { - if (!json) { - output->printMSGLine("Start Formating"); - } - ESP_FileSystem::format(); - response = format_response(COMMANDID, json, true, "ok"); - } else { - response = format_response(COMMANDID, json, false, "Invalid parameter"); - noError = false; - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSGLine (response.c_str() ); - } + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + if (has_tag(cmd_params, "FORMATFS")) { + if (!json) { + output->printMSGLine("Start Formating"); + } + ESP_FileSystem::format(); + response = format_response(COMMANDID, json, true, "ok"); } else { - output->printERROR(response.c_str(), errorCode); + response = format_response(COMMANDID, json, false, "Invalid parameter"); + noError = false; } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //FILESYSTEM_FEATURE +#endif // FILESYSTEM_FEATURE diff --git a/esp3d/src/core/espcmd/ESP715.cpp b/esp3d/src/core/espcmd/ESP715.cpp index 5f6180f7..0bfd08bd 100644 --- a/esp3d/src/core/espcmd/ESP715.cpp +++ b/esp3d/src/core/espcmd/ESP715.cpp @@ -18,64 +18,67 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (SD_DEVICE) +#if defined(SD_DEVICE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/filesystem/esp_sd.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#include "../../modules/filesystem/esp_sd.h" -#define COMMANDID 715 -//Format SD Filesystem + +#define COMMANDID 715 +// Format SD Filesystem //[ESP715]FORMATSD json= pwd= -bool Commands::ESP715(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP715(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } + if (auth_type != LEVEL_ADMIN) { + response = + format_response(COMMANDID, json, false, "Wrong authentication level"); + noError = false; + errorCode = 401; + } #else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - if (has_tag (cmd_params, "FORMATSD")) { - if (!ESP_SD::accessFS()) { - response = format_response(COMMANDID, json, false, "Not available"); - noError = false; - } else { - ESP_SD::setState(ESP_SDCARD_BUSY); - if (!json) { - output->printMSGLine("Start Formating"); - } - if (ESP_SD::format(output)) { - response = format_response(COMMANDID, json, true, "ok"); - } else { - response = format_response(COMMANDID, json, false, "Format failed"); - noError = false; - } - ESP_SD::releaseFS(); - } - } else { - response = format_response(COMMANDID, json, false, "Invalid parameter"); - noError = false; + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + if (has_tag(cmd_params, "FORMATSD")) { + if (!ESP_SD::accessFS()) { + response = format_response(COMMANDID, json, false, "Not available"); + noError = false; + } else { + ESP_SD::setState(ESP_SDCARD_BUSY); + if (!json) { + output->printMSGLine("Start Formating"); } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); + if (ESP_SD::format(output)) { + response = format_response(COMMANDID, json, true, "ok"); } else { - output->printMSGLine (response.c_str() ); + response = format_response(COMMANDID, json, false, "Format failed"); + noError = false; } + ESP_SD::releaseFS(); + } } else { - output->printERROR(response.c_str(), errorCode); + response = format_response(COMMANDID, json, false, "Invalid parameter"); + noError = false; } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //SD_DEVICE +#endif // SD_DEVICE diff --git a/esp3d/src/core/espcmd/ESP720.cpp b/esp3d/src/core/espcmd/ESP720.cpp index b6173913..529466c7 100644 --- a/esp3d/src/core/espcmd/ESP720.cpp +++ b/esp3d/src/core/espcmd/ESP720.cpp @@ -18,183 +18,187 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (FILESYSTEM_FEATURE) +#if defined(FILESYSTEM_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/filesystem/esp_filesystem.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#include "../../modules/filesystem/esp_filesystem.h" + #ifdef FILESYSTEM_TIMESTAMP_FEATURE -#include "../../modules/time/time_server.h" -#endif //FILESYSTEM_TIMESTAMP_FEATURE -#define COMMANDID 720 -//List ESP Filesystem +#include "../../modules/time/time_service.h" +#endif // FILESYSTEM_TIMESTAMP_FEATURE +#define COMMANDID 720 +// List ESP Filesystem //[ESP720] json= pwd= -bool Commands::ESP720(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP720(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } + if (auth_type != LEVEL_ADMIN) { + response = + format_response(COMMANDID, json, false, "Wrong authentication level"); + noError = false; + errorCode = 401; + } #else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - if (parameter.length() == 0) { - parameter = "/"; - } - - if (ESP_FileSystem::exists(parameter.c_str())) { - String line = ""; - ESP_File f ; - f = ESP_FileSystem::open(parameter.c_str(), ESP_FILE_READ); - uint countf = 0; - uint countd = 0; - if (f) { - if(json) { - line = "{\"cmd\":\"720\",\"status\":\"ok\",\"data\":{\"path\":\"" + parameter + "\",\"files\":["; - output->print (line.c_str()); - } else { - line = "Directory on FS : " + parameter; - output->printMSGLine(line.c_str()); - } - //Check directories - ESP_File sub; - sub = f.openNextFile(); - while (sub) { - if (sub.isDirectory()) { - line=""; - countd++; - if (json) { - line=""; - if (countd > 1) { - line += ","; - } - line += "{\"name\":\"" ; - line+=sub.name() ; - line+= "\",\"size\":\"-1\"}"; - } else { - line = "[DIR] \t"; - line+= sub.name(); - } - if (json) { - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - } - sub.close(); - sub = f.openNextFile(); - } - f.close(); - f = ESP_FileSystem::open(parameter.c_str(), ESP_FILE_READ); - //Check files - sub = f.openNextFile(); - while (sub) { - if (!sub.isDirectory()) { - countf++; - String time = ""; - line=""; -#ifdef FILESYSTEM_TIMESTAMP_FEATURE - time = timeserver.current_time(sub.getLastWrite()); -#endif //FILESYSTEM_TIMESTAMP_FEATURE - if (json) { - line=""; - if (countd > 0 || countf>1) { - line += ","; - } - line+= "{\"name\":\""; - line+=sub.name() ; - line+="\",\"size\":\""; - line+=ESP_FileSystem::formatBytes(sub.size()); - if (time.length() > 0) { - line += "\",\"time\":\""; - line += time; - } - line+="\"}"; - } else { - line+=" \t "; - line+=sub.name(); - line+=" \t"; - line+=ESP_FileSystem::formatBytes(sub.size()); - line+=" \t"; - line+=time; - } - if (json) { - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - } - sub.close(); - sub = f.openNextFile(); - } - f.close(); - - if (json) { - line = "], \"total\":\""; - line += ESP_FileSystem::formatBytes(ESP_FileSystem::totalBytes()); - line += "\",\"used\":\""; - line += ESP_FileSystem::formatBytes(ESP_FileSystem::usedBytes()); - line+="\",\"occupation\":\""; - uint64_t total =ESP_FileSystem::totalBytes(); - if (total==0) { - total=1; - } - float occupation = 100.0*ESP_FileSystem::usedBytes()/total; - if ((occupation < 1) && (ESP_FileSystem::usedBytes()>0)) { - occupation=1; - } - line+= String((int)round(occupation)); - line+="\"}}"; - output->printLN (line.c_str()); - } else { - line =String(countf) + " file"; - if (countf > 1) { - line += "s"; - } - line += " , " + String(countd) + " dir"; - if (countd > 1) { - line += "s"; - } - output->printMSGLine(line.c_str()); - line = "Total "; - line+=ESP_FileSystem::formatBytes(ESP_FileSystem::totalBytes()); - line+=", Used "; - line+=ESP_FileSystem::formatBytes(ESP_FileSystem::usedBytes()); - line+=", Available: "; - line+=ESP_FileSystem::formatBytes(ESP_FileSystem::freeBytes()); - output->printMSGLine(line.c_str()); - } - - return true; - } else { - response = format_response(COMMANDID, json, false, "Invalid directory"); - noError = false; - } - } else { - response = format_response(COMMANDID, json, false, "Invalid directory"); - noError = false; - } + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + if (parameter.length() == 0) { + parameter = "/"; } - if (noError) { + + if (ESP_FileSystem::exists(parameter.c_str())) { + String line = ""; + ESP_File f; + f = ESP_FileSystem::open(parameter.c_str(), ESP_FILE_READ); + uint countf = 0; + uint countd = 0; + if (f) { if (json) { - output->printLN (response.c_str() ); + line = "{\"cmd\":\"720\",\"status\":\"ok\",\"data\":{\"path\":\"" + + parameter + "\",\"files\":["; + output->print(line.c_str()); } else { - output->printMSG (response.c_str() ); + line = "Directory on FS : " + parameter; + output->printMSGLine(line.c_str()); } + // Check directories + ESP_File sub; + sub = f.openNextFile(); + while (sub) { + if (sub.isDirectory()) { + line = ""; + countd++; + if (json) { + line = ""; + if (countd > 1) { + line += ","; + } + line += "{\"name\":\""; + line += sub.name(); + line += "\",\"size\":\"-1\"}"; + } else { + line = "[DIR] \t"; + line += sub.name(); + } + if (json) { + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + } + sub.close(); + sub = f.openNextFile(); + } + f.close(); + f = ESP_FileSystem::open(parameter.c_str(), ESP_FILE_READ); + // Check files + sub = f.openNextFile(); + while (sub) { + if (!sub.isDirectory()) { + countf++; + String time = ""; + line = ""; +#ifdef FILESYSTEM_TIMESTAMP_FEATURE + time = timeService.getDateTime((time_t)sub.getLastWrite()); +#endif // FILESYSTEM_TIMESTAMP_FEATURE + if (json) { + line = ""; + if (countd > 0 || countf > 1) { + line += ","; + } + line += "{\"name\":\""; + line += sub.name(); + line += "\",\"size\":\""; + line += ESP_FileSystem::formatBytes(sub.size()); + if (time.length() > 0) { + line += "\",\"time\":\""; + line += time; + } + line += "\"}"; + } else { + line += " \t "; + line += sub.name(); + line += " \t"; + line += ESP_FileSystem::formatBytes(sub.size()); + line += " \t"; + line += time; + } + if (json) { + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + } + sub.close(); + sub = f.openNextFile(); + } + f.close(); + + if (json) { + line = "], \"total\":\""; + line += ESP_FileSystem::formatBytes(ESP_FileSystem::totalBytes()); + line += "\",\"used\":\""; + line += ESP_FileSystem::formatBytes(ESP_FileSystem::usedBytes()); + line += "\",\"occupation\":\""; + uint64_t total = ESP_FileSystem::totalBytes(); + if (total == 0) { + total = 1; + } + float occupation = 100.0 * ESP_FileSystem::usedBytes() / total; + if ((occupation < 1) && (ESP_FileSystem::usedBytes() > 0)) { + occupation = 1; + } + line += String((int)round(occupation)); + line += "\"}}"; + output->printLN(line.c_str()); + } else { + line = String(countf) + " file"; + if (countf > 1) { + line += "s"; + } + line += " , " + String(countd) + " dir"; + if (countd > 1) { + line += "s"; + } + output->printMSGLine(line.c_str()); + line = "Total "; + line += ESP_FileSystem::formatBytes(ESP_FileSystem::totalBytes()); + line += ", Used "; + line += ESP_FileSystem::formatBytes(ESP_FileSystem::usedBytes()); + line += ", Available: "; + line += ESP_FileSystem::formatBytes(ESP_FileSystem::freeBytes()); + output->printMSGLine(line.c_str()); + } + + return true; + } else { + response = format_response(COMMANDID, json, false, "Invalid directory"); + noError = false; + } } else { - output->printERROR(response.c_str(), errorCode); + response = format_response(COMMANDID, json, false, "Invalid directory"); + noError = false; } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //FILESYSTEM_FEATURE +#endif // FILESYSTEM_FEATURE diff --git a/esp3d/src/core/espcmd/ESP730.cpp b/esp3d/src/core/espcmd/ESP730.cpp index fca0a6f4..b14e4fd5 100644 --- a/esp3d/src/core/espcmd/ESP730.cpp +++ b/esp3d/src/core/espcmd/ESP730.cpp @@ -18,105 +18,107 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (FILESYSTEM_FEATURE) +#if defined(FILESYSTEM_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/filesystem/esp_filesystem.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#include "../../modules/filesystem/esp_filesystem.h" -#define COMMANDID 730 -// Action on ESP Filesystem -//rmdir / remove / mkdir / exists / create -//[ESP730]= json= pwd= -bool Commands::ESP730(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - bool hasParam = false; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead; -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = get_param (cmd_params, "mkdir="); - if (parameter.length() != 0) { - hasParam = true; - if (!ESP_FileSystem::mkdir(parameter.c_str())) { - response = format_response(COMMANDID, json, false, "mkdir failed"); - noError = false; - } - } - if (noError && !hasParam) { - parameter = get_param (cmd_params, "rmdir="); - if (parameter.length() != 0) { - hasParam = true; - if (!ESP_FileSystem::rmdir(parameter.c_str())) { - response = format_response(COMMANDID, json, false, "rmdir failed"); - noError = false; - } - } - } - if (noError && !hasParam) { - parameter = get_param (cmd_params, "remove="); - if (parameter.length() != 0) { - hasParam = true; - if (!ESP_FileSystem::remove(parameter.c_str())) { - response = format_response(COMMANDID, json, false, "remove failed"); - noError = false; - } - } - } - if (noError && !hasParam) { - parameter = get_param (cmd_params, "exists="); - if (parameter.length() != 0) { - hasParam = true; - if (ESP_FileSystem::exists(parameter.c_str())) { - response = format_response(COMMANDID, json, true, "yes"); - } else { - response = format_response(COMMANDID, json, false, "no"); - } - } - } - if (noError && !hasParam) { - parameter = get_param (cmd_params, "create="); - if (parameter.length() != 0) { - hasParam = true; - ESP_File f = ESP_FileSystem::open(parameter.c_str(), ESP_FILE_WRITE); - if (!f.isOpen()) { - response = format_response(COMMANDID, json, false, "create failed"); - noError = false; - } else { - f.close(); - } - } - } - if (hasParam && noError && response.length() == 0) { - response = format_response(COMMANDID, json, true, "ok"); - } - if (!hasParam) { - response = format_response(COMMANDID, json, false, "Missing parameter"); - noError = false; - } +#define COMMANDID 730 +// Action on ESP Filesystem +// rmdir / remove / mkdir / exists / create +//[ESP730]= json= pwd= +bool Commands::ESP730(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + bool hasParam = false; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead; +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = + format_response(COMMANDID, json, false, "Wrong authentication level"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = get_param(cmd_params, "mkdir="); + if (parameter.length() != 0) { + hasParam = true; + if (!ESP_FileSystem::mkdir(parameter.c_str())) { + response = format_response(COMMANDID, json, false, "mkdir failed"); + noError = false; + } } - if (noError) { - if (json) { - output->printLN (response.c_str() ); + if (noError && !hasParam) { + parameter = get_param(cmd_params, "rmdir="); + if (parameter.length() != 0) { + hasParam = true; + if (!ESP_FileSystem::rmdir(parameter.c_str())) { + response = format_response(COMMANDID, json, false, "rmdir failed"); + noError = false; + } + } + } + if (noError && !hasParam) { + parameter = get_param(cmd_params, "remove="); + if (parameter.length() != 0) { + hasParam = true; + if (!ESP_FileSystem::remove(parameter.c_str())) { + response = format_response(COMMANDID, json, false, "remove failed"); + noError = false; + } + } + } + if (noError && !hasParam) { + parameter = get_param(cmd_params, "exists="); + if (parameter.length() != 0) { + hasParam = true; + if (ESP_FileSystem::exists(parameter.c_str())) { + response = format_response(COMMANDID, json, true, "yes"); } else { - output->printMSG (response.c_str() ); + response = format_response(COMMANDID, json, false, "no"); } - } else { - output->printERROR(response.c_str(), errorCode); + } } - return noError; + if (noError && !hasParam) { + parameter = get_param(cmd_params, "create="); + if (parameter.length() != 0) { + hasParam = true; + ESP_File f = ESP_FileSystem::open(parameter.c_str(), ESP_FILE_WRITE); + if (!f.isOpen()) { + response = format_response(COMMANDID, json, false, "create failed"); + noError = false; + } else { + f.close(); + } + } + } + if (hasParam && noError && response.length() == 0) { + response = format_response(COMMANDID, json, true, "ok"); + } + if (!hasParam) { + response = format_response(COMMANDID, json, false, "Missing parameter"); + noError = false; + } + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //FILESYSTEM_FEATURE +#endif // FILESYSTEM_FEATURE diff --git a/esp3d/src/core/espcmd/ESP740.cpp b/esp3d/src/core/espcmd/ESP740.cpp index e80ba11b..e4c14e4a 100644 --- a/esp3d/src/core/espcmd/ESP740.cpp +++ b/esp3d/src/core/espcmd/ESP740.cpp @@ -18,190 +18,197 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (SD_DEVICE) +#if defined(SD_DEVICE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/filesystem/esp_sd.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#include "../../modules/filesystem/esp_sd.h" + #ifdef SD_TIMESTAMP_FEATURE -#include "../../modules/time/time_server.h" -#endif //SD_TIMESTAMP_FEATURE -#define COMMANDID 740 -//List SD Filesystem +#include "../../modules/time/time_service.h" +#endif // SD_TIMESTAMP_FEATURE +#define COMMANDID 740 +// List SD Filesystem //[ESP740] json= pwd= -bool Commands::ESP740(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP740(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } + if (auth_type != LEVEL_ADMIN) { + response = + format_response(COMMANDID, json, false, "Wrong authentication level"); + noError = false; + errorCode = 401; + } #else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - if (parameter.length() == 0) { - parameter = "/"; - } - if (!ESP_SD::accessFS()) { - response = format_response(COMMANDID, json, false, "Not available"); - noError = false; - } else { - if (ESP_SD::getState(true) == ESP_SDCARD_NOT_PRESENT) { - response = format_response(COMMANDID, json, false, "No SD card"); - noError = false; + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + if (parameter.length() == 0) { + parameter = "/"; + } + if (!ESP_SD::accessFS()) { + response = format_response(COMMANDID, json, false, "Not available"); + noError = false; + } else { + if (ESP_SD::getState(true) == ESP_SDCARD_NOT_PRESENT) { + response = format_response(COMMANDID, json, false, "No SD card"); + noError = false; + } else { + ESP_SD::setState(ESP_SDCARD_BUSY); + if (ESP_SD::exists(parameter.c_str())) { + String line = ""; + ESP_SDFile f = ESP_SD::open(parameter.c_str(), ESP_FILE_READ); + uint countf = 0; + uint countd = 0; + if (f) { + if (json) { + line = + "{\"cmd\":\"720\",\"status\":\"ok\",\"data\":{\"path\":\"" + + parameter + "\",\"files\":["; + output->print(line.c_str()); } else { - ESP_SD::setState(ESP_SDCARD_BUSY ); - if (ESP_SD::exists(parameter.c_str())) { - String line = ""; - ESP_SDFile f = ESP_SD::open(parameter.c_str(), ESP_FILE_READ); - uint countf = 0; - uint countd = 0; - if (f) { - if(json) { - line = "{\"cmd\":\"720\",\"status\":\"ok\",\"data\":{\"path\":\"" + parameter + "\",\"files\":["; - output->print (line.c_str()); - } else { - line = "Directory on SD : " + parameter; - output->printMSGLine(line.c_str()); - } - //Check directories - ESP_SDFile sub = f.openNextFile(); - while (sub) { - if (sub.isDirectory()) { - line=""; - countd++; - if (json) { - line=""; - if (countd > 1) { - line += ","; - } - line += "{\"name\":\"" ; - line+=sub.name() ; - line+= "\",\"size\":\"-1\"}"; - } else { - line = "[DIR] \t"; - line+= sub.name(); - } - if (json) { - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - } - sub.close(); - sub = f.openNextFile(); - } - f.close(); - f = ESP_SD::open(parameter.c_str(), ESP_FILE_READ); - //Check files - sub = f.openNextFile(); - while (sub) { - if (!sub.isDirectory()) { - String time = ""; - line=""; - countf++; -#ifdef FILESYSTEM_TIMESTAMP_FEATURE - time = timeserver.current_time(sub.getLastWrite()); -#endif //FILESYSTEM_TIMESTAMP_FEATURE - if (json) { - if (countd > 0 || countf>1) { - line += ","; - } - line+= "{\"name\":\""; - line+=sub.name() ; - line+="\",\"size\":\""; - line+=ESP_SD::formatBytes(sub.size()); - if (time.length() > 0) { - line += "\",\"time\":\""; - line += time; - } - line+="\"}"; - } else { - line+=" \t "; - line+=sub.name(); - line+=" \t"; - line+=ESP_SD::formatBytes(sub.size()); - line+=" \t"; - line+=time; - } - if (json) { - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - } - sub.close(); - sub = f.openNextFile(); - } - f.close(); - if (json) { - line = "], \"total\":\""; - line += ESP_SD::formatBytes(ESP_SD::totalBytes()); - line += "\",\"used\":\""; - line += ESP_SD::formatBytes(ESP_SD::usedBytes()); - line+="\",\"occupation\":\""; - uint64_t total =ESP_SD::totalBytes(); - if (total==0) { - total=1; - } - float occupation = 100.0*ESP_SD::usedBytes()/total; - if ((occupation < 1) && (ESP_SD::usedBytes()>0)) { - occupation=1; - } - line+= String((int)round(occupation)); - line+="\"}}"; - output->printLN (line.c_str()); - } else { - line =String(countf) + " file"; - if (countf > 1) { - line += "s"; - } - line += " , " + String(countd) + " dir"; - if (countd > 1) { - line += "s"; - } - output->printMSGLine(line.c_str()); - line = "Total "; - line+=ESP_SD::formatBytes(ESP_SD::totalBytes()); - line+=", Used "; - line+=ESP_SD::formatBytes(ESP_SD::usedBytes()); - line+=", Available: "; - line+=ESP_SD::formatBytes(ESP_SD::freeBytes()); - output->printMSGLine(line.c_str()); - } - ESP_SD::releaseFS(); - return true; - } else { - response = format_response(COMMANDID, json, false, "Invalid directory"); - noError = false; - } + line = "Directory on SD : " + parameter; + output->printMSGLine(line.c_str()); + } + // Check directories + ESP_SDFile sub = f.openNextFile(); + while (sub) { + if (sub.isDirectory()) { + line = ""; + countd++; + if (json) { + line = ""; + if (countd > 1) { + line += ","; + } + line += "{\"name\":\""; + line += sub.name(); + line += "\",\"size\":\"-1\"}"; } else { - response = format_response(COMMANDID, json, false, "Invalid directory"); - noError = false; + line = "[DIR] \t"; + line += sub.name(); } + if (json) { + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + } + sub.close(); + sub = f.openNextFile(); + } + f.close(); + f = ESP_SD::open(parameter.c_str(), ESP_FILE_READ); + // Check files + sub = f.openNextFile(); + while (sub) { + if (!sub.isDirectory()) { + String time = ""; + line = ""; + countf++; +#ifdef FILESYSTEM_TIMESTAMP_FEATURE + time = timeService.getDateTime((time_t)sub.getLastWrite()); +#endif // FILESYSTEM_TIMESTAMP_FEATURE + if (json) { + if (countd > 0 || countf > 1) { + line += ","; + } + line += "{\"name\":\""; + line += sub.name(); + line += "\",\"size\":\""; + line += ESP_SD::formatBytes(sub.size()); + if (time.length() > 0) { + line += "\",\"time\":\""; + line += time; + } + line += "\"}"; + } else { + line += " \t "; + line += sub.name(); + line += " \t"; + line += ESP_SD::formatBytes(sub.size()); + line += " \t"; + line += time; + } + if (json) { + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + } + sub.close(); + sub = f.openNextFile(); + } + f.close(); + if (json) { + line = "], \"total\":\""; + line += ESP_SD::formatBytes(ESP_SD::totalBytes()); + line += "\",\"used\":\""; + line += ESP_SD::formatBytes(ESP_SD::usedBytes()); + line += "\",\"occupation\":\""; + uint64_t total = ESP_SD::totalBytes(); + if (total == 0) { + total = 1; + } + float occupation = 100.0 * ESP_SD::usedBytes() / total; + if ((occupation < 1) && (ESP_SD::usedBytes() > 0)) { + occupation = 1; + } + line += String((int)round(occupation)); + line += "\"}}"; + output->printLN(line.c_str()); + } else { + line = String(countf) + " file"; + if (countf > 1) { + line += "s"; + } + line += " , " + String(countd) + " dir"; + if (countd > 1) { + line += "s"; + } + output->printMSGLine(line.c_str()); + line = "Total "; + line += ESP_SD::formatBytes(ESP_SD::totalBytes()); + line += ", Used "; + line += ESP_SD::formatBytes(ESP_SD::usedBytes()); + line += ", Available: "; + line += ESP_SD::formatBytes(ESP_SD::freeBytes()); + output->printMSGLine(line.c_str()); } ESP_SD::releaseFS(); - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); + return true; + } else { + response = + format_response(COMMANDID, json, false, "Invalid directory"); + noError = false; + } } else { - output->printMSG (response.c_str() ); + response = + format_response(COMMANDID, json, false, "Invalid directory"); + noError = false; } - } else { - output->printERROR(response.c_str(), errorCode); + } + ESP_SD::releaseFS(); } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //SD_DEVICE +#endif // SD_DEVICE diff --git a/esp3d/src/core/espcmd/ESP750.cpp b/esp3d/src/core/espcmd/ESP750.cpp index b709c986..ab510eee 100644 --- a/esp3d/src/core/espcmd/ESP750.cpp +++ b/esp3d/src/core/espcmd/ESP750.cpp @@ -18,116 +18,123 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (SD_DEVICE) +#if defined(SD_DEVICE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/filesystem/esp_sd.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#include "../../modules/filesystem/esp_sd.h" -#define COMMANDID 750 + +#define COMMANDID 750 // Action on SD Filesystem -//rmdir / remove / mkdir / exists /create +// rmdir / remove / mkdir / exists /create //[ESP750]= json= pwd= -bool Commands::ESP750(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - bool hasParam = false; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead; +bool Commands::ESP750(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + bool hasParam = false; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead; #ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } + if (auth_type != LEVEL_ADMIN) { + response = + format_response(COMMANDID, json, false, "Wrong authentication level"); + noError = false; + errorCode = 401; + } #else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - if (!ESP_SD::accessFS()) { - response = format_response(COMMANDID, json, false, "Not available"); - noError = false; - } else { - if (ESP_SD::getState(true) == ESP_SDCARD_NOT_PRESENT) { - response = format_response(COMMANDID, json, false, "No SD card"); - noError = false; - } else { - ESP_SD::setState(ESP_SDCARD_BUSY ); - parameter = get_param (cmd_params, "mkdir="); - if (parameter.length() != 0) { - hasParam = true; - if (!ESP_SD::mkdir(parameter.c_str())) { - response = format_response(COMMANDID, json, false, "mkdir failed"); - noError = false; - } - } - if (noError && !hasParam) { - parameter = get_param (cmd_params, "rmdir="); - if (parameter.length() != 0) { - hasParam = true; - if (!ESP_SD::rmdir(parameter.c_str())) { - response = format_response(COMMANDID, json, false, "rmdir failed"); - noError = false; - } - } - } - if (noError && !hasParam) { - parameter = get_param (cmd_params, "remove="); - if (parameter.length() != 0) { - hasParam = true; - if (ESP_SD::remove(parameter.c_str())) { - response = format_response(COMMANDID, json, false, "remove failed"); - noError = false; - } - } - } - if (noError && !hasParam) { - parameter = get_param (cmd_params, "exists="); - if (parameter.length() != 0) { - hasParam = true; - if (ESP_SD::exists(parameter.c_str())) { - response = format_response(COMMANDID, json, true, "yes"); - } else { - response = format_response(COMMANDID, json, false, "no"); - } - } - } - if (noError && !hasParam) { - parameter = get_param (cmd_params, "create="); - if (parameter.length() != 0) { - hasParam = true; - ESP_SDFile f = ESP_SD::open(parameter.c_str(), ESP_FILE_WRITE); - if (!f.isOpen()) { - response = format_response(COMMANDID, json, false, "create failed"); - noError = false; - } else { - f.close(); - } - } - } - if (hasParam && noError && response.length() == 0) { - response = format_response(COMMANDID, json, true, "ok"); - } - if (!hasParam) { - response = format_response(COMMANDID, json, false, "Missing parameter"); - noError = false; - } - } - ESP_SD::releaseFS(); - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); - } + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + if (!ESP_SD::accessFS()) { + response = format_response(COMMANDID, json, false, "Not available"); + noError = false; } else { - output->printERROR(response.c_str(), errorCode); + if (ESP_SD::getState(true) == ESP_SDCARD_NOT_PRESENT) { + response = format_response(COMMANDID, json, false, "No SD card"); + noError = false; + } else { + ESP_SD::setState(ESP_SDCARD_BUSY); + parameter = get_param(cmd_params, "mkdir="); + if (parameter.length() != 0) { + hasParam = true; + if (!ESP_SD::mkdir(parameter.c_str())) { + response = format_response(COMMANDID, json, false, "mkdir failed"); + noError = false; + } + } + if (noError && !hasParam) { + parameter = get_param(cmd_params, "rmdir="); + if (parameter.length() != 0) { + hasParam = true; + if (!ESP_SD::rmdir(parameter.c_str())) { + response = + format_response(COMMANDID, json, false, "rmdir failed"); + noError = false; + } + } + } + if (noError && !hasParam) { + parameter = get_param(cmd_params, "remove="); + if (parameter.length() != 0) { + hasParam = true; + if (ESP_SD::remove(parameter.c_str())) { + response = + format_response(COMMANDID, json, false, "remove failed"); + noError = false; + } + } + } + if (noError && !hasParam) { + parameter = get_param(cmd_params, "exists="); + if (parameter.length() != 0) { + hasParam = true; + if (ESP_SD::exists(parameter.c_str())) { + response = format_response(COMMANDID, json, true, "yes"); + } else { + response = format_response(COMMANDID, json, false, "no"); + } + } + } + if (noError && !hasParam) { + parameter = get_param(cmd_params, "create="); + if (parameter.length() != 0) { + hasParam = true; + ESP_SDFile f = ESP_SD::open(parameter.c_str(), ESP_FILE_WRITE); + if (!f.isOpen()) { + response = + format_response(COMMANDID, json, false, "create failed"); + noError = false; + } else { + f.close(); + } + } + } + if (hasParam && noError && response.length() == 0) { + response = format_response(COMMANDID, json, true, "ok"); + } + if (!hasParam) { + response = + format_response(COMMANDID, json, false, "Missing parameter"); + noError = false; + } + } + ESP_SD::releaseFS(); } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //SD_DEVICE +#endif // SD_DEVICE diff --git a/esp3d/src/core/espcmd/ESP780.cpp b/esp3d/src/core/espcmd/ESP780.cpp index 42f8c8dd..e3db51ba 100644 --- a/esp3d/src/core/espcmd/ESP780.cpp +++ b/esp3d/src/core/espcmd/ESP780.cpp @@ -18,189 +18,193 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (GLOBAL_FILESYSTEM_FEATURE) +#if defined(GLOBAL_FILESYSTEM_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/filesystem/esp_globalFS.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#include "../../modules/filesystem/esp_globalFS.h" -#if defined(SD_TIMESTAMP_FEATURE) || defined(FILESYSTEM_TIMESTAMP_FEATURE) -#include "../../modules/time/time_server.h" -#endif //SD_TIMESTAMP_FEATURE || FILESYSTEM_TIMESTAMP_FEATURE -#define COMMANDID 780 -//List Global Filesystem + +#if defined(SD_TIMESTAMP_FEATURE) || defined(FILESYSTEM_TIMESTAMP_FEATURE) +#include "../../modules/time/time_service.h" +#endif // SD_TIMESTAMP_FEATURE || FILESYSTEM_TIMESTAMP_FEATURE +#define COMMANDID 780 +// List Global Filesystem //[ESP780] json= pwd= -bool Commands::ESP780(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP780(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } + if (auth_type != LEVEL_ADMIN) { + response = + format_response(COMMANDID, json, false, "Wrong authentication level"); + noError = false; + errorCode = 401; + } #else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - if (parameter.length() == 0) { - parameter = "/"; - } - uint8_t fsType = ESP_GBFS::getFSType(parameter.c_str()); - if (fsType==FS_UNKNOWN) { - response = format_response(COMMANDID, json, false, "Invalid path"); - noError = false; - } else { - if (!ESP_GBFS::accessFS(fsType)) { - response = format_response(COMMANDID, json, false, "Not available"); - noError = false; - } else { - String line = ""; - ESP_GBFile f; - f = ESP_GBFS::open(parameter.c_str(), ESP_FILE_READ); - uint countf = 0; - uint countd = 0; - if (f) { - if(json) { - line = "{\"cmd\":\"720\",\"status\":\"ok\",\"data\":{\"path\":\"" + parameter + "\",\"files\":["; - output->print (line.c_str()); - } else { - line = "Directory on Global FS : " + parameter; - output->printMSGLine(line.c_str()); - } - //Check directories - ESP_GBFile sub; - sub = f.openNextFile(); - while (sub) { - if (sub.isDirectory()) { - line=""; - countd++; - if (json) { - line=""; - if (countd > 1) { - line += ","; - } - line += "{\"name\":\"" ; - line+=sub.name() ; - line+= "\",\"size\":\"-1\"}"; - } else { - line = "[DIR] \t"; - line+= sub.name(); - } - if (json) { - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - } - sub.close(); - sub = f.openNextFile(); - } - f.close(); - f = ESP_GBFS::open(parameter.c_str(), ESP_FILE_READ); - //Check files - sub = f.openNextFile(); - while (sub) { - if (!sub.isDirectory()) { - String time = ""; - line=""; - countf++; -#ifdef FILESYSTEM_TIMESTAMP_FEATURE - time = timeserver.current_time(sub.getLastWrite()); -#endif //FILESYSTEM_TIMESTAMP_FEATURE - if (json) { - if (countd > 0 || countf>1) { - line += ","; - } - line+= "{\"name\":\""; - line+=sub.name() ; - line+="\",\"size\":\""; - line+=ESP_GBFS::formatBytes(sub.size()); - if (time.length() > 0) { - line += "\",\"time\":\""; - line += time; - } - line+="\"}"; - } else { - line+=" \t "; - line+=sub.name(); - line+=" \t"; - line+=ESP_GBFS::formatBytes(sub.size()); - line+=" \t"; - line+=time; - } - if (json) { - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - } - sub.close(); - sub = f.openNextFile(); - } - f.close(); - if (json) { - line = "], \"total\":\""; - line += ESP_GBFS::formatBytes(ESP_GBFS::totalBytes()); - line += "\",\"used\":\""; - line += ESP_GBFS::formatBytes(ESP_GBFS::usedBytes()); - line+="\",\"occupation\":\""; - uint64_t total =ESP_GBFS::totalBytes(); - if (total==0) { - total=1; - } - float occupation = 100.0*ESP_GBFS::usedBytes()/total; - if ((occupation < 1) && (ESP_GBFS::usedBytes()>0)) { - occupation=1; - } - line+= String((int)round(occupation)); - line+="\"}}"; - output->printLN (line.c_str()); - } else { - line =String(countf) + " file"; - if (countf > 1) { - line += "s"; - } - line += " , " + String(countd) + " dir"; - if (countd > 1) { - line += "s"; - } - output->printMSGLine(line.c_str()); - line = "Total "; - line+=ESP_GBFS::formatBytes(ESP_GBFS::totalBytes(fsType)); - line+=", Used "; - line+=ESP_GBFS::formatBytes(ESP_GBFS::usedBytes(fsType)); - line+=", Available: "; - line+=ESP_GBFS::formatBytes(ESP_GBFS::freeBytes(fsType)); - if (fsType!=FS_ROOT) { - output->printMSGLine(line.c_str()); - } - } - ESP_GBFS::releaseFS(fsType); - return true; - } else { - response = format_response(COMMANDID, json, false, "Invalid path"); - noError = false; - } - ESP_GBFS::releaseFS(fsType); - } - } + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + if (parameter.length() == 0) { + parameter = "/"; } - if (noError) { - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); - } + uint8_t fsType = ESP_GBFS::getFSType(parameter.c_str()); + if (fsType == FS_UNKNOWN) { + response = format_response(COMMANDID, json, false, "Invalid path"); + noError = false; } else { - output->printERROR(response.c_str(), errorCode); + if (!ESP_GBFS::accessFS(fsType)) { + response = format_response(COMMANDID, json, false, "Not available"); + noError = false; + } else { + String line = ""; + ESP_GBFile f; + f = ESP_GBFS::open(parameter.c_str(), ESP_FILE_READ); + uint countf = 0; + uint countd = 0; + if (f) { + if (json) { + line = "{\"cmd\":\"720\",\"status\":\"ok\",\"data\":{\"path\":\"" + + parameter + "\",\"files\":["; + output->print(line.c_str()); + } else { + line = "Directory on Global FS : " + parameter; + output->printMSGLine(line.c_str()); + } + // Check directories + ESP_GBFile sub; + sub = f.openNextFile(); + while (sub) { + if (sub.isDirectory()) { + line = ""; + countd++; + if (json) { + line = ""; + if (countd > 1) { + line += ","; + } + line += "{\"name\":\""; + line += sub.name(); + line += "\",\"size\":\"-1\"}"; + } else { + line = "[DIR] \t"; + line += sub.name(); + } + if (json) { + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + } + sub.close(); + sub = f.openNextFile(); + } + f.close(); + f = ESP_GBFS::open(parameter.c_str(), ESP_FILE_READ); + // Check files + sub = f.openNextFile(); + while (sub) { + if (!sub.isDirectory()) { + String time = ""; + line = ""; + countf++; +#ifdef FILESYSTEM_TIMESTAMP_FEATURE + time = timeService.getDateTime((time_t)sub.getLastWrite()); +#endif // FILESYSTEM_TIMESTAMP_FEATURE + if (json) { + if (countd > 0 || countf > 1) { + line += ","; + } + line += "{\"name\":\""; + line += sub.name(); + line += "\",\"size\":\""; + line += ESP_GBFS::formatBytes(sub.size()); + if (time.length() > 0) { + line += "\",\"time\":\""; + line += time; + } + line += "\"}"; + } else { + line += " \t "; + line += sub.name(); + line += " \t"; + line += ESP_GBFS::formatBytes(sub.size()); + line += " \t"; + line += time; + } + if (json) { + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + } + sub.close(); + sub = f.openNextFile(); + } + f.close(); + if (json) { + line = "], \"total\":\""; + line += ESP_GBFS::formatBytes(ESP_GBFS::totalBytes()); + line += "\",\"used\":\""; + line += ESP_GBFS::formatBytes(ESP_GBFS::usedBytes()); + line += "\",\"occupation\":\""; + uint64_t total = ESP_GBFS::totalBytes(); + if (total == 0) { + total = 1; + } + float occupation = 100.0 * ESP_GBFS::usedBytes() / total; + if ((occupation < 1) && (ESP_GBFS::usedBytes() > 0)) { + occupation = 1; + } + line += String((int)round(occupation)); + line += "\"}}"; + output->printLN(line.c_str()); + } else { + line = String(countf) + " file"; + if (countf > 1) { + line += "s"; + } + line += " , " + String(countd) + " dir"; + if (countd > 1) { + line += "s"; + } + output->printMSGLine(line.c_str()); + line = "Total "; + line += ESP_GBFS::formatBytes(ESP_GBFS::totalBytes(fsType)); + line += ", Used "; + line += ESP_GBFS::formatBytes(ESP_GBFS::usedBytes(fsType)); + line += ", Available: "; + line += ESP_GBFS::formatBytes(ESP_GBFS::freeBytes(fsType)); + if (fsType != FS_ROOT) { + output->printMSGLine(line.c_str()); + } + } + ESP_GBFS::releaseFS(fsType); + return true; + } else { + response = format_response(COMMANDID, json, false, "Invalid path"); + noError = false; + } + ESP_GBFS::releaseFS(fsType); + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //GLOBAL_FILESYSTEM_FEATURE +#endif // GLOBAL_FILESYSTEM_FEATURE diff --git a/esp3d/src/core/espcmd/ESP790.cpp b/esp3d/src/core/espcmd/ESP790.cpp index ac6ae5f7..51efcdd2 100644 --- a/esp3d/src/core/espcmd/ESP790.cpp +++ b/esp3d/src/core/espcmd/ESP790.cpp @@ -18,125 +18,132 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (GLOBAL_FILESYSTEM_FEATURE) +#if defined(GLOBAL_FILESYSTEM_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/filesystem/esp_globalFS.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#include "../../modules/filesystem/esp_globalFS.h" -#define COMMANDID 790 -// Action on Global Filesystem -//rmdir / remove / mkdir / exists /create -//[ESP790]= json= pwd= -bool Commands::ESP790(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - bool hasParam = false; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead; -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - parameter.replace("mkdir=", "path="); - parameter.replace("rmdir=", "path="); - parameter.replace("exists=", "path="); - parameter.replace("create=", "path="); - parameter.replace("remove=", "path="); - String path = get_param (parameter.c_str(), "path="); - if (path.length()!=0) { - uint8_t fsType = ESP_GBFS::getFSType(path.c_str()); - if (!ESP_GBFS::accessFS(fsType)) { - response = format_response(COMMANDID, json, false, "Not available"); - noError = false; - } else { - parameter = get_param (cmd_params, "mkdir="); - if (parameter.length() != 0) { - hasParam = true; - if (!ESP_GBFS::mkdir(parameter.c_str())) { - response = format_response(COMMANDID, json, false, "mkdir failed"); - noError = false; - } - } - if (noError && !hasParam) { - parameter = get_param (cmd_params, "rmdir="); - if (parameter.length() != 0) { - hasParam = true; - if (!ESP_GBFS::rmdir(parameter.c_str())) { - response = format_response(COMMANDID, json, false, "rmdir failed"); - noError = false; - } - } - } - if (noError && !hasParam) { - parameter = get_param (cmd_params, "remove="); - if (parameter.length() != 0) { - hasParam = true; - if (ESP_GBFS::remove(parameter.c_str())) { - response = format_response(COMMANDID, json, false, "remove failed"); - noError = false; - } - } - } - if (noError && !hasParam) { - parameter = get_param (cmd_params, "exists="); - if (parameter.length() != 0) { - hasParam = true; - if (ESP_GBFS::exists(parameter.c_str())) { - response = format_response(COMMANDID, json, true, "yes"); - } else { - response = format_response(COMMANDID, json, false, "no"); - } - } - } - if (noError && !hasParam) { - parameter = get_param (cmd_params, "create="); - if (parameter.length() != 0) { - hasParam = true; - ESP_GBFile f; - f = ESP_GBFS::open(parameter.c_str(), ESP_FILE_WRITE); - if (!f.isOpen()) { - response = format_response(COMMANDID, json, false, "create failed"); - noError = false; - } else { - f.close(); - } - } - } - if (hasParam && noError && response.length() == 0) { - response = format_response(COMMANDID, json, true, "ok"); - } - if (!hasParam) { - response = format_response(COMMANDID, json, false, "Missing parameter"); - noError = false; - } - ESP_GBFS::releaseFS(fsType); - } - } else { - response = format_response(COMMANDID, json, false, "Missing parameter"); +#define COMMANDID 790 +// Action on Global Filesystem +// rmdir / remove / mkdir / exists /create +//[ESP790]= json= pwd= +bool Commands::ESP790(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + bool hasParam = false; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead; +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = + format_response(COMMANDID, json, false, "Wrong authentication level"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + parameter.replace("mkdir=", "path="); + parameter.replace("rmdir=", "path="); + parameter.replace("exists=", "path="); + parameter.replace("create=", "path="); + parameter.replace("remove=", "path="); + String path = get_param(parameter.c_str(), "path="); + if (path.length() != 0) { + uint8_t fsType = ESP_GBFS::getFSType(path.c_str()); + if (!ESP_GBFS::accessFS(fsType)) { + response = format_response(COMMANDID, json, false, "Not available"); + noError = false; + } else { + parameter = get_param(cmd_params, "mkdir="); + if (parameter.length() != 0) { + hasParam = true; + if (!ESP_GBFS::mkdir(parameter.c_str())) { + response = format_response(COMMANDID, json, false, "mkdir failed"); noError = false; + } } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); + if (noError && !hasParam) { + parameter = get_param(cmd_params, "rmdir="); + if (parameter.length() != 0) { + hasParam = true; + if (!ESP_GBFS::rmdir(parameter.c_str())) { + response = + format_response(COMMANDID, json, false, "rmdir failed"); + noError = false; + } + } } + if (noError && !hasParam) { + parameter = get_param(cmd_params, "remove="); + if (parameter.length() != 0) { + hasParam = true; + if (ESP_GBFS::remove(parameter.c_str())) { + response = + format_response(COMMANDID, json, false, "remove failed"); + noError = false; + } + } + } + if (noError && !hasParam) { + parameter = get_param(cmd_params, "exists="); + if (parameter.length() != 0) { + hasParam = true; + if (ESP_GBFS::exists(parameter.c_str())) { + response = format_response(COMMANDID, json, true, "yes"); + } else { + response = format_response(COMMANDID, json, false, "no"); + } + } + } + if (noError && !hasParam) { + parameter = get_param(cmd_params, "create="); + if (parameter.length() != 0) { + hasParam = true; + ESP_GBFile f; + f = ESP_GBFS::open(parameter.c_str(), ESP_FILE_WRITE); + if (!f.isOpen()) { + response = + format_response(COMMANDID, json, false, "create failed"); + noError = false; + } else { + f.close(); + } + } + } + if (hasParam && noError && response.length() == 0) { + response = format_response(COMMANDID, json, true, "ok"); + } + if (!hasParam) { + response = + format_response(COMMANDID, json, false, "Missing parameter"); + noError = false; + } + + ESP_GBFS::releaseFS(fsType); + } } else { - output->printERROR(response.c_str(), errorCode); + response = format_response(COMMANDID, json, false, "Missing parameter"); + noError = false; } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //GLOBAL_FILESYSTEM_FEATURE +#endif // GLOBAL_FILESYSTEM_FEATURE diff --git a/esp3d/src/core/espcmd/ESP800.cpp b/esp3d/src/core/espcmd/ESP800.cpp index 2aafecc3..80c892bd 100644 --- a/esp3d/src/core/espcmd/ESP800.cpp +++ b/esp3d/src/core/espcmd/ESP800.cpp @@ -18,409 +18,431 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/network/netconfig.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/network/netconfig.h" -#include "../../modules/authentication/authentication_service.h" + #ifdef FILESYSTEM_FEATURE #include "../../modules/filesystem/esp_filesystem.h" -#endif //FILESYSTEM_FEATURE -#if defined (WIFI_FEATURE) || defined(ETH_FEATURE) ||defined(BLUETOOTH_FEATURE) +#endif // FILESYSTEM_FEATURE +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BLUETOOTH_FEATURE) #include "../../modules/network/netconfig.h" -#if defined (WIFI_FEATURE) +#if defined(WIFI_FEATURE) #include "../../modules/wifi/wificonfig.h" -#endif //WIFI_FEATURE -#endif //WIFI_FEATURE || ETH_FEATURE || BLUETOOTH_FEATURE +#endif // WIFI_FEATURE +#endif // WIFI_FEATURE || ETH_FEATURE || BLUETOOTH_FEATURE #ifdef HTTP_FEATURE #include "../../modules/http/http_server.h" #include "../../modules/websocket/websocket_server.h" -#endif //HTTP_FEATURE +#endif // HTTP_FEATURE #ifdef TIMESTAMP_FEATURE -#include "../../modules/time/time_server.h" -#endif //TIMESTAMP_FEATURE +#include "../../modules/time/time_service.h" +#endif // TIMESTAMP_FEATURE #ifdef CAMERA_DEVICE #include "../../modules/camera/camera.h" -#endif //CAMERA_DEVICE -#define COMMANDID 800 -//get fw version firmare target and fw version -//eventually set time with pc time -//output is JSON or plain text according parameter +#endif // CAMERA_DEVICE +#define COMMANDID 800 +// get fw capabilities +// eventually set time with pc time +// output is JSON or plain text according parameter //[ESP800]json= -bool Commands::ESP800(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP800(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = get_param(cmd_params, "setup="); + if (parameter.length() > 0) { + if (!Settings_ESP3D::write_byte(ESP_SETUP, parameter == "0" ? 0 : 1)) { + response = + format_response(COMMANDID, json, false, "Save setup flag failed"); noError = false; - errorCode = 401; + } + } + } + if (noError) { +#ifdef TIMESTAMP_FEATURE + String newtime = get_param(cmd_params, "time="); + String timezone = get_param(cmd_params, "tz="); + String tparm = (timeService.is_internet_time()) ? "Auto" : "Manual"; + if (!timeService.is_internet_time()) { + if (newtime.length() > 0) { + if (!timeService.setTime(newtime.c_str())) { + tparm = "Failed to set time"; + log_esp3d_e("Failed to set time"); + } else { + tparm = "Manual"; + } + } else { + tparm = "Not set"; + } + if (timezone.length() > 0) { + if (!timeService.setTimeZone(timezone.c_str())) { + tparm = "Failed to set timezone"; + log_esp3d_e("Failed to set timezone"); + } + } + } else { + if (timeService.started()) { + tparm = "Auto"; + } else { + tparm = "Not set"; + } } #else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = get_param (cmd_params, "setup="); - if(parameter.length() > 0) { - if (!Settings_ESP3D::write_byte (ESP_SETUP, parameter =="0"?0:1)) { - response = format_response(COMMANDID, json, false, "Save setup flag failed"); - noError = false; - } - } + String tparm = "none"; +#endif // TIMESTAMP_FEATURE + + String line = ""; + if (json) { + line = "{\"cmd\":\"800\",\"status\":\"ok\",\"data\":{"; } - if (noError) { -#ifdef TIMESTAMP_FEATURE - String newtime = get_param (cmd_params, "time="); - String tparm = (timeserver.is_internet_time())?"Auto":"Manual"; - if (!timeserver.is_internet_time() && (newtime.length() > 0)) { - if (!timeserver.setTime(newtime.c_str())) { - tparm="Failed to set"; - } - } else { - if (!timeserver.is_internet_time() && (newtime.length() == 0)) { - tparm="Not set"; - } - } -#endif //TIMESTAMP_FEATURE + // FW version + if (json) { + line += "\"FWVersion\":\""; + } else { + line += "FW version:"; + } +#if defined(SHORT_BUILD_VERSION) + line += SHORT_BUILD_VERSION; + line += "-"; +#endif // SHORT_BUILD_VERSION + line += FW_VERSION; + if (json) { + line += "\""; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // FW target + if (json) { + line += ",\"FWTarget\":\""; + } else { + line += "FW target:"; + } + line += Settings_ESP3D::GetFirmwareTargetShortName(); + if (json) { + line += "\""; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // FW ID + if (json) { + line += ",\"FWTargetID\":\""; + } else { + line += "FW ID:"; + } + line += Settings_ESP3D::GetFirmwareTarget(); + if (json) { + line += "\""; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // Setup done + if (json) { + line += ",\"Setup\":\""; + } else { + line += "Setup:"; + } + line += Settings_ESP3D::read_byte(ESP_SETUP) == 0 ? F("Enabled") + : F("Disabled"); + if (json) { + line += "\""; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; - String line = ""; - if(json) { - line = "{\"cmd\":\"800\",\"status\":\"ok\",\"data\":{"; - } - //FW version - if (json) { - line+="\"FWVersion\":\""; - } else { - line+="FW version:"; - } -#if defined (SHORT_BUILD_VERSION) - line+=SHORT_BUILD_VERSION; - line+="-"; -#endif //SHORT_BUILD_VERSION - line+=FW_VERSION; - if (json) { - line +="\""; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //FW target - if (json) { - line+=",\"FWTarget\":\""; - } else { - line+="FW target:"; - } - line+=Settings_ESP3D::GetFirmwareTargetShortName(); - if (json) { - line +="\""; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //FW ID - if (json) { - line+=",\"FWTargetID\":\""; - } else { - line+="FW ID:"; - } - line+=Settings_ESP3D::GetFirmwareTarget(); - if (json) { - line +="\""; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //Setup done - if (json) { - line+=",\"Setup\":\""; - } else { - line+= "Setup:"; - } - line+=Settings_ESP3D::read_byte (ESP_SETUP) == 0?F("Enabled"):F("Disabled"); - if (json) { - line +="\""; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; + // SD connection + if (json) { + line += ",\"SDConnection\":\""; + } else { + line += "SD connection:"; + } + if (Settings_ESP3D::GetSDDevice() == ESP_DIRECT_SD) { + line += "direct"; + } else if (Settings_ESP3D::GetSDDevice() == ESP_SHARED_SD) { + line += "shared"; + } else { + line += "none"; + } + if (json) { + line += "\""; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // Serial protocol + if (json) { + line += ",\"SerialProtocol\":\""; + } else { + line += "Serial protocol:"; + } - //SD connection - if (json) { - line+=",\"SDConnection\":\""; - } else { - line+= "SD connection:"; - } - if (Settings_ESP3D::GetSDDevice() == ESP_DIRECT_SD) { - line+="direct"; - } else if (Settings_ESP3D::GetSDDevice() == ESP_SHARED_SD) { - line+="shared"; - } else { - line+="none"; - } - if (json) { - line +="\""; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //Serial protocol - if (json) { - line+=",\"SerialProtocol\":\""; - } else { - line+= "Serial protocol:"; - } - -#if COMMUNICATION_PROTOCOL == MKS_SERIAL - line+="MKS"; -#endif //COMMUNICATION_PROTOCOL == MKS_SERIAL -#if COMMUNICATION_PROTOCOL == RAW_SERIAL - line+="Raw"; -#endif //COMMUNICATION_PROTOCOL == RAW_SERIAL -#if COMMUNICATION_PROTOCOL == SOCKET_SERIAL - line+="Socket"; -#endif //COMMUNICATION_PROTOCOL == SOCKET_SERIAL - if (json) { - line +="\""; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //Authentication - if (json) { - line+=",\"Authentication\":\""; - } else { - line+= "Authentication:"; - } +#if COMMUNICATION_PROTOCOL == MKS_SERIAL + line += "MKS"; +#endif // COMMUNICATION_PROTOCOL == MKS_SERIAL +#if COMMUNICATION_PROTOCOL == RAW_SERIAL + line += "Raw"; +#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL +#if COMMUNICATION_PROTOCOL == SOCKET_SERIAL + line += "Socket"; +#endif // COMMUNICATION_PROTOCOL == SOCKET_SERIAL + if (json) { + line += "\""; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // Authentication + if (json) { + line += ",\"Authentication\":\""; + } else { + line += "Authentication:"; + } #ifdef AUTHENTICATION_FEATURE - line+="Enabled"; + line += "Enabled"; #else - line+="Disabled"; -#endif //AUTHENTICATION_FEATURE - if (json) { - line +="\""; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; -#if (defined(WIFI_FEATURE) || defined(ETH_FEATURE)) && defined(HTTP_FEATURE) - //Web Communication - if (json) { - line+=",\"WebCommunication\":\""; - } else { - line+= "Web Communication:"; - } -#if defined (ASYNCWEBSERVER_FEATURE) - line+="Asynchronous"; -#else - line+="Synchronous"; -#endif //ASYNCWEBSERVER_FEATURE - if (json) { - line +="\""; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //WebSocket IP - if (json) { - line+=",\"WebSocketIP\":\""; - } else { - line+= "Web Socket IP:"; - } - line+=NetConfig::localIP().c_str(); - if (json) { - line +="\""; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //WebSocket Port - if (json) { - line+=",\"WebSocketPort\":\""; - } else { - line+= "Web Socket Port:"; - } -#if defined (ASYNCWEBSERVER_FEATURE) - line+=HTTP_Server::port(); -#else - line+=websocket_terminal_server.getPort(); -#endif - if (json) { - line +="\""; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - -#endif // (WIFI_FEATURE) || ETH_FEATURE) && HTTP_FEATURE) -#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BT_FEATURE) - //Hostname - if (json) { - line+=",\"Hostname\":\""; - } else { - line+= "Hostname:"; - } - line+=NetConfig::hostname(); - if (json) { - line +="\""; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; -#endif //WIFI_FEATURE|| ETH_FEATURE || BT_FEATURE -#if defined(WIFI_FEATURE) - if (WiFiConfig::started()) { - //WiFi mode - if (json) { - line+=",\"WiFiMode\":\""; - } else { - line+= "WiFi mode:"; - } - line+=(WiFi.getMode() == WIFI_AP)?"AP":"STA"; - if (json) { - line +="\""; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - } -#endif //WIFI_FEATURE -#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) - //Update - if (json) { - line+=",\"WebUpdate\":\""; - } else { - line+= "Web update:"; - } -#ifdef WEB_UPDATE_FEATURE - if (ESP_FileSystem::max_update_size()!=0) { - line+="Enabled"; - } else { - line+="Disabled"; - } -#else - line+="Disabled"; -#endif //WEB_UPDATE_FEATURE - if (json) { - line +="\""; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; -#endif //WIFI_FEATURE|| ETH_FEATURE - //FS - if (json) { - line+=",\"FlashFileSystem\":\""; - } else { - line+= "Flash File System:"; - } -#if defined(FILESYSTEM_FEATURE) - line+=ESP_FileSystem::FilesystemName(); -#else - line+="none"; -#endif //FILESYSTEM_FEATURE - if (json) { - line +="\""; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; -// Host path - if (json) { - line+=",\"HostPath\":\""; - } else { - line+= "Host Path:"; - } - - line+= ESP3D_HOST_PATH; - if (json) { - line +="\""; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //time server - if (json) { - line+=",\"Time\":\""; - } else { - line+= "Time:"; - } -#ifdef TIMESTAMP_FEATURE - line+=tparm; -#else - line+="none"; -#endif //TIMESTAMP_FEATURE - if (json) { - line +="\""; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; -#ifdef CAMERA_DEVICE - //camera ID - if (json) { - line+=",\"CameraID\":\""; - } else { - line+= "Camera ID:"; - } - line+=esp3d_camera.GetModel(); - if (json) { - line +="\""; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; - //camera Name - if (json) { - line+=",\"CameraName\":\""; - } else { - line+= "Camera name:"; - } - line+=esp3d_camera.GetModelString(); - if (json) { - line +="\""; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; -#endif //CAMERA_DEVICE - - if(json) { - output->printLN("}}"); - } - return true; - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); - } + line += "Disabled"; +#endif // AUTHENTICATION_FEATURE + if (json) { + line += "\""; + output->print(line.c_str()); } else { - output->printERROR(response.c_str(), errorCode); + output->printMSGLine(line.c_str()); } - return noError; -} + line = ""; +#if (defined(WIFI_FEATURE) || defined(ETH_FEATURE)) && defined(HTTP_FEATURE) + // Web Communication + if (json) { + line += ",\"WebCommunication\":\""; + } else { + line += "Web Communication:"; + } +#if defined(ASYNCWEBSERVER_FEATURE) + line += "Asynchronous"; +#else + line += "Synchronous"; +#endif // ASYNCWEBSERVER_FEATURE + if (json) { + line += "\""; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // WebSocket IP + if (json) { + line += ",\"WebSocketIP\":\""; + } else { + line += "Web Socket IP:"; + } + line += NetConfig::localIP().c_str(); + if (json) { + line += "\""; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // WebSocket Port + if (json) { + line += ",\"WebSocketPort\":\""; + } else { + line += "Web Socket Port:"; + } +#if defined(ASYNCWEBSERVER_FEATURE) + line += HTTP_Server::port(); +#else + line += websocket_terminal_server.getPort(); +#endif + if (json) { + line += "\""; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; +#endif // (WIFI_FEATURE) || ETH_FEATURE) && HTTP_FEATURE) +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BT_FEATURE) + // Hostname + if (json) { + line += ",\"Hostname\":\""; + } else { + line += "Hostname:"; + } + line += NetConfig::hostname(); + if (json) { + line += "\""; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; +#endif // WIFI_FEATURE|| ETH_FEATURE || BT_FEATURE +#if defined(WIFI_FEATURE) + if (WiFiConfig::started()) { + // WiFi mode + if (json) { + line += ",\"WiFiMode\":\""; + } else { + line += "WiFi mode:"; + } + line += (WiFi.getMode() == WIFI_AP) ? "AP" : "STA"; + if (json) { + line += "\""; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + } +#endif // WIFI_FEATURE +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) + // Update + if (json) { + line += ",\"WebUpdate\":\""; + } else { + line += "Web update:"; + } +#ifdef WEB_UPDATE_FEATURE + if (ESP_FileSystem::max_update_size() != 0) { + line += "Enabled"; + } else { + line += "Disabled"; + } +#else + line += "Disabled"; +#endif // WEB_UPDATE_FEATURE + if (json) { + line += "\""; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; +#endif // WIFI_FEATURE|| ETH_FEATURE + // FS + if (json) { + line += ",\"FlashFileSystem\":\""; + } else { + line += "Flash File System:"; + } +#if defined(FILESYSTEM_FEATURE) + line += ESP_FileSystem::FilesystemName(); +#else + line += "none"; +#endif // FILESYSTEM_FEATURE + if (json) { + line += "\""; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // Host path + if (json) { + line += ",\"HostPath\":\""; + } else { + line += "Host Path:"; + } + + line += ESP3D_HOST_PATH; + if (json) { + line += "\""; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // time server + if (json) { + line += ",\"Time\":\""; + } else { + line += "Time:"; + } +#ifdef TIMESTAMP_FEATURE + line += tparm; +#else + line += "none"; +#endif // TIMESTAMP_FEATURE + if (json) { + line += "\""; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; +#ifdef CAMERA_DEVICE + // camera ID + if (json) { + line += ",\"CameraID\":\""; + } else { + line += "Camera ID:"; + } + line += esp3d_camera.GetModel(); + if (json) { + line += "\""; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; + // camera Name + if (json) { + line += ",\"CameraName\":\""; + } else { + line += "Camera name:"; + } + line += esp3d_camera.GetModelString(); + if (json) { + line += "\""; + output->print(line.c_str()); + } else { + output->printMSGLine(line.c_str()); + } + line = ""; +#endif // CAMERA_DEVICE + + if (json) { + output->printLN("}}"); + } + return true; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; +} diff --git a/esp3d/src/core/espcmd/ESP900.cpp b/esp3d/src/core/espcmd/ESP900.cpp index 96a0132f..3bc1979d 100644 --- a/esp3d/src/core/espcmd/ESP900.cpp +++ b/esp3d/src/core/espcmd/ESP900.cpp @@ -19,68 +19,72 @@ */ #include "../../include/esp3d_config.h" #if COMMUNICATION_PROTOCOL != SOCKET_SERIAL +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/serial/serial_service.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#include "../../modules/serial/serial_service.h" -#define COMMANDID 900 -//Get state / Set Enable / Disable Serial Communication + +#define COMMANDID 900 +// Get state / Set Enable / Disable Serial Communication //[ESP900] json= [pwd=] -bool Commands::ESP900(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP900(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); - noError = false; - errorCode = 401; - } + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } #else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - String r; - if (parameter.length() == 0) { - if (serial_service.started()) { - r="ENABLED"; - } else { - r="DISABLED"; - } - r+=" - Serial" + String(serial_service.serialIndex()); - response = format_response(COMMANDID, json, true, r.c_str()); - } else { //set - if (parameter == "ENABLE" ) { - if (serial_service.begin(ESP_SERIAL_OUTPUT)) { - response = format_response(COMMANDID, json, true, "ok"); - } else { - response = format_response(COMMANDID, json, false, "Cannot enable serial communication"); - noError = false; - } - } else if (parameter == "DISABLE" ) { - response = format_response(COMMANDID, json, true, "ok"); - serial_service.end(); - } else { - response = format_response(COMMANDID, json, false, "Incorrect command"); - noError = false; - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + String r; + if (parameter.length() == 0) { + if (serial_service.started()) { + r = "ENABLED"; + } else { + r = "DISABLED"; + } + r += " - Serial" + String(serial_service.serialIndex()); + response = format_response(COMMANDID, json, true, r.c_str()); + } else { // set + if (parameter == "ENABLE") { + if (serial_service.begin(ESP_SERIAL_OUTPUT)) { + response = format_response(COMMANDID, json, true, "ok"); } else { - output->printMSG (response.c_str() ); + response = format_response(COMMANDID, json, false, + "Cannot enable serial communication"); + noError = false; } - } else { - output->printERROR(response.c_str(), errorCode); + } else if (parameter == "DISABLE") { + response = format_response(COMMANDID, json, true, "ok"); + serial_service.end(); + } else { + response = format_response(COMMANDID, json, false, "Incorrect command"); + noError = false; + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } #endif \ No newline at end of file diff --git a/esp3d/src/core/espcmd/ESP901.cpp b/esp3d/src/core/espcmd/ESP901.cpp index 0bb613e8..fc4b17e1 100644 --- a/esp3d/src/core/espcmd/ESP901.cpp +++ b/esp3d/src/core/espcmd/ESP901.cpp @@ -19,69 +19,75 @@ */ #include "../../include/esp3d_config.h" #if COMMUNICATION_PROTOCOL != SOCKET_SERIAL +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/serial/serial_service.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#include "../../modules/serial/serial_service.h" -#define COMMANDID 901 -//Set Serial baudrate + +#define COMMANDID 901 +// Set Serial baudrate //[ESP901] json= pwd= -bool Commands::ESP901(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP901(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + response = format_response( + COMMANDID, json, true, + String(Settings_ESP3D::read_uint32(ESP_BAUD_RATE)).c_str()); + } else { // set +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = format_response(COMMANDID, json, false, + "Wrong authentication level"); noError = false; errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - response = format_response(COMMANDID, json, true,String(Settings_ESP3D::read_uint32(ESP_BAUD_RATE)).c_str()); - } else { //set -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } -#endif //AUTHENTICATION_FEATURE - if (noError) { - uint ibuf = parameter.toInt(); - if (serial_service.is_valid_baudrate(ibuf)) { - response = format_response(COMMANDID, json, false, "Incorrect port"); - noError = false; - } else { - if (!Settings_ESP3D::write_uint32 (ESP_BAUD_RATE, ibuf)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } else { - response = format_response(COMMANDID, json, true, "ok"); - } - } - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); + } +#endif // AUTHENTICATION_FEATURE + if (noError) { + uint ibuf = parameter.toInt(); + if (serial_service.is_valid_baudrate(ibuf)) { + response = format_response(COMMANDID, json, false, "Incorrect port"); + noError = false; } else { - output->printMSG (response.c_str() ); + if (!Settings_ESP3D::write_uint32(ESP_BAUD_RATE, ibuf)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } else { + response = format_response(COMMANDID, json, true, "ok"); + } } - } else { - output->printERROR(response.c_str(), errorCode); + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //COMMUNICATION_PROTOCOL != SOCKET_SERIAL +#endif // COMMUNICATION_PROTOCOL != SOCKET_SERIAL diff --git a/esp3d/src/core/espcmd/ESP910.cpp b/esp3d/src/core/espcmd/ESP910.cpp index 89e43e0f..35dd45cc 100644 --- a/esp3d/src/core/espcmd/ESP910.cpp +++ b/esp3d/src/core/espcmd/ESP910.cpp @@ -18,73 +18,78 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (BUZZER_DEVICE) +#if defined(BUZZER_DEVICE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/buzzer/buzzer.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#include "../../modules/buzzer/buzzer.h" -#define COMMANDID 910 -//Get state / Set Enable / Disable buzzer + +#define COMMANDID 910 +// Get state / Set Enable / Disable buzzer //[ESP910][pwd=] -bool Commands::ESP910(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP910(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); - noError = false; - errorCode = 401; - } + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } #else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - if (esp3d_buzzer.started()) { - response = format_response(COMMANDID, json, true, "ENABLED"); - } else { - response = format_response(COMMANDID, json, true, "DISABLED"); - } - } else { //set - if (parameter == "ENABLE" || parameter == "DISABLE" ) { - if (!Settings_ESP3D::write_byte (ESP_BUZZER, (parameter == "ENABLE")?1:0)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } else { - if (parameter == "ENABLE" ) { - if (!esp3d_buzzer.begin()) { - response = format_response(COMMANDID, json, false, "Starting service failed"); - noError = false; - } - } else if (parameter == "DISABLE" ) { - esp3d_buzzer.end(); - } - if (noError) { - response = format_response(COMMANDID, json, true, "ok"); - } - } - } else { - response = format_response(COMMANDID, json, false, "Incorrect command"); - noError = false; - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + if (esp3d_buzzer.started()) { + response = format_response(COMMANDID, json, true, "ENABLED"); + } else { + response = format_response(COMMANDID, json, true, "DISABLED"); + } + } else { // set + if (parameter == "ENABLE" || parameter == "DISABLE") { + if (!Settings_ESP3D::write_byte(ESP_BUZZER, + (parameter == "ENABLE") ? 1 : 0)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; } else { - output->printMSG (response.c_str() ); + if (parameter == "ENABLE") { + if (!esp3d_buzzer.begin()) { + response = format_response(COMMANDID, json, false, + "Starting service failed"); + noError = false; + } + } else if (parameter == "DISABLE") { + esp3d_buzzer.end(); + } + if (noError) { + response = format_response(COMMANDID, json, true, "ok"); + } } - } else { - output->printERROR(response.c_str(), errorCode); + } else { + response = format_response(COMMANDID, json, false, "Incorrect command"); + noError = false; + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //BUZZER_DEVICE +#endif // BUZZER_DEVICE diff --git a/esp3d/src/core/espcmd/ESP920.cpp b/esp3d/src/core/espcmd/ESP920.cpp index 3a5812b9..037c79c0 100644 --- a/esp3d/src/core/espcmd/ESP920.cpp +++ b/esp3d/src/core/espcmd/ESP920.cpp @@ -18,331 +18,365 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" +#include "../../modules/authentication/authentication_service.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#define COMMANDID 920 -//Get state / Set state of output message clients -//[ESP920]= json= [pwd=] -bool Commands::ESP920(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - bool hasParam = false; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead -#ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); - noError = false; - errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - String s = ""; - if (json) { - s += "{"; - } - bool hasData=false; -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL || COMMUNICATION_PROTOCOL == SOCKET_SERIAL - hasData=true; - if (json) { - s += "\""; - } - s += "SERIAL"; - if (json) { - s += "\":\""; - } else { - s += ":"; - } - s += ESP3DOutput::isOutput(ESP_SERIAL_CLIENT)?"ON":"OFF"; - if (json) { - s += "\""; - } -#endif //COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL || COMMUNICATION_PROTOCOL == SOCKET_SERIAL -#if !defined(ESP3DLIB_ENV) || (defined (ESP3DLIB_ENV) && (HAS_DISPLAY || defined (HAS_SERIAL_DISPLAY))) - if (hasData) { - if (json) { - s += ","; - } else { - s += ", "; - } - } else { - hasData = true; - } - if (json) { - s += "\""; - } - s += "REMOTE_SCREEN"; - if (json) { - s += "\":\""; - } else { - s += ":"; - } - s += ESP3DOutput::isOutput(ESP_REMOTE_SCREEN_CLIENT)?"ON":"OFF"; - if (json) { - s += "\""; - } -#endif //!defined(ESP3DLIB_ENV) || (defined (ESP3DLIB_ENV) && HAS_DISPLAY) -#ifdef DISPLAY_DEVICE - if (hasData) { - if (json) { - s += ","; - } else { - s += ", "; - } - } else { - hasData = true; - } - if (json) { - s += "\""; - } - s += "REMOTE_SCREEN"; - if (json) { - s += "\":\""; - } else { - s += ":"; - } - s += ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)?"ON":"OFF"; - if (json) { - s += "\""; - } -#endif //DISPLAY_DEVICE -#ifdef WS_DATA_FEATURE - if (hasData) { - if (json) { - s += ","; - } else { - s += ", "; - } - } else { - hasData = true; - } - if (json) { - s += "\""; - } - s += "WEBSOCKET"; - if (json) { - s += "\":\""; - } else { - s += ":"; - } - s += ESP3DOutput::isOutput(ESP_WEBSOCKET_CLIENT)?"ON":"OFF"; - if (json) { - s += "\""; - } -#endif //WS_DATA_FEATURE -#ifdef BLUETOOTH_FEATURE - if (hasData) { - if (json) { - s += ","; - } else { - s += ", "; - } - } else { - hasData = true; - } - if (json) { - s += "\""; - } - s += "BT"; - if (json) { - s += "\":\""; - } else { - s += ":"; - } - s += ESP3DOutput::isOutput(ESP_BT_CLIENT)?"ON":"OFF"; - if (json) { - s += "\""; - } -#endif //BLUETOOTH_FEATURE -#ifdef TELNET_FEATURE - if (hasData) { - if (json) { - s += ","; - } else { - s += ", "; - } - } else { - hasData = true; - } - if (json) { - s += "\""; - } - s += "TELNET"; - if (json) { - s += "\":\""; - } else { - s += ":"; - } - s += ESP3DOutput::isOutput(ESP_TELNET_CLIENT)?"ON":"OFF"; - if (json) { - s += "\""; - } -#endif //TELNET_FEATURE - if (json) { - s += "}"; - } - response = format_response(COMMANDID, json, true, s.c_str()); - } else { //set -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL || COMMUNICATION_PROTOCOL == SOCKET_SERIAL - parameter = get_param (cmd_params, "SERIAL="); - if (parameter.length() != 0) { - hasParam=true; - if ((parameter == "ON")|| (parameter == "OFF")) { - if (!Settings_ESP3D::write_byte (ESP_SERIAL_FLAG, (parameter == "ON")?1:0)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } - } else { - response = format_response(COMMANDID, json, false, "Incorrect value"); - noError = false; - } - } -#endif //COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL || COMMUNICATION_PROTOCOL == SOCKET_SERIAL -#if !defined(ESP3DLIB_ENV) || (defined (ESP3DLIB_ENV) && (HAS_DISPLAY || defined (HAS_SERIAL_DISPLAY))) - if (noError && !hasParam) { - parameter = get_param (cmd_params, "REMOTE_SCREEN="); - if (parameter.length() != 0) { - hasParam=true; - if ((parameter == "ON")|| (parameter == "OFF")) { - if (!Settings_ESP3D::write_byte (ESP_REMOTE_SCREEN_FLAG, (parameter == "ON")?1:0)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } - } else { - response = format_response(COMMANDID, json, false, "Incorrect value"); - noError = false; - } - } - } -#endif //!defined(ESP3DLIB_ENV) || (defined (ESP3DLIB_ENV) && HAS_DISPLAY) - if (noError && !hasParam) { - parameter = get_param (cmd_params, "ALL="); - if (parameter.length() != 0) { - hasParam=true; - if ((parameter == "ON")|| (parameter == "OFF")) { - if ( -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL || COMMUNICATION_PROTOCOL == SOCKET_SERIAL - !Settings_ESP3D::write_byte (ESP_SERIAL_FLAG, (parameter == "ON")?1:0)|| -#endif //COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL || COMMUNICATION_PROTOCOL == SOCKET_SERIAL -#ifdef DISPLAY_DEVICE - !Settings_ESP3D::write_byte (ESP_SCREEN_FLAG, (parameter == "ON")?1:0)|| -#endif //DISPLAY_DEVICE -#ifdef WS_DATA_FEATURE - !Settings_ESP3D::write_byte (ESP_WEBSOCKET_FLAG, (parameter == "ON")?1:0)|| -#endif //WS_DATA_FEATURE -#ifdef BLUETOOTH_FEATURE - !Settings_ESP3D::write_byte (ESP_BT_FLAG, (parameter == "ON")?1:0)|| -#endif //BLUETOOTH_FEATURE -#ifdef TELNET_FEATURE - !Settings_ESP3D::write_byte (ESP_TELNET_FLAG, (parameter == "ON")?1:0)|| -#endif //TELNET_FEATURE - !Settings_ESP3D::write_byte (ESP_REMOTE_SCREEN_FLAG, (parameter == "ON")?1:0)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } - } else { - response = format_response(COMMANDID, json, false, "Incorrect value"); - noError = false; - } - } - } -#ifdef DISPLAY_DEVICE - if (noError && !hasParam) { - parameter = get_param (cmd_params, "SCREEN="); - if (parameter.length() != 0) { - hasParam=true; - if ((parameter == "ON")|| (parameter == "OFF")) { - if (!Settings_ESP3D::write_byte (ESP_SCREEN_FLAG, (parameter == "ON")?1:0)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } - } else { - response = format_response(COMMANDID, json, false, "Incorrect value"); - noError = false; - } - } - } -#endif //DISPLAY_DEVICE -#ifdef WS_DATA_FEATURE - if (noError && !hasParam) { - parameter = get_param (cmd_params, "WEBSOCKET="); - if (parameter.length() != 0) { - hasParam=true; - if ((parameter == "ON")|| (parameter == "OFF")) { - if (!Settings_ESP3D::write_byte (ESP_WEBSOCKET_FLAG, (parameter == "ON")?1:0)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } - } else { - response = format_response(COMMANDID, json, false, "Incorrect value"); - noError = false; - } - } - } -#endif //WS_DATA_FEATURE -#ifdef BLUETOOTH_FEATURE - if (noError && !hasParam) { - parameter = get_param (cmd_params, "BT="); - if (parameter.length() != 0) { - if ((parameter == "ON")|| (parameter == "OFF")) { - if (!Settings_ESP3D::write_byte (ESP_BT_FLAG, (parameter == "ON")?1:0)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } - } else { - response = format_response(COMMANDID, json, false, "Incorrect value"); - noError = false; - } - } - } -#endif //BLUETOOTH_FEATURE -#ifdef TELNET_FEATURE - if (noError && !hasParam) { - parameter = get_param (cmd_params, "TELNET="); - if (parameter.length() != 0) { - hasParam=true; - if ((parameter == "ON")|| (parameter == "OFF")) { - if (!Settings_ESP3D::write_byte (ESP_TELNET_FLAG, (parameter == "ON")?1:0)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } - } else { - response = format_response(COMMANDID, json, false, "Incorrect value"); - noError = false; - } - } - } -#endif //TELNET_FEATURE - //all ok we do the hot change - if(noError) { - if ( hasParam) { - ESP3DOutput::isOutput(ESP_ALL_CLIENTS,true); - response = format_response(COMMANDID, json, true, "ok"); - } else { - response = format_response(COMMANDID, json, false, "Incorrect parameter"); - noError = false; - } - } - } - } - if (noError) { +#define COMMANDID 920 +// Get state / Set state of output message clients +//[ESP920]= json= [pwd=] +bool Commands::ESP920(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + bool hasParam = false; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead +#ifdef AUTHENTICATION_FEATURE + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + String s = ""; + if (json) { + s += "{"; + } + bool hasData = false; +#if COMMUNICATION_PROTOCOL == RAW_SERIAL || \ + COMMUNICATION_PROTOCOL == MKS_SERIAL || \ + COMMUNICATION_PROTOCOL == SOCKET_SERIAL + hasData = true; + if (json) { + s += "\""; + } + s += "SERIAL"; + if (json) { + s += "\":\""; + } else { + s += ":"; + } + s += ESP3DOutput::isOutput(ESP_SERIAL_CLIENT) ? "ON" : "OFF"; + if (json) { + s += "\""; + } +#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == + // MKS_SERIAL || COMMUNICATION_PROTOCOL == SOCKET_SERIAL +#if !defined(ESP3DLIB_ENV) || \ + (defined(ESP3DLIB_ENV) && (HAS_DISPLAY || defined(HAS_SERIAL_DISPLAY))) + if (hasData) { if (json) { - output->printLN (response.c_str() ); + s += ","; } else { - output->printMSG (response.c_str() ); + s += ", "; } - } else { - output->printERROR(response.c_str(), errorCode); + } else { + hasData = true; + } + if (json) { + s += "\""; + } + s += "REMOTE_SCREEN"; + if (json) { + s += "\":\""; + } else { + s += ":"; + } + s += ESP3DOutput::isOutput(ESP_REMOTE_SCREEN_CLIENT) ? "ON" : "OFF"; + if (json) { + s += "\""; + } +#endif //! defined(ESP3DLIB_ENV) || (defined (ESP3DLIB_ENV) && HAS_DISPLAY) +#ifdef DISPLAY_DEVICE + if (hasData) { + if (json) { + s += ","; + } else { + s += ", "; + } + } else { + hasData = true; + } + if (json) { + s += "\""; + } + s += "REMOTE_SCREEN"; + if (json) { + s += "\":\""; + } else { + s += ":"; + } + s += ESP3DOutput::isOutput(ESP_SCREEN_CLIENT) ? "ON" : "OFF"; + if (json) { + s += "\""; + } +#endif // DISPLAY_DEVICE +#ifdef WS_DATA_FEATURE + if (hasData) { + if (json) { + s += ","; + } else { + s += ", "; + } + } else { + hasData = true; + } + if (json) { + s += "\""; + } + s += "WEBSOCKET"; + if (json) { + s += "\":\""; + } else { + s += ":"; + } + s += ESP3DOutput::isOutput(ESP_WEBSOCKET_CLIENT) ? "ON" : "OFF"; + if (json) { + s += "\""; + } +#endif // WS_DATA_FEATURE +#ifdef BLUETOOTH_FEATURE + if (hasData) { + if (json) { + s += ","; + } else { + s += ", "; + } + } else { + hasData = true; + } + if (json) { + s += "\""; + } + s += "BT"; + if (json) { + s += "\":\""; + } else { + s += ":"; + } + s += ESP3DOutput::isOutput(ESP_BT_CLIENT) ? "ON" : "OFF"; + if (json) { + s += "\""; + } +#endif // BLUETOOTH_FEATURE +#ifdef TELNET_FEATURE + if (hasData) { + if (json) { + s += ","; + } else { + s += ", "; + } + } else { + hasData = true; + } + if (json) { + s += "\""; + } + s += "TELNET"; + if (json) { + s += "\":\""; + } else { + s += ":"; + } + s += ESP3DOutput::isOutput(ESP_TELNET_CLIENT) ? "ON" : "OFF"; + if (json) { + s += "\""; + } +#endif // TELNET_FEATURE + if (json) { + s += "}"; + } + response = format_response(COMMANDID, json, true, s.c_str()); + } else { // set + +#if COMMUNICATION_PROTOCOL == RAW_SERIAL || \ + COMMUNICATION_PROTOCOL == MKS_SERIAL || \ + COMMUNICATION_PROTOCOL == SOCKET_SERIAL + parameter = get_param(cmd_params, "SERIAL="); + if (parameter.length() != 0) { + hasParam = true; + if ((parameter == "ON") || (parameter == "OFF")) { + if (!Settings_ESP3D::write_byte(ESP_SERIAL_FLAG, + (parameter == "ON") ? 1 : 0)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } + } else { + response = format_response(COMMANDID, json, false, "Incorrect value"); + noError = false; + } + } +#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == + // MKS_SERIAL || COMMUNICATION_PROTOCOL == SOCKET_SERIAL +#if !defined(ESP3DLIB_ENV) || \ + (defined(ESP3DLIB_ENV) && (HAS_DISPLAY || defined(HAS_SERIAL_DISPLAY))) + if (noError && !hasParam) { + parameter = get_param(cmd_params, "REMOTE_SCREEN="); + if (parameter.length() != 0) { + hasParam = true; + if ((parameter == "ON") || (parameter == "OFF")) { + if (!Settings_ESP3D::write_byte(ESP_REMOTE_SCREEN_FLAG, + (parameter == "ON") ? 1 : 0)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } + } else { + response = + format_response(COMMANDID, json, false, "Incorrect value"); + noError = false; + } + } + } +#endif //! defined(ESP3DLIB_ENV) || (defined (ESP3DLIB_ENV) && HAS_DISPLAY) + if (noError && !hasParam) { + parameter = get_param(cmd_params, "ALL="); + if (parameter.length() != 0) { + hasParam = true; + if ((parameter == "ON") || (parameter == "OFF")) { + if ( +#if COMMUNICATION_PROTOCOL == RAW_SERIAL || \ + COMMUNICATION_PROTOCOL == MKS_SERIAL || \ + COMMUNICATION_PROTOCOL == SOCKET_SERIAL + !Settings_ESP3D::write_byte(ESP_SERIAL_FLAG, + (parameter == "ON") ? 1 : 0) || +#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == + // MKS_SERIAL || COMMUNICATION_PROTOCOL == SOCKET_SERIAL +#ifdef DISPLAY_DEVICE + !Settings_ESP3D::write_byte(ESP_SCREEN_FLAG, + (parameter == "ON") ? 1 : 0) || +#endif // DISPLAY_DEVICE +#ifdef WS_DATA_FEATURE + !Settings_ESP3D::write_byte(ESP_WEBSOCKET_FLAG, + (parameter == "ON") ? 1 : 0) || +#endif // WS_DATA_FEATURE +#ifdef BLUETOOTH_FEATURE + !Settings_ESP3D::write_byte(ESP_BT_FLAG, + (parameter == "ON") ? 1 : 0) || +#endif // BLUETOOTH_FEATURE +#ifdef TELNET_FEATURE + !Settings_ESP3D::write_byte(ESP_TELNET_FLAG, + (parameter == "ON") ? 1 : 0) || +#endif // TELNET_FEATURE + !Settings_ESP3D::write_byte(ESP_REMOTE_SCREEN_FLAG, + (parameter == "ON") ? 1 : 0)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } + } else { + response = + format_response(COMMANDID, json, false, "Incorrect value"); + noError = false; + } + } + } +#ifdef DISPLAY_DEVICE + if (noError && !hasParam) { + parameter = get_param(cmd_params, "SCREEN="); + if (parameter.length() != 0) { + hasParam = true; + if ((parameter == "ON") || (parameter == "OFF")) { + if (!Settings_ESP3D::write_byte(ESP_SCREEN_FLAG, + (parameter == "ON") ? 1 : 0)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } + } else { + response = + format_response(COMMANDID, json, false, "Incorrect value"); + noError = false; + } + } + } +#endif // DISPLAY_DEVICE +#ifdef WS_DATA_FEATURE + if (noError && !hasParam) { + parameter = get_param(cmd_params, "WEBSOCKET="); + if (parameter.length() != 0) { + hasParam = true; + if ((parameter == "ON") || (parameter == "OFF")) { + if (!Settings_ESP3D::write_byte(ESP_WEBSOCKET_FLAG, + (parameter == "ON") ? 1 : 0)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } + } else { + response = + format_response(COMMANDID, json, false, "Incorrect value"); + noError = false; + } + } + } +#endif // WS_DATA_FEATURE +#ifdef BLUETOOTH_FEATURE + if (noError && !hasParam) { + parameter = get_param(cmd_params, "BT="); + if (parameter.length() != 0) { + if ((parameter == "ON") || (parameter == "OFF")) { + if (!Settings_ESP3D::write_byte(ESP_BT_FLAG, + (parameter == "ON") ? 1 : 0)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } + } else { + response = + format_response(COMMANDID, json, false, "Incorrect value"); + noError = false; + } + } + } +#endif // BLUETOOTH_FEATURE +#ifdef TELNET_FEATURE + if (noError && !hasParam) { + parameter = get_param(cmd_params, "TELNET="); + if (parameter.length() != 0) { + hasParam = true; + if ((parameter == "ON") || (parameter == "OFF")) { + if (!Settings_ESP3D::write_byte(ESP_TELNET_FLAG, + (parameter == "ON") ? 1 : 0)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } + } else { + response = + format_response(COMMANDID, json, false, "Incorrect value"); + noError = false; + } + } + } +#endif // TELNET_FEATURE + // all ok we do the hot change + if (noError) { + if (hasParam) { + ESP3DOutput::isOutput(ESP_ALL_CLIENTS, true); + response = format_response(COMMANDID, json, true, "ok"); + } else { + response = + format_response(COMMANDID, json, false, "Incorrect parameter"); + noError = false; + } + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } diff --git a/esp3d/src/core/espcmd/ESP930.cpp b/esp3d/src/core/espcmd/ESP930.cpp index 4b0275c2..ec80cb23 100644 --- a/esp3d/src/core/espcmd/ESP930.cpp +++ b/esp3d/src/core/espcmd/ESP930.cpp @@ -18,80 +18,89 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (ESP_SERIAL_BRIDGE_OUTPUT) +#if defined(ESP_SERIAL_BRIDGE_OUTPUT) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/serial/serial_service.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#include "../../modules/serial/serial_service.h" -#define COMMANDID 930 -//Set Bridge Serial state which can be ON, OFF, CLOSE + +#define COMMANDID 930 +// Set Bridge Serial state which can be ON, OFF, CLOSE //[ESP930] json= pwd= -bool Commands::ESP930(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP930(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + String r = + (Settings_ESP3D::read_byte(ESP_SERIAL_BRIDGE_ON) == 0) ? "OFF" : "ON"; + r += " - Serial" + String(serial_bridge_service.serialIndex()); + response = format_response(COMMANDID, json, true, r.c_str()); + } else { // set +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = format_response(COMMANDID, json, false, + "Wrong authentication level"); noError = false; errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - String r = (Settings_ESP3D::read_byte(ESP_SERIAL_BRIDGE_ON) == 0)?"OFF":"ON"; - r+=" - Serial" + String(serial_bridge_service.serialIndex()); - response = format_response(COMMANDID, json, true, r.c_str() ); - } else { //set -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter.toUpperCase(); - if (!((parameter == "ON") || (parameter == "OFF") || (parameter == "CLOSE"))) { - response = format_response(COMMANDID, json, false, "Only ON or OFF or CLOSE mode supported!"); - noError = false; - } else { - if (parameter == "CLOSE") { - serial_bridge_service.end(); - } else { - if (!Settings_ESP3D::write_byte (ESP_SERIAL_BRIDGE_ON, (parameter == "ON")?1:0)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } - if(noError && parameter == "ON" && !serial_bridge_service.started()) { - serial_bridge_service.begin(ESP_SERIAL_BRIDGE_OUTPUT); - } - } - if (noError) { - response = format_response(COMMANDID, json, true, "ok"); - } - } - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); + } +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter.toUpperCase(); + if (!((parameter == "ON") || (parameter == "OFF") || + (parameter == "CLOSE"))) { + response = format_response(COMMANDID, json, false, + "Only ON or OFF or CLOSE mode supported!"); + noError = false; } else { - output->printMSG (response.c_str() ); + if (parameter == "CLOSE") { + serial_bridge_service.end(); + } else { + if (!Settings_ESP3D::write_byte(ESP_SERIAL_BRIDGE_ON, + (parameter == "ON") ? 1 : 0)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } + if (noError && parameter == "ON" && + !serial_bridge_service.started()) { + serial_bridge_service.begin(ESP_SERIAL_BRIDGE_OUTPUT); + } + } + if (noError) { + response = format_response(COMMANDID, json, true, "ok"); + } } - } else { - output->printERROR(response.c_str(), errorCode); + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //TELNET_FEATURE +#endif // TELNET_FEATURE diff --git a/esp3d/src/core/espcmd/ESP931.cpp b/esp3d/src/core/espcmd/ESP931.cpp index 27991c07..58433288 100644 --- a/esp3d/src/core/espcmd/ESP931.cpp +++ b/esp3d/src/core/espcmd/ESP931.cpp @@ -18,70 +18,76 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#if defined (ESP_SERIAL_BRIDGE_OUTPUT) +#if defined(ESP_SERIAL_BRIDGE_OUTPUT) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/serial/serial_service.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#include "../../modules/serial/serial_service.h" -#define COMMANDID 931 -//Set Serial bridge baudrate + +#define COMMANDID 931 +// Set Serial bridge baudrate //[ESP931] json= pwd= -bool Commands::ESP931(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP931(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } +#else + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + response = format_response( + COMMANDID, json, true, + String(Settings_ESP3D::read_uint32(ESP_SERIAL_BRIDGE_BAUD)).c_str()); + } else { // set +#ifdef AUTHENTICATION_FEATURE + if (auth_type != LEVEL_ADMIN) { + response = format_response(COMMANDID, json, false, + "Wrong authentication level"); noError = false; errorCode = 401; - } -#else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - response = format_response(COMMANDID, json, true,String(Settings_ESP3D::read_uint32(ESP_SERIAL_BRIDGE_BAUD)).c_str()); - } else { //set -#ifdef AUTHENTICATION_FEATURE - if (auth_type != LEVEL_ADMIN) { - response = format_response(COMMANDID, json, false, "Wrong authentication level"); - noError = false; - errorCode = 401; - } -#endif //AUTHENTICATION_FEATURE - if (noError) { - uint ibuf = parameter.toInt(); - if (serial_bridge_service.is_valid_baudrate(ibuf)) { - response = format_response(COMMANDID, json, false, "Incorrect port"); - noError = false; - } else { - if (!Settings_ESP3D::write_uint32 (ESP_SERIAL_BRIDGE_BAUD, ibuf)) { - response = format_response(COMMANDID, json, false, "Set failed"); - noError = false; - } else { - response = format_response(COMMANDID, json, true, "ok"); - } - } - } - } - } - if (noError) { - if (json) { - output->printLN (response.c_str() ); + } +#endif // AUTHENTICATION_FEATURE + if (noError) { + uint ibuf = parameter.toInt(); + if (serial_bridge_service.is_valid_baudrate(ibuf)) { + response = format_response(COMMANDID, json, false, "Incorrect port"); + noError = false; } else { - output->printMSG (response.c_str() ); + if (!Settings_ESP3D::write_uint32(ESP_SERIAL_BRIDGE_BAUD, ibuf)) { + response = format_response(COMMANDID, json, false, "Set failed"); + noError = false; + } else { + response = format_response(COMMANDID, json, true, "ok"); + } } - } else { - output->printERROR(response.c_str(), errorCode); + } } - return noError; + } + if (json) { + output->printLN(response.c_str()); + } else { + if (noError) { + output->printMSG(response.c_str()); + } else { + output->printERROR(response.c_str(), errorCode); + } + } + return noError; } -#endif //TELNET_FEATURE +#endif // TELNET_FEATURE diff --git a/esp3d/src/core/espcmd/ESP999.cpp b/esp3d/src/core/espcmd/ESP999.cpp index 41557e98..45516224 100644 --- a/esp3d/src/core/espcmd/ESP999.cpp +++ b/esp3d/src/core/espcmd/ESP999.cpp @@ -18,57 +18,65 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" +#include "../../modules/authentication/authentication_service.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#if defined(ARDUINO_ARCH_ESP32) && (CONFIG_IDF_TARGET_ESP32S3 || CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3) + +#if defined(ARDUINO_ARCH_ESP32) && \ + (CONFIG_IDF_TARGET_ESP32S3 || CONFIG_IDF_TARGET_ESP32S2 || \ + CONFIG_IDF_TARGET_ESP32C3) #include -#define COMMANDID 999 -//Set quiet boot if strapping pin is High +#define COMMANDID 999 +// Set quiet boot if strapping pin is High //[ESP999]QUIETBOOT [pwd=] -bool Commands::ESP999(const char* cmd_params, level_authenticate_type auth_type, ESP3DOutput * output) -{ - bool noError = true; - bool json = has_tag (cmd_params, "json"); - String response; - String parameter; - bool hasParam = false; - int errorCode = 200; //unless it is a server error use 200 as default and set error in json instead +bool Commands::ESP999(const char* cmd_params, level_authenticate_type auth_type, + ESP3DOutput* output) { + bool noError = true; + bool json = has_tag(cmd_params, "json"); + String response; + String parameter; + bool hasParam = false; + int errorCode = 200; // unless it is a server error use 200 as default and + // set error in json instead #ifdef AUTHENTICATION_FEATURE - if (auth_type == LEVEL_GUEST) { - response = format_response(COMMANDID, json, false, "Guest user can't use this command"); - noError = false; - errorCode = 401; - } + if (auth_type == LEVEL_GUEST) { + response = format_response(COMMANDID, json, false, + "Guest user can't use this command"); + noError = false; + errorCode = 401; + } #else - (void)auth_type; -#endif //AUTHENTICATION_FEATURE - if (noError) { - parameter = clean_param(get_param (cmd_params, "")); - //get - if (parameter.length() == 0) { - response = format_response(COMMANDID, json, false, "Incorrect parameter"); - noError = false; - } else { //set - if (esp_efuse_set_rom_log_scheme(ESP_EFUSE_ROM_LOG_ON_GPIO_HIGH)!=ESP_OK) { - response = format_response(COMMANDID, json, false, "Set failed(May be already set?)"); - noError = false; - } else { - response = format_response(COMMANDID, json, true, "ok"); - } - } + (void)auth_type; +#endif // AUTHENTICATION_FEATURE + if (noError) { + parameter = clean_param(get_param(cmd_params, "")); + // get + if (parameter.length() == 0) { + response = format_response(COMMANDID, json, false, "Incorrect parameter"); + noError = false; + } else { // set + if (esp_efuse_set_rom_log_scheme(ESP_EFUSE_ROM_LOG_ON_GPIO_HIGH) != + ESP_OK) { + response = format_response(COMMANDID, json, false, + "Set failed(May be already set?)"); + noError = false; + } else { + response = format_response(COMMANDID, json, true, "ok"); + } } + } + if (json) { + output->printLN(response.c_str()); + } else { if (noError) { - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); - } + output->printMSG(response.c_str()); } else { - output->printERROR(response.c_str(), errorCode); + output->printERROR(response.c_str(), errorCode); } - return noError; + } + return noError; } -#endif //defined(ARDUINO_ARCH_ESP32) && (CONFIG_IDF_TARGET_ESP32S3 || CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3) \ No newline at end of file +#endif // defined(ARDUINO_ARCH_ESP32) && (CONFIG_IDF_TARGET_ESP32S3 || + // CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3) \ No newline at end of file diff --git a/esp3d/src/core/hal.h b/esp3d/src/core/hal.h index 2dd4a61b..7e597a50 100644 --- a/esp3d/src/core/hal.h +++ b/esp3d/src/core/hal.h @@ -20,41 +20,52 @@ #ifndef _ESP3D_HAL_H #define _ESP3D_HAL_H -//be sure correct IDE and settings are used for ESP8266 or ESP32 -#if !(defined( ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_ESP32)) +// be sure correct IDE and settings are used for ESP8266 or ESP32 +#if !(defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_ESP32)) #error Oops! Make sure you have 'ESP8266 or ESP32' compatible board selected from the 'Tools -> Boards' menu. -#endif // ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_ESP32 +#endif // ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_ESP32 #if defined(ARDUINO_ARCH_ESP8266) #include -#endif //ARDUINO_ARCH_ESP8266 +#endif // ARDUINO_ARCH_ESP8266 #if defined(ARDUINO_ARCH_ESP32) #include #include -#endif //ARDUINO_ARCH_ESP32 +#endif // ARDUINO_ARCH_ESP32 #include -class Hal -{ -public: - static bool begin(); - static void end(); - static void wait (uint32_t milliseconds); - static uint16_t getChipID(); - static bool has_temperature_sensor(); - static float temperature(); - static bool is_pin_usable(uint pin); - static void clearAnalogChannels(); - static void pinMode(uint8_t pin, uint8_t mode); - static int analogRead(uint8_t pin); - static bool analogWrite(uint8_t pin, uint value); - static void analogWriteFreq(uint32_t freq); - static void analogRange(uint32_t range); +class Hal { + public: + static bool begin(); + static void end(); + static void wait(uint32_t milliseconds); + static uint16_t getChipID(); + static bool has_temperature_sensor(); + static float temperature(); + static bool is_pin_usable(uint pin); + static void clearAnalogChannels(); + static void pinMode(uint8_t pin, uint8_t mode); + static int analogRead(uint8_t pin); + static bool analogWrite(uint8_t pin, uint value); + static void analogWriteFreq(uint32_t freq); + static void analogRange(uint32_t range); #if defined(ARDUINO_ARCH_ESP32) - static TaskHandle_t xHandle; -#endif //ARDUINO_ARCH_ESP32 -private: - static void wdtFeed(); - static uint32_t _analogRange; - static uint32_t _analogWriteFreq; + static TaskHandle_t xHandle; +#endif // ARDUINO_ARCH_ESP32 + private: + static void wdtFeed(); + static uint32_t _analogRange; + static uint32_t _analogWriteFreq; }; -#endif //_ESP3D_HAL_H + +class Esp3dTimout { + public: + Esp3dTimout(uint64_t timeout) { _start = millis(); }; + void reset() { _start = millis(); }; + bool isTimeout() { return (millis() - _start > _timeout); }; + uint64_t getTimeout() { return _timeout; }; + + private: + uint64_t _start; + uint64_t _timeout; +}; +#endif //_ESP3D_HAL_H diff --git a/esp3d/src/core/settings_esp3d.cpp b/esp3d/src/core/settings_esp3d.cpp index 3f628943..d5656ddd 100644 --- a/esp3d/src/core/settings_esp3d.cpp +++ b/esp3d/src/core/settings_esp3d.cpp @@ -57,6 +57,7 @@ #define MAX_NOTIFICATION_TOKEN_LENGTH 63 #define MAX_NOTIFICATION_SETTINGS_LENGTH 128 #define MAX_SERVER_ADDRESS_LENGTH 128 +#define MAX_TIME_ZONE_LENGTH 7 #define MIN_SERVER_ADDRESS_LENGTH 0 // default byte values @@ -104,7 +105,7 @@ #ifndef DEFAULT_FW #define DEFAULT_FW UNKNOWN_FW #endif // DEFAULT_FW -#define DEFAULT_TIME_ZONE 0 +#define DEFAULT_TIME_ZONE "+00:00" #define DEFAULT_TIME_DST 0 #define DEFAULT_SD_MOUNT ESP_SD_ROOT #define DEFAULT_SD_CHECK_UPDATE_AT_BOOT 1 @@ -363,9 +364,6 @@ uint8_t Settings_ESP3D::get_default_byte_value(int pos) { res = DEFAULT_FW; break; #ifdef TIMESTAMP_FEATURE - case ESP_TIMEZONE: - res = DEFAULT_TIME_ZONE; - break; case ESP_TIME_IS_DST: res = DEFAULT_TIME_DST; break; @@ -566,11 +564,6 @@ uint8_t Settings_ESP3D::get_max_byte(int pos) { res = MAX_CHANNEL; break; #endif // WIFI_FEATURE -#ifdef TIMESTAMP_FEATURE - case ESP_TIMEZONE: - res = 12; - break; -#endif // TIMESTAMP_FEATURE default: res = 255; } @@ -585,11 +578,6 @@ int8_t Settings_ESP3D::get_min_byte(int pos) { res = MIN_CHANNEL; break; #endif // WIFI_FEATURE -#ifdef TIMESTAMP_FEATURE - case ESP_TIMEZONE: - res = -12; - break; -#endif // TIMESTAMP_FEATURE default: res = 0; } @@ -611,6 +599,9 @@ const String &Settings_ESP3D::get_default_string_value(int pos) { break; #endif // WIFI_FEATURE || ETH_FEATURE || defined (ETH_FEATURE) #ifdef TIMESTAMP_FEATURE + case ESP_TIME_ZONE: + res = DEFAULT_TIME_ZONE; + break; case ESP_TIME_SERVER1: res = DEFAULT_TIME_SERVER1; break; @@ -673,6 +664,9 @@ uint8_t Settings_ESP3D::get_max_string_size(int pos) { break; #endif // WIFI_FEATURE || ETH_FEATURE || BLUETOOTH_FEATURE #ifdef TIMESTAMP_FEATURE + case ESP_TIME_ZONE: + res = MAX_TIME_ZONE_LENGTH; + break; case ESP_TIME_SERVER1: case ESP_TIME_SERVER2: case ESP_TIME_SERVER3: @@ -1321,8 +1315,9 @@ bool Settings_ESP3D::reset(bool networkonly) { ESP_INTERNET_TIME, Settings_ESP3D::get_default_byte_value(ESP_INTERNET_TIME)); // Time Zone - Settings_ESP3D::write_byte( - ESP_TIMEZONE, Settings_ESP3D::get_default_byte_value(ESP_TIMEZONE)); + Settings_ESP3D::write_string( + ESP_TIME_ZONE, + Settings_ESP3D::get_default_string_value(ESP_TIME_ZONE).c_str()); // Is DST Time Zone Settings_ESP3D::write_byte( ESP_TIME_IS_DST, Settings_ESP3D::get_default_byte_value(ESP_TIME_IS_DST)); diff --git a/esp3d/src/include/defines.h b/esp3d/src/include/defines.h index e8ee93a4..e472211d 100644 --- a/esp3d/src/include/defines.h +++ b/esp3d/src/include/defines.h @@ -99,7 +99,7 @@ // chinese #define ESP_SENSOR_TYPE 460 // 1 bytes = flag #define ESP_TARGET_FW 461 // 1 bytes = flag -#define ESP_TIMEZONE 462 // 1 bytes = flag +#define ESP_FREE 462 // 1 bytes = flag #define ESP_TIME_IS_DST 463 // 1 bytes = flag #define ESP_TIME_SERVER1 \ 464 // 129 bytes 128+1 = string ; warning does not support multibyte char @@ -142,6 +142,7 @@ #define ESP_SERIAL_BRIDGE_ON 1036 // 1 byte = flag #define ESP_SERIAL_BRIDGE_FLAG 1037 // 1 byte = flag #define ESP_SERIAL_BRIDGE_BAUD 1038 // 4 bytes= int +#define ESP_TIME_ZONE 1042 // 7 bytes 6+1 = string // Hidden password #define HIDDEN_PASSWORD "********" diff --git a/esp3d/src/modules/camera/camera.cpp b/esp3d/src/modules/camera/camera.cpp index 85fc0216..fd8b8e5c 100644 --- a/esp3d/src/modules/camera/camera.cpp +++ b/esp3d/src/modules/camera/camera.cpp @@ -78,6 +78,7 @@ bool Camera::handle_snap(WebServer *webserver, const char *path, webserver->sendHeader(String(F("Content-Disposition")), String(F("inline; filename=capture.jpg")), true); webserver->setContentLength(CONTENT_LENGTH_UNKNOWN); + HTTP_Server::set_http_headers(); webserver->send(200); } log_esp3d("Camera capture ongoing"); diff --git a/esp3d/src/modules/filesystem/esp_globalFS.cpp b/esp3d/src/modules/filesystem/esp_globalFS.cpp index 708ee5cf..2483e76b 100644 --- a/esp3d/src/modules/filesystem/esp_globalFS.cpp +++ b/esp3d/src/modules/filesystem/esp_globalFS.cpp @@ -574,6 +574,15 @@ time_t ESP_GBFile::getLastWrite() { return _sdFile.getLastWrite(); } #endif // SD_DEVICE + +#if defined(TIMESTAMP_FEATURE) + static time_t t = 0; + if (t == 0) { + time(&t); + t = t - (millis() / 1000); + } + return t; +#endif // TIMESTAMP_FEATURE return 0; } diff --git a/esp3d/src/modules/filesystem/esp_sd.cpp b/esp3d/src/modules/filesystem/esp_sd.cpp index 2b477d85..fc304d41 100644 --- a/esp3d/src/modules/filesystem/esp_sd.cpp +++ b/esp3d/src/modules/filesystem/esp_sd.cpp @@ -142,6 +142,7 @@ uint8_t ESP_SD::getFSType(const char* path) { bool ESP_SD::accessFS(uint8_t FS) { (void)FS; + bool res = true; // if card is busy do not let another task access SD and so prevent a release if (_state == ESP_SDCARD_BUSY) { log_esp3d("SD Busy"); @@ -149,16 +150,31 @@ bool ESP_SD::accessFS(uint8_t FS) { } #if SD_DEVICE_CONNECTION == ESP_SHARED_SD if (ESP_SD::enableSharedSD()) { - log_esp3d("Access SD ok"); - return true; + log_esp3d("Access shared SD ok"); + res = true; } else { log_esp3d_e("Enable shared SD failed"); - return false; + res = false; } #else - log_esp3d("Access SD"); - return true; + log_esp3d("Accessing Direct SD"); + res = true; #endif // SD_DEVICE_CONNECTION == ESP_SHARED_SD + if (res) { + log_esp3d("Checking SD state"); + if (ESP_SD::getState(true) == ESP_SDCARD_NOT_PRESENT) { + log_esp3d_e("SD not present"); + res = false; + // Sd is not available so release it + ESP_SD::releaseFS(FS); + } else { + log_esp3d("SD present"); + res = true; + log_esp3d("Accessing SD is ok"); + ESP_SD::setState(ESP_SDCARD_BUSY); + } + } + return res; } void ESP_SD::releaseFS(uint8_t FS) { (void)FS; diff --git a/esp3d/src/modules/filesystem/sd/sd_native_esp32.cpp b/esp3d/src/modules/filesystem/sd/sd_native_esp32.cpp index 83c95a22..80a18edb 100644 --- a/esp3d/src/modules/filesystem/sd/sd_native_esp32.cpp +++ b/esp3d/src/modules/filesystem/sd/sd_native_esp32.cpp @@ -202,10 +202,9 @@ bool ESP_SD::exists(const char *path) { } res = SD.exists(p); if (!res) { - ESP_SDFile root = ESP_SD::open(p.c_str(), ESP_FILE_READ); - if (root) { - res = root.isDirectory(); - } + // check if it is a directory + p += '/'; + res = SD.exists(p); } return res; } diff --git a/esp3d/src/modules/http/handles/handle-SD-files.cpp b/esp3d/src/modules/http/handlers/handle-SD-files.cpp similarity index 99% rename from esp3d/src/modules/http/handles/handle-SD-files.cpp rename to esp3d/src/modules/http/handlers/handle-SD-files.cpp index 6842b1e0..58fe3573 100644 --- a/esp3d/src/modules/http/handles/handle-SD-files.cpp +++ b/esp3d/src/modules/http/handlers/handle-SD-files.cpp @@ -35,6 +35,8 @@ void HTTP_Server::handleSDFileList() { level_authenticate_type auth_level = AuthenticationService::authenticated_level(); + HTTP_Server::set_http_headers(); + if (auth_level == LEVEL_GUEST) { _upload_status = UPLOAD_STATUS_NONE; _webserver->send(401, "text/plain", "Wrong authentication!"); diff --git a/esp3d/src/modules/http/handlers/handle-command.cpp b/esp3d/src/modules/http/handlers/handle-command.cpp new file mode 100644 index 00000000..d4d9e430 --- /dev/null +++ b/esp3d/src/modules/http/handlers/handle-command.cpp @@ -0,0 +1,106 @@ +/* + handle-command.cpp - ESP3D http handle + + Copyright (c) 2014 Luc Lebosse. All rights reserved. + + This code is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This code is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with This code; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ +#include "../../../include/esp3d_config.h" +#if defined(HTTP_FEATURE) +#include "../http_server.h" +#if defined(ARDUINO_ARCH_ESP32) +#include +#endif // ARDUINO_ARCH_ESP32 +#if defined(ARDUINO_ARCH_ESP8266) +#include +#endif // ARDUINO_ARCH_ESP8266 +#include "../../../core/commands.h" +#include "../../../core/esp3doutput.h" +#include "../../../core/settings_esp3d.h" +#include "../../authentication/authentication_service.h" + + +const unsigned char realTimeCommands[] = { + '!', '~', '?', 0x18, 0x84, 0x85, 0x90, 0x92, 0x93, 0x94, 0x95, + 0x96, 0x97, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0xA0, 0xA1}; +bool isRealTimeCommand(unsigned char c) { + for (unsigned int i = 0; i < sizeof(realTimeCommands); i++) { + if (c == realTimeCommands[i]) { + return true; + } + } + return false; +} + +// Handle web command query and send answer////////////////////////////// +void HTTP_Server::handle_web_command() { + level_authenticate_type auth_level = + AuthenticationService::authenticated_level(); + if (auth_level == LEVEL_GUEST) { + _webserver->send(401, "text/plain", "Wrong authentication!"); + return; + } + // log_esp3d("Authentication = %d", auth_level); + String cmd = ""; + if (_webserver->hasArg("cmd")) { + cmd = _webserver->arg("cmd"); + ESP3DOutput output(_webserver); + if (!cmd.endsWith("\n")) { + if (Settings_ESP3D::GetFirmwareTarget() == GRBL) { + uint len = cmd.length(); + if (!((len == 1 && isRealTimeCommand(cmd[0])) || + (len == 2 && isRealTimeCommand(cmd[1])))) { + cmd += "\n"; + } else { // no need \n for realtime command + // remove the 0XC2 that should not be there + if (len == 2 && isRealTimeCommand(cmd[1]) && cmd[1] == 0xC2) { + cmd[0] = cmd[1]; + cmd[1] = 0x0; + } + } + } else { + cmd += "\n"; // need to validate command + } + } + log_esp3d("Web Command: %s", cmd.c_str()); + if (esp3d_commands.is_esp_command((uint8_t *)cmd.c_str(), cmd.length())) { + esp3d_commands.process((uint8_t *)cmd.c_str(), cmd.length(), &output, + auth_level); + } else { +#if COMMUNICATION_PROTOCOL == SOCKET_SERIAL + ESP3DOutput outputOnly(ESP_SOCKET_SERIAL_CLIENT); +#endif // COMMUNICATION_PROTOCOL +#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL + ESP3DOutput outputOnly(ESP_SERIAL_CLIENT); +#endif // COMMUNICATION_PROTOCOL == SOCKET_SERIAL + _webserver->sendHeader("Cache-Control", "no-cache"); + HTTP_Server::set_http_headers(); +#ifdef ESP_ACCESS_CONTROL_ALLOW_ORIGIN + _webserver->sendHeader("Access-Control-Allow-Origin", "*"); +#endif // ESP_ACCESS_CONTROL_ALLOw_ORIGIN + // the command is not ESP3D so it will be forwarded to the serial port + // no need to wait to answer then + _webserver->send(200, "text/plain", "ESP3D says: command forwarded"); + esp3d_commands.process((uint8_t *)cmd.c_str(), cmd.length(), &output, + auth_level, &outputOnly); + } + } else if (_webserver->hasArg("ping")) { + _webserver->send(200); + } else { + _webserver->send(400, "text/plain", "Invalid command"); + } + return; +} +#endif // HTTP_FEATURE diff --git a/esp3d/src/modules/http/handles/handle-config.cpp b/esp3d/src/modules/http/handlers/handle-config.cpp similarity index 100% rename from esp3d/src/modules/http/handles/handle-config.cpp rename to esp3d/src/modules/http/handlers/handle-config.cpp diff --git a/esp3d/src/modules/http/handles/handle-description_xml.cpp b/esp3d/src/modules/http/handlers/handle-description_xml.cpp similarity index 100% rename from esp3d/src/modules/http/handles/handle-description_xml.cpp rename to esp3d/src/modules/http/handlers/handle-description_xml.cpp diff --git a/esp3d/src/modules/http/handles/handle-filenotfound.cpp b/esp3d/src/modules/http/handlers/handle-filenotfound.cpp similarity index 95% rename from esp3d/src/modules/http/handles/handle-filenotfound.cpp rename to esp3d/src/modules/http/handlers/handle-filenotfound.cpp index 68c761df..2e4df13e 100644 --- a/esp3d/src/modules/http/handles/handle-filenotfound.cpp +++ b/esp3d/src/modules/http/handlers/handle-filenotfound.cpp @@ -26,6 +26,7 @@ #if defined(ARDUINO_ARCH_ESP8266) #include #endif // ARDUINO_ARCH_ESP8266 +#include "../../../core/esp3d_string.h" #include "../../authentication/authentication_service.h" #include "../../filesystem/esp_filesystem.h" @@ -40,12 +41,14 @@ // Handle not registred path on FS neither SD /////////////////////// void HTTP_Server::handle_not_found() { + HTTP_Server::set_http_headers(); + if (AuthenticationService::authenticated_level() == LEVEL_GUEST) { _webserver->send(401, "text/plain", "Wrong authentication!"); return; } String path = _webserver->urlDecode(_webserver->uri()); - String contentType = getContentType(path.c_str()); + String contentType = esp3d_string::getContentType(path.c_str()); String pathWithGz = path + ".gz"; log_esp3d("URI: %s", path.c_str()); #if defined(FILESYSTEM_FEATURE) @@ -104,7 +107,7 @@ void HTTP_Server::handle_not_found() { #ifdef FILESYSTEM_FEATURE // check local page path = "/404.htm"; - contentType = getContentType(path.c_str()); + contentType = esp3d_string::getContentType(path.c_str()); pathWithGz = path + ".gz"; if (ESP_FileSystem::exists(pathWithGz.c_str()) || ESP_FileSystem::exists(path.c_str())) { diff --git a/esp3d/src/modules/http/handlers/handle-files.cpp b/esp3d/src/modules/http/handlers/handle-files.cpp new file mode 100644 index 00000000..c38efa77 --- /dev/null +++ b/esp3d/src/modules/http/handlers/handle-files.cpp @@ -0,0 +1,226 @@ +/* + handle-files.cpp - ESP3D http handle + + Copyright (c) 2014 Luc Lebosse. All rights reserved. + + This code is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This code is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with This code; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ +#include "../../../include/esp3d_config.h" +#if defined(HTTP_FEATURE) && defined(FILESYSTEM_FEATURE) +#include "../http_server.h" +#if defined(ARDUINO_ARCH_ESP32) +#include +#endif // ARDUINO_ARCH_ESP32 +#if defined(ARDUINO_ARCH_ESP8266) +#include +#endif // ARDUINO_ARCH_ESP8266 +#include "../../authentication/authentication_service.h" +#include "../../filesystem/esp_filesystem.h" + +#ifdef FILESYSTEM_TIMESTAMP_FEATURE +#include "../../time/time_service.h" +#endif // FILESYSTEM_TIMESTAMP_FEATURE + +// Filesystem +// Filesystem files list and file commands +void HTTP_Server::handleFSFileList() { + HTTP_Server::set_http_headers(); + + level_authenticate_type auth_level = + AuthenticationService::authenticated_level(); + if (auth_level == LEVEL_GUEST) { + _upload_status = UPLOAD_STATUS_NONE; + _webserver->send(401, "text/plain", "Wrong authentication!"); + return; + } + String path; + String status = "ok"; + if ((_upload_status == UPLOAD_STATUS_FAILED) || + (_upload_status == UPLOAD_STATUS_CANCELLED)) { + status = "Upload failed"; + _upload_status = UPLOAD_STATUS_NONE; + } + if (_webserver->hasArg("quiet")) { + if (_webserver->arg("quiet") == "yes") { + status = "{\"status\":\"" + status + "\"}"; + _webserver->send(200, "text/plain", status.c_str()); + return; + } + } + // get current path + if (_webserver->hasArg("path")) { + path += _webserver->arg("path"); + } + // to have a clean path + path.trim(); + path.replace("//", "/"); + if (path[path.length() - 1] != '/') { + path += "/"; + } + // check if query need some action + if (_webserver->hasArg("action")) { + // delete a file + if (_webserver->arg("action") == "delete" && + _webserver->hasArg("filename")) { + String filename; + String shortname = _webserver->arg("filename"); + shortname.replace("/", ""); + filename = path + _webserver->arg("filename"); + filename.replace("//", "/"); + if (!ESP_FileSystem::exists(filename.c_str())) { + status = shortname + " does not exists!"; + } else { + if (ESP_FileSystem::remove(filename.c_str())) { + status = shortname + " deleted"; + // what happen if no "/." and no other subfiles for SPIFFS like? + String ptmp = path; + if ((path != "/") && (path[path.length() - 1] = '/')) { + ptmp = path.substring(0, path.length() - 1); + } + if (!ESP_FileSystem::exists(ptmp.c_str())) { + ESP_FileSystem::mkdir(ptmp.c_str()); + } + } else { + status = "Cannot deleted "; + status += shortname; + } + } + } + // delete a directory + if (_webserver->arg("action") == "deletedir" && + _webserver->hasArg("filename")) { + String filename; + String shortname = _webserver->arg("filename"); + shortname.replace("/", ""); + filename = path + _webserver->arg("filename"); + filename += "/"; + filename.replace("//", "/"); + if (filename != "/") { + if (ESP_FileSystem::rmdir(filename.c_str())) { + log_esp3d("Deleting %s", filename.c_str()); + status = shortname; + status += " deleted"; + } else { + status = "Cannot deleted "; + status += shortname; + } + } + } + // create a directory + if (_webserver->arg("action") == "createdir" && + _webserver->hasArg("filename")) { + String filename; + filename = path + _webserver->arg("filename"); + String shortname = _webserver->arg("filename"); + shortname.replace("/", ""); + filename.replace("//", "/"); + if (ESP_FileSystem::exists(filename.c_str())) { + status = shortname + " already exists!"; + } else { + if (!ESP_FileSystem::mkdir(filename.c_str())) { + status = "Cannot create "; + status += shortname; + } else { + status = shortname + " created"; + } + } + } + } + String buffer2send; + buffer2send.reserve(1200); + buffer2send = "{\"files\":["; + String ptmp = path; + if ((path != "/") && (path[path.length() - 1] = '/')) { + ptmp = path.substring(0, path.length() - 1); + } + _webserver->setContentLength(CONTENT_LENGTH_UNKNOWN); + _webserver->sendHeader("Content-Type", "application/json"); + _webserver->sendHeader("Cache-Control", "no-cache"); + _webserver->send(200); + if (ESP_FileSystem::exists(ptmp.c_str())) { + ESP_File f = ESP_FileSystem::open(ptmp.c_str(), ESP_FILE_READ); + // Parse files + ESP_File sub = f.openNextFile(); + if (f) { + bool needseparator = false; + while (sub) { + if (needseparator) { + buffer2send += ","; + } else { + // for next entry + needseparator = true; + } + buffer2send += "{\"name\":\""; + buffer2send += sub.name(); + buffer2send += "\",\"size\":\""; + if (sub.isDirectory()) { + buffer2send += "-1"; + } else { + buffer2send += ESP_FileSystem::formatBytes(sub.size()); + } +#ifdef FILESYSTEM_TIMESTAMP_FEATURE + buffer2send += "\",\"time\":\""; + if (!sub.isDirectory()) { + buffer2send += timeService.getDateTime((time_t)sub.getLastWrite()); + } +#endif // FILESYSTEM_TIMESTAMP_FEATURE + buffer2send += "\"}"; + if (buffer2send.length() > 1100) { + _webserver->sendContent_P(buffer2send.c_str(), buffer2send.length()); + buffer2send = ""; + } + sub.close(); + sub = f.openNextFile(); + } + f.close(); + } else { + if (status == "ok") { + status = "cannot open" + ptmp; + } else { + status += ", cannot open" + ptmp; + } + } + } else { + if (status == "ok") { + status = ptmp + " does not exists!"; + } else { + status += ", " + ptmp + " does not exists!"; + } + } + buffer2send += "],\"path\":\"" + path + "\","; + + if (ESP_FileSystem::totalBytes() > 0) { + buffer2send += "\"occupation\":\"" + + String(100 * ESP_FileSystem::usedBytes() / + ESP_FileSystem::totalBytes()) + + "\","; + } else { + status = "FileSystem Error"; + buffer2send += "\"occupation\":\"0\","; + } + buffer2send += "\"status\":\"" + status + "\","; + buffer2send += "\"total\":\"" + + ESP_FileSystem::formatBytes(ESP_FileSystem::totalBytes()) + + "\","; + buffer2send += "\"used\":\"" + + ESP_FileSystem::formatBytes(ESP_FileSystem::usedBytes()) + + "\"}"; + path = ""; + _webserver->sendContent_P(buffer2send.c_str(), buffer2send.length()); + _webserver->sendContent(""); + _upload_status = UPLOAD_STATUS_NONE; +} + +#endif // HTTP_FEATURE && FILESYSTEM_FEATURE diff --git a/esp3d/src/modules/http/handlers/handle-login.cpp b/esp3d/src/modules/http/handlers/handle-login.cpp new file mode 100644 index 00000000..2203716c --- /dev/null +++ b/esp3d/src/modules/http/handlers/handle-login.cpp @@ -0,0 +1,137 @@ +/* + handle-login.cpp - ESP3D http handle + + Copyright (c) 2014 Luc Lebosse. All rights reserved. + + This code is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This code is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with This code; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ +#include "../../../include/esp3d_config.h" +#if defined(HTTP_FEATURE) +#include "../http_server.h" +#if defined(ARDUINO_ARCH_ESP32) +#include +#endif // ARDUINO_ARCH_ESP32 +#if defined(ARDUINO_ARCH_ESP8266) +#include +#endif // ARDUINO_ARCH_ESP8266 +#include "../../../core/esp3doutput.h" +#include "../../../core/settings_esp3d.h" +#include "../../authentication/authentication_service.h" + + +// login status check +void HTTP_Server::handle_login() { + HTTP_Server::set_http_headers(); + +#ifdef AUTHENTICATION_FEATURE + int code = 401; + String status = "Wrong authentication!"; + // Disconnect can be done anytime no need to check credential + if (_webserver->hasArg("DISCONNECT") && + _webserver->arg("DISCONNECT") == "YES") { + AuthenticationService::ClearCurrentSession(); + _webserver->sendHeader("Set-Cookie", "ESPSESSIONID=0"); + _webserver->sendHeader("Cache-Control", "no-cache"); + _webserver->send( + 401, "application/json", + "{\"status\":\"disconnected\",\"authentication_lvl\":\"guest\"}"); + return; + } + level_authenticate_type auth_level = + AuthenticationService::authenticated_level(); + // check is it is a submission or a query + if (_webserver->hasArg("SUBMIT")) { + // is there a correct list of query? + if (_webserver->hasArg("PASSWORD") && _webserver->hasArg("USER")) { + // User + String sUser = _webserver->arg("USER"); + // Password + String sPassword = _webserver->arg("PASSWORD"); + if ((((sUser == DEFAULT_ADMIN_LOGIN) && + (AuthenticationService::isadmin(sPassword.c_str()))) || + ((sUser == DEFAULT_USER_LOGIN) && + (AuthenticationService::isuser(sPassword.c_str()))))) { + // check if it is to change password or login + if (_webserver->hasArg("NEWPASSWORD")) { + String newpassword = _webserver->arg("NEWPASSWORD"); + // check new password + if (Settings_ESP3D::isLocalPasswordValid(newpassword.c_str())) { + if (!Settings_ESP3D::write_string(ESP_ADMIN_PWD, + newpassword.c_str())) { + code = 500; + status = "Set failed!"; + } else { + code = 200; + status = "ok"; + } + } else { + code = 500; + status = "Incorrect password!"; + } + } else { // do authentication + // allow to change session timeout when login + if (_webserver->hasArg("TIMEOUT")) { + String timeout = _webserver->arg("TIMEOUT"); + AuthenticationService::setSessionTimeout(timeout.toInt()); + } + // it is a change or same level + if (((auth_level == LEVEL_USER) && (sUser == DEFAULT_USER_LOGIN)) || + ((auth_level == LEVEL_ADMIN) && (sUser == DEFAULT_ADMIN_LOGIN))) { + code = 200; + status = "ok"; + } else { // new authentication + String session = AuthenticationService::create_session_ID(); + if (AuthenticationService::CreateSession( + (sUser == DEFAULT_ADMIN_LOGIN) ? LEVEL_ADMIN : LEVEL_USER, + sUser.c_str(), session.c_str())) { + AuthenticationService::ClearCurrentSession(); + code = 200; + status = "ok"; + String tmps = "ESPSESSIONID="; + tmps += session; + _webserver->sendHeader("Set-Cookie", tmps); + } + } + } + } + } + } else { + if (auth_level == LEVEL_USER || auth_level == LEVEL_ADMIN) { + status = "Identified"; + code = 200; + } + } + _webserver->sendHeader("Cache-Control", "no-cache"); + String smsg = "{\"status\":\""; + smsg += status; + smsg += "\",\"authentication_lvl\":\""; + if (auth_level == LEVEL_USER) { + smsg += "user"; + } else if (auth_level == LEVEL_ADMIN) { + smsg += "admin"; + } else { + smsg += "guest"; + } + smsg += "\"}"; + _webserver->send(code, "application/json", smsg); + return; +#else // No AUTHENTICATION_FEATURE + _webserver->sendHeader("Cache-Control", "no-cache"); + _webserver->send(200, "application/json", + "{\"status\":\"ok\",\"authentication_lvl\":\"admin\"}"); +#endif // AUTHENTICATION_FEATURE +} + +#endif // HTTP_FEATURE diff --git a/esp3d/src/modules/http/handles/handle-mks-files.cpp b/esp3d/src/modules/http/handlers/handle-mks-files.cpp similarity index 100% rename from esp3d/src/modules/http/handles/handle-mks-files.cpp rename to esp3d/src/modules/http/handlers/handle-mks-files.cpp diff --git a/esp3d/src/modules/http/handles/handle-root.cpp b/esp3d/src/modules/http/handlers/handle-root.cpp similarity index 94% rename from esp3d/src/modules/http/handles/handle-root.cpp rename to esp3d/src/modules/http/handlers/handle-root.cpp index 53e849c9..15f798a6 100644 --- a/esp3d/src/modules/http/handles/handle-root.cpp +++ b/esp3d/src/modules/http/handlers/handle-root.cpp @@ -28,9 +28,12 @@ #if defined(ARDUINO_ARCH_ESP8266) #include #endif // ARDUINO_ARCH_ESP8266 +#include "../../../core/esp3d_string.h" #include "../../filesystem/esp_filesystem.h" // Root of Webserver///////////////////////////////////////////////////// void HTTP_Server::handle_root() { + HTTP_Server::set_http_headers(); + String path = ESP3D_HOST_PATH; // Some sanity check if (path[0] != '/') { @@ -40,7 +43,7 @@ void HTTP_Server::handle_root() { path = path + "/"; } path += "index.html"; - String contentType = getContentType(path.c_str()); + String contentType = esp3d_string::getContentType(path.c_str()); String pathWithGz = path + ".gz"; // if have a index.html or gzip version this is default root page if ((ESP_FileSystem::exists(pathWithGz.c_str()) || diff --git a/esp3d/src/modules/http/handles/handle-snap.cpp b/esp3d/src/modules/http/handlers/handle-snap.cpp similarity index 100% rename from esp3d/src/modules/http/handles/handle-snap.cpp rename to esp3d/src/modules/http/handlers/handle-snap.cpp diff --git a/esp3d/src/modules/http/handlers/handle-updatefw.cpp b/esp3d/src/modules/http/handlers/handle-updatefw.cpp new file mode 100644 index 00000000..6688ac0a --- /dev/null +++ b/esp3d/src/modules/http/handlers/handle-updatefw.cpp @@ -0,0 +1,69 @@ +/* + handle-updatefw.cpp - ESP3D http handle + + Copyright (c) 2014 Luc Lebosse. All rights reserved. + + This code is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This code is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with This code; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ +#include "../../../include/esp3d_config.h" +#if defined(HTTP_FEATURE) && defined(WEB_UPDATE_FEATURE) +#include "../http_server.h" +#if defined(ARDUINO_ARCH_ESP32) +#include +#endif // ARDUINO_ARCH_ESP32 +#if defined(ARDUINO_ARCH_ESP8266) +#include +#endif // ARDUINO_ARCH_ESP8266 +#include "../../../core/esp3d.h" +#include "../../authentication/authentication_service.h" +// Web Update handler +void HTTP_Server::handleUpdate() { + level_authenticate_type auth_level = + AuthenticationService::authenticated_level(); + HTTP_Server::set_http_headers(); + + if (auth_level != LEVEL_ADMIN) { + _upload_status = UPLOAD_STATUS_NONE; + _webserver->send(401, "text/plain", "Wrong authentication!"); + return; + } + String jsonfile = "{\"status\":\""; + switch (_upload_status) { + case UPLOAD_STATUS_NONE: + jsonfile += "no file"; + break; + case UPLOAD_STATUS_CANCELLED: + jsonfile += "canceled"; + break; + case UPLOAD_STATUS_SUCCESSFUL: + jsonfile += "ok"; + break; + default: + jsonfile += "error"; + break; + } + jsonfile += "\"}"; + _webserver->sendHeader("Cache-Control", "no-cache"); + _webserver->send(200, "application/json", jsonfile); + // if success restart + if (_upload_status == UPLOAD_STATUS_SUCCESSFUL) { + Hal::wait(1000); + Esp3D::restart_esp(); + } else { + _upload_status = UPLOAD_STATUS_NONE; + } +} + +#endif // HTTP_FEATURE && WEB_UPDATE_FEATURE diff --git a/esp3d/src/modules/http/handles/upload-SD-files.cpp b/esp3d/src/modules/http/handlers/upload-SD-files.cpp similarity index 100% rename from esp3d/src/modules/http/handles/upload-SD-files.cpp rename to esp3d/src/modules/http/handlers/upload-SD-files.cpp diff --git a/esp3d/src/modules/http/handles/upload-files.cpp b/esp3d/src/modules/http/handlers/upload-files.cpp similarity index 100% rename from esp3d/src/modules/http/handles/upload-files.cpp rename to esp3d/src/modules/http/handlers/upload-files.cpp diff --git a/esp3d/src/modules/http/handles/upload-mks-files.cpp b/esp3d/src/modules/http/handlers/upload-mks-files.cpp similarity index 100% rename from esp3d/src/modules/http/handles/upload-mks-files.cpp rename to esp3d/src/modules/http/handlers/upload-mks-files.cpp diff --git a/esp3d/src/modules/http/handles/upload-updatefw.cpp b/esp3d/src/modules/http/handlers/upload-updatefw.cpp similarity index 100% rename from esp3d/src/modules/http/handles/upload-updatefw.cpp rename to esp3d/src/modules/http/handlers/upload-updatefw.cpp diff --git a/esp3d/src/modules/http/handles/handle-command.cpp b/esp3d/src/modules/http/handles/handle-command.cpp deleted file mode 100644 index ea40b9d5..00000000 --- a/esp3d/src/modules/http/handles/handle-command.cpp +++ /dev/null @@ -1,100 +0,0 @@ -/* - handle-command.cpp - ESP3D http handle - - Copyright (c) 2014 Luc Lebosse. All rights reserved. - - This code is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This code is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with This code; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ -#include "../../../include/esp3d_config.h" -#if defined (HTTP_FEATURE) -#include "../http_server.h" -#if defined (ARDUINO_ARCH_ESP32) -#include -#endif //ARDUINO_ARCH_ESP32 -#if defined (ARDUINO_ARCH_ESP8266) -#include -#endif //ARDUINO_ARCH_ESP8266 -#include "../../authentication/authentication_service.h" -#include "../../../core/commands.h" -#include "../../../core/esp3doutput.h" -#include "../../../core/settings_esp3d.h" - -const unsigned char realTimeCommands[]= {'!','~','?',0x18,0x84,0x85,0x90,0x92,0x93,0x94,0x95,0x96,0x97,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0xA0,0xA1}; -bool isRealTimeCommand(unsigned char c) -{ - for(unsigned int i=0; isend (401, "text/plain", "Wrong authentication!"); - return; - } - //log_esp3d("Authentication = %d", auth_level); - String cmd = ""; - if (_webserver->hasArg ("cmd")) { - cmd = _webserver->arg ("cmd"); - ESP3DOutput output(_webserver); - if(!cmd.endsWith("\n")) { - if (Settings_ESP3D::GetFirmwareTarget() == GRBL) { - uint len = cmd.length(); - if (!((len ==1 && isRealTimeCommand(cmd[0]))||(len ==2 && isRealTimeCommand(cmd[1])))) { - cmd += "\n"; - } else {//no need \n for realtime command - //remove the 0XC2 that should not be there - if (len==2 && isRealTimeCommand(cmd[1])&& cmd[1]==0xC2) { - cmd[0] = cmd[1]; - cmd[1] = 0x0; - } - } - } else { - cmd += "\n";//need to validate command - } - } - log_esp3d("Web Command: %s",cmd.c_str()); - if (esp3d_commands.is_esp_command((uint8_t *)cmd.c_str(), cmd.length())) { - esp3d_commands.process((uint8_t*)cmd.c_str(), cmd.length(), &output, auth_level); - } else { -#if COMMUNICATION_PROTOCOL == SOCKET_SERIAL - ESP3DOutput outputOnly(ESP_SOCKET_SERIAL_CLIENT); -#endif//COMMUNICATION_PROTOCOL -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - ESP3DOutput outputOnly(ESP_SERIAL_CLIENT); -#endif //COMMUNICATION_PROTOCOL == SOCKET_SERIAL - _webserver->sendHeader("Cache-Control","no-cache"); -#ifdef ESP_ACCESS_CONTROL_ALLOW_ORIGIN - _webserver->sendHeader("Access-Control-Allow-Origin", "*"); -#endif //ESP_ACCESS_CONTROL_ALLOw_ORIGIN - //the command is not ESP3D so it will be forwarded to the serial port - //no need to wait to answer then - _webserver->send (200, "text/plain", "ESP3D says: command forwarded"); - esp3d_commands.process((uint8_t*)cmd.c_str(), cmd.length(), &output, auth_level,&outputOnly); - } - } else if (_webserver->hasArg ("ping")) { - _webserver->send (200); - } else { - _webserver->send (400, "text/plain", "Invalid command"); - } - return; -} -#endif //HTTP_FEATURE diff --git a/esp3d/src/modules/http/handles/handle-files.cpp b/esp3d/src/modules/http/handles/handle-files.cpp deleted file mode 100644 index 696bea5f..00000000 --- a/esp3d/src/modules/http/handles/handle-files.cpp +++ /dev/null @@ -1,212 +0,0 @@ -/* - handle-files.cpp - ESP3D http handle - - Copyright (c) 2014 Luc Lebosse. All rights reserved. - - This code is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This code is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with This code; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ -#include "../../../include/esp3d_config.h" -#if defined (HTTP_FEATURE) && defined(FILESYSTEM_FEATURE) -#include "../http_server.h" -#if defined (ARDUINO_ARCH_ESP32) -#include -#endif //ARDUINO_ARCH_ESP32 -#if defined (ARDUINO_ARCH_ESP8266) -#include -#endif //ARDUINO_ARCH_ESP8266 -#include "../../filesystem/esp_filesystem.h" -#include "../../authentication/authentication_service.h" -#ifdef FILESYSTEM_TIMESTAMP_FEATURE -#include "../../time/time_server.h" -#endif //FILESYSTEM_TIMESTAMP_FEATURE - -//Filesystem -//Filesystem files list and file commands -void HTTP_Server::handleFSFileList () -{ - level_authenticate_type auth_level = AuthenticationService::authenticated_level(); - if (auth_level == LEVEL_GUEST) { - _upload_status = UPLOAD_STATUS_NONE; - _webserver->send (401, "text/plain", "Wrong authentication!"); - return; - } - String path ; - String status = "ok"; - if ( (_upload_status == UPLOAD_STATUS_FAILED) || (_upload_status == UPLOAD_STATUS_CANCELLED) ) { - status = "Upload failed"; - _upload_status = UPLOAD_STATUS_NONE; - } - if (_webserver->hasArg ("quiet")) { - if(_webserver->arg ("quiet") == "yes") { - status = "{\"status\":\"" + status + "\"}"; - _webserver->send (200, "text/plain", status.c_str()); - return; - } - } - //get current path - if (_webserver->hasArg ("path") ) { - path += _webserver->arg ("path") ; - } - //to have a clean path - path.trim(); - path.replace ("//", "/"); - if (path[path.length() - 1] != '/') { - path += "/"; - } - //check if query need some action - if (_webserver->hasArg ("action") ) { - //delete a file - if (_webserver->arg ("action") == "delete" && _webserver->hasArg ("filename") ) { - String filename; - String shortname = _webserver->arg ("filename"); - shortname.replace ("/", ""); - filename = path + _webserver->arg ("filename"); - filename.replace ("//", "/"); - if (!ESP_FileSystem::exists (filename.c_str()) ) { - status = shortname + " does not exists!"; - } else { - if (ESP_FileSystem::remove (filename.c_str()) ) { - status = shortname + " deleted"; - //what happen if no "/." and no other subfiles for SPIFFS like? - String ptmp = path; - if ( (path != "/") && (path[path.length() - 1] = '/') ) { - ptmp = path.substring (0, path.length() - 1); - } - if (!ESP_FileSystem::exists (ptmp.c_str())) { - ESP_FileSystem::mkdir(ptmp.c_str()); - } - } else { - status = "Cannot deleted " ; - status += shortname ; - } - } - } - //delete a directory - if (_webserver->arg ("action") == "deletedir" && _webserver->hasArg ("filename") ) { - String filename; - String shortname = _webserver->arg ("filename"); - shortname.replace ("/", ""); - filename = path + _webserver->arg ("filename"); - filename += "/"; - filename.replace ("//", "/"); - if (filename != "/") { - if (ESP_FileSystem::rmdir(filename.c_str())) { - log_esp3d("Deleting %s",filename.c_str()); - status = shortname ; - status += " deleted"; - } else { - status = "Cannot deleted " ; - status += shortname ; - } - } - } - //create a directory - if (_webserver->arg ("action") == "createdir" && _webserver->hasArg ("filename") ) { - String filename; - filename = path + _webserver->arg ("filename"); - String shortname = _webserver->arg ("filename"); - shortname.replace ("/", ""); - filename.replace ("//", "/"); - if (ESP_FileSystem::exists (filename.c_str()) ) { - status = shortname + " already exists!"; - } else { - if (!ESP_FileSystem::mkdir(filename.c_str())) { - status = "Cannot create "; - status += shortname ; - } else { - status = shortname + " created"; - } - } - } - } - String buffer2send ; - buffer2send.reserve(1200); - buffer2send = "{\"files\":["; - String ptmp = path; - if ( (path != "/") && (path[path.length() - 1] = '/') ) { - ptmp = path.substring (0, path.length() - 1); - } - _webserver->setContentLength(CONTENT_LENGTH_UNKNOWN); - _webserver->sendHeader("Content-Type","application/json"); - _webserver->sendHeader("Cache-Control","no-cache"); - _webserver->send(200); - if (ESP_FileSystem::exists(ptmp.c_str())) { - ESP_File f = ESP_FileSystem::open(ptmp.c_str(), ESP_FILE_READ); - //Parse files - ESP_File sub = f.openNextFile(); - if (f) { - bool needseparator = false; - while (sub) { - if (needseparator) { - buffer2send+=","; - } else { - //for next entry - needseparator=true; - } - buffer2send+="{\"name\":\""; - buffer2send+=sub.name(); - buffer2send+="\",\"size\":\""; - if (sub.isDirectory()) { - buffer2send+="-1"; - } else { - buffer2send+=ESP_FileSystem::formatBytes(sub.size()); - } -#ifdef FILESYSTEM_TIMESTAMP_FEATURE - buffer2send+="\",\"time\":\""; - if (!sub.isDirectory()) { - buffer2send+=timeserver.current_time(sub.getLastWrite()); - } -#endif //FILESYSTEM_TIMESTAMP_FEATURE - buffer2send+="\"}"; - if (buffer2send.length() > 1100) { - _webserver->sendContent_P(buffer2send.c_str(),buffer2send.length()); - buffer2send = ""; - } - sub.close(); - sub = f.openNextFile(); - } - f.close(); - } else { - if (status == "ok") { - status = "cannot open" + ptmp; - } else { - status += ", cannot open" + ptmp; - } - } - } else { - if (status == "ok") { - status = ptmp + " does not exists!"; - } else { - status += ", " + ptmp + " does not exists!"; - } - } - buffer2send += "],\"path\":\"" + path + "\","; - - if (ESP_FileSystem::totalBytes()>0) { - buffer2send += "\"occupation\":\"" + String(100*ESP_FileSystem::usedBytes()/ESP_FileSystem::totalBytes()) + "\","; - } else { - status = "FileSystem Error"; - buffer2send += "\"occupation\":\"0\","; - } - buffer2send += "\"status\":\"" + status + "\","; - buffer2send += "\"total\":\"" + ESP_FileSystem::formatBytes (ESP_FileSystem::totalBytes()) + "\","; - buffer2send += "\"used\":\"" + ESP_FileSystem::formatBytes (ESP_FileSystem::usedBytes()) + "\"}"; - path = ""; - _webserver->sendContent_P(buffer2send.c_str(),buffer2send.length()); - _webserver->sendContent(""); - _upload_status = UPLOAD_STATUS_NONE; -} - -#endif //HTTP_FEATURE && FILESYSTEM_FEATURE diff --git a/esp3d/src/modules/http/handles/handle-login.cpp b/esp3d/src/modules/http/handles/handle-login.cpp deleted file mode 100644 index 512a0cbe..00000000 --- a/esp3d/src/modules/http/handles/handle-login.cpp +++ /dev/null @@ -1,125 +0,0 @@ -/* - handle-login.cpp - ESP3D http handle - - Copyright (c) 2014 Luc Lebosse. All rights reserved. - - This code is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This code is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with This code; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ -#include "../../../include/esp3d_config.h" -#if defined (HTTP_FEATURE) -#include "../http_server.h" -#if defined (ARDUINO_ARCH_ESP32) -#include -#endif //ARDUINO_ARCH_ESP32 -#if defined (ARDUINO_ARCH_ESP8266) -#include -#endif //ARDUINO_ARCH_ESP8266 -#include "../../authentication/authentication_service.h" -#include "../../../core/esp3doutput.h" -#include "../../../core/settings_esp3d.h" - -//login status check -void HTTP_Server::handle_login() -{ -#ifdef AUTHENTICATION_FEATURE - int code = 401; - String status = "Wrong authentication!"; - //Disconnect can be done anytime no need to check credential - if (_webserver->hasArg("DISCONNECT") && _webserver->arg("DISCONNECT")=="YES") { - AuthenticationService::ClearCurrentSession(); - _webserver->sendHeader("Set-Cookie","ESPSESSIONID=0"); - _webserver->sendHeader("Cache-Control","no-cache"); - _webserver->send(401, "application/json", "{\"status\":\"disconnected\",\"authentication_lvl\":\"guest\"}"); - return; - } - level_authenticate_type auth_level = AuthenticationService::authenticated_level(); - //check is it is a submission or a query - if (_webserver->hasArg("SUBMIT")) { - //is there a correct list of query? - if (_webserver->hasArg("PASSWORD") && _webserver->hasArg("USER")) { - //User - String sUser = _webserver->arg("USER"); - //Password - String sPassword = _webserver->arg("PASSWORD"); - if((((sUser == DEFAULT_ADMIN_LOGIN) && (AuthenticationService::isadmin(sPassword.c_str()))) || - ((sUser == DEFAULT_USER_LOGIN) && (AuthenticationService::isuser(sPassword.c_str()))))) { - //check if it is to change password or login - if (_webserver->hasArg("NEWPASSWORD")) { - String newpassword = _webserver->arg("NEWPASSWORD"); - //check new password - if (Settings_ESP3D::isLocalPasswordValid(newpassword.c_str())) { - if (!Settings_ESP3D::write_string (ESP_ADMIN_PWD, newpassword.c_str())) { - code = 500; - status = "Set failed!"; - } else { - code = 200; - status = "ok"; - } - } else { - code = 500; - status = "Incorrect password!"; - } - } else { //do authentication - //allow to change session timeout when login - if (_webserver->hasArg("TIMEOUT")) { - String timeout = _webserver->arg("TIMEOUT"); - AuthenticationService::setSessionTimeout(timeout.toInt()); - } - //it is a change or same level - if (((auth_level == LEVEL_USER) && (sUser == DEFAULT_USER_LOGIN)) || - ((auth_level == LEVEL_ADMIN)&& (sUser == DEFAULT_ADMIN_LOGIN))) { - code = 200; - status = "ok"; - } else { //new authentication - String session = AuthenticationService::create_session_ID(); - if (AuthenticationService::CreateSession((sUser == DEFAULT_ADMIN_LOGIN)?LEVEL_ADMIN:LEVEL_USER,sUser.c_str(), session.c_str())) { - AuthenticationService::ClearCurrentSession(); - code = 200; - status = "ok"; - String tmps ="ESPSESSIONID="; - tmps+=session; - _webserver->sendHeader("Set-Cookie",tmps); - } - } - } - } - } - } else { - if (auth_level == LEVEL_USER || auth_level == LEVEL_ADMIN) { - status = "Identified"; - code = 200; - } - } - _webserver->sendHeader("Cache-Control","no-cache"); - String smsg = "{\"status\":\""; - smsg+=status; - smsg+="\",\"authentication_lvl\":\""; - if (auth_level == LEVEL_USER) { - smsg += "user"; - } else if (auth_level == LEVEL_ADMIN) { - smsg += "admin"; - } else { - smsg += "guest"; - } - smsg += "\"}"; - _webserver->send(code, "application/json", smsg); - return; -#else // No AUTHENTICATION_FEATURE - _webserver->sendHeader("Cache-Control","no-cache"); - _webserver->send(200, "application/json", "{\"status\":\"ok\",\"authentication_lvl\":\"admin\"}"); -#endif //AUTHENTICATION_FEATURE -} - -#endif //HTTP_FEATURE diff --git a/esp3d/src/modules/http/handles/handle-updatefw.cpp b/esp3d/src/modules/http/handles/handle-updatefw.cpp deleted file mode 100644 index f921b53e..00000000 --- a/esp3d/src/modules/http/handles/handle-updatefw.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/* - handle-updatefw.cpp - ESP3D http handle - - Copyright (c) 2014 Luc Lebosse. All rights reserved. - - This code is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This code is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with This code; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ -#include "../../../include/esp3d_config.h" -#if defined (HTTP_FEATURE) && defined(WEB_UPDATE_FEATURE) -#include "../http_server.h" -#if defined (ARDUINO_ARCH_ESP32) -#include -#endif //ARDUINO_ARCH_ESP32 -#if defined (ARDUINO_ARCH_ESP8266) -#include -#endif //ARDUINO_ARCH_ESP8266 -#include "../../../core/esp3d.h" -#include "../../authentication/authentication_service.h" -//Web Update handler -void HTTP_Server::handleUpdate () -{ - level_authenticate_type auth_level = AuthenticationService::authenticated_level(); - if (auth_level != LEVEL_ADMIN) { - _upload_status = UPLOAD_STATUS_NONE; - _webserver->send (401, "text/plain", "Wrong authentication!"); - return; - } - String jsonfile = "{\"status\":\"" ; - switch(_upload_status) { - case UPLOAD_STATUS_NONE : - jsonfile += "no file"; - break; - case UPLOAD_STATUS_CANCELLED : - jsonfile += "canceled"; - break; - case UPLOAD_STATUS_SUCCESSFUL : - jsonfile += "ok"; - break; - default : - jsonfile += "error"; - break; - } - jsonfile += "\"}"; - _webserver->sendHeader("Cache-Control", "no-cache"); - _webserver->send(200, "application/json", jsonfile); - //if success restart - if (_upload_status == UPLOAD_STATUS_SUCCESSFUL) { - Hal::wait(1000); - Esp3D::restart_esp(); - } else { - _upload_status = UPLOAD_STATUS_NONE; - } -} - -#endif //HTTP_FEATURE && WEB_UPDATE_FEATURE diff --git a/esp3d/src/modules/http/http_server.cpp b/esp3d/src/modules/http/http_server.cpp index a097b043..fb83f9b3 100644 --- a/esp3d/src/modules/http/http_server.cpp +++ b/esp3d/src/modules/http/http_server.cpp @@ -18,328 +18,311 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - #include "../../include/esp3d_config.h" -#if defined (HTTP_FEATURE) -#if defined (ARDUINO_ARCH_ESP32) +#if defined(HTTP_FEATURE) +#if defined(ARDUINO_ARCH_ESP32) #include #define DOWNLOAD_PACKET_SIZE 2048 -#endif //ARDUINO_ARCH_ESP32 -#if defined (ARDUINO_ARCH_ESP8266) +#endif // ARDUINO_ARCH_ESP32 +#if defined(ARDUINO_ARCH_ESP8266) #include #define DOWNLOAD_PACKET_SIZE 1024 -#endif //ARDUINO_ARCH_ESP8266 -#include "http_server.h" -#include "../authentication/authentication_service.h" -#include "../network/netconfig.h" +#endif // ARDUINO_ARCH_ESP8266 #include "../../core/settings_esp3d.h" +#include "../authentication/authentication_service.h" #include "../filesystem/esp_filesystem.h" +#include "../network/netconfig.h" #include "../websocket/websocket_server.h" +#include "http_server.h" + #if defined(SD_DEVICE) #include "../filesystem/esp_sd.h" -#endif //SD_DEVICE +#endif // SD_DEVICE #ifdef ESP_BENCHMARK_FEATURE #include "../../core/benchmark.h" -#endif //ESP_BENCHMARK_FEATURE +#endif // ESP_BENCHMARK_FEATURE bool HTTP_Server::_started = false; uint16_t HTTP_Server::_port = 0; -WEBSERVER * HTTP_Server::_webserver = nullptr; +WEBSERVER* HTTP_Server::_webserver = nullptr; uint8_t HTTP_Server::_upload_status = UPLOAD_STATUS_NONE; - -void HTTP_Server::init_handlers() -{ - _webserver->on("/",HTTP_ANY, handle_root); - //Page not found handler - _webserver->onNotFound (handle_not_found); - //web commands - _webserver->on ("/command", HTTP_ANY, handle_web_command); - //config - _webserver->on ("/config", HTTP_ANY, handle_config); - //need to be there even no authentication to say to UI no authentication - _webserver->on("/login", HTTP_ANY, handle_login); +void HTTP_Server::init_handlers() { + _webserver->on("/", HTTP_ANY, handle_root); + // Page not found handler + _webserver->onNotFound(handle_not_found); + // web commands + _webserver->on("/command", HTTP_ANY, handle_web_command); + // config + _webserver->on("/config", HTTP_ANY, handle_config); + // need to be there even no authentication to say to UI no authentication + _webserver->on("/login", HTTP_ANY, handle_login); #ifdef FILESYSTEM_FEATURE - _webserver->on ("/files", HTTP_ANY, handleFSFileList, FSFileupload); -#endif //FILESYSTEM_FEATURE + _webserver->on("/files", HTTP_ANY, handleFSFileList, FSFileupload); +#endif // FILESYSTEM_FEATURE #if COMMUNICATION_PROTOCOL == MKS_SERIAL - //MKS_SERIAL - _webserver->on ("/upload", HTTP_ANY, handleMKSUpload, MKSFileupload); -#endif //COMMUNICATION_PROTOCOL == MKS_SERIAL + // MKS_SERIAL + _webserver->on("/upload", HTTP_ANY, handleMKSUpload, MKSFileupload); +#endif // COMMUNICATION_PROTOCOL == MKS_SERIAL #ifdef SD_DEVICE - //SD - _webserver->on ("/sdfiles", HTTP_ANY, handleSDFileList, SDFileupload); -#endif //SD_DEVICE + // SD + _webserver->on("/sdfiles", HTTP_ANY, handleSDFileList, SDFileupload); +#endif // SD_DEVICE #ifdef WEB_UPDATE_FEATURE - //web update - _webserver->on ("/updatefw", HTTP_ANY, handleUpdate, WebUpdateUpload); -#endif //WEB_UPDATE_FEATURE + // web update + _webserver->on("/updatefw", HTTP_ANY, handleUpdate, WebUpdateUpload); +#endif // WEB_UPDATE_FEATURE #ifdef CAMERA_DEVICE - _webserver->on("/snap", HTTP_GET, handle_snap); -#endif //CAMERA_DEVICE + _webserver->on("/snap", HTTP_GET, handle_snap); +#endif // CAMERA_DEVICE #ifdef SSDP_FEATURE - if(WiFi.getMode() != WIFI_AP) { - _webserver->on("/description.xml", HTTP_GET, handle_SSDP); - } -#endif //SSDP_FEATURE + if (WiFi.getMode() != WIFI_AP) { + _webserver->on("/description.xml", HTTP_GET, handle_SSDP); + } +#endif // SSDP_FEATURE #ifdef CAPTIVE_PORTAL_FEATURE - if(NetConfig::getMode() == ESP_AP_SETUP) { - _webserver->on ("/generate_204", HTTP_ANY, handle_root); - _webserver->on ("/gconnectivitycheck.gstatic.com", HTTP_ANY, handle_root); - //do not forget the / at the end - _webserver->on ("/fwlink/", HTTP_ANY, handle_root); - } -#endif //CAPTIVE_PORTAL_FEATURE + if (NetConfig::getMode() == ESP_AP_SETUP) { + _webserver->on("/generate_204", HTTP_ANY, handle_root); + _webserver->on("/gconnectivitycheck.gstatic.com", HTTP_ANY, handle_root); + // do not forget the / at the end + _webserver->on("/fwlink/", HTTP_ANY, handle_root); + } +#endif // CAPTIVE_PORTAL_FEATURE } -bool HTTP_Server::StreamFSFile(const char* filename, const char * contentType) -{ - ESP_File datafile = ESP_FileSystem::open(filename); - uint64_t last_WS_update = millis(); - if (!datafile) { - return false; - } - size_t totalFileSize = datafile.size(); - size_t i = 0; - bool done = false; - _webserver->setContentLength(totalFileSize); - _webserver->send(200, contentType, ""); - uint8_t buf[DOWNLOAD_PACKET_SIZE]; - while (!done && _webserver->client().connected()) { - Hal::wait(0); - int v = datafile.read(buf,DOWNLOAD_PACKET_SIZE); - if ((v == -1) || (v == 0)) { - done = true; - } else { - _webserver->client().write(buf,v); - i+=v; - } - if (i >= totalFileSize) { - done = true; - } - //update websocket every 2000 ms - if (millis()-last_WS_update > 2000) { - websocket_terminal_server.handle(); - last_WS_update = millis(); - } - } - datafile.close(); - if ( i != totalFileSize) { - return false; - } - return true; -} - -#if defined (SD_DEVICE) -bool HTTP_Server::StreamSDFile(const char* filename, const char * contentType) -{ - ESP_SDFile datafile = ESP_SD::open(filename); - uint64_t last_WS_update = millis(); -#ifdef ESP_BENCHMARK_FEATURE - uint64_t bench_start = millis(); - size_t bench_transfered = 0; -#endif//ESP_BENCHMARK_FEATURE - if (!datafile) { - return false; - } - size_t totalFileSize = datafile.size(); - size_t i = 0; - bool done = false; - _webserver->setContentLength(totalFileSize); - _webserver->send(200, contentType, ""); - uint8_t buf[DOWNLOAD_PACKET_SIZE]; - while (!done && _webserver->client().connected()) { - Hal::wait(0); - int v = datafile.read(buf,DOWNLOAD_PACKET_SIZE); - if ((v == -1) || (v == 0)) { - done = true; - } else { - _webserver->client().write(buf,v); - i+=v; -#ifdef ESP_BENCHMARK_FEATURE - bench_transfered += v; -#endif//ESP_BENCHMARK_FEATURE - } - if (i >= totalFileSize) { - done = true; - } - - //update websocket every 2000 ms - if (millis()-last_WS_update > 2000) { - websocket_terminal_server.handle(); - last_WS_update = millis(); - } - } - datafile.close(); - if ( i != totalFileSize) { - return false; - } -#ifdef ESP_BENCHMARK_FEATURE - benchMark("SD download", bench_start, millis(), bench_transfered); -#endif//ESP_BENCHMARK_FEATURE - return true; -} -#endif //SD_DEVICE - -void HTTP_Server::pushError(int code, const char * st, uint16_t web_error, uint16_t timeout) -{ - log_esp3d("%s:%d",st,web_error); - if (websocket_terminal_server.started() && st) { - String s = "ERROR:" + String(code) + ":"; - s+=st; - websocket_terminal_server.pushMSG(websocket_terminal_server.get_currentID(), s.c_str()); - if (web_error != 0) { - if (_webserver) { - if (_webserver->client().available() > 0) { - _webserver->send (web_error, "text/xml", st); - } - } - } - uint32_t t = millis(); - while (millis() - t < timeout) { - websocket_terminal_server.handle(); - Hal::wait(10); - } - } -} - -void HTTP_Server::cancelUpload() -{ - HTTPUpload& upload = _webserver->upload(); - upload.status = UPLOAD_FILE_ABORTED; -#if defined ( ARDUINO_ARCH_ESP8266) - _webserver->client().stopAll(); -#else - errno = ECONNABORTED; - _webserver->client().stop(); -#endif - Hal::wait(100); -} - - -bool HTTP_Server::begin() -{ - bool no_error = true; - end(); - if (Settings_ESP3D::read_byte(ESP_HTTP_ON) !=1) { - return no_error; - } - _port = Settings_ESP3D::read_uint32(ESP_HTTP_PORT); - _webserver= new WEBSERVER(_port); - if (!_webserver) { - return false; - } - - init_handlers(); - //here the list of headers to be recorded - //Autorization is already added - //ask server to track these headers -#ifdef AUTHENTICATION_FEATURE - const char * headerkeys[] = {"Cookie","Content-Length"} ; -#else - const char * headerkeys[] = {"Content-Length"} ; -#endif - size_t headerkeyssize = sizeof (headerkeys) / sizeof (char*); - _webserver->collectHeaders (headerkeys, headerkeyssize ); - _webserver->begin(); -#ifdef AUTHENTICATION_FEATURE - AuthenticationService::begin(_webserver); -#endif //AUTHENTICATION_FEATURE - - _started = no_error; - return no_error; -} - -void HTTP_Server::end() -{ - _started = false; - _upload_status = UPLOAD_STATUS_NONE; -#ifdef AUTHENTICATION_FEATURE - AuthenticationService::end(); -#endif //AUTHENTICATION_FEATURE - if (_webserver) { - _webserver->stop(); - delete _webserver; - _webserver = NULL; - } -} - -void HTTP_Server::handle() -{ - if (_started) { - if (_webserver) { -#ifdef DISABLE_WDT_CORE_0 - disableCore0WDT(); -#endif //DISABLE_WDT_CORE_0 - _webserver->handleClient(); -#ifdef DISABLE_WDT_CORE_0 - enableCore0WDT(); -#endif //DISABLE_WDT_CORE_0 - } - } -} - - -const char * HTTP_Server::get_Splited_Value(String data, char separator, int index) -{ - int found = 0; - int strIndex[] = {0, -1}; - int maxIndex = data.length()-1; - static String s; - for(int i=0; i<=maxIndex && found<=index; i++) { - if(data.charAt(i)==separator || i==maxIndex) { - found++; - strIndex[0] = strIndex[1]+1; - strIndex[1] = (i == maxIndex) ? i+1 : i; - } - } - if (found>index) { - s = data.substring(strIndex[0], strIndex[1]).c_str(); +bool HTTP_Server::StreamFSFile(const char* filename, const char* contentType) { + ESP_File datafile = ESP_FileSystem::open(filename); + uint64_t last_WS_update = millis(); + if (!datafile) { + return false; + } + size_t totalFileSize = datafile.size(); + size_t i = 0; + bool done = false; + _webserver->setContentLength(totalFileSize); + _webserver->send(200, contentType, ""); + uint8_t buf[DOWNLOAD_PACKET_SIZE]; + while (!done && _webserver->client().connected()) { + Hal::wait(0); + int v = datafile.read(buf, DOWNLOAD_PACKET_SIZE); + if ((v == -1) || (v == 0)) { + done = true; } else { - s = ""; + _webserver->client().write(buf, v); + i += v; } - return s.c_str(); + if (i >= totalFileSize) { + done = true; + } + // update websocket every 2000 ms + if (millis() - last_WS_update > 2000) { + websocket_terminal_server.handle(); + last_WS_update = millis(); + } + } + datafile.close(); + if (i != totalFileSize) { + return false; + } + return true; } -//helper to extract content type from file extension -//Check what is the content tye according extension file -const char* HTTP_Server::getContentType (const char* filename) -{ - String file_name = filename; - file_name.toLowerCase(); - if (file_name.endsWith (".htm") ) { - return "text/html"; - } else if (file_name.endsWith (".html") ) { - return "text/html"; - } else if (file_name.endsWith (".css") ) { - return "text/css"; - } else if (file_name.endsWith (".js") ) { - return "application/javascript"; - } else if (file_name.endsWith (".png") ) { - return "image/png"; - } else if (file_name.endsWith (".gif") ) { - return "image/gif"; - } else if (file_name.endsWith (".jpeg") ) { - return "image/jpeg"; - } else if (file_name.endsWith (".jpg") ) { - return "image/jpeg"; - } else if (file_name.endsWith (".ico") ) { - return "image/x-icon"; - } else if (file_name.endsWith (".xml") ) { - return "text/xml"; - } else if (file_name.endsWith (".pdf") ) { - return "application/x-pdf"; - } else if (file_name.endsWith (".zip") ) { - return "application/x-zip"; - } else if (file_name.endsWith (".gz") ) { - return "application/x-gzip"; - } else if (file_name.endsWith (".txt") ) { - return "text/plain"; +#if defined(SD_DEVICE) +bool HTTP_Server::StreamSDFile(const char* filename, const char* contentType) { + ESP_SDFile datafile = ESP_SD::open(filename); + uint64_t last_WS_update = millis(); +#ifdef ESP_BENCHMARK_FEATURE + uint64_t bench_start = millis(); + size_t bench_transfered = 0; +#endif // ESP_BENCHMARK_FEATURE + if (!datafile) { + return false; + } + size_t totalFileSize = datafile.size(); + size_t i = 0; + bool done = false; + _webserver->setContentLength(totalFileSize); + _webserver->send(200, contentType, ""); + uint8_t buf[DOWNLOAD_PACKET_SIZE]; + while (!done && _webserver->client().connected()) { + Hal::wait(0); + int v = datafile.read(buf, DOWNLOAD_PACKET_SIZE); + if ((v == -1) || (v == 0)) { + done = true; + } else { + _webserver->client().write(buf, v); + i += v; +#ifdef ESP_BENCHMARK_FEATURE + bench_transfered += v; +#endif // ESP_BENCHMARK_FEATURE } - return "application/octet-stream"; + if (i >= totalFileSize) { + done = true; + } + + // update websocket every 2000 ms + if (millis() - last_WS_update > 2000) { + websocket_terminal_server.handle(); + last_WS_update = millis(); + } + } + datafile.close(); + if (i != totalFileSize) { + return false; + } +#ifdef ESP_BENCHMARK_FEATURE + benchMark("SD download", bench_start, millis(), bench_transfered); +#endif // ESP_BENCHMARK_FEATURE + return true; +} +#endif // SD_DEVICE + +void HTTP_Server::pushError(int code, const char* st, uint16_t web_error, + uint16_t timeout) { + log_esp3d("%s:%d", st, web_error); + if (websocket_terminal_server.started() && st) { + String s = "ERROR:" + String(code) + ":"; + s += st; + websocket_terminal_server.pushMSG(websocket_terminal_server.get_currentID(), + s.c_str()); + if (web_error != 0) { + if (_webserver) { + if (_webserver->client().available() > 0) { + _webserver->send(web_error, "text/xml", st); + } + } + } + uint32_t t = millis(); + while (millis() - t < timeout) { + websocket_terminal_server.handle(); + Hal::wait(10); + } + } } -#endif // Enable HTTP +void HTTP_Server::cancelUpload() { + HTTPUpload& upload = _webserver->upload(); + upload.status = UPLOAD_FILE_ABORTED; +#if defined(ARDUINO_ARCH_ESP8266) + _webserver->client().stopAll(); +#else + errno = ECONNABORTED; + _webserver->client().stop(); +#endif + Hal::wait(100); +} +bool HTTP_Server::begin() { + bool no_error = true; + end(); + if (Settings_ESP3D::read_byte(ESP_HTTP_ON) != 1) { + return no_error; + } + _port = Settings_ESP3D::read_uint32(ESP_HTTP_PORT); + _webserver = new WEBSERVER(_port); + if (!_webserver) { + return false; + } + + init_handlers(); + // here the list of headers to be recorded + // Autorization is already added + // ask server to track these headers +#ifdef AUTHENTICATION_FEATURE + const char* headerkeys[] = {"Cookie", "Content-Length"}; +#else + const char* headerkeys[] = {"Content-Length"}; +#endif + size_t headerkeyssize = sizeof(headerkeys) / sizeof(char*); + _webserver->collectHeaders(headerkeys, headerkeyssize); + _webserver->begin(); +#ifdef AUTHENTICATION_FEATURE + AuthenticationService::begin(_webserver); +#endif // AUTHENTICATION_FEATURE + + _started = no_error; + return no_error; +} + +void HTTP_Server::set_http_headers() { + /* + User-Agent: ESP3D-WebServer/1.0 (ESP8266; Firmware/3.0.0; Platform/arduino; +Embedded; http://www.esp3d.io) Host: http://192.168.0.1 + +User-Agent: ESP3D-WebdavServer/1.0 (ESP8266; Firmware/3.0.0; Platform/arduino; +Embedded; http://www.esp3d.io) Host: http://192.168.0.1:8181 + */ + static String ua = ""; + static String host = ""; + if (ua.length() == 0) { + ua = "ESP3D-WebServer/1.0 ("; + ua += Settings_ESP3D::TargetBoard(); + ua += "; Firmware/"; + ua += FW_VERSION; + ua += "; Platform/arduino; Embedded; http://www.esp3d.io)"; + } + if (host.length() == 0) { + host = "Host: http://"; + host += NetConfig::localIP(); + if (_port != 80) { + host += ":"; + host += String(_port); + } + } + if (_webserver) { + _webserver->sendHeader("User-Agent", ua.c_str()); + _webserver->sendHeader("Host", host.c_str()); + } +} + +void HTTP_Server::end() { + _started = false; + _upload_status = UPLOAD_STATUS_NONE; +#ifdef AUTHENTICATION_FEATURE + AuthenticationService::end(); +#endif // AUTHENTICATION_FEATURE + if (_webserver) { + _webserver->stop(); + delete _webserver; + _webserver = NULL; + } +} + +void HTTP_Server::handle() { + if (_started) { + if (_webserver) { +#ifdef DISABLE_WDT_CORE_0 + disableCore0WDT(); +#endif // DISABLE_WDT_CORE_0 + _webserver->handleClient(); +#ifdef DISABLE_WDT_CORE_0 + enableCore0WDT(); +#endif // DISABLE_WDT_CORE_0 + } + } +} + +const char* HTTP_Server::get_Splited_Value(String data, char separator, + int index) { + int found = 0; + int strIndex[] = {0, -1}; + int maxIndex = data.length() - 1; + static String s; + for (int i = 0; i <= maxIndex && found <= index; i++) { + if (data.charAt(i) == separator || i == maxIndex) { + found++; + strIndex[0] = strIndex[1] + 1; + strIndex[1] = (i == maxIndex) ? i + 1 : i; + } + } + if (found > index) { + s = data.substring(strIndex[0], strIndex[1]).c_str(); + } else { + s = ""; + } + return s.c_str(); +} + +#endif // Enable HTTP diff --git a/esp3d/src/modules/http/http_server.h b/esp3d/src/modules/http/http_server.h index 15444d1b..48e2f9a9 100644 --- a/esp3d/src/modules/http/http_server.h +++ b/esp3d/src/modules/http/http_server.h @@ -18,86 +18,80 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - #ifndef _HTTP_SERVER_H #define _HTTP_SERVER_H #include "../../include/esp3d_config.h" -//class WebSocketsServer; -#if defined (ARDUINO_ARCH_ESP32) +// class WebSocketsServer; +#if defined(ARDUINO_ARCH_ESP32) class WebServer; #define WEBSERVER WebServer -#endif //ARDUINO_ARCH_ESP32 -#if defined (ARDUINO_ARCH_ESP8266) +#endif // ARDUINO_ARCH_ESP32 +#if defined(ARDUINO_ARCH_ESP8266) #include #define WEBSERVER ESP8266WebServer -#endif //ARDUINO_ARCH_ESP8266 +#endif // ARDUINO_ARCH_ESP8266 - -//Upload status +// Upload status typedef enum { - UPLOAD_STATUS_NONE = 0, - UPLOAD_STATUS_FAILED = 1, - UPLOAD_STATUS_CANCELLED = 2, - UPLOAD_STATUS_SUCCESSFUL = 3, - UPLOAD_STATUS_ONGOING = 4 + UPLOAD_STATUS_NONE = 0, + UPLOAD_STATUS_FAILED = 1, + UPLOAD_STATUS_CANCELLED = 2, + UPLOAD_STATUS_SUCCESSFUL = 3, + UPLOAD_STATUS_ONGOING = 4 } upload_status_type; -class HTTP_Server -{ -public: - static bool begin(); - static void end(); - static void handle(); - static bool started() - { - return _started; - } - static uint16_t port() - { - return _port; - } -private: - static void pushError(int code, const char * st, uint16_t web_error = 500, uint16_t timeout = 1000); - static void cancelUpload(); - static bool _started; - static WEBSERVER * _webserver; - static uint16_t _port; - static uint8_t _upload_status; - static const char * getContentType (const char * filename); - static const char * get_Splited_Value(String data, char separator, int index); +class HTTP_Server { + public: + static bool begin(); + static void end(); + static void handle(); + static bool started() { return _started; } + static uint16_t port() { return _port; } + static void set_http_headers(); + + private: + static void pushError(int code, const char* st, uint16_t web_error = 500, + uint16_t timeout = 1000); + static void cancelUpload(); + static bool _started; + static WEBSERVER* _webserver; + static uint16_t _port; + static uint8_t _upload_status; + static const char* get_Splited_Value(String data, char separator, int index); #ifdef SSDP_FEATURE - static void handle_SSDP(); -#endif //SSDP_FEATURE + static void handle_SSDP(); +#endif // SSDP_FEATURE #ifdef CAMERA_DEVICE - static void handle_snap(); -#endif //CAMERA_DEVICE - static void init_handlers(); - static bool StreamFSFile(const char* filename, const char * contentType); - static void handle_root(); - static void handle_login(); - static void handle_not_found (); - static void handle_web_command (); - static void handle_config (); - // static void handle_Websocket_Event(uint8_t num, uint8_t type, uint8_t * payload, size_t length); + static void handle_snap(); +#endif // CAMERA_DEVICE + + static void init_handlers(); + static bool StreamFSFile(const char* filename, const char* contentType); + static void handle_root(); + static void handle_login(); + static void handle_not_found(); + static void handle_web_command(); + static void handle_config(); + // static void handle_Websocket_Event(uint8_t num, uint8_t type, uint8_t * + // payload, size_t length); #ifdef FILESYSTEM_FEATURE - static void FSFileupload (); - static void handleFSFileList (); -#endif //FILESYSTEM_FEATURE + static void FSFileupload(); + static void handleFSFileList(); +#endif // FILESYSTEM_FEATURE #ifdef WEB_UPDATE_FEATURE - static void handleUpdate (); - static void WebUpdateUpload (); -#endif //WEB_UPDATE_FEATURE - //static bool is_realtime_cmd(char c); + static void handleUpdate(); + static void WebUpdateUpload(); +#endif // WEB_UPDATE_FEATURE + // static bool is_realtime_cmd(char c); #ifdef SD_DEVICE - static void SDFileupload (); - static void handleSDFileList (); - static bool StreamSDFile(const char* filename, const char * contentType); -#endif //SD_DEVICE + static void SDFileupload(); + static void handleSDFileList(); + static bool StreamSDFile(const char* filename, const char* contentType); +#endif // SD_DEVICE #if COMMUNICATION_PROTOCOL == MKS_SERIAL - static void MKSFileupload (); - static void handleMKSUpload (); -#endif //COMMUNICATION_PROTOCOL == MKS_SERIAL + static void MKSFileupload(); + static void handleMKSUpload(); +#endif // COMMUNICATION_PROTOCOL == MKS_SERIAL }; -#endif //_HTTP_SERVER_H - +#endif //_HTTP_SERVER_H diff --git a/esp3d/src/modules/network/netservices.cpp b/esp3d/src/modules/network/netservices.cpp index 0c94d4a9..569f4b8c 100644 --- a/esp3d/src/modules/network/netservices.cpp +++ b/esp3d/src/modules/network/netservices.cpp @@ -18,384 +18,388 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#include "../../include/esp3d_config.h" - -#include "netconfig.h" #include "netservices.h" -#include "../../core/settings_esp3d.h" + #include "../../core/esp3doutput.h" +#include "../../core/settings_esp3d.h" +#include "../../include/esp3d_config.h" +#include "netconfig.h" + #ifdef MDNS_FEATURE #include "../mDNS/mDNS.h" -#endif //MDNS_FEATURE -#if defined( ARDUINO_ARCH_ESP8266) +#endif // MDNS_FEATURE +#if defined(ARDUINO_ARCH_ESP8266) #ifdef SSDP_FEATURE #include -#endif //SSDP_FEATURE -#endif //ARDUINO_ARCH_ESP8266 -#if defined( ARDUINO_ARCH_ESP32) +#endif // SSDP_FEATURE +#endif // ARDUINO_ARCH_ESP8266 +#if defined(ARDUINO_ARCH_ESP32) #ifdef SSDP_FEATURE #include -#endif //SSDP_FEATURE -#endif //ARDUINO_ARCH_ESP32 +#endif // SSDP_FEATURE +#endif // ARDUINO_ARCH_ESP32 #ifdef OTA_FEATURE #include -#endif //OTA_FEATURE +#endif // OTA_FEATURE #if defined(FILESYSTEM_FEATURE) #include "../filesystem/esp_filesystem.h" -#endif //FILESYSTEM_FEATURE +#endif // FILESYSTEM_FEATURE #ifdef TELNET_FEATURE #include "../telnet/telnet_server.h" -#endif //TELNET_FEATURE +#endif // TELNET_FEATURE #ifdef FTP_FEATURE #include "../ftp/FtpServer.h" -#endif //FP_FEATURE +#endif // FP_FEATURE #ifdef WEBDAV_FEATURE #include "../webdav/webdav_server.h" -#endif //WEBDAV_FEATURE +#endif // WEBDAV_FEATURE #ifdef HTTP_FEATURE #include "../http/http_server.h" -#endif //HTTP_FEATURE +#endif // HTTP_FEATURE #if defined(HTTP_FEATURE) || defined(WS_DATA_FEATURE) #include "../websocket/websocket_server.h" -#endif //HTTP_FEATURE || WS_DATA_FEATURE +#endif // HTTP_FEATURE || WS_DATA_FEATURE #ifdef CAPTIVE_PORTAL_FEATURE #include const byte DNS_PORT = 53; DNSServer dnsServer; -#endif //CAPTIVE_PORTAL_FEATURE +#endif // CAPTIVE_PORTAL_FEATURE #ifdef TIMESTAMP_FEATURE -#include "../time/time_server.h" -#endif //TIMESTAMP_FEATURE +#include "../time/time_service.h" +#endif // TIMESTAMP_FEATURE #ifdef NOTIFICATION_FEATURE #include "../notifications/notifications_service.h" -#endif //NOTIFICATION_FEATURE +#endif // NOTIFICATION_FEATURE #ifdef CAMERA_DEVICE #include "../camera/camera.h" -#endif //CAMERA_DEVICE +#endif // CAMERA_DEVICE #if COMMUNICATION_PROTOCOL == MKS_SERIAL #include "../mks/mks_service.h" -#endif //COMMUNICATION_PROTOCOL == MKS_SERIAL +#endif // COMMUNICATION_PROTOCOL == MKS_SERIAL bool NetServices::_started = false; bool NetServices::_restart = false; -bool NetServices::begin() -{ - bool res = true; - _started = false; - String hostname = Settings_ESP3D::read_string(ESP_HOSTNAME); - ESP3DOutput output(ESP_ALL_CLIENTS); - end(); +bool NetServices::begin() { + bool res = true; + _started = false; + String hostname = Settings_ESP3D::read_string(ESP_HOSTNAME); + ESP3DOutput output(ESP_ALL_CLIENTS); + end(); #ifdef TIMESTAMP_FEATURE - if (WiFi.getMode() != WIFI_AP) { - if(!timeserver.begin()) { - if(timeserver.is_internet_time()) { - output.printERROR("Failed contact time servers!"); - } - } else { - String tmp = "Current time :"; - tmp+=timeserver.current_time(); - if (Settings_ESP3D::isVerboseBoot()) { - output.printMSG(tmp.c_str()); - } - } + if (WiFi.getMode() != WIFI_AP) { + if (!timeService.begin()) { + if (timeService.is_internet_time()) { + output.printERROR("Failed contact time servers!"); + } + } else { + String tmp = "Current time :"; + tmp += timeService.getCurrentTime(); + if (Settings_ESP3D::isVerboseBoot()) { + output.printMSG(tmp.c_str()); + } } -#endif //TIMESTAMP_FEATURE + } +#endif // TIMESTAMP_FEATURE #if defined(MDNS_FEATURE) && defined(ARDUINO_ARCH_ESP8266) - esp3d_mDNS.begin(hostname.c_str()); -#endif //MDNS_FEATURE && ARDUINO_ARCH_ESP8266 + esp3d_mDNS.begin(hostname.c_str()); +#endif // MDNS_FEATURE && ARDUINO_ARCH_ESP8266 #ifdef OTA_FEATURE - if(WiFi.getMode() != WIFI_AP) { - ArduinoOTA.onStart([]() { - ESP3DOutput output(ESP_ALL_CLIENTS); - String type = "Start OTA updating "; - if (ArduinoOTA.getCommand() == U_FLASH) { - type += "sketch"; - } else { // U_SPIFFS or any FS - // NOTE: if updating FS this would be the place to unmount FS using FS.end() - type += "filesystem"; + if (WiFi.getMode() != WIFI_AP) { + ArduinoOTA.onStart([]() { + ESP3DOutput output(ESP_ALL_CLIENTS); + String type = "Start OTA updating "; + if (ArduinoOTA.getCommand() == U_FLASH) { + type += "sketch"; + } else { // U_SPIFFS or any FS + // NOTE: if updating FS this would be the place to unmount FS using + // FS.end() + type += "filesystem"; #if defined(FILESYSTEM_FEATURE) - ESP_FileSystem::end(); -#endif //FILESYSTEM_FEATURE - - } - output.printMSG(type.c_str()); - }); - ArduinoOTA.onEnd([]() { - ESP3DOutput output(ESP_ALL_CLIENTS); - output.printMSG("End OTA"); - }); - ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { - String prg = "OTA Progress "; - ESP3DOutput output(ESP_ALL_CLIENTS); - prg += String(progress / (total / 100)) + "%"; - output.printMSG(prg.c_str()); - }); - ArduinoOTA.onError([](ota_error_t error) { - String stmp = "OTA Error: " + String(error); - ESP3DOutput output(ESP_ALL_CLIENTS); - output.printERROR(stmp.c_str()); - if (error == OTA_AUTH_ERROR) { - output.printERROR("Auth Failed"); - } else if (error == OTA_BEGIN_ERROR) { - output.printERROR("Begin Failed"); - } else if (error == OTA_CONNECT_ERROR) { - output.printERROR("Connect Failed"); - } else if (error == OTA_RECEIVE_ERROR) { - output.printERROR("Receive Failed"); - } else if (error == OTA_END_ERROR) { - output.printERROR("End Failed"); - } - }); - if (Settings_ESP3D::isVerboseBoot()) { - output.printMSG("OTA service started"); - } - String lhostname =hostname; - lhostname.toLowerCase(); - ArduinoOTA.setHostname(hostname.c_str()); - ArduinoOTA.begin(); + ESP_FileSystem::end(); +#endif // FILESYSTEM_FEATURE + } + output.printMSG(type.c_str()); + }); + ArduinoOTA.onEnd([]() { + ESP3DOutput output(ESP_ALL_CLIENTS); + output.printMSG("End OTA"); + }); + ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { + String prg = "OTA Progress "; + ESP3DOutput output(ESP_ALL_CLIENTS); + prg += String(progress / (total / 100)) + "%"; + output.printMSG(prg.c_str()); + }); + ArduinoOTA.onError([](ota_error_t error) { + String stmp = "OTA Error: " + String(error); + ESP3DOutput output(ESP_ALL_CLIENTS); + output.printERROR(stmp.c_str()); + if (error == OTA_AUTH_ERROR) { + output.printERROR("Auth Failed"); + } else if (error == OTA_BEGIN_ERROR) { + output.printERROR("Begin Failed"); + } else if (error == OTA_CONNECT_ERROR) { + output.printERROR("Connect Failed"); + } else if (error == OTA_RECEIVE_ERROR) { + output.printERROR("Receive Failed"); + } else if (error == OTA_END_ERROR) { + output.printERROR("End Failed"); + } + }); + if (Settings_ESP3D::isVerboseBoot()) { + output.printMSG("OTA service started"); } + String lhostname = hostname; + lhostname.toLowerCase(); + ArduinoOTA.setHostname(hostname.c_str()); + ArduinoOTA.begin(); + } #endif #if defined(MDNS_FEATURE) && defined(ARDUINO_ARCH_ESP32) - esp3d_mDNS.begin(hostname.c_str()); -#endif //MDNS_FEATURE && ARDUINO_ARCH_ESP8266 + esp3d_mDNS.begin(hostname.c_str()); +#endif // MDNS_FEATURE && ARDUINO_ARCH_ESP8266 #ifdef CAPTIVE_PORTAL_FEATURE - if(NetConfig::getMode() == ESP_AP_SETUP) { - // if DNSServer is started with "*" for domain name, it will reply with - // provided IP to all DNS request - if (dnsServer.start(DNS_PORT, "*", WiFi.softAPIP())) { - if (Settings_ESP3D::isVerboseBoot()) { - output.printMSG("Captive Portal started"); - } - } else { - output.printERROR("Failed start Captive Portal"); - } + if (NetConfig::getMode() == ESP_AP_SETUP) { + // if DNSServer is started with "*" for domain name, it will reply with + // provided IP to all DNS request + if (dnsServer.start(DNS_PORT, "*", WiFi.softAPIP())) { + if (Settings_ESP3D::isVerboseBoot()) { + output.printMSG("Captive Portal started"); + } + } else { + output.printERROR("Failed start Captive Portal"); } -#endif //CAPTIVE_PORTAL_FEATURE + } +#endif // CAPTIVE_PORTAL_FEATURE #ifdef HTTP_FEATURE - if (!HTTP_Server::begin()) { - res= false; - output.printERROR("HTTP server failed"); - } else { - if(HTTP_Server::started()) { - String stmp = "HTTP server started port " + String(HTTP_Server::port()); - if (Settings_ESP3D::isVerboseBoot()) { - output.printMSG(stmp.c_str()); - } - } + if (!HTTP_Server::begin()) { + res = false; + output.printERROR("HTTP server failed"); + } else { + if (HTTP_Server::started()) { + String stmp = "HTTP server started port " + String(HTTP_Server::port()); + if (Settings_ESP3D::isVerboseBoot()) { + output.printMSG(stmp.c_str()); + } } -#endif //HTTP_FEATURE + } +#endif // HTTP_FEATURE #ifdef TELNET_FEATURE - if (!telnet_server.begin()) { - res= false; - output.printERROR("Telnet server failed"); - } else { - if(telnet_server.started()) { - String stmp = "Telnet server started port " + String(telnet_server.port()); - if (Settings_ESP3D::isVerboseBoot()) { - output.printMSG(stmp.c_str()); - } - } + if (!telnet_server.begin()) { + res = false; + output.printERROR("Telnet server failed"); + } else { + if (telnet_server.started()) { + String stmp = + "Telnet server started port " + String(telnet_server.port()); + if (Settings_ESP3D::isVerboseBoot()) { + output.printMSG(stmp.c_str()); + } } -#endif //TELNET_FEATURE + } +#endif // TELNET_FEATURE #ifdef FTP_FEATURE - if (!ftp_server.begin()) { - res= false; - output.printERROR("Ftp server failed"); - } else { - if(ftp_server.started()) { - String stmp = "Ftp server started ports: " + String(ftp_server.ctrlport()) + ","+ String(ftp_server.dataactiveport()) + ","+ String(ftp_server.datapassiveport()); - if (Settings_ESP3D::isVerboseBoot()) { - output.printMSG(stmp.c_str()); - } - } + if (!ftp_server.begin()) { + res = false; + output.printERROR("Ftp server failed"); + } else { + if (ftp_server.started()) { + String stmp = + "Ftp server started ports: " + String(ftp_server.ctrlport()) + "," + + String(ftp_server.dataactiveport()) + "," + + String(ftp_server.datapassiveport()); + if (Settings_ESP3D::isVerboseBoot()) { + output.printMSG(stmp.c_str()); + } } -#endif //FTP_FEATURE + } +#endif // FTP_FEATURE #ifdef WS_DATA_FEATURE - if (!websocket_data_server.begin(Settings_ESP3D::read_uint32(ESP_WEBSOCKET_PORT))) { - output.printMSG("Failed start Terminal Web Socket"); - } else { - if (websocket_data_server.started()) { - String stmp = "Websocket server started port " + String(websocket_data_server.port()); - if (Settings_ESP3D::isVerboseBoot()) { - output.printMSG(stmp.c_str()); - } - } + if (!websocket_data_server.begin( + Settings_ESP3D::read_uint32(ESP_WEBSOCKET_PORT))) { + output.printMSG("Failed start Terminal Web Socket"); + } else { + if (websocket_data_server.started()) { + String stmp = "Websocket server started port " + + String(websocket_data_server.port()); + if (Settings_ESP3D::isVerboseBoot()) { + output.printMSG(stmp.c_str()); + } } -#endif //WS_DATA_FEATURE + } +#endif // WS_DATA_FEATURE #ifdef WEBDAV_FEATURE - if (!webdav_server.begin()) { - output.printMSG("Failed start Terminal Web Socket"); - } else { - if (webdav_server.started()) { - String stmp = "WebDav server started port " + String(webdav_server.port()); - if (Settings_ESP3D::isVerboseBoot()) { - output.printMSG(stmp.c_str()); - } - } + if (!webdav_server.begin()) { + output.printMSG("Failed start Terminal Web Socket"); + } else { + if (webdav_server.started()) { + String stmp = + "WebDav server started port " + String(webdav_server.port()); + if (Settings_ESP3D::isVerboseBoot()) { + output.printMSG(stmp.c_str()); + } } -#endif //WEBDAV_FEATURE + } +#endif // WEBDAV_FEATURE #if defined(HTTP_FEATURE) - if (!websocket_terminal_server.begin()) { - output.printMSG("Failed start Terminal Web Socket"); - } -#endif //HTTP_FEATURE + if (!websocket_terminal_server.begin()) { + output.printMSG("Failed start Terminal Web Socket"); + } +#endif // HTTP_FEATURE #ifdef MDNS_FEATURE - esp3d_mDNS.addESP3DServices(HTTP_Server::port()); -#endif //MDNS_FEATURE + esp3d_mDNS.addESP3DServices(HTTP_Server::port()); +#endif // MDNS_FEATURE #ifdef SSDP_FEATURE - //SSDP service presentation - if(WiFi.getMode() != WIFI_AP && HTTP_Server::started()) { - //Add specific for SSDP - String stmp = String(Hal::getChipID()); - SSDP.setSchemaURL ("description.xml"); - SSDP.setHTTPPort (HTTP_Server::port()); - SSDP.setName (hostname.c_str()); - SSDP.setURL ("/"); - SSDP.setDeviceType ("upnp:rootdevice"); - SSDP.setSerialNumber (stmp.c_str()); - //Any customization could be here - SSDP.setModelName (ESP_MODEL_NAME); + // SSDP service presentation + if (WiFi.getMode() != WIFI_AP && HTTP_Server::started()) { + // Add specific for SSDP + String stmp = String(Hal::getChipID()); + SSDP.setSchemaURL("description.xml"); + SSDP.setHTTPPort(HTTP_Server::port()); + SSDP.setName(hostname.c_str()); + SSDP.setURL("/"); + SSDP.setDeviceType("upnp:rootdevice"); + SSDP.setSerialNumber(stmp.c_str()); + // Any customization could be here + SSDP.setModelName(ESP_MODEL_NAME); #if defined(ESP_MODEL_DESCRIPTION) - //this one is optional because windows doesn't care about this field - SSDP.setModelDescription(ESP_MODEL_DESCRIPTION); -#endif //ESP_MODEL_DESCRIPTION - SSDP.setModelURL (ESP_MODEL_URL); - SSDP.setModelNumber (ESP_MODEL_NUMBER); - SSDP.setManufacturer (ESP_MANUFACTURER_NAME); - SSDP.setManufacturerURL (ESP_MANUFACTURER_URL); - SSDP.begin(); - stmp = "SSDP started with '" + hostname + "'"; - if (Settings_ESP3D::isVerboseBoot()) { - output.printMSG(stmp.c_str()); - } + // this one is optional because windows doesn't care about this field + SSDP.setModelDescription(ESP_MODEL_DESCRIPTION); +#endif // ESP_MODEL_DESCRIPTION + SSDP.setModelURL(ESP_MODEL_URL); + SSDP.setModelNumber(ESP_MODEL_NUMBER); + SSDP.setManufacturer(ESP_MANUFACTURER_NAME); + SSDP.setManufacturerURL(ESP_MANUFACTURER_URL); + SSDP.begin(); + stmp = "SSDP started with '" + hostname + "'"; + if (Settings_ESP3D::isVerboseBoot()) { + output.printMSG(stmp.c_str()); } -#endif //SSDP_FEATURE + } +#endif // SSDP_FEATURE #ifdef NOTIFICATION_FEATURE - notificationsservice.begin(); - notificationsservice.sendAutoNotification(NOTIFICATION_ESP_ONLINE); -#endif //NOTIFICATION_FEATURE + notificationsservice.begin(); + notificationsservice.sendAutoNotification(NOTIFICATION_ESP_ONLINE); +#endif // NOTIFICATION_FEATURE #ifdef CAMERA_DEVICE - if (!esp3d_camera.begin()) { - output.printMSG("Failed start camera streaming server"); - } -#endif //CAMERA_DEVICE + if (!esp3d_camera.begin()) { + output.printMSG("Failed start camera streaming server"); + } +#endif // CAMERA_DEVICE #if COMMUNICATION_PROTOCOL == MKS_SERIAL - MKSService::begin(); -#endif //COMMUNICATION_PROTOCOL == MKS_SERIAL - if (!res) { - end(); - } - Hal::wait(1000); + MKSService::begin(); +#endif // COMMUNICATION_PROTOCOL == MKS_SERIAL + if (!res) { + end(); + } + Hal::wait(1000); #if COMMUNICATION_PROTOCOL != MKS_SERIAL - output.printMSG(NetConfig::localIP().c_str()); -#endif //#if COMMUNICATION_PROTOCOL == MKS_SERIAL - _started = res; - return _started; + output.printMSG(NetConfig::localIP().c_str()); +#endif // #if COMMUNICATION_PROTOCOL == MKS_SERIAL + _started = res; + return _started; } -void NetServices::end() -{ - _restart = false; - if(!_started) { - return; - } - _started = false; +void NetServices::end() { + _restart = false; + if (!_started) { + return; + } + _started = false; #if COMMUNICATION_PROTOCOL == MKS_SERIAL - MKSService::end(); -#endif //COMMUNICATION_PROTOCOL == MKS_SERIAL + MKSService::end(); +#endif // COMMUNICATION_PROTOCOL == MKS_SERIAL #ifdef CAMERA_DEVICE - esp3d_camera.end(); -#endif //CAMERA_DEVICE + esp3d_camera.end(); +#endif // CAMERA_DEVICE #ifdef NOTIFICATION_FEATURE - notificationsservice.end(); -#endif //NOTIFICATION_FEATURE + notificationsservice.end(); +#endif // NOTIFICATION_FEATURE #ifdef CAPTIVE_PORTAL_FEATURE - if(NetConfig::getMode() == ESP_AP_SETUP) { - dnsServer.stop(); - } -#endif //CAPTIVE_PORTAL_FEATURE + if (NetConfig::getMode() == ESP_AP_SETUP) { + dnsServer.stop(); + } +#endif // CAPTIVE_PORTAL_FEATURE #ifdef SSDP_FEATURE #if defined(ARDUINO_ARCH_ESP32) - SSDP.end(); -#endif //ARDUINO_ARCH_ESP32 -#endif //SSDP_FEATURE + SSDP.end(); +#endif // ARDUINO_ARCH_ESP32 +#endif // SSDP_FEATURE #ifdef MDNS_FEATURE - esp3d_mDNS.end(); -#endif //MDNS_FEATURE + esp3d_mDNS.end(); +#endif // MDNS_FEATURE #ifdef OTA_FEATURE #if defined(ARDUINO_ARCH_ESP32) - if(WiFi.getMode() != WIFI_AP) { - ArduinoOTA.end(); - } -#endif // ARDUINO_ARCH_ESP32 -#endif //OTA_FEATURE + if (WiFi.getMode() != WIFI_AP) { + ArduinoOTA.end(); + } +#endif // ARDUINO_ARCH_ESP32 +#endif // OTA_FEATURE #if defined(HTTP_FEATURE) - websocket_terminal_server.end(); -#endif //HTTP_FEATURE + websocket_terminal_server.end(); +#endif // HTTP_FEATURE #ifdef WEBDAV_FEATURE - webdav_server.end(); -#endif //WEBDAV_FEATURE + webdav_server.end(); +#endif // WEBDAV_FEATURE #ifdef HTTP_FEATURE - HTTP_Server::end(); -#endif //HTTP_FEATURE + HTTP_Server::end(); +#endif // HTTP_FEATURE #ifdef WS_DATA_FEATURE - websocket_data_server.end(); -#endif //WS_DATA_FEATURE + websocket_data_server.end(); +#endif // WS_DATA_FEATURE #ifdef TELNET_FEATURE - telnet_server.end(); -#endif //TELNET_FEATURE + telnet_server.end(); +#endif // TELNET_FEATURE #ifdef FTP_FEATURE - ftp_server.end(); -#endif //FTP_FEATURE + ftp_server.end(); +#endif // FTP_FEATURE } -void NetServices::handle() -{ - if (_started) { +void NetServices::handle() { + if (_started) { #if COMMUNICATION_PROTOCOL == MKS_SERIAL - MKSService::handle(); -#endif //COMMUNICATION_PROTOCOL == MKS_SERIAL + MKSService::handle(); +#endif // COMMUNICATION_PROTOCOL == MKS_SERIAL #ifdef MDNS_FEATURE - esp3d_mDNS.handle(); -#endif //MDNS_FEATURE + esp3d_mDNS.handle(); +#endif // MDNS_FEATURE #ifdef OTA_FEATURE - ArduinoOTA.handle(); -#endif //OTA_FEATURE + ArduinoOTA.handle(); +#endif // OTA_FEATURE #ifdef CAPTIVE_PORTAL_FEATURE - if (NetConfig::getMode() == ESP_AP_SETUP) { - dnsServer.processNextRequest(); - } -#endif //CAPTIVE_PORTAL_FEATURE + if (NetConfig::getMode() == ESP_AP_SETUP) { + dnsServer.processNextRequest(); + } +#endif // CAPTIVE_PORTAL_FEATURE #ifdef HTTP_FEATURE - HTTP_Server::handle(); -#endif //HTTP_FEATURE + HTTP_Server::handle(); +#endif // HTTP_FEATURE #ifdef WEBDAV_FEATURE - webdav_server.handle(); -#endif //WEBDAV_FEATURE + webdav_server.handle(); +#endif // WEBDAV_FEATURE #ifdef WS_DATA_FEATURE - websocket_data_server.handle(); -#endif //WS_DATA_FEATURE + websocket_data_server.handle(); +#endif // WS_DATA_FEATURE #if defined(HTTP_FEATURE) - websocket_terminal_server.handle(); -#endif //HTTP_FEATURE + websocket_terminal_server.handle(); +#endif // HTTP_FEATURE #ifdef TELNET_FEATURE - telnet_server.handle(); -#endif //TELNET_FEATURE + telnet_server.handle(); +#endif // TELNET_FEATURE #ifdef FTP_FEATURE - ftp_server.handle(); -#endif //FTP_FEATURE + ftp_server.handle(); +#endif // FTP_FEATURE #ifdef NOTIFICATION_FEATURE - notificationsservice.handle(); -#endif //NOTIFICATION_FEATURE - } - if (_restart) { - begin(); - } + notificationsservice.handle(); +#endif // NOTIFICATION_FEATURE + } + if (_restart) { + begin(); + } } - diff --git a/esp3d/src/modules/telnet/telnet_server.cpp b/esp3d/src/modules/telnet/telnet_server.cpp index 4ff16199..22483e17 100644 --- a/esp3d/src/modules/telnet/telnet_server.cpp +++ b/esp3d/src/modules/telnet/telnet_server.cpp @@ -20,300 +20,273 @@ #include "../../include/esp3d_config.h" -#if defined (TELNET_FEATURE) -#include +#if defined(TELNET_FEATURE) #include -#include "telnet_server.h" -#include "../../core/settings_esp3d.h" -#include "../../core/esp3doutput.h" +#include + #include "../../core/commands.h" +#include "../../core/esp3doutput.h" +#include "../../core/settings_esp3d.h" +#include "telnet_server.h" Telnet_Server telnet_server; #define TIMEOUT_TELNET_FLUSH 1500 -void Telnet_Server::closeClient() -{ - if(_telnetClients) { +void Telnet_Server::closeClient() { + if (_telnetClients) { + _telnetClients.stop(); + } +} + +bool Telnet_Server::isConnected() { + if (!_started || _telnetserver == NULL) { + return false; + } + // check if there are any new clients + if (_telnetserver->hasClient()) { + // find free/disconnected spot + if (!_telnetClients || !_telnetClients.connected()) { + if (_telnetClients) { _telnetClients.stop(); + } + _telnetClients = _telnetserver->accept(); + // new client } + } + if (_telnetserver->hasClient()) { + // no free/disconnected spot so reject + _telnetserver->accept().stop(); + } + return _telnetClients.connected(); } -bool Telnet_Server::isConnected() -{ - if ( !_started || _telnetserver == NULL) { - return false; - } - //check if there are any new clients - if (_telnetserver->hasClient()) { - //find free/disconnected spot - if (!_telnetClients || !_telnetClients.connected()) { - if(_telnetClients) { - _telnetClients.stop(); - } - _telnetClients = _telnetserver->available(); - //new client - } - } - if (_telnetserver->hasClient()) { - //no free/disconnected spot so reject - _telnetserver->available().stop(); - } - return _telnetClients.connected(); +const char *Telnet_Server::clientIPAddress() { + static String res; + res = "0.0.0.0"; + if (_telnetClients && _telnetClients.connected()) { + res = _telnetClients.remoteIP().toString(); + } + return res.c_str(); } -const char* Telnet_Server::clientIPAddress() -{ - static String res; - res = "0.0.0.0"; - if (_telnetClients && _telnetClients.connected()) { - res = _telnetClients.remoteIP().toString(); - } - return res.c_str(); -} - - -Telnet_Server::Telnet_Server() -{ - _buffer_size = 0; - _started = false; - _isdebug = false; - _port = 0; - _buffer = nullptr; - _telnetserver = nullptr; -} -Telnet_Server::~Telnet_Server() -{ - end(); +Telnet_Server::Telnet_Server() { + _buffer_size = 0; + _started = false; + _isdebug = false; + _port = 0; + _buffer = nullptr; + _telnetserver = nullptr; } +Telnet_Server::~Telnet_Server() { end(); } /** * begin Telnet setup */ -bool Telnet_Server::begin(uint16_t port, bool debug) -{ - end(); - if (Settings_ESP3D::read_byte(ESP_TELNET_ON) !=1) { - return true; +bool Telnet_Server::begin(uint16_t port, bool debug) { + end(); + if (Settings_ESP3D::read_byte(ESP_TELNET_ON) != 1) { + return true; + } + // Get telnet port + if (port == 0) { + _port = Settings_ESP3D::read_uint32(ESP_TELNET_PORT); + } else { + _port = port; + } + _isdebug = debug; + if (!_isdebug) { + _buffer = (uint8_t *)malloc(ESP3D_TELNET_BUFFER_SIZE + 1); + if (!_buffer) { + return false; } - //Get telnet port - if (port == 0) { - _port = Settings_ESP3D::read_uint32(ESP_TELNET_PORT); - } else { - _port = port; - } - _isdebug = debug; - if (!_isdebug) { - _buffer= (uint8_t *)malloc(ESP3D_TELNET_BUFFER_SIZE +1); - if (!_buffer) { - return false; - } - } - //create instance - _telnetserver= new WiFiServer(_port); - if (!_telnetserver) { - return false; - } - _telnetserver->setNoDelay(true); - //start telnet server - _telnetserver->begin(); - _started = true; - _lastflush = millis(); - return _started; + } + // create instance + _telnetserver = new WiFiServer(_port); + if (!_telnetserver) { + return false; + } + _telnetserver->setNoDelay(true); + // start telnet server + _telnetserver->begin(); + _started = true; + _lastflush = millis(); + return _started; } /** * End Telnet */ -void Telnet_Server::end() -{ - _started = false; - _buffer_size = 0; - _port = 0; - _isdebug = false; - closeClient(); - if (_telnetserver) { - delete _telnetserver; - _telnetserver = nullptr; - } +void Telnet_Server::end() { + _started = false; + _buffer_size = 0; + _port = 0; + _isdebug = false; + closeClient(); + if (_telnetserver) { + delete _telnetserver; + _telnetserver = nullptr; + } - if (_buffer) { - free(_buffer); - _buffer = nullptr; - } + if (_buffer) { + free(_buffer); + _buffer = nullptr; + } } /** * Reset Telnet */ -bool Telnet_Server::reset() -{ - //nothing to reset - return true; +bool Telnet_Server::reset() { + // nothing to reset + return true; } -bool Telnet_Server::started() -{ - return _started; -} +bool Telnet_Server::started() { return _started; } -void Telnet_Server::handle() -{ - Hal::wait(0); - if (isConnected()) { - //check clients for data - size_t len = _telnetClients.available(); - if(len > 0) { - //if yes read them - uint8_t * sbuf = (uint8_t *)malloc(len); - if(sbuf) { - size_t count = _telnetClients.read(sbuf, len); - //push to buffer - if (count > 0) { - push2buffer(sbuf, count); - } - //free buffer - free(sbuf); - } +void Telnet_Server::handle() { + Hal::wait(0); + if (isConnected()) { + // check clients for data + size_t len = _telnetClients.available(); + if (len > 0) { + // if yes read them + uint8_t *sbuf = (uint8_t *)malloc(len); + if (sbuf) { + size_t count = _telnetClients.read(sbuf, len); + // push to buffer + if (count > 0) { + push2buffer(sbuf, count); } - - } - //we cannot left data in buffer too long - //in case some commands "forget" to add \n - if (((millis() - _lastflush) > TIMEOUT_TELNET_FLUSH) && (_buffer_size > 0)) { - flushbuffer(); + // free buffer + free(sbuf); + } } + } + // we cannot left data in buffer too long + // in case some commands "forget" to add \n + if (((millis() - _lastflush) > TIMEOUT_TELNET_FLUSH) && (_buffer_size > 0)) { + flushbuffer(); + } } -void Telnet_Server::flushbuffer() -{ - if (!_buffer || !_started) { - _buffer_size = 0; - return; - } - ESP3DOutput output(ESP_TELNET_CLIENT); - _buffer[_buffer_size] = 0x0; - //dispatch command - esp3d_commands.process(_buffer, _buffer_size, &output); - _lastflush = millis(); +void Telnet_Server::flushbuffer() { + if (!_buffer || !_started) { _buffer_size = 0; + return; + } + ESP3DOutput output(ESP_TELNET_CLIENT); + _buffer[_buffer_size] = 0x0; + // dispatch command + esp3d_commands.process(_buffer, _buffer_size, &output); + _lastflush = millis(); + _buffer_size = 0; } -void Telnet_Server::push2buffer(uint8_t * sbuf, size_t len) -{ - if (!_buffer) { - return; - } - for (size_t i = 0; i < len; i++) { - _lastflush = millis(); - //command is defined - if ((char(sbuf[i]) == '\n') || (char(sbuf[i]) == '\r')) { - if (_buffer_size < ESP3D_TELNET_BUFFER_SIZE) { - _buffer[_buffer_size] = sbuf[i]; - _buffer_size++; - } - flushbuffer(); - } else if (isPrintable (char(sbuf[i]) )) { - if (_buffer_size < ESP3D_TELNET_BUFFER_SIZE) { - _buffer[_buffer_size] = sbuf[i]; - _buffer_size++; - } else { - flushbuffer(); - _buffer[_buffer_size] = sbuf[i]; - _buffer_size++; - } - } else { //it is not printable char - //clean buffer first - if (_buffer_size > 0) { - flushbuffer(); - } - //process char - _buffer[_buffer_size] = sbuf[i]; - _buffer_size++; - flushbuffer(); - } +void Telnet_Server::push2buffer(uint8_t *sbuf, size_t len) { + if (!_buffer) { + return; + } + for (size_t i = 0; i < len; i++) { + _lastflush = millis(); + // command is defined + if ((char(sbuf[i]) == '\n') || (char(sbuf[i]) == '\r')) { + if (_buffer_size < ESP3D_TELNET_BUFFER_SIZE) { + _buffer[_buffer_size] = sbuf[i]; + _buffer_size++; + } + flushbuffer(); + } else if (isPrintable(char(sbuf[i]))) { + if (_buffer_size < ESP3D_TELNET_BUFFER_SIZE) { + _buffer[_buffer_size] = sbuf[i]; + _buffer_size++; + } else { + flushbuffer(); + _buffer[_buffer_size] = sbuf[i]; + _buffer_size++; + } + } else { // it is not printable char + // clean buffer first + if (_buffer_size > 0) { + flushbuffer(); + } + // process char + _buffer[_buffer_size] = sbuf[i]; + _buffer_size++; + flushbuffer(); } + } } -size_t Telnet_Server::write(uint8_t c) -{ - return write(&c,1); -} +size_t Telnet_Server::write(uint8_t c) { return write(&c, 1); } -size_t Telnet_Server::write(const uint8_t *buffer, size_t size) -{ - if (isConnected() && (size>0) && _started) { - if ((size_t)availableForWrite() >= size) { - //push data to connected telnet client - return _telnetClients.write(buffer, size); +size_t Telnet_Server::write(const uint8_t *buffer, size_t size) { + if (isConnected() && (size > 0) && _started) { + if ((size_t)availableForWrite() >= size) { + // push data to connected telnet client + return _telnetClients.write(buffer, size); + } else { + size_t sizetosend = size; + size_t sizesent = 0; + uint8_t *buffertmp = (uint8_t *)buffer; + uint32_t starttime = millis(); + // loop until all is sent or timeout + while (sizetosend > 0 && ((millis() - starttime) < 100)) { + size_t available = availableForWrite(); + if (available > 0) { + // in case less is sent + available = _telnetClients.write( + &buffertmp[sizesent], + (available >= sizetosend) ? sizetosend : available); + sizetosend -= available; + sizesent += available; + starttime = millis(); } else { - size_t sizetosend = size; - size_t sizesent = 0; - uint8_t *buffertmp=(uint8_t *)buffer; - uint32_t starttime = millis(); - //loop until all is sent or timeout - while (sizetosend>0 && ((millis() - starttime) < 100)) { - size_t available = availableForWrite(); - if(available>0) { - //in case less is sent - available = _telnetClients.write(&buffertmp[sizesent], (available >= sizetosend)?sizetosend:available); - sizetosend-=available; - sizesent+=available; - starttime=millis(); - } else { - Hal::wait(5); - } - } - return sizesent; + Hal::wait(5); } + } + return sizesent; } - return 0; + } + return 0; } -int Telnet_Server::availableForWrite() -{ - if (!isConnected()) { - return 0; - } +int Telnet_Server::availableForWrite() { + if (!isConnected()) { + return 0; + } #ifdef ARDUINO_ARCH_ESP32 - return 128; //hard code for esp32 -#endif //ARDUINO_ARCH_ESP32 + return 128; // hard code for esp32 +#endif // ARDUINO_ARCH_ESP32 #ifdef ARDUINO_ARCH_ESP8266 - return _telnetClients.availableForWrite(); -#endif //ARDUINO_ARCH_ESP8266 + return _telnetClients.availableForWrite(); +#endif // ARDUINO_ARCH_ESP8266 } -int Telnet_Server::available() -{ - if(isConnected()) { - return _telnetClients.available(); +int Telnet_Server::available() { + if (isConnected()) { + return _telnetClients.available(); + } + return 0; +} + +int Telnet_Server::read(void) { + if (isConnected()) { + if (_telnetClients.available() > 0) { + return _telnetClients.read(); } - return 0; + } + return -1; } -int Telnet_Server::read(void) -{ - if(isConnected()) { - if(_telnetClients.available() > 0) { - return _telnetClients.read(); - } +size_t Telnet_Server::readBytes(uint8_t *sbuf, size_t len) { + if (isConnected()) { + if (_telnetClients.available() > 0) { + return _telnetClients.read(sbuf, len); } - return -1; + } + return 0; } -size_t Telnet_Server::readBytes(uint8_t * sbuf, size_t len) -{ - if(isConnected()) { - if(_telnetClients.available() > 0) { - return _telnetClients.read(sbuf, len); - } - } - return 0; -} +void Telnet_Server::flush() { _telnetClients.flush(); } - -void Telnet_Server::flush() -{ - _telnetClients.flush(); -} - -#endif //TELNET_FEATURE +#endif // TELNET_FEATURE diff --git a/esp3d/src/modules/time/time_server.cpp b/esp3d/src/modules/time/time_service.cpp similarity index 50% rename from esp3d/src/modules/time/time_server.cpp rename to esp3d/src/modules/time/time_service.cpp index 4386c11e..519064ad 100644 --- a/esp3d/src/modules/time/time_server.cpp +++ b/esp3d/src/modules/time/time_service.cpp @@ -23,7 +23,7 @@ #include "../../core/esp3doutput.h" #include "../../core/settings_esp3d.h" -#include "time_server.h" +#include "time_service.h" #if defined(WIFI_FEATURE) #include "../wifi/wificonfig.h" @@ -35,15 +35,35 @@ #include "../ethernet/ethconfig.h" #endif // ETH_FEATURE -TimeServer timeserver; +TimeService timeService; -TimeServer::TimeServer() { +const char* SupportedTimeZones[] = { + "-12:00", "-11:00", "-10:00", "-09:00", "-08:00", "-07:00", "-06:00", + "-05:00", "-04:00", "-03:30", "-03:00", "-02:00", "-01:00", "+00:00", + "+01:00", "+02:00", "+03:00", "+03:30", "+04:00", "+04:30", "+05:00", + "+05:30", "+05:45", "+06:00", "+06:30", "+07:00", "+08:00", "+08:45", + "+09:00", "+09:30", "+10:00", "+10:30", "+11:00", "+12:00", "+12:45", + "+13:00", "+14:00"}; + +const uint8_t SupportedTimeZonesSize = + sizeof(SupportedTimeZones) / sizeof(const char*); + +TimeService::TimeService() { _started = false; _is_internet_time = false; + _time_zone = "+00:00"; } -TimeServer::~TimeServer() { end(); } +TimeService::~TimeService() { end(); } -bool TimeServer::is_internet_time(bool readfromsettings) { +// FIXME: this is a WIP +const char* TimeService::getDateTime(time_t t) { + static char buff[20]; + strftime(buff, sizeof(buff), "%Y-%m-%d %H:%M:%S", localtime(&t)); + + return buff; +} + +bool TimeService::is_internet_time(bool readfromsettings) { if (readfromsettings) { _is_internet_time = Settings_ESP3D::read_byte(ESP_INTERNET_TIME) ? true : false; @@ -53,12 +73,11 @@ bool TimeServer::is_internet_time(bool readfromsettings) { return _is_internet_time; } -bool TimeServer::begin() { - bool res = true; +bool TimeService::begin() { end(); - String s1, s2, s3; - int8_t t1; + String s1, s2, s3, t1; byte d1; + updateTimeZone(true); #if defined(WIFI_FEATURE) // no time server in AP mode if (WiFi.getMode() == WIFI_AP) { @@ -92,9 +111,14 @@ bool TimeServer::begin() { s1 = Settings_ESP3D::read_string(ESP_TIME_SERVER1); s2 = Settings_ESP3D::read_string(ESP_TIME_SERVER2); s3 = Settings_ESP3D::read_string(ESP_TIME_SERVER3); - t1 = (int8_t)Settings_ESP3D::read_byte(ESP_TIMEZONE); - d1 = Settings_ESP3D::read_byte(ESP_TIME_IS_DST); - configTime(3600 * (t1), d1 * 3600, s1.c_str(), s2.c_str(), s3.c_str()); + // d1 = Settings_ESP3D::read_byte(ESP_TIME_IS_DST); +#if defined(ARDUINO_ARCH_ESP32) + configTzTime(_time_zone.c_str(), s1.c_str(), s2.c_str(), s3.c_str()); +#endif // ARDUINO_ARCH_ESP32 +#if defined(ARDUINO_ARCH_ESP8266) + configTime(t1.c_str(), s1.c_str(), s2.c_str(), s3.c_str()); +#endif // ARDUINO_ARCH_ESP8266 + time_t now = time(nullptr); int nb = 0; while ((now < (8 * 3600 * 2)) && (nb < 20)) { @@ -103,58 +127,78 @@ bool TimeServer::begin() { nb++; now = time(nullptr); } - if (now < (8 * 3600 * 2)) { - res = false; - } - if (!res) { - end(); - } - _started = res; + _started = true; // always true, time is set asynchrously return _started; } -const char* TimeServer::current_time(time_t t) { - static String stmp; +const char* TimeService::getTimeZone() { return _time_zone.c_str(); } + +bool TimeService::setTimeZone(const char* stime) { + bool valid = false; + for (uint8_t i = 0; i < SupportedTimeZonesSize; i++) { + if (strcmp(stime, SupportedTimeZones[i]) == 0) { + valid = true; + break; + } + } + if (valid) { + _time_zone = stime; + return Settings_ESP3D::write_string(ESP_TIME_ZONE, _time_zone.c_str()); + } + return false; +} + +bool TimeService::updateTimeZone(bool fromsettings) { + char out_str[7] = {0}; + _time_zone = Settings_ESP3D::read_string(ESP_TIME_ZONE); + + bool valid = false; + for (uint8_t i = 0; i < SupportedTimeZonesSize; i++) { + if (strcmp(_time_zone.c_str(), SupportedTimeZones[i]) == 0) { + valid = true; + break; + } + } + + if (!valid) { + log_esp3d_e("Invalid time zone %s", _time_zone.c_str()); + _time_zone = "+00:00"; + } + String stmp = _time_zone; + if (stmp[0] == '+') { + stmp[0] = '-'; + } else if (stmp[0] == '-') { + stmp[0] = '+'; + } else { + return false; + } + stmp = "GMT" + stmp; +#if defined(ARDUINO_ARCH_ESP32) + setenv("TZ", stmp.c_str(), 1); + tzset(); +#endif // ARDUINO_ARCH_ESP32 +#if defined(ARDUINO_ARCH_ESP8266) + setTZ(stmp.c_str()); +#endif // ARDUINO_ARCH_ESP8266 + + return true; +} + +const char* TimeService::getCurrentTime() { struct tm tmstruct; time_t now; - stmp = ""; // get current time - if (t == 0) { - log_esp3d("No time provided"); - time(&now); - localtime_r(&now, &tmstruct); - } else { - log_esp3d("Got time initialization"); - localtime_r(&t, &tmstruct); - } - stmp = String((tmstruct.tm_year) + 1900) + "-"; - if (((tmstruct.tm_mon) + 1) < 10) { - stmp += "0"; - } - stmp += String((tmstruct.tm_mon) + 1) + "-"; - if (tmstruct.tm_mday < 10) { - stmp += "0"; - } - stmp += String(tmstruct.tm_mday) + " "; - if (tmstruct.tm_hour < 10) { - stmp += "0"; - } - stmp += String(tmstruct.tm_hour) + ":"; - if (tmstruct.tm_min < 10) { - stmp += "0"; - } - stmp += String(tmstruct.tm_min) + ":"; - if (tmstruct.tm_sec < 10) { - stmp += "0"; - } - stmp += String(tmstruct.tm_sec); - log_esp3d("Current time is %s", stmp.c_str()); - return stmp.c_str(); + time(&now); + localtime_r(&now, &tmstruct); + static char buf[20]; + strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &tmstruct); + log_esp3d("Time string is %s", buf); + return buf; } // the string date time need to be iso-8601 // the time zone part will be ignored -bool TimeServer::setTime(const char* stime) { +bool TimeService::setTime(const char* stime) { log_esp3d("Set time to %s", stime); String stmp = stime; struct tm tmstruct; @@ -164,34 +208,49 @@ bool TimeServer::setTime(const char* stime) { log_esp3d("Invalid time format, try without seconds"); // allow not to set seconds for lazy guys typing command line if (strptime(stime, "%Y-%m-%dT%H:%M", &tmstruct) == nullptr) { - log_esp3d_e("Invalid time format"); + log_esp3d("Invalid time format"); return false; } } - char buf[80]; - strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &tmstruct); - log_esp3d("Time string is %s", buf); + time_val.tv_usec = 0; time_val.tv_sec = mktime(&tmstruct); - // try to setTime - if (settimeofday(&time_val, 0) == -1) { + + // need to set timezone also + int offset = _get_time_zone_offset_min(); + struct timezone tz = {offset, 0}; + // now set time to system + if (settimeofday(&time_val, &tz) == -1) { return false; } return true; } -bool TimeServer::started() { return _started; } +bool TimeService::started() { return _started; } // currently not used -void TimeServer::end() { +void TimeService::end() { _started = false; _is_internet_time = false; + _time_zone = "+00:00"; } // currently not used -void TimeServer::handle() { +void TimeService::handle() { if (_started) { } } -#endif // TimeServer_DEVICE +int TimeService::_get_time_zone_offset_min() { + int offset = 0; + int hour = atoi(_time_zone.substring(1, 1 + 2).c_str()); + int min = atoi(_time_zone.substring(4, 4 + 2).c_str()); + offset = hour * 60 + min; + // result is in minutes west of GMT + if (_time_zone[0] == '+' && offset > 0) { + offset = -offset; + } + return offset; +} + +#endif // TimeService_DEVICE diff --git a/esp3d/src/modules/time/time_service.h b/esp3d/src/modules/time/time_service.h new file mode 100644 index 00000000..5fbb2839 --- /dev/null +++ b/esp3d/src/modules/time/time_service.h @@ -0,0 +1,55 @@ +/* + time_service.h - time server functions class + + Copyright (c) 2014 Luc Lebosse. All rights reserved. + + This code is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This code is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with This code; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef _TIME_SERVICE_H +#define _TIME_SERVICE_H + +#include + +class TimeService { + public: + TimeService(); + ~TimeService(); + bool begin(); + void end(); + void handle(); + const char* getDateTime(time_t t = 0); + const char* getCurrentTime(); + const char* getTimeZone(); + bool updateTimeZone(bool fromsettings = false); + bool setTimeZone(const char* stime); + bool setTime(const char* stime); + bool started(); + bool is_internet_time(bool readfromsettings = false); + + private: + int _get_time_zone_offset_min(); + bool _started; + bool _is_internet_time; + String _time_zone; +}; + +extern TimeService timeService; + +extern const char* SupportedTimeZones[]; + +extern const uint8_t SupportedTimeZonesSize; + +#endif //_TIME_SERVICE_H diff --git a/esp3d/src/modules/update/update_service.cpp b/esp3d/src/modules/update/update_service.cpp index 9fa84a6b..b453bee7 100644 --- a/esp3d/src/modules/update/update_service.cpp +++ b/esp3d/src/modules/update/update_service.cpp @@ -49,10 +49,12 @@ const uint16_t NetstringKeysPos[] = { ESP_HOSTNAME, ESP_STA_SSID, ESP_STA_PASSWORD, ESP_AP_SSID, ESP_AP_PASSWORD}; const char* ServstringKeysVal[] = { - "Time_server1", "Time_server2", "Time_server3", "ADMIN_PASSWORD", - "USER_PASSWORD", "NOTIF_TOKEN1", "NOTIF_TOKEN2", "NOTIF_TOKEN_Settings"}; + "Time_zone", "Time_server1", "Time_server2", + "Time_server3", "ADMIN_PASSWORD", "USER_PASSWORD", + "NOTIF_TOKEN1", "NOTIF_TOKEN2", "NOTIF_TOKEN_Settings"}; -const uint16_t ServstringKeysPos[] = {ESP_TIME_SERVER1, +const uint16_t ServstringKeysPos[] = {ESP_TIME_ZONE, + ESP_TIME_SERVER1, ESP_TIME_SERVER2, ESP_TIME_SERVER3, ESP_ADMIN_PWD, @@ -132,10 +134,9 @@ const uint16_t SysboolKeysPos[] = {ESP_SERIAL_BRIDGE_FLAG, const char* NetbyteKeysVal[] = {"AP_channel"}; const uint16_t NetbyteKeysPos[] = {ESP_AP_CHANNEL}; -const char* ServbyteKeysVal[] = {"Time_zone", "Sesion_timeout", "SD_SPEED"}; +const char* ServbyteKeysVal[] = {"Session_timeout", "SD_SPEED"}; -const uint16_t ServbyteKeysPos[] = {ESP_TIMEZONE, ESP_SESSION_TIMEOUT, - ESP_SD_SPEED_DIV}; +const uint16_t ServbyteKeysPos[] = {ESP_SESSION_TIMEOUT, ESP_SD_SPEED_DIV}; bool processString(const char** keysval, const uint16_t* keypos, const size_t size, const char* key, const char* value, diff --git a/esp3d/src/modules/webdav/ESPWebDAV.cpp b/esp3d/src/modules/webdav/ESPWebDAV.cpp deleted file mode 100644 index 980bc8db..00000000 --- a/esp3d/src/modules/webdav/ESPWebDAV.cpp +++ /dev/null @@ -1,1733 +0,0 @@ -/* - Copyright (c) 2018 Gurpreet Bal https://github.com/ardyesp/ESPWebDAV - Copyright (c) 2020 David Gauchard https://github.com/d-a-v/ESPWebDAV - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED - WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO - EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Modified 22 Jan 2021 by Luc - Lebosse (ESP3D Integration) - -*/ -// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 -#include "../../include/esp3d_config.h" - -#if defined(WEBDAV_FEATURE) -#include - -#include "ESPWebDAV.h" - -#if defined(ARDUINO_ARCH_ESP8266) -#include -#include -#include // crc32() - -#define PolledTimeout esp8266::polledTimeout::oneShotFastMs -#define BUFFER_SIZE 128 -#endif // ARDUINO_ARCH_ESP8266 -#if defined(ARDUINO_ARCH_ESP32) -#include - -#include "PolledTimeout_esp32.h" - -#if defined __has_include -#if __has_include() -#include -#else -#if CONFIG_IDF_TARGET_ESP32 -#include -#elif CONFIG_IDF_TARGET_ESP32S2 -#include -#elif CONFIG_IDF_TARGET_ESP32S3 -#include -#elif CONFIG_IDF_TARGET_ESP32C3 -#include -#endif -#endif -#else -#error Cannot define which path to use -#endif -#undef crc32 -#define crc32(a, len) mz_crc32(0xffffffff, (const unsigned char*)a, len) -#define BUFFER_SIZE 3072 -#endif // ARDUINO_ARCH_ESP32 - -// define cal constants -const char* months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; -const char* wdays[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; - -#define ALLOW \ - "PROPPATCH,PROPFIND,OPTIONS,DELETE" SCUNLOCK ",COPY" SCLOCK \ - ",MOVE,HEAD,POST,PUT,GET" - -#if WEBDAV_LOCK_SUPPORT -#define SLOCK "LOCK" -#define SCLOCK ",LOCK" -#define SUNLOCK "UNLOCK" -#define SCUNLOCK ",UNLOCK" -#else -#define SLOCK "" -#define SCLOCK "" -#define SUNLOCK "" -#define SCUNLOCK "" -#endif - -#define DEBUG_LEN 160 - -#define PROC \ - "proc" // simple virtual file. TODO XXX real virtual fs with user callbacks - -void ESPWebDAVCore::begin() { - _maxPathLength = WebDavFS::maxPathLength(); - _davRoot = "/"; - _fsRoot = "/"; -} - -void ESPWebDAVCore::stripSlashes(String& name) { - size_t i = 0; - while (i < name.length()) - if (name[i] == '/' && name.length() > 1 && - ((i == name.length() - 1) || name[i + 1] == '/')) { - name.remove(i, 1); - } else { - i++; - } -} - -#if WEBDAV_LOCK_SUPPORT - -void ESPWebDAVCore::makeToken(String& ret, uint32_t pash, uint32_t ownash) { - char lock_token[17]; - snprintf(lock_token, sizeof(lock_token), "%08x%08x", pash, ownash); - ret = lock_token; -} - -int ESPWebDAVCore::extractLockToken(const String& someHeader, const char* start, - const char* end, uint32_t& pash, - uint32_t& ownash) { - // If: (<46dd353d7e585af1>) - // => - // IfToken: path:0x46dd353d / owner:0x7e585af1 - - pash = 0; - ownash = 0; - - log_esp3d("extracting lockToken from '%s'", someHeader.c_str()); - // extract "... <:[lock > - int startIdx = someHeader.indexOf(start); - if (startIdx < 0) { - log_esp3d("lock: can't find '%s'", start); - return 412; // fail with precondition failed - } - startIdx += strlen(start); - int endIdx = someHeader.indexOf(end, startIdx); - if (endIdx < 0) { - log_esp3d("lock: can't find '%s'", end); - return 412; // fail with precondition fail - } - log_esp3d("found in [%d..%d[ (%d)", startIdx, endIdx, endIdx - startIdx); - int len = endIdx - startIdx; - if (len < 1 || len > 16) { - log_esp3d("lock: format error (1-16 hex chars)"); - return 423; // fail with lock - } - char cp[len + 1]; - memcpy(cp, &(someHeader.c_str()[startIdx]), len); - cp[len] = 0; - log_esp3d("IfToken: '%s'", cp); - int ownIdx = std::max(len - 8, 0); - ownash = strtoul(&cp[ownIdx], nullptr, 16); - cp[ownIdx] = 0; - pash = strtoul(cp, nullptr, 16); - log_esp3d("IfToken: path:0x%08x / owner:0x%08x", pash, ownash); - return 200; -} - -#endif // WEBDAV_LOCK_SUPPORT - -int ESPWebDAVCore::allowed(const String& uri, uint32_t ownash) { -#if WEBDAV_LOCK_SUPPORT > 1 - - String test = uri; - while (test.length()) { - stripSlashes(test); - log_esp3d("lock: testing '%s'", test.c_str()); - uint32_t hash = crc32(test.c_str(), test.length()); - const auto& lock = _locks.find(hash); - if (lock != _locks.end()) { - log_esp3d("lock: found lock, %sowner!", - lock->second == ownash ? "" : "not"); - return lock->second == ownash ? 200 : 423; - } - int s = test.lastIndexOf('/'); - if (s < 0) { - break; - } - test.remove(s); - } - log_esp3d("lock: none found"); - return 200; - -#else - - (void)uri; - (void)ownash; - return 200; - -#endif -} - -int ESPWebDAVCore::allowed(const String& uri, - const String& xml /* = emptyString */) { - log_esp3d("allowed: '%s' , xml:%s", uri.c_str(), xml.c_str()); -#if WEBDAV_LOCK_SUPPORT > 1 - uint32_t hpash, anyownash; - if (ifHeader.length()) { - int code = extractLockToken(ifHeader, "(<", ">", hpash, anyownash); - if (code != 200) { - log_esp3d("lock: extractLockToken failed: %d", code); - return code; - } - if (anyownash == 0) - // malformed - { - log_esp3d("lock: malformed If: '%s'", ifHeader.c_str()); - return 412; // PUT failed with 423 not 412 - } - } else { - int startIdx = xml.indexOf(""); - int endIdx = xml.indexOf(""); - anyownash = startIdx > 0 && endIdx > 0 - ? crc32(&(xml.c_str()[startIdx + 7]), endIdx - startIdx - 7) - : 0; - } - return allowed(uri, anyownash); -#else - (void)uri; - (void)xml; - return true; -#endif -} - -void ESPWebDAVCore::stripName(String& name) { - if (name.length() > (size_t)_maxPathLength) { - int dot = name.lastIndexOf('.'); - int newDot = _maxPathLength - (name.length() - dot); - if (dot <= 0 || newDot < 0) { - name.remove(_maxPathLength); - } else { - name.remove(newDot, dot - newDot); - } - } -} - -void ESPWebDAVCore::stripHost(String& name) { - int remove = name.indexOf(hostHeader); - if (remove >= 0) { - name.remove(0, remove + hostHeader.length()); - } -} - -void ESPWebDAVCore::dir(const String& path, Print* out) { - dirAction( - path, true, - [out](int depth, const String& parent, WebDavFile& entry) -> bool { - (void)parent; - for (int i = 0; i < depth; i++) out->print(" "); - if (entry.isDirectory()) - out->printf("[%s]\n", entry.name()); - else - out->printf("%-40s%4dMiB %6dKiB %d\n", entry.name(), - ((int)entry.size() + (1 << 19)) >> 20, - ((int)entry.size() + (1 << 9)) >> 10, (int)entry.size()); - return true; - }, - /*false=subdir first*/ false); -} - -size_t ESPWebDAVCore::makeVirtual(virt_e v, String& internal) { - if (v == VIRT_PROC) { -#if defined(ARDUINO_ARCH_ESP8266) - internal = ESP.getFullVersion(); -#endif // ARDUINO_ARCH_ESP8266 -#if defined(ARDUINO_ARCH_ESP32) - internal = "SDK:"; - internal += ESP.getSdkVersion(); -#endif // ARDUINO_ARCH_ESP32 - internal += '\n'; - } - return internal.length(); -} - -ESPWebDAVCore::virt_e ESPWebDAVCore::isVirtual(const String& uri) { - const char* n = &(uri.c_str()[0]); - while (*n && *n == '/') { - n++; - } - if (strcmp(n, PROC) == 0) { - return VIRT_PROC; - } - return VIRT_NONE; -} - -bool ESPWebDAVCore::getPayload(StreamString& payload) { - log_esp3d("content length=%d", (int)contentLengthHeader); - payload.clear(); - if (contentLengthHeader > 0) { - payload.reserve(contentLengthHeader); - PolledTimeout timeout(HTTP_MAX_POST_WAIT); - while (payload.length() < (size_t)contentLengthHeader) { - uint8_t buf[16]; - auto n = - client->read(buf, std::min((size_t)client->available(), sizeof(buf))); - if (n <= 0 && timeout) { - log_esp3d("get content: short read (%d < %d)", (int)payload.length(), - (int)contentLengthHeader); - return false; - } - if (n > 0) { - payload.write(buf, n); - timeout.reset(); - } - } - log_esp3d(">>>>>>>>>>> CONTENT:"); - log_esp3ds("%s", payload.c_str()); - log_esp3ds("\n"); - log_esp3d("<<<<<<<<<<< CONTENT"); - } - return true; -} - -bool ESPWebDAVCore::dirAction( - const String& path, bool recursive, - const std::function& cb, - bool callAfter, int depth) { - log_esp3d("diraction: scanning dir '%s'", path.c_str()); - WebDavFile root = WebDavFS::open(path.c_str()); - WebDavFile entry = root.openNextFile(); - while (entry) { - if (!entry.isDirectory()) { - log_esp3d("diraction: %s/%s (%d B): ", path.c_str(), entry.name(), - (int)entry.size()); - if (cb(depth, path, entry)) { - log_esp3d("(file-OK)"); - } else { - log_esp3d("(file-abort)"); - entry.close(); - root.close(); - return false; - } - } - entry.close(); - entry = root.openNextFile(); - } - root.close(); - if (recursive) { - root = WebDavFS::open(path.c_str()); - entry = root.openNextFile(); - while (entry) { - if (entry.isDirectory()) { - log_esp3d("diraction: -------- %s/%s/", path.c_str(), entry.name()); - if ((callAfter || cb(depth, path, entry)) && - dirAction(path + '/' + entry.name(), recursive, cb, callAfter, - depth + 1) && - (!callAfter || cb(depth, path, entry))) { - log_esp3d("(dir-OK)"); - } else { - log_esp3d("(dir-abort)"); - entry.close(); - root.close(); - return false; - } - } - entry.close(); - entry = root.openNextFile(); - } - root.close(); - } - - return true; -} - -void ESPWebDAVCore::handleIssue(int code, const char* text) { - String message; - message.reserve(strlen(text) + uri.length() + method.length() + 32); - message += text; - message += "\nURI: "; - message += uri; - message += " Method: "; - message += method; - message += "\n"; - - String err; - err.reserve(strlen(text) + 32); - err += code; - err += ' '; - err += text; - - log_esp3d("Issue:\ncode=%d\ntext='%s'", code, text); - log_esp3d("message='%s'", message.c_str()); - log_esp3d("err='%s'", err.c_str()); - - send(err, "text/plain", message); -} - -void ESPWebDAVCore::handleRequest() { - payload.clear(); - replaceFront(uri, _davRoot, _fsRoot); - - ResourceType resource = RESOURCE_NONE; - - // check depth header - depth = DEPTH_NONE; - if (depthHeader.length()) { - if (depthHeader.equals("1")) { - depth = DEPTH_CHILD; - } else if (depthHeader.equals("infinity")) { - depth = DEPTH_ALL; - } - log_esp3d("Depth: %d", depth); - } - log_esp3d("URI: %s", uri.c_str()); - WebDavFile file; - if (WebDavFS::exists(uri.c_str()) || (uri == "/")) { - // does uri refer to a file or directory or a null? - file = WebDavFS::open(uri.c_str()); - if (file) { - resource = file.isDirectory() ? RESOURCE_DIR : RESOURCE_FILE; - log_esp3d("resource: '%s' is %s", uri.c_str(), - resource == RESOURCE_DIR ? "dir" : "file"); - } else { - log_esp3d("resource: '%s': no file nor dir", uri.c_str()); - } - } else { - log_esp3d("resource: '%s': not exists", uri.c_str()); - } - - log_esp3d("m: %s", method.c_str()); - log_esp3d(" r: %d", resource); - log_esp3d(" u: %s", uri.c_str()); - - // add header that gets sent everytime -#if WEBDAV_LOCK_SUPPORT - sendHeader("DAV", "1, 2"); -#else - sendHeader("DAV", "1"); -#endif - sendHeader("Accept-Ranges", "bytes"); - sendHeader("Allow", ALLOW); - - // handle file create/uploads - if (method.equals("PUT")) - // payload is managed - { - file.close(); - handlePut(resource); - return; - } - - // swallow content - if (!getPayload(payload)) { - handleIssue(408, "Request Time-out"); - client->stop(); - file.close(); - return; - } - - // handle properties - if (method.equals("PROPFIND")) { - handleProp(resource, file); - file.close(); - return; - } - - if (method.equals("GET")) { - handleGet(resource, file, true); - file.close(); - return; - } - - if (method.equals("HEAD")) { - handleGet(resource, file, false); - file.close(); - return; - } - - // handle options - if (method.equals("OPTIONS")) { - file.close(); - handleOptions(resource); - return; - } - -#if WEBDAV_LOCK_SUPPORT - // handle file locks - if (method.equals("LOCK")) { - file.close(); - handleLock(resource); - return; - } - - if (method.equals("UNLOCK")) { - file.close(); - handleUnlock(resource); - return; - } -#endif - - if (method.equals("PROPPATCH")) { - handlePropPatch(resource, file); - file.close(); - return; - } - - // directory creation - if (method.equals("MKCOL")) { - file.close(); - handleDirectoryCreate(resource); - return; - } - - // move a file or directory - if (method.equals("MOVE")) { - handleMove(resource, file); - file.close(); - return; - } - - // delete a file or directory - if (method.equals("DELETE")) { - file.close(); - handleDelete(resource); - return; - } - - // delete a file or directory - if (method.equals("COPY")) { - handleCopy(resource, file); - file.close(); - return; - } - - // if reached here, means its a unhandled - handleIssue(404, "Not found"); - file.close(); - // return false; -} - -void ESPWebDAVCore::handleOptions(ResourceType resource) { - (void)resource; - log_esp3d("Processing OPTION"); - send("200 OK", NULL, ""); -} - -#if WEBDAV_LOCK_SUPPORT - -void ESPWebDAVCore::handleLock(ResourceType resource) { - log_esp3d("Processing LOCK"); - - // does URI refer to an existing resource - (void)resource; - log_esp3d("r=%d/%d", resource, RESOURCE_NONE); - -#if WEBDAV_LOCK_SUPPORT > 1 - // lock owner - uint32_t hpash, ownash; - if (ifHeader.length()) { - int code; - if ((code = extractLockToken(ifHeader, "(<", ">", hpash, ownash)) != 200) { - return handleIssue(code, "Lock error"); - } - } else { - int startIdx, endIdx; - startIdx = payload.indexOf(""); - endIdx = payload.indexOf(""); - ownash = startIdx > 0 && endIdx > 0 - ? crc32(&payload[startIdx + 7], endIdx - startIdx - 7) - : 0; - } - - if (!ownash) { - /* XXXFIXME xml extraction should be improved (on macOS) - 0:10:08.058253: - 0:10:08.058391: http://www.apple.com/webdav_fs/ - 0:10:08.058898: - */ - ownash = 0xdeadbeef; - } - uint32_t pash = crc32(uri.c_str(), uri.length()); - const auto& lock = _locks.find(pash); - if (lock == _locks.end()) { - _locks[pash] = ownash; - } else { - if (lock->second != ownash) { - log_esp3d("cannot relock '%s' (owner is 0x%08x)", uri.c_str(), - lock->second); - return handleIssue(423, "Locked"); - } - log_esp3d("owner has relocked"); - } -#else - const char* lock_token = "0"; -#endif - - String lock_token; - makeToken(lock_token, pash, ownash); - sendHeader("Lock-Token", lock_token); - -#if 1 - String resp; - resp.reserve(500 + uri.length()); - resp += - F("" - "" - "" - "" - "" - ""); - resp += lock_token; - resp += - F("" - "" -#if 0 - "" - "" - "" - "" - "" - "" - "" - ""); - resp += uri; - resp += F("" - "" - "" - "infinity" - ""); -#if 0 - if (href.length()) { - resp += F("" - ""); - resp += href; - resp += F("" - ""); - } -#endif - resp += F("" - "Second-3600" - "" -#endif - "" - "" - ""); - send("200 OK", "application/xml;charset=utf-8", resp); -#else - send("200 OK", "application/xml;charset=utf-8", ""); -#endif -} - -void ESPWebDAVCore::handleUnlock(ResourceType resource) { -#if WEBDAV_LOCK_SUPPORT > 1 - uint32_t pash = crc32(uri.c_str(), uri.length()); - - uint32_t hpash, hownash; - (void)extractLockToken(lockTokenHeader, "<", ">", hpash, hownash); - - auto lock = _locks.find(pash); - if (lock == _locks.end()) { - log_esp3d("wasn't locked: '%s'", uri.c_str()); - return handleIssue(423, "Locked"); - } - if (lock->second != hownash) { - log_esp3d("lock found, bad owner 0x%08x != 0x%08x", hownash, lock->second); - return handleIssue(423, "Locked"); - } - _locks.erase(lock); -#endif - - (void)resource; - log_esp3d("Processing UNLOCK"); - send("204 No Content", NULL, ""); -} - -#endif // WEBDAV_LOCK_SUPPORT - -void ESPWebDAVCore::handlePropPatch(ResourceType resource, WebDavFile& file) { - log_esp3d("PROPPATCH forwarding to PROPFIND"); - handleProp(resource, file); -} - -void ESPWebDAVCore::handleProp(ResourceType resource, WebDavFile& file) { - log_esp3d("Processing PROPFIND"); - auto v = isVirtual(uri); - - if (v) { - resource = RESOURCE_FILE; - } - // does URI refer to an existing resource - else if (resource == RESOURCE_NONE) { - return handleIssue(404, "Not found"); - } - - int code; - if (payload.indexOf("lockdiscovery") < 0 && (code = allowed(uri)) != 200) { - return handleIssue(code, "Locked"); - } - - setContentLength(CONTENT_LENGTH_UNKNOWN); - send("207 Multi-Status", "application/xml;charset=utf-8", ""); - sendContent(F("")); - sendContent(F("")); - - if (v) { - // virtual file - sendPropResponse(false, uri.c_str(), 1024, time(nullptr), 0); - } else if (!file.isDirectory() || depth == DEPTH_NONE) { - log_esp3d("----- PROP FILE '%s':", uri.c_str()); - sendPropResponse(file.isDirectory(), uri.c_str(), file.size(), - file.getLastWrite(), file.getLastWrite()); - } else { - log_esp3d("----- PROP DIR '%s':", uri.c_str()); - sendPropResponse(true, uri, 0, time(nullptr), 0); - - WebDavFile root = WebDavFS::open(uri.c_str()); - WebDavFile entry = root.openNextFile(); - while (entry) { - yield(); - String path; - path.reserve(uri.length() + 1 + strlen(entry.name())); - path += uri; - path += '/'; - path += entry.name(); - stripSlashes(path); - log_esp3d("Path: %s", path.c_str()); - sendPropResponse(entry.isDirectory(), path.c_str(), entry.size(), - entry.getLastWrite(), entry.getLastWrite()); - entry.close(); - entry = root.openNextFile(); - } - root.close(); - } - if (payload.indexOf(F("quota-available-bytes")) >= 0 || - payload.indexOf(F("quota-used-bytes")) >= 0) { - sendContentProp( - F("quota-available-bytes"), - String(1.0 * (WebDavFS::totalBytes() - WebDavFS::usedBytes()), 0)); - sendContentProp(F("quota-used-bytes"), - String(1.0 * WebDavFS::usedBytes(), 0)); - } - sendContent(F("")); -} - -void ESPWebDAVCore::sendContentProp(const String& what, - const String& response) { - String one; - one.reserve(100 + 2 * what.length() + response.length()); - one += F(""); - one += response; - one += F(""); - sendContent(one); -} - -String ESPWebDAVCore::date2date(time_t date) { - // get & convert time to required format - // Tue, 13 Oct 2015 17:07:35 GMT - tm* gTm = gmtime(&date); - char buf[40]; - snprintf(buf, sizeof(buf), "%s, %02d %s %04d %02d:%02d:%02d GMT", - wdays[gTm->tm_wday], gTm->tm_mday, months[gTm->tm_mon], - gTm->tm_year + 1900, gTm->tm_hour, gTm->tm_min, gTm->tm_sec); - return buf; -} - -void ESPWebDAVCore::sendPropResponse(bool isDir, const String& fullResPathFS, - size_t size, time_t lastWrite, - time_t creationDate) { - String fullResPath = fullResPathFS; - replaceFront(fullResPath, _fsRoot, _davRoot); - fullResPath = c2enc(fullResPath); - String blah; - blah.reserve(100); - blah += F(""); - blah += fullResPath; - blah += - F("HTTP/1.1 200 OK"); - sendContent(blah); - - sendContentProp(F("getlastmodified"), date2date(lastWrite)); - sendContentProp(F("creationdate"), date2date(creationDate)); - - log_esp3d("-----\nentry: '%s'(dir:%d)\n-----", fullResPath.c_str(), isDir); - - if (isDir) { - sendContentProp(F("resourcetype"), F("")); - } else { - sendContentProp(F("getcontentlength"), String(size)); - sendContentProp(F("getcontenttype"), contentTypeFn(fullResPath)); - - sendContent(""); - - char entityTag[uri.length() + 32]; - sprintf(entityTag, "%s%lu", uri.c_str(), (unsigned long)lastWrite); - uint32_t crc = crc32(entityTag, strlen(entityTag)); - sprintf(entityTag, "\"%08x\"", crc); - sendContentProp(F("getetag"), entityTag); - } - - sendContentProp(F("displayname"), fullResPath); - - sendContent(F("")); -} - -void ESPWebDAVCore::handleGet(ResourceType resource, WebDavFile& file, - bool isGet) { - log_esp3d("Processing GET (ressource=%d)", (int)resource); - - // does URI refer to an existing file resource - auto v = isVirtual(uri); - if (!v) { - if (resource == RESOURCE_DIR) { - return handleIssue(200, "GET/HEAD on dir"); - } - if (resource != RESOURCE_FILE) { - return handleIssue(404, "Not found"); - } - } - - // no lock on GET - -#if defined(ESP_LOG_FEATURE) - long tStart = millis(); -#endif - - size_t fileSize = file.size(); - String contentType = contentTypeFn(uri); - if (uri.endsWith(".gz") && contentType != "application/x-gzip" && - contentType != "application/octet-stream") { - sendHeader("Content-Encoding", "gzip"); - } - - String internal = emptyString; - if (v) { - fileSize = makeVirtual(v, internal); - } else if (!fileSize) { - setContentLength(0); - send("200 OK", contentType.c_str(), ""); - log_esp3d("send empty file"); - return; - } - - char buf[BUFFER_SIZE]; /// XXX use stream::to(): file.to(client); - - // Content-Range: bytes 0-1023/146515 - // Content-Length: 1024 - - int remaining; - if (_rangeStart == 0 && (_rangeEnd < 0 || _rangeEnd == (int)fileSize - 1)) { - _rangeEnd = fileSize - 1; - remaining = fileSize; - setContentLength(remaining); - send("200 OK", contentType.c_str(), ""); - } else { - if (_rangeEnd == -1 || _rangeEnd >= (int)fileSize) { - _rangeEnd = _rangeStart + (2 * TCP_MSS - 100); - if (_rangeEnd >= (int)fileSize) { - _rangeEnd = fileSize - 1; - } - } - snprintf(buf, sizeof(buf), "bytes %d-%d/%d", _rangeStart, _rangeEnd, - (int)fileSize); - sendHeader("Content-Range", buf); - remaining = _rangeEnd - _rangeStart + 1; - setContentLength(remaining); - send("206 Partial Content", contentType.c_str(), ""); - } - - if (isGet && (internal.length() || file.seek(_rangeStart))) { - log_esp3d("GET: (%d bytes)", remaining); - - if (internal.length()) { - if (transferStatusFn) { - transferStatusFn(file.name(), (100 * _rangeStart) / fileSize, false); - } - if (client->write(&internal.c_str()[_rangeStart], remaining) != - (size_t)remaining) { - log_esp3d("file->net short transfer"); - } else if (transferStatusFn) { - transferStatusFn(file.name(), - (100 * (_rangeStart + remaining)) / fileSize, false); - } - } else { - if (transferStatusFn) { - transferStatusFn(file.name(), 0, false); - } - int percent = 0; - - while (remaining > 0 && file.available()) { - size_t toRead = - (size_t)remaining > sizeof(buf) ? sizeof(buf) : remaining; - size_t numRead = file.read((uint8_t*)buf, toRead); - log_esp3d("read %d bytes from file", (int)numRead); - - if (client->write(buf, numRead) != numRead) { - log_esp3d("file->net short transfer"); - break; - } - -#if defined(ESP_LOG_FEATURE) - for (size_t i = 0; i < 80 && i < numRead; i++) { - log_esp3ds("%c", buf[i] < 32 || buf[i] > 127 ? '.' : buf[i]); - } -#endif - - remaining -= numRead; - if (transferStatusFn) { - int p = (100 * (file.size() - remaining)) / file.size(); - if (p != percent) { - transferStatusFn(file.name(), percent = p, false); - } - } - log_esp3d("wrote %d bytes to http client", (int)numRead); - } - } - } - - log_esp3d("File %d bytes sent in: %d sec", fileSize, - (millis() - tStart) / 1000); -} - -void ESPWebDAVCore::handlePut(ResourceType resource) { - log_esp3d("Processing Put"); - - // does URI refer to a directory - if (resource == RESOURCE_DIR) { - return handleIssue(404, "Not found"); - } - - int code; - if ((code = allowed(uri)) != 200) { - return handleIssue(code, "Lock error"); - } - - WebDavFile file; - stripName(uri); - log_esp3d("create file '%s'", uri.c_str()); - String s = uri; - if (uri[0] != '/') { - s = "/" + uri; - } - log_esp3d("Create file %s", s.c_str()); - if (!(file = WebDavFS::open(s.c_str(), ESP_FILE_WRITE))) { - return handleWriteError("Unable to create a new file", file); - } - - // file is created/open for writing at this point - // did server send any data in put - log_esp3d("%s - ready for data (%i bytes)", uri.c_str(), - (int)contentLengthHeader); - - if (contentLengthHeader != 0) { - uint8_t buf[BUFFER_SIZE]; -#if defined(ESP_LOG_FEATURE) - long tStart = millis(); -#endif - size_t numRemaining = contentLengthHeader; - - if (transferStatusFn) { - transferStatusFn(file.name(), 0, true); - } - int percent = 0; - - // read data from stream and write to the file - while (numRemaining > 0) { - size_t numToRead = numRemaining; - if (numToRead > sizeof(buf)) { - numToRead = sizeof(buf); - } - auto numRead = readBytesWithTimeout(buf, numToRead); - if (numRead == 0) { - break; - } - - size_t written = 0; - while (written < numRead) { - auto numWrite = file.write(buf + written, numRead - written); - if (numWrite == 0 || (int)numWrite == -1) { - log_esp3d("error: numread=%d write=%d written=%d", (int)numRead, - (int)numWrite, (int)written); - file.close(); - return handleWriteError("Write data failed", file); - } - written += numWrite; - } - - // reduce the number outstanding - numRemaining -= numRead; - if (transferStatusFn) { - int p = - (100 * (contentLengthHeader - numRemaining)) / contentLengthHeader; - if (p != percent) { - transferStatusFn(file.name(), percent = p, true); - } - } - } - - // detect timeout condition - if (numRemaining) { - file.close(); - return handleWriteError("Timed out waiting for data", file); - } - - log_esp3d("File %d bytes stored in: %d sec", - (contentLengthHeader - numRemaining), - ((millis() - tStart) / 1000)); - } - file.close(); - log_esp3d("file written ('%s': %d = %d bytes)", String(file.name()).c_str(), - (int)contentLengthHeader, (int)file.size()); - - if (resource == RESOURCE_NONE) { - send("201 Created", NULL, ""); - } else { - send("200 OK", NULL, ""); - } -} - -void ESPWebDAVCore::handleWriteError(const String& message, WebDavFile& file) { - // close this file - file.close(); - // delete the wrile being written - WebDavFS::remove(uri.c_str()); - // send error - send("500 Internal Server Error", "text/plain", message); - log_esp3d("%s", message.c_str()); -} - -void ESPWebDAVCore::handleDirectoryCreate(ResourceType resource) { - log_esp3d("Processing MKCOL (r=%d uri='%s' cl=%d)", (int)resource, - uri.c_str(), (int)contentLengthHeader); - - if (contentLengthHeader) { - return handleIssue(415, "Unsupported Media Type"); - } - - // does URI refer to anything - if (resource != RESOURCE_NONE) { - return handleIssue(405, "Not allowed"); - } - - int parentLastIndex = uri.lastIndexOf('/'); - if (parentLastIndex > 0) { - WebDavFile testParent = - WebDavFS::open(uri.substring(0, parentLastIndex).c_str()); - if (!testParent.isDirectory()) { - testParent.close(); - return handleIssue(409, "Conflict"); - } - testParent.close(); - } - - if (!WebDavFS::mkdir(uri.c_str())) { - // send error - send("500 Internal Server Error", "text/plain", - "Unable to create directory"); - log_esp3d("Unable to create directory"); - return; - } - - log_esp3d("%s directory created", uri.c_str()); - send("201 Created", NULL, ""); -} - -String ESPWebDAVCore::urlToUri(const String& url) { - int index; - if (url.startsWith("http") && (index = url.indexOf("://")) <= 5) { - int uriStart = url.indexOf('/', index + 3); - return url.substring(uriStart); - } - return url; -} - -void ESPWebDAVCore::handleMove(ResourceType resource, WebDavFile& src) { - const char* successCode = "201 Created"; - - log_esp3d("Processing MOVE"); - - // does URI refer to anything - if (resource == RESOURCE_NONE || destinationHeader.length() == 0) { - return handleIssue(404, "Not found"); - } - - String dest = enc2c(urlToUri(destinationHeader)); - stripHost(dest); - stripSlashes(dest); - stripName(dest); - replaceFront(dest, _davRoot, _fsRoot); - log_esp3d("Move destination: %s", dest.c_str()); - - int code; - if ((code = allowed(uri)) != 200 || (code = allowed(dest)) != 200) { - return handleIssue(code, "Locked"); - } - - WebDavFile destFile; - if (WebDavFS::exists(dest.c_str()) || (dest == "/")) { - destFile = WebDavFS::open(dest.c_str()); - } - if (destFile && destFile.isDirectory()) { - dest += '/'; - dest += src.name(); - stripSlashes(dest); - stripName(dest); - destFile.close(); - destFile = WebDavFS::open(dest.c_str()); - successCode = "204 No Content"; // MOVE to existing collection resource - // didn't give 204 - } - - if (destFile) { - if (overwrite.equalsIgnoreCase("F")) { - destFile.close(); - return handleIssue(412, "Precondition Failed"); - } - if (destFile.isDirectory()) { - destFile.close(); - deleteDir(dest); - } else { - destFile.close(); - WebDavFS::remove(dest.c_str()); - } - } - - src.close(); - - log_esp3d("finally rename '%s' -> '%s'", uri.c_str(), dest.c_str()); - - if (!WebDavFS::rename(uri.c_str(), dest.c_str())) { - // send error - send("500 Internal Server Error", "text/plain", "Unable to move"); - log_esp3d("Unable to move file/directory"); - return; - } - - log_esp3d("Move successful"); - send(successCode, NULL, ""); -} - -bool ESPWebDAVCore::mkFullDir(String fullDir) { - bool ret = true; - stripSlashes(fullDir); - int idx = 0; - while (idx != -1) { - idx = fullDir.indexOf('/', idx + 1); - String part = idx == -1 ? /*last part*/ fullDir : fullDir.substring(0, idx); - if (!WebDavFS::mkdir(part.c_str())) { - ret = false; - break; - } - } - return ret; -} - -bool ESPWebDAVCore::deleteDir(const String& dir) { - dirAction( - dir, true, - [this](int depth, const String& parent, WebDavFile& entry) -> bool { - (void)depth; - String toRemove; - toRemove.reserve(parent.length() + strlen(entry.name()) + 2); - toRemove += parent; - toRemove += '/'; - toRemove += entry.name(); - bool ok = !!(entry.isDirectory() ? WebDavFS::rmdir(toRemove.c_str()) - : WebDavFS::remove(toRemove.c_str())); - log_esp3d("DELETE %s %s: %s", entry.isDirectory() ? "[ dir]" : "[file]", - toRemove.c_str(), ok ? "ok" : "bad"); - return ok; - }); - - log_esp3d("delete dir '%s'", uri.c_str()); - WebDavFS::rmdir(uri.c_str()); - return true; -} - -void ESPWebDAVCore::handleDelete(ResourceType resource) { - log_esp3d("Processing DELETE '%s'", uri.c_str()); - - // does URI refer to anything - if (resource == RESOURCE_NONE) { - return handleIssue(404, "Not found"); - } - - int code; - if ((code = allowed(uri)) != 200) { - return handleIssue(code, "Locked"); - } - - bool retVal; - if (resource == RESOURCE_FILE) - // delete a file - { - log_esp3d("DELETE file '%s'", uri.c_str()); - retVal = WebDavFS::remove(uri.c_str()); - } else { - log_esp3d("DELETE dir '%s'", uri.c_str()); - retVal = deleteDir(uri); - } - - // for some reason, parent dir can be removed if empty - // need to leave it there (also to pass compliance tests). - int parentIdx = uri.lastIndexOf('/'); - uri.remove(parentIdx); - mkFullDir(uri); - - if (!retVal) { - // send error - send("500 Internal Server Error", "text/plain", "Unable to delete"); - log_esp3d("Unable to delete file/directory"); - return; - } - - log_esp3d("Delete successful"); - send("200 OK", NULL, ""); -} - -bool ESPWebDAVCore::copyFile(WebDavFile srcFile, const String& destName) { - WebDavFile dest; - if (overwrite.equalsIgnoreCase("F")) { - if (WebDavFS::exists(destName.c_str())) { - log_esp3d("copy dest '%s' already exists and overwrite is false", - destName.c_str()); - handleIssue(412, "Precondition Failed"); - return false; - } - } - String s = destName; - if (destName[0] != '/') { - s = "/" + destName; - } - dest = WebDavFS::open(s.c_str(), ESP_FILE_WRITE); - log_esp3d("Create file %s", s.c_str()); - if (!dest) { - handleIssue(413, "Request Entity Too Large"); - return false; - } - while (srcFile.available()) { - /// XXX USE STREAMTO - yield(); - char cp[128]; - int nb = srcFile.read((uint8_t*)cp, sizeof(cp)); - if (!nb) { - log_esp3d("copy: short read"); - handleIssue(500, "Internal Server Error"); - dest.close(); - return false; - } - int wr = dest.write((const uint8_t*)cp, nb); - if (wr != nb) { - log_esp3d("copy: short write wr=%d != rd=%d", (int)wr, (int)nb); - handleIssue(500, "Internal Server Error"); - dest.close(); - return false; - } - } - dest.close(); - return true; -} - -void ESPWebDAVCore::handleCopy(ResourceType resource, WebDavFile& src) { - const char* successCode = "201 Created"; - - log_esp3d("Processing COPY"); - - if (resource == RESOURCE_NONE) { - return handleIssue(404, "Not found"); - } - - if (!src) { // || resource != RESOURCE_FILE) - return handleIssue(413, "Request Entity Too Large"); - } - - String destParentPath = destinationHeader; - { - int j = -1; - for (int i = 0; i < 3; i++) { - j = destParentPath.indexOf('/', j + 1); - } - destParentPath.remove(0, j); - } - - String destPath = destParentPath; - if (destPath.length()) { - if (destPath[destPath.length() - 1] == '/') { - // add file name - destPath += src.name(); - successCode = "204 No Content"; // COPY to existing resource should give - // 204 (RFC2518:S8.8.5) - } else { - // remove last part - int lastSlash = destParentPath.lastIndexOf('/'); - if (lastSlash > 0) { - destParentPath.remove(lastSlash); - } - } - } - replaceFront(destPath, _davRoot, _fsRoot); - replaceFront(destParentPath, _davRoot, _fsRoot); - - log_esp3d("copy: src='%s'=>'%s' dest='%s'=>'%s' parent:'%s'", uri.c_str(), - src.filename(), destinationHeader.c_str(), destPath.c_str(), - destParentPath.c_str()); - WebDavFile destParent = WebDavFS::open(destParentPath.c_str()); - - stripName(destPath); - int code; - if (/*(code = allowed(uri)) != 200 ||*/ (code = allowed(destParentPath)) != - 200 || - (code = allowed(destPath)) != 200) { - destParent.close(); - return handleIssue(code, "Locked"); - } - - // copy directory - if (src.isDirectory()) { - log_esp3d("Source is directory"); - if (!destParent.isDirectory()) { - log_esp3d("'%s' is not a directory", destParentPath.c_str()); - destParent.close(); - return handleIssue(409, "Conflict"); - } - - if (!dirAction(src.filename(), depth == DEPTH_ALL, - [this, destParentPath](int depth, const String& parent, - WebDavFile& source) -> bool { - (void)depth; - (void)parent; - String destNameX = destParentPath + '/'; - destNameX += source.name(); - stripName(destNameX); - log_esp3d("COPY: '%s' -> '%s", source.name(), - destNameX.c_str()); - WebDavFile orifile = WebDavFS::open(source.name()); - bool res = copyFile(orifile, destNameX); - orifile.close(); - return res; - // return copyFile(WebDavFS::open(source.name()), - // destNameX); - })) { - destParent.close(); - return; // handleIssue already called by failed copyFile() - // handleIssue(409, "Conflict"); - } - } else { - log_esp3d("Source is file"); - - // (COPY into non-existant collection '/litmus/nonesuch' succeeded) - if (!destParent || !destParent.isDirectory()) { - log_esp3d("dest dir '%s' not existing", destParentPath.c_str()); - destParent.close(); - return handleIssue(409, "Conflict"); - } - - // copy file - - if (!copyFile(src, destPath)) { - return; - } - } - - log_esp3d("COPY successful"); - send(successCode, NULL, ""); -} - -void ESPWebDAVCore::_prepareHeader(String& response, const String& code, - const char* content_type, - size_t contentLength) { - response = "HTTP/1.1 " + code + "\r\n"; - - if (content_type) { - sendHeader("Content-Type", content_type, true); - } - - if ((size_t)_contentLengthAnswer == CONTENT_LENGTH_NOT_SET) { - sendHeader("Content-Length", String(contentLength)); - } else if ((size_t)_contentLengthAnswer != CONTENT_LENGTH_UNKNOWN) { - sendHeader("Content-Length", String(_contentLengthAnswer)); - } else { // if ((size_t)_contentLengthAnswer == CONTENT_LENGTH_UNKNOWN) - _chunked = true; - // sendHeader("Accept-Ranges", "none"); - sendHeader("Transfer-Encoding", "chunked"); - } - if (m_persistent) { - sendHeader("Connection", "keep-alive"); - } else { - sendHeader("Connection", "close"); - } - - response += _responseHeaders; - response += "\r\n"; -} - -bool ESPWebDAVCore::parseRequest(const String& givenMethod, - const String& givenUri, - WiFiClient* givenClient, - ContentTypeFunction givenContentTypeFn) { - method = givenMethod; - uri = enc2c(givenUri); - stripSlashes(uri); - client = givenClient; - contentTypeFn = givenContentTypeFn; - uint8_t fsType = WebDavFS::getFSType(uri.c_str()); - - log_esp3d("############################################"); - log_esp3d(">>>>>>>>>> RECV"); - - log_esp3d("method: %s", method.c_str()); - log_esp3d(" url: %s", uri.c_str()); - log_esp3d(" FS: %d", fsType); - // parse and finish all headers - String headerName; - String headerValue; - _rangeStart = 0; - _rangeEnd = -1; - - log_esp3d("INPUT"); - // no new client is waiting, allow more time to current client - m_persistent_timer_ms = millis(); - - m_persistent = false; // ((millis() - m_persistent_timer_ms) < - // m_persistent_timer_init_ms); - - // reset all variables - _chunked = false; - _responseHeaders.clear(); - _contentLengthAnswer = (int)CONTENT_LENGTH_NOT_SET; - contentLengthHeader = 0; - depthHeader.clear(); - hostHeader.clear(); - destinationHeader.clear(); - overwrite.clear(); - ifHeader.clear(); - lockTokenHeader.clear(); - bool fsAvailable = true; - if (WebDavFS::accessFS(fsType)) { -#if WEBDAV_FEATURE == FS_SD - // if not global FS and FS is SD, need to manually check/set the SD card - // state - if (WebDavFS::getState(true) == ESP_SDCARD_NOT_PRESENT) { - fsAvailable = false; - } else { - ESP_SD::setState(ESP_SDCARD_BUSY); - } -#endif // WEBDAV_FEATURE == FS_SD - if (fsAvailable) { - while (1) { - String req = client->readStringUntil('\r'); - client->readStringUntil('\n'); - if (req == "") - // no more headers - { - break; - } - - int headerDiv = req.indexOf(':'); - if (headerDiv == -1) { - break; - } - - headerName = req.substring(0, headerDiv); - headerValue = req.substring(headerDiv + 2); - log_esp3d("\t%s: %s", headerName.c_str(), headerValue.c_str()); - - if (headerName.equalsIgnoreCase("Host")) { - hostHeader = headerValue; - } else if (headerName.equalsIgnoreCase("Depth")) { - depthHeader = headerValue; - } else if (headerName.equalsIgnoreCase("Content-Length")) { - contentLengthHeader = headerValue.toInt(); - } else if (headerName.equalsIgnoreCase("Destination")) { - destinationHeader = headerValue; - } else if (headerName.equalsIgnoreCase("Range")) { - processRange(headerValue); - } else if (headerName.equalsIgnoreCase("Overwrite")) { - overwrite = headerValue; - } else if (headerName.equalsIgnoreCase("If")) { - ifHeader = headerValue; - } else if (headerName.equalsIgnoreCase("Lock-Token")) { - lockTokenHeader = headerValue; - } - } - log_esp3d("<<<<<<<<<< RECV"); - handleRequest(); - } else { - handleIssue(404, "Not found"); - } - WebDavFS::releaseFS(fsType); - } else { - handleIssue(404, "Not found"); - } - - // finalize the response - if (_chunked) { - sendContent(""); - } - - return true; -} - -size_t ESPWebDAVCore::readBytesWithTimeout(uint8_t* buf, size_t size) { - size_t where = 0; - - while (where < size) { - int timeout_ms = HTTP_MAX_POST_WAIT; - while (!client->available() && client->connected() && timeout_ms--) { - delay(1); - } - - if (!client->available()) { - break; - } - - where += client->read(buf + where, size - where); - } - - return where; -} - -void ESPWebDAVCore::sendHeader(const String& name, const String& value, - bool first) { - String headerLine = name + ": " + value + "\r\n"; - - if (first) { - _responseHeaders = headerLine + _responseHeaders; - } else { - _responseHeaders += headerLine; - } -} - -void ESPWebDAVCore::send(const String& code, const char* content_type, - const String& content) { - String header; - _prepareHeader(header, code, content_type, content.length()); - - client->write(header.c_str(), header.length()); - - // log_esp3d(">>>>>>>>>> SENT"); - // log_esp3d("---- header: \n%s", header.c_str()); - - if (content.length()) { - sendContent(content); -#if defined(ESP_LOG_FEATURE) - log_esp3d("send content (%d bytes):", (int)content.length()); - for (size_t i = 0; i < DEBUG_LEN && i < content.length(); i++) { - log_esp3ds("%c", content[i] < 32 || content[i] > 127 ? '.' : content[i]); - } - if (content.length() > DEBUG_LEN) { - log_esp3ds("..."); - } - log_esp3ds("\n"); -#endif - } - // log_esp3d("<<<<<<<<<< SENT"); -} - -bool ESPWebDAVCore::sendContent(const String& content) { - return sendContent(content.c_str(), content.length()); -} - -bool ESPWebDAVCore::sendContent(const char* data, size_t size) { - if (_chunked) { - char chunkSize[32]; - snprintf(chunkSize, sizeof(chunkSize), "%x\r\n", (int)size); - size_t l = strlen(chunkSize); - if (client->write(chunkSize, l) != l) { - return false; - } - log_esp3d("---- chunk %s", chunkSize); - } - -#if defined(ESP_LOG_FEATURE) - log_esp3d("---- %scontent (%d bytes):", _chunked ? "chunked " : "", - (int)size); - for (size_t i = 0; i < DEBUG_LEN && i < size; i++) { - log_esp3ds("%c", data[i] < 32 || data[i] > 127 ? '.' : data[i]); - } - if (size > DEBUG_LEN) { - log_esp3ds("..."); - } - log_esp3ds("\n"); -#endif - - if (client->write(data, size) != size) { - log_esp3d("SHORT WRITE"); - return false; - } - - if (_chunked) { - if (client->write("\r\n", 2) != 2) { - log_esp3d("SHORT WRITE 2"); - return false; - } - if (size == 0) { - log_esp3d("END OF CHUNKS"); - _chunked = false; - } - } - - log_esp3d("OK with sendContent"); - return true; -} - -bool ESPWebDAVCore::sendContent_P(PGM_P content) { - const char* footer = "\r\n"; - size_t size = strlen_P(content); - - if (_chunked) { - char chunkSize[32]; - snprintf(chunkSize, sizeof(chunkSize), "%x%s", (int)size, footer); - size_t l = strlen(chunkSize); - if (client->write(chunkSize, l) != l) { - return false; - } - } - - if (client->write_P(content, size) != size) { - log_esp3d("SHORT WRITE"); - return false; - } - - if (_chunked) { - if (client->write(footer, 2) != 2) { - log_esp3d("SHORT WRITE 2"); - return false; - } - if (size == 0) { - log_esp3d("END OF CHUNKS"); - _chunked = false; - } - } - - log_esp3d("OK with sendContent_P"); - return true; -} - -void ESPWebDAVCore::setContentLength(size_t len) { _contentLengthAnswer = len; } - -void ESPWebDAVCore::processRange(const String& range) { - // "Range": "bytes=0-5" - // "Range": "bytes=0-" - - size_t i = 0; - while (i < range.length() && (range[i] < '0' || range[i] > '9')) { - i++; - } - size_t j = i; - while (j < range.length() && range[j] >= '0' && range[j] <= '9') { - j++; - } - if (j > i) { - _rangeStart = atoi(&range.c_str()[i]); - if (range.c_str()[j + 1]) { - _rangeEnd = atoi(&range.c_str()[j + 1]); - } else { - _rangeEnd = -1; - } - } - log_esp3d("Range: %d -> %d", _rangeStart, _rangeEnd); -} - -int ESPWebDAVCore::htoi(char c) { - c = tolower(c); - return c >= '0' && c <= '9' ? c - '0' - : c >= 'a' && c <= 'f' ? c - 'a' + 10 - : -1; -} - -char ESPWebDAVCore::itoH(int c) { return c <= 9 ? c + '0' : c - 10 + 'A'; } - -int ESPWebDAVCore::hhtoi(const char* c) { - int h = htoi(*c); - int l = htoi(*(c + 1)); - return h < 0 || l < 0 ? -1 : (h << 4) + l; -} - -String ESPWebDAVCore::enc2c(const String& encoded) { - int v; - String ret; - ret.reserve(encoded.length()); - for (size_t i = 0; i < encoded.length(); i++) { - if (encoded[i] == '%' && (i + 3) <= encoded.length() && - (v = hhtoi(encoded.c_str() + i + 1)) > 0) { - ret += v; - i += 2; - } else { - ret += encoded[i]; - } - } - return ret; -} - -String ESPWebDAVCore::c2enc(const String& decoded) { - size_t l = decoded.length(); - for (size_t i = 0; i < decoded.length(); i++) { - if (!notEncodable(decoded[i])) { - l += 2; - } - } - String ret; - ret.reserve(l); - for (size_t i = 0; i < decoded.length(); i++) { - char c = decoded[i]; - if (notEncodable(c)) { - ret += c; - } - - else { - ret += '%'; - ret += itoH(c >> 4); - ret += itoH(c & 0xf); - } - } - return ret; -} - -bool ESPWebDAVCore::notEncodable(char c) { return c > 32 && c < 127; } - -void ESPWebDAVCore::replaceFront(String& str, const String& from, - const String& to) { - if (from.length() && to.length() && str.indexOf(from) == 0) { - String repl; - repl.reserve(str.length() + to.length() - from.length() + 1); - repl = to; - size_t skip = from.length() == 1 ? 0 : from.length(); - repl += str.c_str() + skip; - str = repl; - stripSlashes(str); - } -} - -#endif // WEBDAV_FEATURE diff --git a/esp3d/src/modules/webdav/ESPWebDAV.h b/esp3d/src/modules/webdav/ESPWebDAV.h deleted file mode 100644 index 186b3be3..00000000 --- a/esp3d/src/modules/webdav/ESPWebDAV.h +++ /dev/null @@ -1,262 +0,0 @@ -/* - Copyright (c) 2018 Gurpreet Bal https://github.com/ardyesp/ESPWebDAV - Copyright (c) 2020 David Gauchard https://github.com/d-a-v/ESPWebDAV - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - 3. The name of the author may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED - WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT - SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT - OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING - IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY - OF SUCH DAMAGE. - -*/ - -#ifndef __ESPWEBDAV_H -#define __ESPWEBDAV_H - -#if defined(WEBDAV_LOCK_SUPPORT) || defined(DBG_WEBDAV) -#error WEBDAV_LOCK_SUPPORT or DBG_WEBDAV: cannot be defined by user -#endif - -// LOCK support is not mandatory -// WEBDAV_LOCK_SUPPORT -// = 0: no support -// = 1: fake support -// > 1: supported with a std::map<> -#define WEBDAV_LOCK_SUPPORT 2 - -// constants for WebServer -#define CONTENT_LENGTH_UNKNOWN ((size_t) -1) -#define CONTENT_LENGTH_NOT_SET ((size_t) -2) -#define HTTP_MAX_POST_WAIT 5000 - -#if WEBDAV_LOCK_SUPPORT > 1 -#include -#endif -#include -#include -#include "../../include/esp3d_config.h" -class WiFiServer; -class WiFiClient; - -#if WEBDAV_FEATURE == FS_ROOT -#include "../filesystem/esp_globalFS.h" -typedef ESP_GBFile WebDavFile; -typedef ESP_GBFS WebDavFS; -#endif //WEBDAV_FEATURE == FS_ROOT - -#if WEBDAV_FEATURE == FS_FLASH -#include "../filesystem/esp_filesystem.h" -typedef ESP_File WebDavFile; -typedef ESP_FileSystem WebDavFS; -#endif //WEBDAV_FEATURE == FS_FLASH - -#if WEBDAV_FEATURE == FS_SD -#include "../filesystem/esp_sd.h" -typedef ESP_SDFile WebDavFile; -typedef ESP_SD WebDavFS; -#endif //WEBDAV_FEATURE == FS_SD - -class ESPWebDAVCore -{ -public: - - enum ResourceType { RESOURCE_NONE, RESOURCE_FILE, RESOURCE_DIR }; - enum DepthType { DEPTH_NONE, DEPTH_CHILD, DEPTH_ALL }; - - typedef String(*ContentTypeFunction)(const String&); - using TransferStatusCallback = std::function; - void begin(); - bool dirAction( - const String& path, - bool recursive, - const std::function& cb, - bool callAfter = true, - int depth = 0); - - void dir(const String& path, Print* out); - - bool parseRequest(const String& method, const String& uri, WiFiClient* client, ContentTypeFunction contentType); - - void setTransferStatusCallback(const TransferStatusCallback& cb) - { - transferStatusFn = cb; - } - bool isIgnored (const String& uri) - { - return _userIgnoreFunction && _userIgnoreFunction(uri); - } - void setIgnored (std::function userFunction) - { - _userIgnoreFunction = userFunction; - } - - const String& getDAVRoot () - { - return _davRoot; - } - void setDAVRoot (const String& davRoot) - { - _davRoot = davRoot; - } - void setFsRoot (const String& fsRoot) - { - _fsRoot = fsRoot; - } - - static void stripSlashes(String& name); - static String date2date(time_t date); - static String enc2c(const String& encoded); - static String c2enc(const String& decoded); - static void replaceFront (String& str, const String& from, const String& to); - -protected: - - static int htoi(char c); - static int hhtoi(const char* c); - static char itoH(int c); - static bool notEncodable (char c); - - //XXXFIXME this function must be replaced by some Stream::to() - size_t readBytesWithTimeout(uint8_t *buf, size_t size); - - typedef void (ESPWebDAVCore::*THandlerFunction)(const String&); - - bool copyFile(WebDavFile file, const String& destName); - bool deleteDir(const String& dir); - bool mkFullDir(String fullDir); - - void processClient(THandlerFunction handler, const String& message); - void handleIssue(int code, const char* text); - //void handleReject(const String& rejectMessage); - void handleRequest(); - void handleOptions(ResourceType resource); - void handleLock(ResourceType resource); - void handleUnlock(ResourceType resource); - void handlePropPatch(ResourceType resource, WebDavFile& file); - void handleProp(ResourceType resource, WebDavFile& file); - void handleGet(ResourceType resource, WebDavFile& file, bool isGet); - void handlePut(ResourceType resource); - void handleWriteError(const String& message, WebDavFile& wFile); - void handleDirectoryCreate(ResourceType resource); - void handleMove(ResourceType resource, WebDavFile& file); - void handleDelete(ResourceType resource); - void handleCopy(ResourceType resource, WebDavFile& file); - - void sendPropResponse(bool isDir, const String& name, size_t size, time_t lastWrite, time_t creationTime); - void sendContentProp(const String& what, const String& response); - - void sendHeader(const String& name, const String& value, bool first = false); - void send(const String& code, const char* content_type, const String& content); - void _prepareHeader(String& response, const String& code, const char* content_type, size_t contentLength); - bool sendContent(const String& content); - bool sendContent_P(PGM_P content); - bool sendContent(const char* data, size_t size); - void setContentLength(size_t len); - void processRange(const String& range); - - int allowed(const String& uri, uint32_t ownash); - int allowed(const String& uri, const String& xml = emptyString); - void makeToken(String& ret, uint32_t pash, uint32_t ownash); - int extractLockToken(const String& someHeader, const char* start, const char* end, uint32_t& pash, uint32_t& ownash); - bool getPayload(StreamString& payload); - void stripName(String& name); - void stripHost(String& name); - String urlToUri(const String& url); - - enum virt_e { VIRT_NONE, VIRT_PROC }; - virt_e isVirtual(const String& uri); - size_t makeVirtual(virt_e v, String& internal); - - // variables pertaining to current most HTTP request being serviced - constexpr static int m_persistent_timer_init_ms = 5000; - long unsigned int m_persistent_timer_ms; - bool m_persistent; - int _maxPathLength; - - String method; - String uri; - StreamString payload; - WiFiClient* client = nullptr; - - size_t contentLengthHeader; - String depthHeader; - String hostHeader; - String destinationHeader; - String overwrite; - String ifHeader; - String lockTokenHeader; - DepthType depth; - - String _responseHeaders; - bool _chunked; - int _contentLengthAnswer; - int _rangeStart; - int _rangeEnd; - -#if WEBDAV_LOCK_SUPPORT > 1 - // infinite-depth exclusive locks - // map - std::map _locks; -#endif - - ContentTypeFunction contentTypeFn = nullptr; - TransferStatusCallback transferStatusFn = nullptr; - - std::function _userIgnoreFunction = nullptr; - - // allowing to rewrite DAV root in FS - // (dav:////path <=> FS:///path) - // empty by default (dav:////path <=> FS:///path) - String _davRoot; - String _fsRoot; -}; - -class ESPWebDAV: public ESPWebDAVCore -{ -public: - - void begin(WiFiServer* srv) - { - ESPWebDAVCore::begin(); - this->server = srv; - m_persistent = false; - } - void end() - { - this->server = nullptr; - } - void handleClient(); - WiFiClient & Client() - { - return locClient; - } -protected: - - // Sections are copied from ESP8266Webserver - static String getMimeType(const String& path); - String urlDecode(const String& text); - - bool parseRequest(); - - WiFiServer* server = nullptr; - WiFiClient locClient; -}; - -#endif // __ESPWEBDAV_H diff --git a/esp3d/src/modules/webdav/PolledTimeout_esp32.h b/esp3d/src/modules/webdav/PolledTimeout_esp32.h deleted file mode 100644 index 8723e41a..00000000 --- a/esp3d/src/modules/webdav/PolledTimeout_esp32.h +++ /dev/null @@ -1,27 +0,0 @@ -#ifndef __POLLEDTIMING_H__ -#define __POLLEDTIMING_H__ - -#include - -class PolledTimeout -{ -public: - PolledTimeout(uint32_t timeout) - { - _timeOut = timeout; - _startMS = millis(); - } - operator bool() const - { - return ((millis() - _startMS) > _timeOut); - } - void reset() - { - _startMS = millis(); - } -private: - uint32_t _startMS; - uint32_t _timeOut; -}; - -#endif diff --git a/esp3d/src/modules/webdav/WebSrv.cpp b/esp3d/src/modules/webdav/WebSrv.cpp deleted file mode 100644 index 687c177c..00000000 --- a/esp3d/src/modules/webdav/WebSrv.cpp +++ /dev/null @@ -1,163 +0,0 @@ -/* - Dead simple web-server. - Supports only one simultaneous client, knows how to handle GET and POST. - - Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. - Simplified/Adapted for ESPWebDav: - Copyright (c) 2018 Gurpreet Bal https://github.com/ardyesp/ESPWebDAV - Copyright (c) 2020 David Gauchard https://github.com/d-a-v/ESPWebDAV - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - Modified 8 May 2015 by Hristo Gochkov (proper post and file upload handling) - Modified 22 Jan 2021 by Luc Lebosse (ESP3D Integration) -*/ -// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 -#include "../../include/esp3d_config.h" - -#if defined(WEBDAV_FEATURE) -#include "ESPWebDAV.h" - -// Sections are copied from ESP8266Webserver - -String ESPWebDAV::getMimeType(const String& path) { - if (path.endsWith(".html")) { - return "text/html"; - } else if (path.endsWith(".htm")) { - return "text/html"; - } else if (path.endsWith(".css")) { - return "text/css"; - } else if (path.endsWith(".txt")) { - return "text/plain"; - } else if (path.endsWith(".js")) { - return "application/javascript"; - } else if (path.endsWith(".json")) { - return "application/json"; - } else if (path.endsWith(".png")) { - return "image/png"; - } else if (path.endsWith(".gif")) { - return "image/gif"; - } else if (path.endsWith(".jpg")) { - return "image/jpeg"; - } else if (path.endsWith(".ico")) { - return "image/x-icon"; - } else if (path.endsWith(".svg")) { - return "image/svg+xml"; - } else if (path.endsWith(".ttf")) { - return "application/x-font-ttf"; - } else if (path.endsWith(".otf")) { - return "application/x-font-opentype"; - } else if (path.endsWith(".woff")) { - return "application/font-woff"; - } else if (path.endsWith(".woff2")) { - return "application/font-woff2"; - } else if (path.endsWith(".eot")) { - return "application/vnd.ms-fontobject"; - } else if (path.endsWith(".sfnt")) { - return "application/font-sfnt"; - } else if (path.endsWith(".xml")) { - return "text/xml"; - } else if (path.endsWith(".pdf")) { - return "application/pdf"; - } else if (path.endsWith(".zip")) { - return "application/zip"; - } else if (path.endsWith(".gz")) { - return "application/x-gzip"; - } else if (path.endsWith(".appcache")) { - return "text/cache-manifest"; - } - - return "application/octet-stream"; -} - -String ESPWebDAV::urlDecode(const String& text) { - String decoded = ""; - char temp[] = "0x00"; - unsigned int len = text.length(); - unsigned int i = 0; - while (i < len) { - char decodedChar; - char encodedChar = text.charAt(i++); - if ((encodedChar == '%') && (i + 1 < len)) { - temp[2] = text.charAt(i++); - temp[3] = text.charAt(i++); - decodedChar = strtol(temp, NULL, 16); - } else { - if (encodedChar == '+') { - decodedChar = ' '; - } else { - decodedChar = encodedChar; // normal ascii char - } - } - decoded += decodedChar; - } - return decoded; -} - -void ESPWebDAV::handleClient() { - if (!server) { - log_esp3d_e("handleClient: server is null"); - return; - } - - if (server->hasClient()) { - if (!locClient || !locClient.available()) { - // no or sleeping current client - // take it over - locClient = server->available(); - m_persistent_timer_ms = millis(); - log_esp3d( - "NEW CLIENT-------------------------------------------------------"); - } - } - - if (!locClient || !locClient.available()) { - // no current client - // do not put debug here or it will flood the serial - return; - } - - // extract uri, headers etc - parseRequest(); - - if (!m_persistent) - // close the connection - { - log_esp3d( - "CLOSE " - "CONNECTION-------------------------------------------------------"); - locClient.stop(); - } -} - -bool ESPWebDAV::parseRequest() { - // Read the first line of HTTP request - String req = locClient.readStringUntil('\r'); - locClient.readStringUntil('\n'); - - // First line of HTTP request looks like "GET /path HTTP/1.1" - // Retrieve the "/path" part by finding the spaces - int addr_start = req.indexOf(' '); - int addr_end = req.indexOf(' ', addr_start + 1); - if (addr_start == -1 || addr_end == -1) { - log_esp3d("Invalid request %s", req.c_str()); - return false; - } - - method = req.substring(0, addr_start); - uri = urlDecode(req.substring(addr_start + 1, addr_end)); - return ESPWebDAVCore::parseRequest(method, uri, &locClient, getMimeType); -} - -#endif // WEBDAV_FEATURE diff --git a/esp3d/src/modules/webdav/handlers/handler_copy.cpp b/esp3d/src/modules/webdav/handlers/handler_copy.cpp new file mode 100644 index 00000000..13f843fa --- /dev/null +++ b/esp3d/src/modules/webdav/handlers/handler_copy.cpp @@ -0,0 +1,197 @@ +/* + webdav_server.cpp - webdav server functions class + + Copyright (c) 2023 Luc Lebosse. All rights reserved. + + This code is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This code is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with This code; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "../../../include/esp3d_config.h" + +#if defined(WEBDAV_FEATURE) +#include "../../../core/esp3d_string.h" +#include "../webdav_server.h" + +void WebdavServer::handler_copy(const char* url) { + log_esp3d("Processing COPY"); + int code = 201; + size_t sp = clearPayload(); + log_esp3d("Payload size: %d", sp); + uint8_t fsTypeOrigin = WebDavFS::getFSType(url); + log_esp3d("FS type of %s : %d", url, fsTypeOrigin); + String destination = ""; + if (hasHeader("Destination")) { + destination = getHeader("Destination"); + log_esp3d("Destination: %s", destination.c_str()); + destination = urlDecode(destination.c_str()); + if (destination.startsWith("http://") || + destination.startsWith("https://")) { + destination = destination.substring(destination.indexOf("/", 8)); + destination = destination.substring(destination.indexOf("/")); + log_esp3d("Destination trimmed: %s", destination.c_str()); + if (destination != "/") { + if (destination.endsWith("/")) { + destination = destination.substring(0, destination.length() - 1); + } + } + } + uint8_t fsTypeDestination = WebDavFS::getFSType(destination.c_str()); + log_esp3d("FS type of %s : %d", destination.c_str(), fsTypeDestination); + if (fsTypeDestination != fsTypeOrigin) { + code = 409; + log_esp3d_e("Destination and origin must be on same FS"); + } else { + bool overwrite = false; + if (hasHeader("Overwrite")) { + overwrite = (strcmp(getHeader("Overwrite"), "T") == 0); + log_esp3d("Overwrite: %s", overwrite ? "true" : "false"); + } + // url cannot be root + if (!isRoot(url) && !isRoot(destination.c_str())) { + if (WebDavFS::accessFS(fsTypeOrigin)) { + // check if file exists + if (WebDavFS::exists(url)) { + // Check if origin is a directory + WebDavFile fileOrigin = WebDavFS::open(url); + if (fileOrigin) { + if (fileOrigin.isDirectory()) { + code = 413; + log_esp3d_e("File %s is a directory", url); + } else { + // check if destination exists + WebDavFile fileDestination = + WebDavFS::open(destination.c_str()); + if (fileDestination) { + if (fileDestination.isDirectory()) { + code = 412; + log_esp3d_e("File %s is a directory", destination.c_str()); + } + fileDestination.close(); + overwrite = false; + } else { + log_esp3d("Destination does not exist"); + overwrite = true; + } + // check available space + if (overwrite) { + if (WebDavFS::exists(destination.c_str())) { + if (WebDavFS::freeBytes(fsTypeOrigin) + fileOrigin.size() < + fileDestination.size()) { + code = 507; + log_esp3d_e("Not enough space"); + overwrite = false; + } else { // there is enough space to overwrite + code = 204; + } + } else { + if (WebDavFS::freeBytes(fsTypeOrigin) < fileOrigin.size()) { + code = 507; + log_esp3d_e("Not enough space"); + overwrite = false; + } + } + + if (overwrite) { + log_esp3d("Overwrite allowed"); + if (WebDavFS::exists(destination.c_str()) && + !WebDavFS::remove(destination.c_str())) { + code = 500; + log_esp3d_e("Failed to remove %s", destination.c_str()); + overwrite = false; + } else { + // copy file + WebDavFile fileDestination = + WebDavFS::open(destination.c_str(), ESP_FILE_WRITE); + if (fileDestination) { + size_t data_read = 0; + size_t data_to_read = fileOrigin.size(); + while (data_read < data_to_read) { + Hal::wait(0); +#if defined(ARDUINO_ARCH_ESP32) + uint8_t buff[2048]; +#endif // ARDUINO_ARCH_ESP32 +#if defined(ARDUINO_ARCH_ESP8266) + uint8_t buff[512]; +#endif // ARDUINO_ARCH_ESP8266 + size_t read_size = + fileOrigin.read(buff, sizeof(buff)); + if (read_size > 0) { + // always check if data is sent as expected for each + // write + if (read_size != + fileDestination.write(buff, read_size)) { + log_esp3d_e("Failed to write data"); + code = 500; + break; + } + data_read += read_size; + } else { + // done reading + break; + } + } + fileDestination.close(); + if (data_read != data_to_read) { + code = 500; + log_esp3d_e("Failed to copy %s to %s", url, + destination.c_str()); + overwrite = false; + } + } else { + code = 500; + log_esp3d_e("Failed to open %s", destination.c_str()); + overwrite = false; + } + } + } + } + if (overwrite) { + if (!WebDavFS::rename(url, destination.c_str())) { + code = 500; + log_esp3d_e("Failed to move %s to %s", url, + destination.c_str()); + } + } + } + fileOrigin.close(); + } else { + code = 500; + log_esp3d_e("Failed to open %s", url); + } + } else { + code = 404; + log_esp3d_e("File not found"); + } + WebDavFS::releaseFS(fsTypeOrigin); + } else { + code = 503; + log_esp3d_e("FS not available"); + } + } else { + code = 400; + log_esp3d_e("Root cannot be deleted"); + } + } + } else { + code = 400; + log_esp3d_e("Destination not set"); + } + + log_esp3d_e("Sending response code %d", code); + send_response_code(code); + send_webdav_headers(); +} + +#endif // WEBDAV_FEATURE diff --git a/esp3d/src/modules/webdav/handlers/handler_delete.cpp b/esp3d/src/modules/webdav/handlers/handler_delete.cpp new file mode 100644 index 00000000..87dc1350 --- /dev/null +++ b/esp3d/src/modules/webdav/handlers/handler_delete.cpp @@ -0,0 +1,68 @@ +/* + webdav_server.cpp - webdav server functions class + + Copyright (c) 2023 Luc Lebosse. All rights reserved. + + This code is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This code is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with This code; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "../../../include/esp3d_config.h" + +#if defined(WEBDAV_FEATURE) +#include "../webdav_server.h" + +void WebdavServer::handler_delete(const char* url) { + log_esp3d("Processing DELETE"); + int code = 204; + size_t sp = clearPayload(); + log_esp3d("Payload size: %d", sp); + uint8_t fsType = WebDavFS::getFSType(url); + log_esp3d("FS type of %s : %d", url, fsType); + // url cannot be root + if (!isRoot(url)) { + if (WebDavFS::accessFS(fsType)) { + // check if file exists + if (WebDavFS::exists(url)) { + // try remove as file + if (!WebDavFS::remove(url)) { + log_esp3d("Failed to remove file %s", url); + log_esp3d("Trying to remove as directory"); + // if failed try remove as directory + if (!WebDavFS::rmdir(url)) { + log_esp3d("Failed to remove directory %s", url); + code = 500; + log_esp3d_e("Failed to remove %s", url); + } + } + } else { + code = 404; + log_esp3d_e("File not found"); + } + WebDavFS::releaseFS(fsType); + } else { + code = 503; + log_esp3d_e("FS not available"); + } + } else { + code = 400; + log_esp3d_e("Root cannot be deleted"); + } + + log_esp3d_e("Sending response code %d", code); + send_response_code(code); + send_webdav_headers(); +} + +#endif // WEBDAV_FEATURE diff --git a/esp3d/src/modules/webdav/handlers/handler_get.cpp b/esp3d/src/modules/webdav/handlers/handler_get.cpp new file mode 100644 index 00000000..35ca7baa --- /dev/null +++ b/esp3d/src/modules/webdav/handlers/handler_get.cpp @@ -0,0 +1,115 @@ +/* + webdav_server.cpp - webdav server functions class + + Copyright (c) 2023 Luc Lebosse. All rights reserved. + + This code is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This code is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with This code; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "../../../include/esp3d_config.h" + +#if defined(WEBDAV_FEATURE) +#include "../../../core/esp3d_string.h" +#if defined(HTTP_FEATURE) +#include "../../websocket/websocket_server.h" +#endif // HTTP_FEATURE +#include "../webdav_server.h" + +void WebdavServer::handler_get(const char* url) { + log_esp3d("Processing GET"); + int code = 200; + size_t sp = clearPayload(); + log_esp3d("Payload size: %d", sp); + uint8_t fsType = WebDavFS::getFSType(url); + log_esp3d("FS type of %s : %d", url, fsType); + // url cannot be root + if (!isRoot(url)) { + if (WebDavFS::accessFS(fsType)) { + // check if file exists + if (WebDavFS::exists(url)) { + WebDavFile file = WebDavFS::open(url); + if (file) { + // send response + send_response_code(code); + send_webdav_headers(); + send_header("Last-Modified", esp3d_string::getTimeString( + (time_t)file.getLastWrite(), true)); + send_header("Content-Length", String(file.size()).c_str()); + send_header("Content-Type", esp3d_string::getContentType(url)); + // end the headers with a blank line + _client.write("\r\n"); + // send file content + size_t sent = 0; + size_t toSend = file.size(); +#if defined(ARDUINO_ARCH_ESP32) + uint8_t buff[2048]; +#endif // ARDUINO_ARCH_ESP32 +#if defined(ARDUINO_ARCH_ESP8266) + uint8_t buff[1024]; +#endif // ARDUINO_ARCH_ESP8266 +#if defined(HTTP_FEATURE) + Esp3dTimout updateWS(2000); +#endif // HTTP_FEATURE + while (sent < toSend && _client.connected()) { + Hal::wait(0); + size_t read = file.read(buff, sizeof(buff)); + if (read > 0) { + // always check if data is sent as expected for each write + if (read != _client.write(buff, read)) { + log_esp3d_e("Failed to send data"); + break; + } + sent += read; + } else { + // done reading + break; + } +#if defined(HTTP_FEATURE) + // update websocket every 2000 ms + if (updateWS.isTimeout()) { + websocket_terminal_server.handle(); + updateWS.reset(); + } +#endif // HTTP_FEATURE + } + // always check if data is sent as expected in total + if (sent != toSend) { + log_esp3d_e("Failed to send data, sent %d of %d", sent, toSend); + } + file.close(); + } else { + code = 500; + log_esp3d_e("Failed to open %s", url); + } + } else { + code = 404; + log_esp3d_e("File not found"); + } + WebDavFS::releaseFS(fsType); + } else { + code = 503; + log_esp3d_e("FS not available"); + } + } else { + code = 400; + log_esp3d_e("Root cannot be deleted"); + } + if (code != 200) { + log_esp3d_e("Sending response code %d", code); + send_response_code(code); + send_webdav_headers(); + } +} +#endif // WEBDAV_FEATURE diff --git a/esp3d/src/modules/webdav/handlers/handler_head.cpp b/esp3d/src/modules/webdav/handlers/handler_head.cpp new file mode 100644 index 00000000..df4b57dd --- /dev/null +++ b/esp3d/src/modules/webdav/handlers/handler_head.cpp @@ -0,0 +1,73 @@ +/* + webdav_server.cpp - webdav server functions class + + Copyright (c) 2023 Luc Lebosse. All rights reserved. + + This code is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This code is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with This code; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "../../../include/esp3d_config.h" + +#if defined(WEBDAV_FEATURE) +#include "../../../core/esp3d_string.h" +#include "../webdav_server.h" + +void WebdavServer::handler_head(const char* url) { + log_esp3d("Processing HEAD"); + int code = 200; + size_t sp = clearPayload(); + log_esp3d("Payload size: %d", sp); + uint8_t fsType = WebDavFS::getFSType(url); + log_esp3d("FS type of %s : %d", url, fsType); + // url cannot be root + if (!isRoot(url)) { + if (WebDavFS::accessFS(fsType)) { + // check if file exists + if (WebDavFS::exists(url)) { + WebDavFile file = WebDavFS::open(url); + if (file) { + // send response + send_response_code(code); + send_webdav_headers(); + send_header("Last-Modified", esp3d_string::getTimeString( + (time_t)file.getLastWrite(), true)); + send_header("Content-Length", String(file.size()).c_str()); + send_header("Content-Type", esp3d_string::getContentType(url)); + file.close(); + } else { + code = 500; + log_esp3d_e("Failed to open %s", url); + } + } else { + code = 404; + log_esp3d_e("File not found"); + } + WebDavFS::releaseFS(fsType); + } else { + code = 503; + log_esp3d_e("FS not available"); + } + } else { + code = 400; + log_esp3d_e("Root cannot be deleted"); + } + if (code != 200) { + log_esp3d_e("Sending response code %d", code); + send_response_code(code); + send_webdav_headers(); + } +} + +#endif // WEBDAV_FEATURE diff --git a/esp3d/src/modules/webdav/handlers/handler_lock.cpp b/esp3d/src/modules/webdav/handlers/handler_lock.cpp new file mode 100644 index 00000000..011b07ec --- /dev/null +++ b/esp3d/src/modules/webdav/handlers/handler_lock.cpp @@ -0,0 +1,80 @@ +/* + webdav_server.cpp - webdav server functions class + + Copyright (c) 2023 Luc Lebosse. All rights reserved. + + This code is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This code is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with This code; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "../../../include/esp3d_config.h" + +#if defined(WEBDAV_FEATURE) +#include "../../../core/esp3d_string.h" +#include "../webdav_server.h" + +#define LOCK_RESPONSE_BODY_PART_1 \ + "" +#define LOCK_RESPONSE_BODY_PART_2 \ + "" + +void WebdavServer::handler_lock(const char* url) { + log_esp3d("Processing LOCK"); + int code = 200; + + size_t sp = clearPayload(); + log_esp3d("Payload size: %d", sp); + + uint8_t fsType = WebDavFS::getFSType(url); + log_esp3d("FS type of %s : %d", url, fsType); + if (!isRoot(url)) { + if (WebDavFS::accessFS(fsType)) { + if (WebDavFS::exists(url)) { + // make token + String token = "opaquelocktoken:"; + token += esp3d_string::generateUUID(url); + send_response_code(code); + send_webdav_headers(); + // add token to header + send_header("Lock-Token", token.c_str()); + + // build response body + String body = LOCK_RESPONSE_BODY_PART_1; + body += token; + body += LOCK_RESPONSE_BODY_PART_2; + // send body + send_response(body.c_str()); + log_esp3d("%s", body.c_str()); + } else { + code = 404; + log_esp3d_e("File not found"); + } + WebDavFS::releaseFS(fsType); + } else { + code = 503; + log_esp3d_e("FS not available"); + } + } else { + code = 400; + log_esp3d_e("Root cannot be locked"); + } + if (code != 200) { + log_esp3d_e("Sending response code %d", code); + send_response_code(code); + send_webdav_headers(); + } +} + +#endif // WEBDAV_FEATURE diff --git a/esp3d/src/modules/webdav/handlers/handler_mkcol.cpp b/esp3d/src/modules/webdav/handlers/handler_mkcol.cpp new file mode 100644 index 00000000..d9629b5c --- /dev/null +++ b/esp3d/src/modules/webdav/handlers/handler_mkcol.cpp @@ -0,0 +1,62 @@ +/* + webdav_server.cpp - webdav server functions class + + Copyright (c) 2023 Luc Lebosse. All rights reserved. + + This code is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This code is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with This code; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "../../../include/esp3d_config.h" + +#if defined(WEBDAV_FEATURE) +#include "../webdav_server.h" + +void WebdavServer::handler_mkcol(const char* url) { + log_esp3d("Processing MKCOL"); + int code = 201; + size_t sp = clearPayload(); + log_esp3d("Payload size: %d", sp); + uint8_t fsType = WebDavFS::getFSType(url); + log_esp3d("FS type of %s : %d", url, fsType); + // url cannot be root + if (!isRoot(url)) { + if (WebDavFS::accessFS(fsType)) { + // check if file exists + if (!WebDavFS::exists(url)) { + // Create dir + if (!WebDavFS::mkdir(url)) { + code = 500; + log_esp3d_e("Creation failed"); + } + } else { + code = 409; + log_esp3d_e("File not found"); + } + WebDavFS::releaseFS(fsType); + } else { + code = 503; + log_esp3d_e("FS not available"); + } + } else { + code = 400; + log_esp3d_e("Root cannot be created"); + } + + log_esp3d_e("Sending response code %d", code); + send_response_code(code); + send_webdav_headers(); +} + +#endif // WEBDAV_FEATURE diff --git a/esp3d/src/modules/webdav/handlers/handler_move.cpp b/esp3d/src/modules/webdav/handlers/handler_move.cpp new file mode 100644 index 00000000..065daa2c --- /dev/null +++ b/esp3d/src/modules/webdav/handlers/handler_move.cpp @@ -0,0 +1,118 @@ +/* + webdav_server.cpp - webdav server functions class + + Copyright (c) 2023 Luc Lebosse. All rights reserved. + + This code is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This code is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with This code; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "../../../include/esp3d_config.h" + +#if defined(WEBDAV_FEATURE) +#include "../../../core/esp3d_string.h" +#include "../webdav_server.h" + +void WebdavServer::handler_move(const char* url) { + log_esp3d("Processing MOVE"); + int code = 201; + size_t sp = clearPayload(); + log_esp3d("Payload size: %d", sp); + uint8_t fsTypeOrigin = WebDavFS::getFSType(url); + log_esp3d("FS type of %s : %d", url, fsTypeOrigin); + String destination = ""; + if (hasHeader("Destination")) { + destination = getHeader("Destination"); + destination = urlDecode(destination.c_str()); + if (destination.startsWith("http://") || + destination.startsWith("https://")) { + destination = destination.substring(destination.indexOf("/", 8)); + destination = destination.substring(destination.indexOf("/")); + log_esp3d("Destination trimmed: %s", destination.c_str()); + if (destination != "/") { + if (destination.endsWith("/")) { + destination = destination.substring(0, destination.length() - 1); + } + } + } + log_esp3d("Destination: %s", destination.c_str()); + uint8_t fsTypeDestination = WebDavFS::getFSType(destination.c_str()); + log_esp3d("FS type of %s : %d", destination.c_str(), fsTypeDestination); + if (fsTypeDestination != fsTypeOrigin) { + code = 409; + log_esp3d_e("Destination and origin must be on same FS"); + } else { + bool overwrite = false; + if (hasHeader("Overwrite")) { + overwrite = (strcmp(getHeader("Overwrite"), "T") == 0); + log_esp3d("Overwrite: %s", overwrite ? "true" : "false"); + } + // url cannot be root + if (!isRoot(url) && !isRoot(destination.c_str())) { + String url_dir = url_dir + "/"; + if (WebDavFS::accessFS(fsTypeOrigin)) { + // check if file exists + log_esp3d("Checking if %s exists", url); + if (WebDavFS::exists(url) || WebDavFS::exists(url_dir.c_str())) { + // check if destination exists + log_esp3d("Checking if %s exists", destination.c_str()); + if (WebDavFS::exists(destination.c_str())) { + log_esp3d("Destination already exists"); + if (!overwrite) { + code = 412; + log_esp3d_e("Overwrite not allowed"); + } else { + log_esp3d("Overwrite allowed"); + code = 204; + if (!WebDavFS::remove(destination.c_str())) { + code = 500; + log_esp3d_e("Failed to remove %s", destination.c_str()); + overwrite = false; + } + } + } else { + log_esp3d("Destination does not exist"); + overwrite = true; + } + if (overwrite) { + if (!WebDavFS::rename(url, destination.c_str())) { + code = 500; + log_esp3d_e("Failed to move %s to %s", url, + destination.c_str()); + } + } + } else { + code = 404; + log_esp3d_e("File not found"); + } + WebDavFS::releaseFS(fsTypeOrigin); + } else { + code = 503; + log_esp3d_e("FS not available"); + } + } else { + code = 400; + log_esp3d_e("Root cannot be deleted"); + } + } + } else { + code = 400; + log_esp3d_e("Destination not set"); + } + log_esp3d_e("Sending response code %d", code); + send_response_code(code); + send_webdav_headers(); +} + +#endif // WEBDAV_FEATURE diff --git a/esp3d/src/modules/webdav/handlers/handler_options.cpp b/esp3d/src/modules/webdav/handlers/handler_options.cpp new file mode 100644 index 00000000..c59efd32 --- /dev/null +++ b/esp3d/src/modules/webdav/handlers/handler_options.cpp @@ -0,0 +1,33 @@ +/* + webdav_server.cpp - webdav server functions class + + Copyright (c) 2023 Luc Lebosse. All rights reserved. + + This code is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This code is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with This code; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "../../../include/esp3d_config.h" + +#if defined(WEBDAV_FEATURE) +#include "../webdav_server.h" + +void WebdavServer::handler_options(const char* url) { + log_esp3d("Processing OPTIONS"); + clearPayload(); + send_response_code(200); + send_webdav_headers(); +} + +#endif // WEBDAV_FEATURE diff --git a/esp3d/src/modules/webdav/handlers/handler_propfind.cpp b/esp3d/src/modules/webdav/handlers/handler_propfind.cpp new file mode 100644 index 00000000..81f77ed7 --- /dev/null +++ b/esp3d/src/modules/webdav/handlers/handler_propfind.cpp @@ -0,0 +1,175 @@ +/* + webdav_server.cpp - webdav server functions class + + Copyright (c) 2023 Luc Lebosse. All rights reserved. + + This code is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This code is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with This code; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "../../../include/esp3d_config.h" + +#if defined(WEBDAV_FEATURE) +#include "../../../core/esp3d_string.h" +#include "../webdav_server.h" + +#define PROPFIND_RESPONSE_BODY_HEADER_1 \ + "" \ + "" + +#define PROPFIND_RESPONSE_BODY_FOOTER "" + +void WebdavServer::handler_propfind(const char* url) { + log_esp3d("Processing PROPFIND"); + int code = 207; + String depth = "0"; + String requestedDepth = "0"; + if (hasHeader("Depth")) { + depth = getHeader("Depth"); + log_esp3d("Depth: %s", depth.c_str()); + requestedDepth = depth; + if (depth == "infinity") { + depth = "1"; + log_esp3d("Depth set to 1"); + } + } else { + log_esp3d("Depth not set"); + } + + size_t sp = clearPayload(); + log_esp3d("Payload size: %d", sp); + + uint8_t fsType = WebDavFS::getFSType(url); + log_esp3d("FS type of %s : %d", url, fsType); + if (WebDavFS::accessFS(fsType)) { + if (WebDavFS::exists(url) || url == "/") { + WebDavFile root = WebDavFS::open(url); + if (root) { + send_response_code(code); + send_webdav_headers(); + + String body = PROPFIND_RESPONSE_BODY_HEADER_1; + if (depth != requestedDepth) { + body += " depth=\""; + body += depth; + body += "\""; + } + body += PROPFIND_RESPONSE_BODY_HEADER_2; + body += ""; + body += ""; + body += url; + body += ""; + body += ""; + body += ""; + body += ""; + body += esp3d_string::getTimeString((time_t)root.getLastWrite(), true); + body += ""; + if (root.isDirectory()) { + body += ""; + body += ""; + body += ""; + } else { + body += ""; + body += ""; + body += root.size(); + body += ""; + } + body += ""; + body += url; + body += ""; + body += ""; + body += "HTTP/1.1 200 OK"; + body += ""; + body += ""; + + if (depth == "0") { + body += PROPFIND_RESPONSE_BODY_FOOTER; + send_response(body.c_str()); + log_esp3d("%s", body.c_str()); + } else { + send_chunk_content(body.c_str()); + log_esp3d("%s", body.c_str()); + if (depth == "1" && root.isDirectory()) { + log_esp3d("Depth 1, parsing directory"); + WebDavFile entry = root.openNextFile(); + while (entry) { + yield(); + log_esp3d("Processing %s from %s", entry.name(), url); + body = ""; + body += ""; + body += url; + if (strcmp(url, "/") != 0) { + body += "/"; + log_esp3d("Adding / to *%s*", url); + } + body += entry.name()[0] == '/' ? entry.name() + 1 : entry.name(); + body += ""; + body += ""; + body += ""; + body += ""; + body += esp3d_string::getTimeString((time_t)entry.getLastWrite(), + true); + body += ""; + if (entry.isDirectory()) { + body += ""; + body += ""; + body += ""; + } else { + body += ""; + body += ""; + body += entry.size(); + body += ""; + } + body += ""; + body += entry.name()[0] == '/' ? entry.name() + 1 : entry.name(); + body += ""; + body += ""; + body += "HTTP/1.1 200 OK"; + body += ""; + body += ""; + log_esp3d("%s", body.c_str()); + send_chunk_content(body.c_str()); + entry.close(); + entry = root.openNextFile(); + } + log_esp3d("%s", PROPFIND_RESPONSE_BODY_FOOTER); + send_chunk_content(PROPFIND_RESPONSE_BODY_FOOTER); + // End of chunk + send_chunk_content(""); + } + } + root.close(); + } else { + code = 503; + log_esp3d_e("File not opened"); + } + + } else { + code = 404; + log_esp3d_e("File not found"); + } + WebDavFS::releaseFS(fsType); + } else { + code = 503; + log_esp3d_e("FS not available"); + } + if (code != 207) { + log_esp3d_e("Sending response code %d", code); + send_response_code(code); + send_webdav_headers(); + } +} + +#endif // WEBDAV_FEATURE diff --git a/esp3d/src/modules/webdav/handlers/handler_proppatch.cpp b/esp3d/src/modules/webdav/handlers/handler_proppatch.cpp new file mode 100644 index 00000000..b3f5d56f --- /dev/null +++ b/esp3d/src/modules/webdav/handlers/handler_proppatch.cpp @@ -0,0 +1,32 @@ +/* + webdav_server.cpp - webdav server functions class + + Copyright (c) 2023 Luc Lebosse. All rights reserved. + + This code is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This code is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with This code; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "../../../include/esp3d_config.h" + +#if defined(WEBDAV_FEATURE) +#include "../webdav_server.h" + +void WebdavServer::handler_proppatch(const char* url) { + log_esp3d("Processing PROPPATCH"); + // No support for the moment, so redirect to propfind + handler_propfind(url); +} + +#endif // WEBDAV_FEATURE diff --git a/esp3d/src/modules/webdav/handlers/handler_put.cpp b/esp3d/src/modules/webdav/handlers/handler_put.cpp new file mode 100644 index 00000000..80cc3398 --- /dev/null +++ b/esp3d/src/modules/webdav/handlers/handler_put.cpp @@ -0,0 +1,153 @@ +/* + webdav_server.cpp - webdav server functions class + + Copyright (c) 2023 Luc Lebosse. All rights reserved. + + This code is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This code is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with This code; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "../../../include/esp3d_config.h" + +#if defined(WEBDAV_FEATURE) +#include "../../../core/esp3d_string.h" +#include "../webdav_server.h" +#if defined(HTTP_FEATURE) +#include "../../websocket/websocket_server.h" +#endif // HTTP_FEATURE + +void WebdavServer::handler_put(const char* url) { + log_esp3d("Processing PUT"); + int code = 201; + size_t content_length = 0; + uint8_t fsType = WebDavFS::getFSType(url); + log_esp3d("FS type of %s : %d", url, fsType); + if (hasHeader("Content-Length")) { + content_length = atoi(getHeader("Content-Length")); + log_esp3d("Content-Length: %d", content_length); + } else { + log_esp3d("Content-Length not set"); + } + + // url cannot be root + if (!isRoot(url)) { + if (WebDavFS::accessFS(fsType)) { + bool hasError = false; + // check if file exists + if (WebDavFS::exists(url)) { + log_esp3d("File %s already exists", url); + code = 204; + WebDavFile file = WebDavFS::open(url); + if (file) { + if (file.isDirectory()) { + code = 412; + log_esp3d_e("File %s is a directory", url); + hasError = true; + } + file.close(); + if (!hasError) { + // check size available + if (WebDavFS::freeBytes(fsType) + file.size() < content_length) { + code = 507; + log_esp3d_e("Not enough space"); + hasError = true; + } else { // there is enough space + if (!WebDavFS::remove( + url)) { // so delete existing file to replace it + code = 500; + log_esp3d_e("Failed to remove %s", url); + hasError = true; + } + } + } + } else { + hasError = true; + code = 500; + log_esp3d_e("Failed to open %s", url); + } + } else { + // check size available + if (WebDavFS::freeBytes(fsType) < content_length) { + code = 507; + log_esp3d_e("Not enough space"); + hasError = true; + } + } + if (!hasError) { // read payload and write it to file + WebDavFile file = WebDavFS::open(url, ESP_FILE_WRITE); + if (file) { + size_t received = 0; +#if defined(ARDUINO_ARCH_ESP32) + uint8_t chunk[2048]; +#endif // ARDUINO_ARCH_ESP32 +#if defined(ARDUINO_ARCH_ESP8266) + uint8_t chunk[512]; +#endif // ARDUINO_ARCH_ESP8266 +#if defined(HTTP_FEATURE) + Esp3dTimout updateWS(2000); +#endif // HTTP_FEATURE + while (_client.available() && received < content_length) { + Hal::wait(0); + size_t received_bytes = _client.read(chunk, sizeof(chunk)); + if (received_bytes != file.write(chunk, received_bytes)) { + code = 500; + log_esp3d_e("Failed to write %s", url); + break; + } else { + received += received_bytes; + } + +#if defined(HTTP_FEATURE) + // update websocket every 2000 ms + if (updateWS.isTimeout()) { + websocket_terminal_server.handle(); + updateWS.reset(); + } +#endif // HTTP_FEATURE + } + if (received != content_length) { + code = 500; + log_esp3d_e("Failed to write %s", url); + } else { + log_esp3d("File %s written", url); + send_response_code(code); // 201 or 204 + send_webdav_headers(); + time_t now = time(nullptr); + send_header("Last-Modified", + esp3d_string::getTimeString(now, true)); + } + + file.close(); + } else { + code = 500; + log_esp3d_e("Failed to open %s for writing", url); + } + } + WebDavFS::releaseFS(fsType); + } else { + code = 503; + log_esp3d_e("FS not available"); + } + } else { + code = 400; + log_esp3d_e("Root cannot be deleted"); + } + if (code != 201 && code != 204) { + log_esp3d_e("Sending response code %d", code); + send_response_code(code); + send_webdav_headers(); + } +} + +#endif // WEBDAV_FEATURE diff --git a/esp3d/src/modules/webdav/handlers/handler_unlock.cpp b/esp3d/src/modules/webdav/handlers/handler_unlock.cpp new file mode 100644 index 00000000..208da174 --- /dev/null +++ b/esp3d/src/modules/webdav/handlers/handler_unlock.cpp @@ -0,0 +1,56 @@ +/* + webdav_server.cpp - webdav server functions class + + Copyright (c) 2023 Luc Lebosse. All rights reserved. + + This code is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This code is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with This code; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "../../../include/esp3d_config.h" + +#if defined(WEBDAV_FEATURE) +#include "../webdav_server.h" + +void WebdavServer::handler_unlock(const char* url) { + log_esp3d("Processing UNLOCK"); + int code = 204; + size_t sp = clearPayload(); + log_esp3d("Payload size: %d", sp); + uint8_t fsType = WebDavFS::getFSType(url); + log_esp3d("FS type of %s : %d", url, fsType); + // url cannot be root + if (!isRoot(url)) { + if (WebDavFS::accessFS(fsType)) { + // check if file exists + if (!WebDavFS::exists(url)) { + code = 404; + log_esp3d_e("File not found"); + } + WebDavFS::releaseFS(fsType); + } else { + code = 503; + log_esp3d_e("FS not available"); + } + } else { + code = 400; + log_esp3d_e("Root cannot be unlocked"); + } + + log_esp3d_e("Sending response code %d", code); + send_response_code(code); + send_webdav_headers(); +} + +#endif // WEBDAV_FEATURE diff --git a/esp3d/src/modules/webdav/webdav_server.cpp b/esp3d/src/modules/webdav/webdav_server.cpp index df86f950..3c77ac62 100644 --- a/esp3d/src/modules/webdav/webdav_server.cpp +++ b/esp3d/src/modules/webdav/webdav_server.cpp @@ -1,7 +1,7 @@ /* webdav_server.cpp - webdav server functions class - Copyright (c) 2014 Luc Lebosse. All rights reserved. + Copyright (c) 2023 Luc Lebosse. All rights reserved. This code is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -20,97 +20,549 @@ #include "../../include/esp3d_config.h" -#if defined (WEBDAV_FEATURE) -#include +#if defined(WEBDAV_FEATURE) #include -#include "webdav_server.h" +#include + +#include "../../core/hal.h" #include "../../core/settings_esp3d.h" -#include "../../core/esp3doutput.h" -#include "../../core/commands.h" +#include "../../include/version.h" +#include "../network/netconfig.h" +#include "webdav_server.h" -Webdav_Server webdav_server; +WebdavServer webdav_server; -void Webdav_Server::closeClient() -{ - if(_dav.Client()) { - _dav.Client().stop(); +#define TIMEOUT_WEBDAV_FLUSH 1500 +#define TIMEOUT_WEBDAV_REQUEST 5000 + +void WebdavServer::closeClient() { + if (_client) { + if (!_headers_sent) { + _client.print("\r\n"); + _headers_sent = true; } + _client.stop(); + } } -void Webdav_Server::dir() -{ - _dav.dir("/", &Serial); -}; - -bool Webdav_Server::isConnected() -{ - if ( !_started) { - return false; - } - if (_dav.Client()) { - return (_dav.Client().connected()); - } +bool WebdavServer::isConnected() { + if (!_started || _tcpServer == NULL) { return false; -} - -const char* Webdav_Server::clientIPAddress() -{ - static String res; - res = "0.0.0.0"; - if (_dav.Client() && _dav.Client().connected()) { - res = _dav.Client().remoteIP().toString(); + } + // check if there are any new clients + if (_tcpServer->hasClient()) { + // find free/disconnected spot + if (!_client || !_client.connected()) { + if (_client) { + _client.stop(); + } + _client = _tcpServer->accept(); + // new client } - return res.c_str(); + } + if (_tcpServer->hasClient()) { + // no free/disconnected spot so reject + _tcpServer->accept().stop(); + } + return _client.connected(); } - -Webdav_Server::Webdav_Server():_tcpserver(0) -{ - _started = false; - _port = 0; +const char* WebdavServer::clientIPAddress() { + static String res; + res = "0.0.0.0"; + if (_client && _client.connected()) { + res = _client.remoteIP().toString(); + } + return res.c_str(); } -Webdav_Server::~Webdav_Server() -{ - end(); +WebdavServer::WebdavServer() { + _started = false; + _port = 0; + _tcpServer = nullptr; } +WebdavServer::~WebdavServer() { end(); } /** - * begin WebDav setup + * begin Telnet setup */ -bool Webdav_Server::begin() -{ - end(); - if (Settings_ESP3D::read_byte(ESP_WEBDAV_ON) !=1) { - return true; - } - _port = Settings_ESP3D::read_uint32(ESP_WEBDAV_PORT); +bool WebdavServer::begin() { + end(); + if (Settings_ESP3D::read_byte(ESP_WEBDAV_ON) != 1) { + return true; + } + // Get webdav port + _port = Settings_ESP3D::read_uint32(ESP_WEBDAV_PORT); - _tcpserver.begin(_port); - _dav.begin(&_tcpserver); - _started = true; - return _started; + // create instance + _tcpServer = new WiFiServer(_port); + if (!_tcpServer) { + return false; + } + _tcpServer->setNoDelay(true); + // start webdav server + _tcpServer->begin(); + _started = true; + return _started; } /** - * End WebDav + * End Telnet */ -void Webdav_Server::end() -{ - _started = false; - _port = 0; +void WebdavServer::end() { + _started = false; + _port = 0; + closeClient(); + if (_tcpServer) { + delete _tcpServer; + _tcpServer = nullptr; + } +} + +bool WebdavServer::started() { return _started; } + +void WebdavServer::handle() { + Hal::wait(0); + if (isConnected()) { + parseRequest(); closeClient(); - _tcpserver.stop(); - _dav.end(); + } } -bool Webdav_Server::started() -{ - return _started; +void WebdavServer::parseRequest() { + String line = ""; + _headers_sent = false; + _is_chunked = false; + _response_code_sent = false; + _headers.clear(); + // read the first line of the request to get the request method, URL and + // HTTP + log_esp3d("Parsing new request:\n"); + if (_client.connected() && _client.available()) { + bool hasError = false; + bool lineIsRead = false; + size_t has_r = 0; + Esp3dTimout timeout(TIMEOUT_WEBDAV_REQUEST); + while (!lineIsRead) { + int c = _client.read(); + if (c == -1) { + if (timeout.isTimeout()) { + hasError = true; + log_esp3d_e("Timeout"); + lineIsRead = true; + } + } else { + if (c == '\n') { + lineIsRead = true; + if (has_r != 1) { + hasError = true; + log_esp3d_e("Bad line ending"); + } + } else if (c != '\r') { + line += (char)c; + } else { + has_r++; + } + } + } + if (hasError) { + send_response_code(400); + send_webdav_headers(); + _client.print("\r\n"); // empty line + log_esp3d_e("Bad request line: %s", line.c_str()); + return; + } + + log_esp3d("Request: %s", line.c_str()); + size_t pos1 = line.indexOf(' '); + size_t pos2 = line.indexOf(' ', pos1 + 1); + if (pos1 == -1 || pos2 == -1) { + send_response_code(400); + log_esp3d_e("Bad request line: %s", line.c_str()); + send_webdav_headers(); + _client.print("\r\n"); // empty line + return; + } + String method = line.substring(0, pos1); + method.toUpperCase(); + String url = line.substring(pos1 + 1, pos2); + // Do some sanity check + url.trim(); + method.trim(); + // if empty + if (url.length() == 0) { + url = "/"; + } + // if encoded + url = urlDecode(url.c_str()); + log_esp3d("url ini: %s", url.c_str()); + if (url != "/" && url[url.length() - 1] == '/') { + url = url.substring(0, url.length() - 1); + } + // if not starting with / + if (url[0] != '/') { + url = "/" + url; + } + log_esp3d("url clean: %s", url.c_str()); + + // Now list all headers + bool headers_read = false; + while (!headers_read) { + lineIsRead = false; + has_r = 0; + line = ""; + timeout.reset(); + while (!lineIsRead && !hasError) { + int c = _client.read(); + if (c == -1) { + if (timeout.isTimeout()) { + hasError = true; + log_esp3d_e("Timeout"); + lineIsRead = true; + } + } else { + if (c == '\n') { + lineIsRead = true; + if (has_r != 1) { + hasError = true; + log_esp3d_e("Bad line ending %d r, %s", has_r, line.c_str()); + } + } else if (c != '\r') { + line += (char)c; + } else { + has_r++; + } + } + } + log_esp3d("Line: %s", line.c_str()); + if (hasError) { + send_response_code(400); + send_webdav_headers(); + _client.print("\r\n"); // empty line + log_esp3d_e("Bad request line: %s", line.c_str()); + return; + } + if (line.length() == 0) { + headers_read = true; + } else { + pos1 = line.indexOf(':'); + String header_name = line.substring(0, pos1); + String header_value = line.substring(pos1 + 1); + header_name.trim(); + header_value.trim(); + log_esp3d("Header: %s = %s", header_name.c_str(), header_value.c_str()); + _headers.push_back(std::make_pair(header_name, header_value)); + } + } + + selectHandler(method.c_str(), url.c_str()); + } } -void Webdav_Server::handle() -{ - _dav.handleClient(); +bool WebdavServer::send_response_code(int code) { + if (_headers_sent) { + log_esp3d_e("Headers already sent"); + return false; + } + if (_response_code_sent) { + log_esp3d_e("Response code already sent"); + return false; + } + + _client.print("HTTP/1.1 "); + _client.print(String(code).c_str()); + _client.print(" "); + _response_code_sent = true; + switch (code) { + case 200: + _client.print("OK"); + break; + case 201: + _client.print("Created"); + break; + case 204: + _client.print("No Content"); + break; + case 207: + _client.print("Multi-Status"); + break; + case 400: + _client.print("Bad Request"); + break; + case 401: + _client.print("Unauthorized"); + break; + case 403: + _client.print("Forbidden"); + break; + case 404: + _client.print("Not Found"); + break; + case 405: + _client.print("Method Not Allowed"); + break; + case 409: + _client.print("Conflict"); + break; + case 412: + _client.print("Precondition Failed"); + break; + case 423: + _client.print("Locked"); + break; + case 424: + _client.print("Failed Dependency"); + break; + case 500: + _client.print("Internal Server Error"); + break; + case 501: + _client.print("Not Implemented"); + break; + case 507: + _client.print("Insufficient Storage"); + break; + default: + _client.print("Unknown"); + _client.print("\r\n\r\n"); + log_esp3d_e("Unknown code %d", code); + return false; + break; + } + _client.print("\r\n"); + return true; } -#endif //WEBDAV_FEATURE +const char* WebdavServer::urlDecode(const char* url) { + static char* decoded = nullptr; + if (decoded) { + free(decoded); + } + char temp[] = "0x00"; + unsigned int len = strlen(url); + unsigned int i = 0; + unsigned int p = 0; + decoded = (char*)malloc(len + 1); + if (decoded) { + while (i < len) { + char decodedChar; + char encodedChar = url[i++]; + if ((encodedChar == '%') && (i + 1 < len)) { + temp[2] = url[i++]; + temp[3] = url[i++]; + decodedChar = strtol(temp, NULL, 16); + } else { + if (encodedChar == '+') { + decodedChar = ' '; + } else { + decodedChar = encodedChar; // normal ascii char + } + } + decoded[p++] = decodedChar; + } + decoded[p] = 0x0; + return decoded; + } else { + log_esp3d_e("Can't allocate memory for decoded url"); + return nullptr; + } +} + +bool WebdavServer::send_header(const char* name, const char* value) { + if (_headers_sent) { + log_esp3d_e("Headers already sent"); + return false; + } + if (!_response_code_sent) { + send_response_code(200); + } + _client.print(name); + _client.print(": "); + _client.print(value); + _client.print("\r\n"); + return true; +} + +bool WebdavServer::send_webdav_headers() { + if (_headers_sent) { + log_esp3d_e("Headers already sent"); + return false; + } + if (!_response_code_sent) { + send_response_code(200); + } + send_header("DAV", "1"); + send_header("Allow", + "OPTIONS, GET, HEAD, PUT, DELETE, COPY, MOVE, MKCOL, PROPFIND"); + send_header("Connection", "close"); + send_header("Cache-Control", "no-cache"); + + static String ua = ""; + static String host = ""; + if (ua.length() == 0) { + ua = "ESP3D-WebdavServer/1.0 ("; + ua += Settings_ESP3D::TargetBoard(); + ua += "; Firmware/"; + ua += FW_VERSION; + ua += "; Platform/arduino; Embedded; http://www.esp3d.io)"; + } + if (host.length() == 0) { + host = "Host: http://"; + host += NetConfig::localIP(); + if (_port != 80) { + host += ":"; + host += String(_port); + } + } + + send_header("User-Agent", ua.c_str()); + send_header("Host", host.c_str()); + + return true; +} + +bool WebdavServer::send_chunk_content(const char* response) { + if (!_is_chunked) { + _is_chunked = true; + if (!send_header("Transfer-Encoding", "chunked")) { + log_esp3d_e("Can't send chunked header"); + return false; + } + _headers_sent = true; + _client.print("\r\n"); + } + _client.printf("%X", strlen(response)); + _client.print("\r\n"); + _client.print(response); + _client.print("\r\n"); + // end of chunk + if (strlen(response) == 0) { + // set it end of chunk + _client.print("\r\n"); + } + return true; +} + +bool WebdavServer::send_response(const char* response) { + if (send_header("Content-Length", String(strlen(response)).c_str())) { + send_header("Content-Type", "text/html; charset=utf-8"); + _client.print("\r\n"); + _headers_sent = true; + _client.print(response); + _client.print("\r\n"); + return true; + } + return false; +} + +bool WebdavServer::selectHandler(const char* method, const char* url) { + log_esp3d("Method: %s", method); + log_esp3d("URL: %s", url); + if (strcasecmp(method, "OPTIONS") == 0) { + handler_options(url); + return true; + } + if (strcasecmp(method, "GET") == 0) { + handler_get(url); + return true; + } + if (strcasecmp(method, "PUT") == 0) { + handler_put(url); + return true; + } + if (strcasecmp(method, "HEAD") == 0) { + handler_head(url); + return true; + } + if (strcasecmp(method, "COPY") == 0) { + handler_copy(url); + return true; + } + if (strcasecmp(method, "MOVE") == 0) { + handler_move(url); + return true; + } + if (strcasecmp(method, "MKCOL") == 0) { + handler_mkcol(url); + return true; + } + if (strcasecmp(method, "DELETE") == 0) { + handler_delete(url); + return true; + } + if (strcasecmp(method, "LOCK") == 0) { + handler_lock(url); + return true; + } + if (strcasecmp(method, "UNLOCK") == 0) { + handler_unlock(url); + return true; + } + if (strcasecmp(method, "PROPFIND") == 0) { + handler_propfind(url); + return true; + } + if (strcasecmp(method, "PROPPATCH") == 0) { + handler_proppatch(url); + return true; + } + log_esp3d_e("Unknown method %s for %s", method, url); + send_response_code(405); + send_webdav_headers(); + _client.print("\r\n"); // empty line + return false; +} +size_t WebdavServer::clearPayload() { + size_t res = 0; + uint8_t chunk[50]; + if (_client) { + while (_client.available()) { + res += _client.read(chunk, sizeof(chunk)); + } + } + return res; +} +bool WebdavServer::hasHeader(const char* name) { + for (auto it = _headers.begin(); it != _headers.end(); ++it) { + // look for header with name + std::pair header = *it; + log_esp3d("Header: %s = %s", header.first.c_str(), header.second.c_str()); + // if present return true + if (strcasecmp(header.first.c_str(), name) == 0) { + return true; + } + } + return false; +} +const char* WebdavServer::getHeader(const char* name) { + static String res; + res = ""; + for (auto it = _headers.begin(); it != _headers.end(); ++it) { + // look for header with name + std::pair header = *it; + // if present return true + if (strcasecmp(header.first.c_str(), name) == 0) { + log_esp3d("Header %s found value %s", name, header.second.c_str()); + res = header.second; + return res.c_str(); + } + } + + return res.c_str(); +} + +bool WebdavServer::isRoot(const char* url) { + if (strcmp(url, "/") == 0) { + return true; + } +#if WEBDAV_FEATURE == FS_ROOT +#ifdef FILESYSTEM_FEATURE + if (strcmp(url, ESP_FLASH_FS_HEADER) == 0) return true; +#endif // FILESYSTEM_FEATURE +#if defined(SD_FEATURE) + if (strcmp(url, ESP_SD_FS_HEADER) == 0) return true; +#endif // SD_FEATURE + +#endif // WEBDAV_FEATURE == FS_ROOT + return false; +} +#endif // WEBDAV_FEATURE diff --git a/esp3d/src/modules/webdav/webdav_server.h b/esp3d/src/modules/webdav/webdav_server.h index 747b20b8..2c69f1ce 100644 --- a/esp3d/src/modules/webdav/webdav_server.h +++ b/esp3d/src/modules/webdav/webdav_server.h @@ -1,7 +1,7 @@ /* - webdav_server.h - webdav service functions class + webdav_server.h - webdav service functions class - Copyright (c) 2014 Luc Lebosse. All rights reserved. + Copyright (c) 2023 Luc Lebosse. All rights reserved. This code is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -20,35 +20,82 @@ #ifndef _WEBDAV_SERVER_H #define _WEBDAV_SERVER_H +#include + +#include +#include + +#include "../../include/esp3d_config.h" + +#if WEBDAV_FEATURE == FS_ROOT +#include "../filesystem/esp_globalFS.h" +typedef ESP_GBFile WebDavFile; +typedef ESP_GBFS WebDavFS; +#endif // WEBDAV_FEATURE == FS_ROOT + +#if WEBDAV_FEATURE == FS_FLASH +#include "../filesystem/esp_filesystem.h" +typedef ESP_File WebDavFile; +typedef ESP_FileSystem WebDavFS; +#endif // WEBDAV_FEATURE == FS_FLASH + +#if WEBDAV_FEATURE == FS_SD +#include "../filesystem/esp_sd.h" +typedef ESP_SDFile WebDavFile; +typedef ESP_SD WebDavFS; +#endif // WEBDAV_FEATURE == FS_SD -#include "ESPWebDAV.h" class WiFiServer; +class WiFiClient; -class Webdav_Server -{ -public: - Webdav_Server(); - ~Webdav_Server(); - bool begin(); - void end(); - void handle(); - bool started(); - bool isConnected(); - const char* clientIPAddress(); - uint16_t port() - { - return _port; - } - void dir(); - void closeClient(); -private: - bool _started; - uint16_t _port; - WiFiServer _tcpserver; - ESPWebDAV _dav; +class WebdavServer { + public: + WebdavServer(); + ~WebdavServer(); + bool begin(); + void end(); + void handle(); + bool started(); + bool isConnected(); + const char* clientIPAddress(); + uint16_t port() { return _port; } + void closeClient(); + void parseRequest(); + bool selectHandler(const char* method, const char* url); + size_t clearPayload(); + bool hasHeader(const char* name); + const char* getHeader(const char* name); + void handler_options(const char* url); + void handler_get(const char* url); + void handler_put(const char* url); + void handler_head(const char* url); + void handler_copy(const char* url); + void handler_move(const char* url); + void handler_mkcol(const char* url); + void handler_delete(const char* url); + void handler_lock(const char* url); + void handler_unlock(const char* url); + void handler_propfind(const char* url); + void handler_proppatch(const char* url); + bool send_response_code(int code); + bool send_header(const char* name, const char* value); + bool send_webdav_headers(); + bool send_response(const char* response); + bool send_chunk_content(const char* content); + const char* urlDecode(const char* url); + bool isRoot(const char* url); + + private: + bool _started; + bool _headers_sent; + bool _is_chunked; + bool _response_code_sent; + std::list> _headers; + WiFiServer* _tcpServer; + WiFiClient _client; + uint16_t _port; }; -extern Webdav_Server webdav_server; +extern WebdavServer webdav_server; #endif - diff --git a/libraries/arduinoWebSockets-2.3.6/src/WebSocketsServer.cpp b/libraries/arduinoWebSockets-2.3.6/src/WebSocketsServer.cpp index a32a27d8..3fd25c51 100644 --- a/libraries/arduinoWebSockets-2.3.6/src/WebSocketsServer.cpp +++ b/libraries/arduinoWebSockets-2.3.6/src/WebSocketsServer.cpp @@ -412,9 +412,9 @@ IPAddress WebSocketsServerCore::remoteIP(uint8_t num) { } #endif -//################################################################################# -//################################################################################# -//################################################################################# +// ################################################################################# +// ################################################################################# +// ################################################################################# /** * handle new client connection @@ -636,7 +636,7 @@ void WebSocketsServer::handleNewClients(void) { #endif // store new connection - WEBSOCKETS_NETWORK_CLASS * tcpClient = new WEBSOCKETS_NETWORK_CLASS(_server->available()); + WEBSOCKETS_NETWORK_CLASS * tcpClient = new WEBSOCKETS_NETWORK_CLASS(_server->accept()); if(!tcpClient) { DEBUG_WEBSOCKETS("[WS-Client] creating Network class failed!"); return; @@ -659,7 +659,7 @@ void WebSocketsServerCore::handleClientData(void) { if(clientIsConnected(client)) { int len = client->tcp->available(); if(len > 0) { - //DEBUG_WEBSOCKETS("[WS-Server][%d][handleClientData] len: %d\n", client->num, len); + // DEBUG_WEBSOCKETS("[WS-Server][%d][handleClientData] len: %d\n", client->num, len); switch(client->status) { case WSC_HEADER: { String headerLine = client->tcp->readStringUntil('\n'); @@ -713,7 +713,7 @@ void WebSocketsServerCore::handleHeader(WSclient_t * client, String * headerLine // cut URL out client->cUrl = headerLine->substring(4, headerLine->indexOf(' ', 4)); - //reset non-websocket http header validation state for this client + // reset non-websocket http header validation state for this client client->cHttpHeadersValid = true; client->cMandatoryHeadersCount = 0;