diff --git a/.vscode/settings.json b/.vscode/settings.json index a0476bfb..7e6afad8 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,6 +1,8 @@ { "git.ignoreLimitWarning": true, "files.associations": { + "**/frontmatter.json": "jsonc", + "**/.frontmatter/config/*.json": "jsonc", "*.tcc": "cpp", "fstream": "cpp", "string": "cpp", @@ -11,7 +13,45 @@ "vector": "cpp", "string_view": "cpp", "initializer_list": "cpp", - "typeinfo": "cpp" + "typeinfo": "cpp", + "atomic": "cpp", + "cctype": "cpp", + "clocale": "cpp", + "cmath": "cpp", + "cstdarg": "cpp", + "cstddef": "cpp", + "cstdint": "cpp", + "cstdio": "cpp", + "cstdlib": "cpp", + "cstring": "cpp", + "ctime": "cpp", + "cwchar": "cpp", + "cwctype": "cpp", + "list": "cpp", + "exception": "cpp", + "algorithm": "cpp", + "functional": "cpp", + "iterator": "cpp", + "map": "cpp", + "memory": "cpp", + "memory_resource": "cpp", + "numeric": "cpp", + "optional": "cpp", + "random": "cpp", + "system_error": "cpp", + "tuple": "cpp", + "type_traits": "cpp", + "utility": "cpp", + "iomanip": "cpp", + "iosfwd": "cpp", + "istream": "cpp", + "limits": "cpp", + "new": "cpp", + "ostream": "cpp", + "sstream": "cpp", + "stdexcept": "cpp", + "streambuf": "cpp", + "cinttypes": "cpp" }, "cmake.configureOnOpen": false } \ No newline at end of file diff --git a/Features.md b/Features.md index 655c1394..52127dec 100644 --- a/Features.md +++ b/Features.md @@ -56,6 +56,7 @@ * Telegram * PushOver * IFTTT + * HomeAssistant * Sensors support * DHT 11/22 * Analog diff --git a/README.md b/README.md index 3140a10d..5e28ab61 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,7 @@ Please use discord : [![discord](https://img.shields.io/discord/7528221487955969 - Pushover support come from https://github.com/ArduinoHannover/Pushover - Email support come from https://github.com/CosmicBoris/ESP8266SMTP and https://www.electronicshub.org/send-an-email-using-esp8266/ - Telegram support come from https://medium.com/@xabaras/sending-a-message-to-a-telegram-channel-the-easy-way-eb0a0b32968 +- HomeAssistant support come from https://developers.home-assistant.io/docs/api/rest/ # Credits: libraries diff --git a/docs/Commands.md b/docs/Commands.md index 339b52c0..92428840 100644 --- a/docs/Commands.md +++ b/docs/Commands.md @@ -164,7 +164,7 @@ label can be: light/framesize/quality/contrast/brightness/saturation/gainceiling ESP_INTERNET_TIME 120 //1 byte = flag ESP_HTTP_PORT 121 //4 bytes = int ESP_TELNET_PORT 125 //4 bytes = int - ESP_SERIAL_FLAG 129 //1 bytes = flag + FREE 129 //1 bytes = flag ESP_HOSTNAME 130 //33 bytes 32+1 = string ; warning does not support multibyte char like chinese ESP_SENSOR_INTERVAL 164 //4 bytes = int ESP_SETTINGS_VERSION 168 //8 bytes = 7+1 = string ESP3D + 2 digits @@ -179,44 +179,44 @@ label can be: light/framesize/quality/contrast/brightness/saturation/gainceiling ESP_TELNET_ON 329 //1 byte = flag ESP_WEBSOCKET_ON 330 //1 byte = flag ESP_SD_SPEED_DIV 331 //1 byte = flag - ESP_NOTIFICATION_TOKEN1 332 //64 bytes 63+1 = string ; warning does not support multibyte char like chinese - 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_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 - ESP_TIME_SERVER3 722 //129 bytes 128+1 = string ; warning does not support multibyte char like chinese - ESP_REMOTE_SCREEN 851 //1 bytes = flag - ESP_SD_MOUNT 852 //1 bytes = flag - ESP_SESSION_TIMEOUT 853 //1 bytes = flag - ESP_WEBSOCKET_FLAG 854 //1 bytes = flag - ESP_SD_CHECK_UPDATE_AT_BOOT 855//1 bytes = flag - ESP_NOTIFICATION_SETTINGS 856 //129 bytes 128+1 = string ; warning does not support multibyte char like chinese - ESP_CALIBRATION_1 985 //4 bytes = int - ESP_CALIBRATION_2 989 //4 bytes = int - ESP_CALIBRATION_3 993 //4 bytes = int - ESP_CALIBRATION_4 997 //4 bytes = int - ESP_CALIBRATION_5 1001 //4 bytes = int - ESP_SETUP 1005 //1 byte = flag - ESP_TELNET_FLAG 1006 //1 byte = flag - ESP_BT_FLAG 1007 //1 byte = flag - ESP_SCREEEN_FLAG 1008 //1 byte = flag - ESP_FTP_CTRL_PORT 1009 //4 bytes = int - ESP_FTP_DATA_ACTIVE_PORT 1013 //4 bytes = int - ESP_FTP_DATA_PASSIVE_PORT 1017 //4 bytes = int - ESP_FTP_ON 1021 //1 byte = flag - ESP_AUTO_NOTIFICATION 1022 //1 byte = flag - ESP_VERBOSE_BOOT 1023 //1 byte = flag - ESP_WEBDAV_ON 1024 //1 byte = flag - ESP_WEBDAV_PORT 1025 //4 bytes = int - ESP_STA_DNS_VALUE 1029 //4 bytes= int - ESP_SECURE_SERIAL 1033 //1 byte = flag - 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 + ESP_NOTIFICATION_TOKEN1 332 //251 bytes 250+1 = string ; warning does not support multibyte char like chinese + ESP_NOTIFICATION_TOKEN2 583 //64 bytes 63+1 = string ; warning does not support multibyte char like chinese + ESP_SENSOR_TYPE 647 //1 bytes = flag + ESP_TARGET_FW 648 //1 bytes = flag + FREE 649 //1 bytes = flag + FREE 650 //1 bytes = flag + ESP_TIME_SERVER1 651 //129 bytes 128+1 = string ; warning does not support multibyte char like chinese + ESP_TIME_SERVER2 780 //129 bytes 128+1 = string ; warning does not support multibyte char like chinese + ESP_TIME_SERVER3 909 //129 bytes 128+1 = string ; warning does not support multibyte char like chinese + ESP_REMOTE_SCREEN 1038 //1 bytes = flag + ESP_SD_MOUNT 1039 //1 bytes = flag + ESP_SESSION_TIMEOUT 1040 //1 bytes = flag + FREE FLAG 1041 //1 bytes = flag + ESP_SD_CHECK_UPDATE_AT_BOOT 1042//1 bytes = flag + ESP_NOTIFICATION_SETTINGS 1043 //129 bytes 128+1 = string ; warning does not support multibyte char like chinese + ESP_CALIBRATION_1 1172 //4 bytes = int + ESP_CALIBRATION_2 1176 //4 bytes = int + ESP_CALIBRATION_3 1180 //4 bytes = int + ESP_CALIBRATION_4 1184 //4 bytes = int + ESP_CALIBRATION_5 1188 //4 bytes = int + ESP_SETUP 1192 //1 byte = flag + FREE 1193 //1 byte = flag + FREE 1194 //1 byte = flag + FREE 1195 //1 byte = flag + ESP_FTP_CTRL_PORT 1196 //4 bytes = int + ESP_FTP_DATA_ACTIVE_PORT 1200 //4 bytes = int + ESP_FTP_DATA_PASSIVE_PORT 1204 //4 bytes = int + ESP_FTP_ON 1208 //1 byte = flag + ESP_AUTO_NOTIFICATION 1209 //1 byte = flag + ESP_VERBOSE_BOOT 1210 //1 byte = flag + ESP_WEBDAV_ON 1211 //1 byte = flag + ESP_WEBDAV_PORT 1212 //4 bytes = int + ESP_STA_DNS_VALUE 1216 //4 bytes= int + ESP_SECURE_SERIAL 1220 //1 byte = flag + ESP_SERIAL_BRIDGE_ON 1223 //1 byte = flag + FREE 1224 //1 byte = flag + ESP_SERIAL_BRIDGE_BAUD 1225 //4 bytes= int + ESP_TIME_ZONE 1229 //7 bytes= string ``` * Get/Set Check update at boot state which can be ON, OFF @@ -238,6 +238,12 @@ label can be: light/framesize/quality/contrast/brightness/saturation/gainceiling output is JSON or plain text according parameter `[ESP450]json= ` +* Get authentication level + `[ESP500] json=` + +* Get/Set session timeout + `[ESP510] json= pwd=` + * Change admin password `[ESP550] json= pwd=` @@ -299,8 +305,6 @@ label can be: light/framesize/quality/contrast/brightness/saturation/gainceiling * Get state / Set Enable / Disable buzzer `[ESP910] json= pwd=` -* Get state / Set state of output message clients - `[ESP920]= json= pwd=` * Get state / Set Enable / Disable Serial Bridge Communication `[ESP930] json= pwd=` diff --git a/docs/authentication.md b/docs/authentication.md new file mode 100644 index 00000000..a1cc30a9 --- /dev/null +++ b/docs/authentication.md @@ -0,0 +1,157 @@ ++++ +archetype = "section" +title = "Authentication" +description = "What is authentication in ESP3D?" +weight = 800 ++++ + +# Definition +The authentication is an additional security layer to protect the ESP3D web interface and ESP3D commands from unauthorized access. It is based on a username and a password. The authentication is optional and can be enabled/disabled in the ESP3D configuration. There are 3 login levels for authentication: +- guest, which is does not need any authentication +- user, which has limited access to ESP3D features +- admin, which has full access to ESP3D features + +Currently the login cannot be customized and so is limited to `user` and `admin` levels. The `guest` level is always available and cannot be disabled. + +# Configuration + +In configuration.h just uncomment the following line to enable the authentication: +```c++ +#define AUTHENTICATION_FEATURE +``` +Default password authentication for `admin` is `admin` and for 'user' is `user`. You can change them using WebInterface or [ESP550] and [ESP555] commands. + +# Usage + +## Web Interface + +When user authentication is enabled, the web interface will ask for a username and a password. If the authentication is successful, the user will be redirected to the web interface. If the authentication fails, the user will be redirected to the login page. + +The web interface allows also inline authentication. This means that you can pass the username and password in the URL. This is useful if you want to use some command line to access the web interface like curl or wget. The URL format is the following: + +```html +http://user:password@ +``` + +On the web interface an authenticated session will stay open until the browser is closed. So if you close the browser and reopen it, you will be asked for authentication again. This session can also have a timeout. The default timeout is 3 minutes of inactivity. This timeout can be changed in the ESP3D configuration web interface or using `[ESP510]` command. + +## ESPXXX Command + +When user authentication is enabled, the ESPXXX commands will ask for a password. If the authentication is successful, the command will be executed. If the authentication fails, the command will be rejected. + +The session for ESPXXX commands is a sticky session. This means that once authenticated, the session will stay authenticated until the ESP3D is restarted or session is closed (e.g: Telnet / WebSocket). +# Limitations + +The current authentication miss a lot of features, like: +- user management +- https support +- password encryption +- password recovery +- password expiration in time +- password lockout if too many failed attempts + +So you must not consider authentication as fullproof for security. It is just an additional layer of security. + +Because ESPXXX commands only rely on password, do not use same password for user and admin users. If you do so, you will not be able to use ESPXXX commands with user level, everything will be considered as admin when authenticated. + +The password are never been displayed in clear text, but they are stored in the ESP3D configuration in clear text. So if you want to change the password, you must use the WebInterface or ESPXXX commands. +In web interface the passwords are replaced by `*******` so any modification must be complete not partial. + +All passwords and sensitive informations are sent using plain text. So if you want to use ESP3D in a public network or outside of your local network (which is not recommended), you must use a VPN. + +# Scope + +Here the scope of right for each authentication level: +|Feature | not authenticated | guest | user | admin | +|-|:-------------------:|:--------:|:------:|:-------:| +| Web Interface | No | No | Yes | Yes | +| Telnet | No | No | Yes | Yes | +| WebSocket | No | No | Yes | Yes | +| WebDav | No | No | Yes | Yes | +| Bluetooth | No | No | Yes | Yes | +| Upload | No | No | Yes | Yes | +| Update | No | No | No | Yes | +| ESP0 | Yes | Yes | Yes | Yes | +| ESP100 | No | No | Get | Get/Set | +| ESP101 | No | No | No | Set | +| ESP102 | No | No | Get | Get/Set | +| ESP103 | No | No | Get | Get/Set | +| ESP104 | No | No | Get | Get/Set | +| ESP105 | No | No | Get | Get/Set | +| ESP106 | No | No | Set | Set | +| ESP107 | No | No | Get | Get/Set | +| ESP108 | No | No | Get | Get/Set | +| ESP110 | No | No | Get | Get/Set | +| ESP111 | No | No | Get | Get | +| ESP112 | No | No | Get | Get/Set | +| ESP114 | No | No | Get | Get/Set | +| ESP115 | No | No | Get | Get/Set | +| ESP120 | No | No | Get | Get/Set | +| ESP121 | No | No | Get | Get/Set | +| ESP130 | No | No | Get | Get/Set | +| ESP131 | No | No | Get | Get/Set | +| ESP140 | No | No | Get | Get/Set | +| ESP150 | No | No | Get | Get/Set | +| ESP160 | No | No | Get | Get/Set | +| ESP161 | No | No | Get | Get/Set | +| ESP170 | No | No | Get/Set | Get/Set | +| ESP171 | No | No | Get | Get| +| ESP180 | No | No | Get | Get/Set | +| ESP181 | No | No | Get | Get/Set | +| ESP190 | No | No | Get | Get/Set | +| ESP191 | No | No | Get | Get/Set | +| ESP200 | No | No | Get/Set | Get/Set | +| ESP201 | No | No | Get/Set | Get/Set | +| ESP202 | No | No | Get | Get/Set | +| ESP210 | No | No | Get | Get/Set | +| ESP214 | No | No | Set | Set | +| ESP215 | No | No | No | Set | +| ESP220 | No | No | Get | Get | +| ESP250 | No | No | Set | Set | +| ESP290 | No | No | Set | Set | +| ESP400 | No | No | Get | Get | +| ESP401 | No | No | No | Set | +| ESP402 | No | No | Get | Get/Set | +| ESP410 | No | No | Get | Get | +| ESP420 | No | No | Get | Get | +| ESP444 | No | No | Set(only RESTART) | Set | +| ESP450 | No | No | Get | Get | +| ESP500 | Get/Set | Get/Set | Get/Set | Get/Set | +| ESP510 | No | No | Get | Get/Set | +| ESP550 | No | No | No | Get/Set | +| ESP555 | No | No | Get/Set | Get/Set | +| ESP600 | No | No | Set | Set | +| ESP610 | No | No | Get | Get/Set | +| ESP620 | No | No | Set | Set | +| ESP700 | No | No | Set | Set | +| ESP701 | No | No | Get/Set | Get/Set | +| ESP710 | No | No | No | Set | +| ESP715 | No | No | No | Set | +| ESP720 | No | No | Get | Get | +| ESP730 | No | No | Get/Set | Get/Set | +| ESP740 | No | No | Get | Get | +| ESP750 | No | No | Get/Set | Get/Set | +| ESP780 | No | No | Get | Get | +| ESP790 | No | No | Get/Set | Get/Set | +| ESP800 | No | No | Get/Set | Get/Set | +| ESP900 | No | No | Get/Set | Get/Set | +| ESP901 | No | No | Get | Get/Set | +| ESP910 | No | No | Get/Set | Get/Set | +| ESP930 | No | No | Get | Get/Set | +| ESP931 | No | No | Get | Get/Set | +| ESP999 | No | No | No | Set | + +# API Description + +## Global +Each authenticated session have unique session id, that will be stored on ESP3D with additionnal informations: +- session id (25 characters) +- session level (Guest / Admin / User) +- client_id (serial / http / telnet / WebSocket) +- session last activity (timestamp) +- client IP (http) +- Client socket ID (telnet / WebSocket) + +## Http +When authentication is enabled, the http server will check if the session is authenticated. If not, it will ask for authentication. If the session is authenticated, it will check if the session is still valid. If not, it will ask for authentication again. If the session is still valid, it will process the request. +the Session ID is stored in the cookie `ESP3D_SESSIONID`. diff --git a/docs/esp3dcnf.ini b/docs/esp3dcnf.ini index 644a4c6a..86109d7b 100644 --- a/docs/esp3dcnf.ini +++ b/docs/esp3dcnf.ini @@ -90,7 +90,7 @@ FTP_Passive_Port = 55600 #Auto notification AUTONOTIFICATION = Yes -#Notification type None / PushOver / Line / Email / Telegram /IFTTT +#Notification type None / PushOver / Line / Email / Telegram / IFTTT / HomeAssistant NOTIF_TYPE = None #Notification token 1 string of 64 chars max diff --git a/docs/espXXX.md b/docs/espXXX.md index 7e763949..6bdc2410 100644 --- a/docs/espXXX.md +++ b/docs/espXXX.md @@ -182,44 +182,6 @@ the admin password if authentication is enabled * `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]" @@ -252,6 +214,10 @@ the admin password if authentication is enabled "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" @@ -455,7 +421,7 @@ weight = 800 Display current IP ## Input -`[ESP111] json= pwd=` +`[ESP111] json= pwd=` * json=no the output format @@ -468,6 +434,9 @@ the admin password if authentication is enabled * 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` +* ALL + * it is set it will display IP, GW, MSK, DNS ip + ## Output - In json format @@ -1215,12 +1184,11 @@ the admin password if authentication is enabled * 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 + * if RAW is present, it will set the pin mode * PULLUP - * if PULLUP is present, it will set the pin mode to pullup + * if PULLUP is present, it will set the pullup pin mode - * ANALOG * if ANALOG is present, it will set the pin ANALOG @@ -1663,6 +1631,7 @@ Passwords are not displayed and replaced by `********` {"line":"3"}, {"telegram":"4"}, {"IFTTT":"5"}]}, +{"HomeAssistant":"6"}]}, {"F":"service/notification","P":"332","T":"S","R":"1","V":"********","S":"63","H":"t1","M":"0"}, {"F":"service/notification","P":"396","T":"S","R":"1","V":"********","S":"63","H":"t2","M":"0"}, {"F":"service/notification","P":"856","T":"S","R":"1","V":" ","S":"128","H":"ts","M":"0"}, @@ -1723,9 +1692,1595 @@ Note2 : the 2.1 Flag type is no more used, several entries are used instead grou If no json the list is limited to a list of `: ` ```text - Settings: network/network/hostname: esp3d -network/network/mdns: 1 +network/network/radio mode: 5 +network/network/radio_boot: 1 +network/sta/SSID: NETWORK_SSID +network/sta/pwd: ******** +network/sta/ip mode: 1 +network/sta/ip: 192.168.0.254 +network/sta/gw: 192.168.0.254 +network/sta/msk: 255.255.255.0 +network/sta/DNS: 192.168.0.254 +network/sta/sta fallback mode: 5 +network/ap/SSID: ESP3D +network/ap/pwd: ******** +network/ap/ip: 192.168.0.1 +network/ap/channel: 11 +service/time/i-time: 0 +service/time/tzone: +00:00 +service/time/t-server: time.windows.com +service/time/t-server: time.google.com +service/time/t-server: 0.pool.ntp.org +service/notification/auto notif: 1 +service/notification/notification: 0 +service/notification/t1: +service/notification/t2: +service/notification/ts: +system/system/targetfw: 0 +system/system/baud: 115200 +system/boot/bootdelay: 10000 +system/boot/verbose: 0 +ok ``` ++++ +archetype = "section" +title = "[ESP401]" +weight = 800 ++++ +Set ESP3D settings + +## Input +`[ESP401] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* P + * P is the id or position in EEPROM of the setting to change + +* T + * T is the type of the setting to change + * T can be: + - S: for string + - I: for integer + - B: for Byte + - A: for IP address / Mask + - F: for float (only grblHAL) + - M: for bits mask (only grblHAL) + - X: for exclusive bitsfield (only grblHAL) + +* V + * V is the value to set + if value has space add `\`` in front of space to not be seen as separator + e.g: `[ESP401]P=1 T=S V=My\ SSID json` + +## Output + +- In json format + +```json +{ + "cmd":"401", + "status":"ok", + "data":"1" +} +``` + +* `cmd` Id of requested command, should be `401` +* `status` status of command, should be `ok` +* `data` content of response, here the id/position of the setting changed + + ++++ +archetype = "section" +title = "[ESP402]" +weight = 800 ++++ + Get/Set SD updater check at boot time + +## Input +`[ESP402] 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 + +## Output + +- In json format + +```json +{ + "cmd":"402", + "status":"ok", + "data":"OFF" +} +``` + +* `cmd` Id of requested command, should be `402` +* `status` status of command, should be `ok` +* `data` content of response, here the state + + ++++ +archetype = "section" +title = "[ESP410]" +weight = 800 ++++ +List all AP detected around, if signal is too low, AP is not listed to avoid connection problems. + +## Input +`[ESP410] 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":"410", + "status":"ok", + "data":[ + {"SSID":"Luc-Lab","SIGNAL":"100","IS_PROTECTED":"1"}, + {"SSID":"CHT0573(Mesh)","SIGNAL":"100","IS_PROTECTED":"1"}, + {"SSID":"[LG_AirPurifier]","SIGNAL":"48","IS_PROTECTED":"1"}, + ] +} +``` + +* `cmd` Id of requested command, should be `410` +* `status` status of command, should be `ok` +* `data` content of response, here the list of AP detected with signal strength and if protected or not + + - plain text format + +```text +Start Scan +Luc-Lab 100% Secure +CHT0573(Mesh) 100% Secure +[LG_AirPurifier] 46% Secure +End Scan +``` + ++++ +archetype = "section" +title = "[ESP420]" +weight = 800 ++++ +Get ESP3D current status + +## Input +`[ESP420] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + + +## Output + +```json +{ + "cmd":"420", + "status":"ok", + "data":[ + {"id":"chip id","value":"11111"}, + {"id":"CPU Freq","value":"240Mhz"}, + {"id":"CPU Temp","value":"72.8C"}, + {"id":"free mem","value":"232.43 KB"}, + {"id":"SDK","value":"v4.4.4"}, + {"id":"flash size","value":"4.00 MB"}, + {"id":"FS type","value":"LittleFS"}, + {"id":"FS usage","value":"112.00 KB/128.00 KB"}, + {"id":"baud","value":"115200"}, + {"id":"sleep mode","value":"none"}, + {"id":"wifi","value":"ON"}, + {"id":"hostname","value":"esp3d"}, + {"id":"wifi mode","value":"ap"}, + {"id":"mac","value":"D4:D4:D4:D4:D4:D4"}, + {"id":"SSID","value":"ESP3D"}, + {"id":"visible","value":"yes"}, + {"id":"authentication","value":"WPA2"}, + {"id":"DHCP Server","value":"ON"}, + {"id":"ip","value":"192.168.0.1"}, + {"id":"gw","value":"192.168.0.1"}, + {"id":"msk","value":"255.255.255.0"}, + {"id":"clients","value":"0"},{"id":"sta","value":"OFF"}, + {"id":"mac","value":"D4:D4:D4:D4:D4:D4"}, + {"id":"ntp","value":"OFF"}, + {"id":"serial","value":"ON"}, + {"id":"notification","value":"ON (none)"}, + {"id":"targetfw","value":"unknown"}, + {"id":"FW ver","value":"3.0.0.a225"}, + {"id":"FW arch","value":"ESP32"}]} + +``` + +* `cmd` Id of requested command, should be `420` +* `status` status of command, should be `ok` +* `data` content of response, where each status is a key/value pair of id/value + + - plain text format + +```Text +Configuration: +chip id: 1010100 +CPU Freq: 240Mhz +CPU Temp: 72.8C +free mem: 232.47 KB +SDK: v4.4.4 +flash size: 4.00 MB +FS type: LittleFS +FS usage: 112.00 KB/128.00 KB +baud: 115200 +sleep mode: none +wifi: ON +hostname: esp3d +wifi mode: ap +mac: D4:D4:D4:D4:D4:D4 +SSID: ESP3D +visible: yes +authentication: WPA2 +DHCP Server: ON +ip: 192.168.0.1 +gw: 192.168.0.1 +msk: 255.255.255.0 +clients: 0 +sta: OFF +mac: D4:D4:D4:D4:D4:D4 +ntp: OFF +serial: ON +notification: ON (none) +targetfw: unknown +FW ver: 3.0.0.a225 +FW arch: ESP32 +ok +``` + ++++ +archetype = "section" +title = "[ESP444]" +weight = 800 ++++ +Set ESP3D state + +## Input +`[ESP444] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* state + * RESET to reset all settings to default + * RESTART to restart ESP3D + +## Output + +- In json format + +```json +{ + "cmd":"444", + "status":"ok", + "data":"ok" +} +``` + +* `cmd` Id of requested command, should be `444` +* `status` status of command, should be `ok` +* `data` content of response, here `ok` + ++++ +archetype = "section" +title = "[ESP450]" +weight = 800 ++++ +List available ESP3D modules/ ESP3D related devices around + +## Input +`[ESP450] 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":"450", + "status":"ok", + "data":[ + { + "Hostname":"esp3d-tft", + "IP":"192.168.1.108", + "port":"80", + "TxT":[ + {"key":"version","value":"1.0.0.a18"}, + {"key":"firmware","value":"ESP3D-TFT"} + ] + } + ] +} +``` + +* `cmd` Id of requested command, should be `450` +* `status` status of command, should be `ok` +* `data` content of response, here the list of modules detected with hostname, IP, port and TXT record + + - plain text format + +```Text +Start Scan +esp3d-tft (192.168.1.108:80) version=1.0.0.a18,firmware=ESP3D-TFT +End Scan +``` + + ++++ +archetype = "section" +title = "[ESP500]" +weight = 800 ++++ +Get authentication status + +## Input +`[ESP500] 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":"500", + "status":"ok", + "data":"admin" +} +``` + +* `cmd` Id of requested command, should be `500` +* `status` status of command, should be `ok` +* `data` content of response, here the current user authenticated + + - plain text format + +```Text +admin +``` + ++++ +archetype = "section" +title = "[ESP510]" +weight = 800 ++++ +Set/display session time out + +## Input +`[ESP510] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* timeout + * if timeout is empty, it will display current timeout (0~255 minutes), 0 means disable timeout + * if timeout is not empty, it will set the timeout + +* pwd= +the admin password if authentication is enabled + + +## Output + +- In json format + +```json +{ + "cmd":"510", + "status":"ok", + "data":"10" +} +``` + +* `cmd` Id of requested command, should be `510` +* `status` status of command, should be `ok` +* `data` content of response, here the current timeout + + - plain text format + +```Text +10 +``` + ++++ +archetype = "section" +title = "[ESP550]" +weight = 800 ++++ +Set/Change admin password, only authenticated admin can change the password + +## Input +`[ESP550] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* password + for the admin limited to 20 characters + + +## Output + +- In json format + +```json +{ + "cmd":"550", + "status":"ok", + "data":"ok" +} +``` + +* `cmd` Id of requested command, should be `550` +* `status` status of command, should be `ok` +* `data` content of response, here `ok` when password is changed + + ++++ +archetype = "section" +title = "[ESP555]" +weight = 800 ++++ +Set/Change user password, only authenticated admin/user can change the password + +## Input +`[ESP555] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* password + for the user limited to 20 characters + + +## Output + +- In json format + +```json +{ + "cmd":"555", + "status":"ok", + "data":"ok" +} +``` + +* `cmd` Id of requested command, should be `555` +* `status` status of command, should be `ok` +* `data` content of response, here `ok` when password is changed + + + + ++++ +archetype = "section" +title = "[ESP600]" +weight = 800 ++++ +Send Notification using defined method, will also send notification to webui and eventually to any connected screen + +## Input +`[ESP600] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* message + the message to send, limited to 128 characters. + Message can contain some variables: + - %ESP_NAME% : ESP3D hostname + - %ESP_IP% : ESP3D local IP address + + +## Output + +- In json format + +```json +{ + "cmd":"600", + "status":"ok", + "data":"ok" +} +``` + +* `cmd` Id of requested command, should be `600` +* `status` status of command, should be `ok` +* `data` content of response, here `ok` when notification is sent + ++++ +archetype = "section" +title = "[ESP610]" +weight = 800 ++++ + Set/Get Notification settings + +## Input +`[ESP610]type= T1= T2= TS= json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* type + * if type is empty, it will display current type + * if type is not empty, it will set the type + currently only these types are supported: + - NONE + - PUSHOVER + - EMAIL + - LINE + - TELEGRAM + - IFTTT (by webhook) + - HomeAssistant (via webhook) + +* T1 + * if T1 is not empty, it will set the token1 which depend on [type of notification](https://esp3d.io/esp3d/v3.x/documentation/notifications/index.html) + +* T2 + * if T2 is not empty, it will set the token2 which depend on [type of notification](https://esp3d.io/esp3d/v3.x/documentation/notifications/index.html) + +* TS + if TS is not empty, it will set the setting token which depend on [type of notification](https://esp3d.io/esp3d/v3.x/documentation/notifications/index.html) + + +* pwd= +the admin password if authentication is enabled + + +## Output + +- In json format + +```json +{ + "cmd":"610", + "status":"ok", + "data":"ok" +} +``` + +* `cmd` Id of requested command, should be `610` +* `status` status of command, should be `ok` +* `data` content of response, here `ok` when notification is sent + ++++ +archetype = "section" +title = "[ESP620]" +weight = 800 ++++ +Send Notification using encodded URL + +## Input +`[ESP620] json= pwd=` +* json=no +the output format can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* url + the url to send, limited to 128 characters, must be encoded + + +## Output + +- In json format + +```json +{ + "cmd":"620", + "status":"ok", + "data":"ok" +} +``` + +* `cmd` Id of requested command, should be `620` +* `status` status of command, should be `ok` +* `data` content of response, here `ok` when notification is sent + ++++ +archetype = "section" +title = "[ESP700]" +weight = 800 ++++ +Process local file on /FS or /SD + +## Input +`[ESP700] json= pwd=` + +* json=no +the output format can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* filename + the filename to process, must be a valid file on /FS or /SD + + +## Output + +- In json format + +```json +{ + "cmd":"700", + "status":"ok", + "data":"Processing " +} +``` + +* `cmd` Id of requested command, should be `700` +* `status` status of command, should be `ok` +* `data` content of response, here `Processing ` when file is processing + ++++ +archetype = "section" +title = "[ESP701]" +weight = 800 ++++ +Query and Control ESP700 stream + +## Input +`[ESP701]action= json= pwd=` + +* json=no +the output format can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* action + * if action is empty, it will display current state + * if action is not empty, it will set the action + currently only these actions are supported: + - ABORT + - PAUSE + - RESUME + +* CLEAR_ERROR + * if CLEAR_ERROR is present, it will clear the current error state + + +## Output + +- In json format + +```json +{ + "cmd":"701", + "status":"ok", + "data":{ + "status":"processing", + "total":"1000", + "processed":"500", + "type":"1", + "name":"/SD/myfile.gco" + } +} +``` + +* `cmd` Id of requested command, should be `701` +* `status` status of command, should be `ok` +* `data` content of response, here the current state of stream + + + ++++ +archetype = "section" +title = "[ESP710]" +weight = 800 ++++ +Format ESP Filesystem + +## Input +`[ESP710]FORMATFS json= pwd=` + +* json=no +the output format can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* FORMATFS + * if FORMATFS is present, it will format the local filesystem + + +## Output + +- In json format + +```json +{ + "cmd":"710", + "status":"ok", + "data":"Starting formating..." +} +``` + +* `cmd` Id of requested command, should be `710` +* `status` status of command, should be `ok` +* `data` content of response, here `Starting formating...` when filesystem is starting + + +an new message is sent when formating is done + +```json +{ + "cmd":"710", + "status":"ok", + "data":"Formating done" +} +``` + +* `cmd` Id of requested command, should be `710` +* `status` status of command, should be `ok` +* `data` content of response, here `Formating done` when filesystem is done + ++++ +archetype = "section" +title = "[ESP715]" +weight = 800 ++++ +Format SD Card + +## Input +`[ESP715]FORMATSD json= pwd=` + +* json=no +the output format can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* FORMATSD + * if FORMATSD is present, it will format the SD card + + +## Output + +- In json format + +```json +{ + "cmd":"715", + "status":"ok", + "data":"Starting formating..." +} +``` + +* `cmd` Id of requested command, should be `715` +* `status` status of command, should be `ok` +* `data` content of response, here `Starting formating...` when SD card is starting + +an new message is sent when formating is done + +```json +{ + "cmd":"715", + "status":"ok", + "data":"Formating done" +} +``` + +* `cmd` Id of requested command, should be `715` +* `status` status of command, should be `ok` +* `data` content of response, here `Formating done` when SD card is done + ++++ +archetype = "section" +title = "[ESP720]" +weight = 800 ++++ +List files on /FS or defined repository + +## Input +`[ESP720] json= pwd=` + +* json=no +the output format can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* Root + * if Root is empty, it will list files on /FS + * if Root is not empty, it will list files on defined repository + + +## Output + +* json + +```json +{ + "cmd":"720", + "status":"ok", + "data":{ + "path":"/", + "files":[ + {"name":"index.html.gz","size":"88.67 KB","time":"2023-11-05 11:57:57"} + ], + "total":"128.00 KB", + "used":"100.00 KB", + "occupation":"78" + } +} +``` + +* `cmd` Id of requested command, should be `720` +* `status` status of command, should be `ok` +* `data` content of response, here the list of files on /FS or defined repository + + +* txt + +```text +Directory on Flash : / + index.html.gz 88.67 KB 2023-11-05 11:57:57 +Files: 1, Dirs :0 +Total: 128.00 KB, Used: 100.00 KB, Available: 28.00 KB +``` + ++++ +archetype = "section" +title = "[ESP730]" +weight = 800 ++++ +Do some actions on ESP Filesystem: rmdir / remove / mkdir / exists / create + +## Input +`[ESP730]= json= pwd=` + +* json=no +the output format can be in JSON or plain text + +* action + * if action is not empty, it will set the action + currently only these actions are supported: + - RMDIR (dir) + - REMOVE (file) + - MKDIR (dir) + - EXISTS (file/dir) + - CREATE (file) + + +* path + the path to process, must be a valid file or directory on /FS + + +## Output + +- In json format + +```json +{ + "cmd":"730", + "status":"ok", + "data":"ok" +} +``` + +* `cmd` Id of requested command, should be `730` +* `status` status of command, should be `ok` +* `data` content of response, here `ok` when action is done + ++++ +archetype = "section" +title = "[ESP740]" +weight = 800 ++++ +List files on /SD or defined repository + +## Input +`[ESP740] json= pwd=` + +* json=no +the output format can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* Root + * if Root is empty, it will list files on /SD + * if Root is not empty, it will list files on defined repository + + +## Output + +* json + +```json +{ + "cmd":"720", + "status":"ok", + "data":{ + "path":"/", + "files":[ + {"name":"System Volume Information","size":"-1"}, + {"name":"src","size":"-1"}, + {"name":"testdir","size":"-1"}, + {"name":"Newfolder2","size":"-1"}, + {"name":"conventions","size":"-1"}, + {"name":"extensions","size":"-1"}, + {"name":"fileupload","size":"-1"}, + {"name":"realtimecmd","size":"-1"}, + {"name":"variableslist","size":"-1"}, + {"name":"webhandlers","size":"-1"}, + {"name":"websockets","size":"-1"}, + {"name":"main","size":"-1"}, + {"name":"mks_pft70.sys","size":"5 B"}, + {"name":"index.html","size":"57.47 KB"}, + {"name":"index.xml","size":"7.53 KB"}, + {"name":"index.print.html","size":"77.74 KB"} + ], + "total":"7.20 GB", + "used":"52.06 MB", + "occupation":"1" + } +} +``` + +* `cmd` Id of requested command, should be `740` +* `status` status of command, should be `ok` +* `data` content of response, here the list of files on /SD or defined repository + +* text + + ```text + Directory on SD : / +[DIR] System Volume Information +[DIR] src +[DIR] testdir +[DIR] New%20folder2 +[DIR] conventions +[DIR] extensions +[DIR] fileupload +[DIR] realtimecmd +[DIR] variableslist +[DIR] webhandlers +[DIR] websockets +[DIR] main + mks_pft70.sys 5 B + index.html 57.47 KB + index.xml 7.53 KB + index.print.html 77.74 KB +Files: 4, Dirs :12 +Total: 7.20 GB, Used: 52.06 MB, Available: 7.15 GB +``` + + ++++ +archetype = "section" +title = "[ESP750]" +weight = 800 ++++ +Do some actions on SD Card: rmdir / remove / mkdir / exists / create + +## Input +`[ESP750]= json= pwd=` + +* json=no +the output format can be in JSON or plain text + +* action + * if action is not empty, it will set the action + currently only these actions are supported: + - RMDIR (dir) + - REMOVE (file) + - MKDIR (dir) + - EXISTS (file/dir) + - CREATE (file) + + +* path + the path to process, must be a valid file or directory on /SD + +## Output + +- In json format + +```json +{ + "cmd":"750", + "status":"ok", + "data":"ok" +} +``` + +* `cmd` Id of requested command, should be `750` +* `status` status of command, should be `ok` +* `data` content of response, here `ok` when action is done + ++++ +archetype = "section" +title = "[ESP780]" +weight = 800 ++++ +List Global Filesystem + +## Input +`[ESP780] json= pwd=` + +* json=no +the output format can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* Root + * if Root is empty, it will list files on /FS + * if Root is not empty, it will list files on defined repository + + +## Output + +* json + +```json +{ + "cmd":"780", + "status":"ok", + "data":{ + "path":"/", + "files":[ + {"name":"FS","size":"-1"}, + {"name":"SD","size":"-1"} + ], + "total":"0 B", + "used":"0 B", + "occupation":"0" + } +} +``` + +* `cmd` Id of requested command, should be `780` +* `status` status of command, should be `ok` +* `data` content of response, here the list of files on /FS or defined repository + +* text + + ```text +Directory on Global FS : / +[DIR] FS +[DIR] SD +Files: 0, Dirs :2 +Total: 0 B, Used: 0 B, Available: 0 B +``` + ++++ +archetype = "section" +title = "[ESP790]" +weight = 800 ++++ +Do some actions on Global Filesystem: rmdir / remove / mkdir / exists / create + +## Input +`[ESP790]= json= pwd=` + +* json=no +the output format can be in JSON or plain text + +* pwd= +the admin password if authentication is enabled + +* action + * if action is not empty, it will set the action + currently only these actions are supported: + - RMDIR (dir) + - REMOVE (file) + - MKDIR (dir) + - EXISTS (file/dir) + - CREATE (file) + + +* path + the path to process, must be a valid file or directory on /FS or /SD + +## Output + +- In json format + +```json +{ + "cmd":"790", + "status":"ok", + "data":"ok" +} +``` + +* `cmd` Id of requested command, should be `790` +* `status` status of command, should be `ok` +* `data` content of response, here `ok` when action is done + ++++ +archetype = "section" +title = "[ESP800]" +weight = 800 ++++ +Get fw capabilities +eventually set time with pc time and set setup state + + +## Input + +`[ESP800] json= pwd=` + + * json=yes + the output format + * time= + to set ESP3D time using ISO 8601 format : `YYYY`-`MM`-`DD`T`HH`:`minutes`:`seconds` + * tz=+08:00 (optional) + to set ESP3D time zone using ISO 8601 format : `+`/`-` `HH`-`minutes` + * version + version of webUI + * setup flag + Enable / Disable the setup flag + +## Output + +- In json format + +``` +{ + "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) + + + + + ++++ +archetype = "section" +title = "[ESP900]" +weight = 800 ++++ +Get state / Set Serial Communication + +## Input +`[ESP900] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* state + * if state is empty, it will display current state + * if state is not empty, it will set the state + currently only these states are supported: + - ENABLE + - DISABLE + +* pwd= +the admin password if authentication is enabled + + +## Output + +- In json format + +```json +{ + "cmd":"900", + "status":"ok", + "data":"ENABLED" +} +``` + +* `cmd` Id of requested command, should be `900` +* `status` status of command, should be `ok` +* `data` content of response, here the current state + + - plain text format + +```Text +ENABLED +``` + ++++ +archetype = "section" +title = "[ESP901]" +weight = 800 ++++ + Set Serial baudrate for main serial communication + +## Input +`[ESP901] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* baudrate + * if baudrate is empty, it will display current baudrate + * if baudrate is not empty, it will set the baudrate + currently only these baudrates are supported: + - 9600 + - 19200 + - 38400 + - 57600 + - 74880 + - 115200 + - 230400 + - 250000 + - 500000 + - 921600 + - 1958400 + +* pwd= +the admin password if authentication is enabled + + +## Output + +- In json format + +```json +{ + "cmd":"901", + "status":"ok", + "data":"115200" +} +``` + +* `cmd` Id of requested command, should be `901` +* `status` status of command, should be `ok` +* `data` content of response, here the current baudrate + + - plain text format + +```Text +115200 +``` + ++++ +archetype = "section" +title = "[ESP910]" +weight = 800 ++++ +Get state / Set Enable / Disable buzzer + +## Input +`[ESP910] json= pwd=` + +* json=no +the output format +can be in JSON or plain text + +* state + * if state is empty, it will display current state + * if state is not empty, it will set the state + currently only these states are supported: + - ENABLE + - DISABLE + +* pwd= +the admin password if authentication is enabled + + +## Output + +- In json format + +```json +{ + "cmd":"910", + "status":"ok", + "data":"ENABLED" +} +``` + +* `cmd` Id of requested command, should be `910` +* `status` status of command, should be `ok` +* `data` content of response, here the current state + + - plain text format + +```Text +ENABLED +``` + ++++ +archetype = "section" +title = "[ESP930]" +weight = 800 ++++ +Set Bridge Serial state which can be ON, OFF, CLOSE + +## Input +`[ESP930] json= pwd=` + +* json=no +the output format + +* state + * if state is empty, it will display current state + * if state is not empty, it will set the state + currently only these states are supported: + - ENABLE + - DISABLE + - CLOSE + +* pwd= +the admin password if authentication is enabled + + +## Output + +- In json format + +```json +{ + "cmd":"930", + "status":"ok", + "data":"ENABLED" +} +``` + +* `cmd` Id of requested command, should be `930` +* `status` status of command, should be `ok` +* `data` content of response, here the current state + + - plain text format + +```Text +ENABLED +``` + ++++ +archetype = "section" +title = "[ESP931]" +weight = 800 ++++ +Set Bridge Serial baudrate + +## Input +`[ESP931] json= pwd=` + +* json=no +the output format + +* baudrate + * if baudrate is empty, it will display current baudrate + * if baudrate is not empty, it will set the baudrate + currently only these baudrates are supported: + - 9600 + - 19200 + - 38400 + - 57600 + - 74880 + - 115200 + - 230400 + - 250000 + - 500000 + - 921600 + - 1958400 + +* pwd= +the admin password if authentication is enabled + + +## Output + +- In json format + +```json +{ + "cmd":"931", + "status":"ok", + "data":"115200" +} +``` + +* `cmd` Id of requested command, should be `931` +* `status` status of command, should be `ok` +* `data` content of response, here the current baudrate + + - plain text format + +```Text +115200 +``` + ++++ +archetype = "section" +title = "[ESP999]" +weight = 800 ++++ +Set quiet boot if strapping pin is High, can only e done o6nce and cannot be reverted + +## Input +`[ESP999]QUIETBOOT json= pwd=` + +* json=no +the output format + +* pwd= +the admin password if authentication is enabled + +* QUIETBOOT + * if QUIETBOOT is present, it will set the quiet boot flag + + +## Output + +- In json format + +```json +{ + "cmd":"999", + "status":"ok", + "data":"ok" +} +``` + +* `cmd` Id of requested command, should be `999` +* `status` status of command, should be `ok` +* `data` content of response, here `ok` when quiet boot is set + + - plain text format + +```Text +ok +``` + + diff --git a/embedded/config/server.js b/embedded/config/server.js index 1f31897f..0aa219b4 100644 --- a/embedded/config/server.js +++ b/embedded/config/server.js @@ -329,7 +329,7 @@ app.get("/command", function (req, res) { }, { F: "service/ftp", - P: "1021", + P: "1208", T: "B", V: "1", H: "enable", @@ -337,7 +337,7 @@ app.get("/command", function (req, res) { }, { F: "service/ftp", - P: "1009", + P: "1196", T: "I", V: "21", H: "control port", @@ -346,7 +346,7 @@ app.get("/command", function (req, res) { }, { F: "service/ftp", - P: "1013", + P: "1200", T: "I", V: "20", H: "active port", @@ -355,7 +355,7 @@ app.get("/command", function (req, res) { }, { F: "service/ftp", - P: "1017", + P: "1204", T: "I", V: "55600", H: "passive port", @@ -364,7 +364,7 @@ app.get("/command", function (req, res) { }, { F: "service/notification", - P: "1004", + P: "1191", T: "B", V: "1", H: "auto notif", @@ -389,7 +389,7 @@ app.get("/command", function (req, res) { }, { F: "service/notification", - P: "396", + P: "583", T: "S", V: "********", S: "63", @@ -398,7 +398,7 @@ app.get("/command", function (req, res) { }, { F: "service/notification", - P: "855", + P: "1042", T: "S", V: " ", S: "127", @@ -407,7 +407,7 @@ app.get("/command", function (req, res) { }, { F: "system/system", - P: "461", + P: "648", T: "B", V: "40", H: "targetfw", diff --git a/esp3d/configuration.h b/esp3d/configuration.h index c3292a43..eb7af154 100644 --- a/esp3d/configuration.h +++ b/esp3d/configuration.h @@ -498,9 +498,9 @@ // #define CAMERA_DEVICE_FLIP_VERTICALY /* Flip horizontally -* Flip camera horizontally -*/ -//#define CAMERA_DEVICE_FLIP_HORIZONTALY + * Flip camera horizontally + */ +// #define CAMERA_DEVICE_FLIP_HORIZONTALY /************************************ * @@ -527,7 +527,7 @@ /* Enable authentication * Force usage of authentication for commands */ -// #define AUTHENTICATION_FEATURE +//#define AUTHENTICATION_FEATURE /************************************ * @@ -564,7 +564,7 @@ /* Gcode Host Feature * This feature allows to process Gcode files like macros. */ -#define GCODE_HOST_FEATURE +// #define GCODE_HOST_FEATURE /* Settings location * SETTINGS_IN_EEPROM //ESP8266/ESP32 @@ -576,7 +576,7 @@ /* Add serial task * ESP32 need to add a task to handle serial communication */ -#define SERIAL_INDEPENDANT_TASK +// #define SERIAL_INDEPENDANT_TASK /************************************ * @@ -592,11 +592,11 @@ // LOG_OUTPUT_SERIAL2 // LOG_OUTPUT_TELNET // LOG_OUTPUT_WEBSOCKET -// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 +#define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 -#define ESP3D_DEBUG_LEVEL LOG_LEVEL_ERROR +#define ESP3D_DEBUG_LEVEL LOG_LEVEL_DEBUG -// #define ESP_NO_SANITY_CHECK +#define ESP_NO_SANITY_CHECK #ifdef ESP_LOG_FEATURE #define LOG_ESP3D_BAUDRATE 115200 @@ -643,4 +643,4 @@ #undef NOTIFICATION_FEATURE #endif -#endif //_CONFIGURATION_H +#endif //_CONFIGURATION_H \ No newline at end of file diff --git a/esp3d/src/core/commands.cpp b/esp3d/src/core/commands.cpp deleted file mode 100644 index 7f13147a..00000000 --- a/esp3d/src/core/commands.cpp +++ /dev/null @@ -1,969 +0,0 @@ -/* - commands.cpp - ESP3D commands 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 -*/ -// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 -#include "commands.h" - -#include "../include/esp3d_config.h" -#include "esp3d.h" -#include "esp3doutput.h" -#include "settings_esp3d.h" - -#if COMMUNICATION_PROTOCOL == MKS_SERIAL -#include "../modules/mks/mks_service.h" -#endif // COMMUNICATION_PROTOCOL == MKS_SERIAL - -Commands esp3d_commands; - -Commands::Commands() {} - -Commands::~Commands() {} - -// dispatch the command -void Commands::process(uint8_t *sbuf, size_t len, ESP3DOutput *output, - level_authenticate_type auth, ESP3DOutput *outputonly, - uint8_t outputignore) { - static bool lastIsESP3D = false; - log_esp3d("Client is %d, has only %d, has ignore %d", - output ? output->client() : 0, - outputonly ? outputonly->client() : 0, outputignore); - if (is_esp_command(sbuf, len)) { - lastIsESP3D = true; - size_t slen = len; - String tmpbuf = (const char *)sbuf; - if (tmpbuf.startsWith("echo:")) { - tmpbuf.replace("echo: ", ""); - tmpbuf.replace("echo:", ""); - slen = tmpbuf.length(); - } - - uint8_t cmd[4] = {0, 0, 0, 0}; - cmd[0] = tmpbuf[4] == ']' ? 0 : tmpbuf[4]; - cmd[1] = tmpbuf[5] == ']' ? 0 : tmpbuf[5]; - cmd[2] = tmpbuf[6] == ']' ? 0 : tmpbuf[6]; - cmd[3] = 0x0; - log_esp3d("It is ESP command %s", cmd); - log_esp3d("Respond to client %d", (outputonly == nullptr) - ? output->client() - : outputonly->client()); - execute_internal_command( - String((const char *)cmd).toInt(), - (slen > (strlen((const char *)cmd) + 5)) - ? (const char *)&tmpbuf[strlen((const char *)cmd) + 5] - : "", - auth, (outputonly == nullptr) ? output : outputonly); - } else { - // Work around to avoid to dispatch single \n to everyone as it is part of - // previous ESP3D command - if (lastIsESP3D && len == 1 && sbuf[0] == '\n') { - lastIsESP3D = false; - return; - } - lastIsESP3D = false; - // Dispatch to all clients but current or to define output -#if defined(HTTP_FEATURE) - // the web command will never get answer as answer go to websocket - // This is sanity check as the http client should already answered - if (output->client() == ESP_HTTP_CLIENT && !output->footerSent()) { - if (auth != LEVEL_GUEST) { - output->printMSG(""); - } else { - output->printERROR("Wrong authentication!", 401); - return; - } - } -#endif // HTTP_FEATURE - if (outputonly == nullptr) { - log_esp3d("Dispatch from %d, but %d", output->client(), outputignore); - output->dispatch(sbuf, len, outputignore); - } else { - log_esp3d("Dispatch from %d to only %d", output->client(), - outputonly->client()); -#if COMMUNICATION_PROTOCOL == MKS_SERIAL - if (outputonly->client() == ESP_SERIAL_CLIENT) { - MKSService::sendGcodeFrame((const char *)sbuf); - } else { - outputonly->write(sbuf, len); - } -#else - outputonly->write(sbuf, len); -#endif // COMMUNICATION_PROTOCOL == MKS_SERIAL - } - } -} - -// check if current line is an [ESPXXX] command -bool Commands::is_esp_command(uint8_t *sbuf, size_t len) { - // TODO - // M117 should be handled here and transfered to [ESP214] if it is an host - if (len < 5) { - return false; - } - if ((char(sbuf[0]) == '[') && (char(sbuf[1]) == 'E') && - (char(sbuf[2]) == 'S') && (char(sbuf[3]) == 'P') && - ((char(sbuf[4]) == ']') || (char(sbuf[5]) == ']') || - (char(sbuf[6]) == ']') || (char(sbuf[7]) == ']'))) { - return true; - } - if ((char(sbuf[0]) == 'e') && (char(sbuf[1]) == 'c') && - (char(sbuf[2]) == 'h') && (char(sbuf[3]) == 'o') && - (char(sbuf[4]) == ':') && (char(sbuf[5]) == ' ') && - (char(sbuf[6]) == '[') && (char(sbuf[7]) == 'E')) { - if (len >= 14) { - if ((char(sbuf[8]) == 'S') && (char(sbuf[9]) == 'P') && - ((char(sbuf[4]) == ']') || (char(sbuf[5]) == ']') || - (char(sbuf[6]) == ']') || (char(sbuf[7]) == ']'))) { - return true; - } - } - } - return false; -} - -// find space in string -// if space is has \ before it is ignored -int Commands::get_space_pos(const char *string, uint from) { - uint len = strlen(string); - if (len < from) { - return -1; - } - for (uint i = from; i < len; i++) { - if (string[i] == ' ') { - // if it is first char - if (i == from) { - return from; - } - // if not first one and previous char is not '\' - if (string[i - 1] != '\\') { - return (i); - } - } - } - return -1; -} - -// return first label but pwd using labelseparator (usualy =) like -// mylabel=myvalue will return mylabel -const char *Commands::get_label(const char *cmd_params, - const char *labelseparator, - uint8_t startindex) { - static String res; - String tmp = ""; - res = ""; - int start = 1; - int end = -1; - res = cmd_params; - res.replace("\r ", ""); - res.replace("\n ", ""); - res.trim(); - if ((res.length() == 0) || (startindex >= res.length())) { - return res.c_str(); - } - - if (strlen(labelseparator) > 0) { - end = res.indexOf(labelseparator, startindex); - if (end == -1) { - return ""; - } - start = end; - for (int8_t p = end; p >= startindex; p--, start--) { - if (res[p] == ' ') { - p = -1; - start += 2; - } - } - if (start == -1) { - start = 0; - } - if (start > end) { - return ""; - } - tmp = res.substring(start, end); - if (tmp == "pwd") { - res = get_label(cmd_params, labelseparator, end + 1); - } else { - res = tmp; - } - } - return res.c_str(); -} - -const char *Commands::format_response(uint cmdID, bool isjson, bool isok, - const char *message) { - static String res; - res = ""; - if (!isjson) { - res += message; - } else { - res = "{\"cmd\":\""; - res += String(cmdID); - res += "\",\"status\":\""; - if (isok) { - res += "ok"; - } else { - res += "error"; - } - res += "\",\"data\":"; - if (message[0] != '{') { - res += "\""; - } - res += message; - if (message[0] != '{') { - res += "\""; - } - res += "}"; - } - return res.c_str(); -} - -const char *Commands::clean_param(const char *cmd_params) { - static String res; - res = cmd_params; - if (strlen(cmd_params) == 0) { - return ""; - } - String tmp = cmd_params; - tmp.trim(); - if (tmp == "json" || tmp.startsWith("json ")) { - return ""; - } - if (tmp.indexOf("json=") != -1) { - // remove formating flag - res = tmp.substring(0, tmp.indexOf("json=")); - } else { - if (tmp.endsWith(" json")) { - // remove formating flag - res = tmp.substring(0, tmp.length() - 5); - } - } - return res.c_str(); -} - -// extract parameter with corresponding label -// if label is empty give whole line without authentication label/parameter -const char *Commands::get_param(const char *cmd_params, const char *label) { - static String res; - res = ""; - int start = 1; - int end = -1; - String tmp = ""; - String slabel = " "; - res = cmd_params; - res.replace("\r ", ""); - res.replace("\n ", ""); - res.trim(); - if (res.length() == 0) { - return res.c_str(); - } - - tmp = " " + res; - slabel += label; - if (strlen(label) > 0) { - start = tmp.indexOf(slabel); - if (start == -1) { - return ""; - } - start += slabel.length(); - end = get_space_pos(tmp.c_str(), start); - } - if (end == -1) { - end = tmp.length(); - } - // extract parameter - res = tmp.substring(start, end); - -#ifdef AUTHENTICATION_FEATURE - // if no label remove authentication parameters - if (strlen(label) == 0) { - tmp = " " + res; - start = tmp.indexOf(" pwd="); - if (start != -1) { - end = get_space_pos(tmp.c_str(), start + 1); - res = ""; - if (start != 0) { - res = tmp.substring(0, start); - } - if (end != -1) { - res += " " + tmp.substring(end + 1, tmp.length()); - } - } - } -#endif // AUTHENTICATION_FEATURE - // remove space format - res.replace("\\ ", " "); - // be sure no extra space - res.trim(); - return res.c_str(); -} - -bool Commands::has_tag(const char *cmd_params, const char *tag) { - log_esp3d("Checking for tag: %s, in %s", tag, cmd_params); - String tmp = ""; - String stag = " "; - if ((strlen(cmd_params) == 0) || (strlen(tag) == 0)) { - log_esp3d_e("No value provided for tag"); - return false; - } - stag += tag; - tmp = cmd_params; - tmp.trim(); - tmp = " " + tmp; - if (tmp.indexOf(stag) == -1) { - log_esp3d("No tag detected"); - return false; - } - log_esp3d("Tag detected"); - // to support plain , plain=yes , plain=no - String param = String(tag) + "="; - log_esp3d("Checking %s , in %s", param.c_str(), cmd_params); - String parameter = get_param(cmd_params, param.c_str()); - if (parameter.length() != 0) { - log_esp3d("Parameter is %s", parameter.c_str()); - if (parameter == "YES" || parameter == "true" || parameter == "TRUE" || - parameter == "yes" || parameter == "1") { - return true; - } - log_esp3d("No parameter to enable %s ", param.c_str()); - return false; - } - log_esp3d("No parameter for %s but tag detected", param.c_str()); - return true; -} - -// execute internal command -bool Commands::execute_internal_command(int cmd, const char *cmd_params, - level_authenticate_type auth_level, - ESP3DOutput *output) { -#ifndef SERIAL_COMMAND_FEATURE - if (output->client() == ESP_SERIAL_CLIENT) { - output->printMSG("Feature disabled"); - return false; - } -#endif // SERIAL_COMMAND_FEATURE - bool response = true; - level_authenticate_type auth_type = auth_level; - // log_esp3d("Authentication = %d", auth_type); -// override if parameters -#ifdef AUTHENTICATION_FEATURE - - // do not overwrite previous authetic ation level - if (auth_type == LEVEL_GUEST) { - String pwd = get_param(cmd_params, "pwd="); - auth_type = AuthenticationService::authenticated_level(pwd.c_str(), output); - } -#endif // AUTHENTICATION_FEATURE - // log_esp3d("Authentication = %d", auth_type); - String parameter; - switch (cmd) { - // ESP3D Help - //[ESP0] or [ESP] - case 0: - response = ESP0(cmd_params, auth_type, output); - break; -#if defined(WIFI_FEATURE) - // STA SSID - //[ESP100][pwd=] - case 100: - response = ESP100(cmd_params, auth_type, output); - break; - // STA Password - //[ESP101][pwd=] - case 101: - response = ESP101(cmd_params, auth_type, output); - break; -#endif // WIFI_FEATURE -#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) - // Change STA IP mode (DHCP/STATIC) - //[ESP102]pwd= - case 102: - response = ESP102(cmd_params, auth_type, output); - break; - // Change STA IP/Mask/GW - //[ESP103]IP= MSK= GW= pwd= - case 103: - response = ESP103(cmd_params, auth_type, output); - break; -#endif // WIFI_FEATURE ||ETH_FEATURE -#if defined(WIFI_FEATURE) || defined(BLUETOOTH_FEATURE) || defined(ETH_FEATURE) - // Set fallback mode which can be BT, WIFI-AP, OFF - //[ESP104]pwd= - case 104: - response = ESP104(cmd_params, auth_type, output); - break; -#endif // WIFI_FEATURE || BLUETOOTH_FEATURE || ETH_FEATURE) -#if defined(WIFI_FEATURE) - // AP SSID - //[ESP105][pwd=] - case 105: - response = ESP105(cmd_params, auth_type, output); - break; - // AP Password - //[ESP106][pwd=] - case 106: - response = ESP106(cmd_params, auth_type, output); - break; - // Change AP IP - //[ESP107] pwd= - case 107: - response = ESP107(cmd_params, auth_type, output); - break; - // Change AP channel - //[ESP108]pwd= - case 108: - response = ESP108(cmd_params, auth_type, output); - break; -#endif // WIFI_FEATURE - -#if defined(WIFI_FEATURE) || defined(BLUETOOTH_FEATURE) || defined(ETH_FEATURE) - // Set radio state at boot which can be BT, WIFI-STA, WIFI-AP, ETH-STA, OFF - //[ESP110]pwd= - case 110: - response = ESP110(cmd_params, auth_type, output); - break; -#endif // WIFI_FEATURE || BLUETOOTH_FEATURE || ETH_FEATURE) - -#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) - // Get current IP - //[ESP111] - case 111: - response = ESP111(cmd_params, auth_type, output); - break; -#endif // WIFI_FEATURE || ETH_FEATURE) - -#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BT_FEATURE) - // Get/Set hostname - //[ESP112] pwd= - case 112: - response = ESP112(cmd_params, auth_type, output); - break; - // Get/Set boot Network (WiFi/BT/Ethernet) state which can be ON, OFF - //[ESP114]pwd= - case 114: - response = ESP114(cmd_params, auth_type, output); - break; - // Get/Set immediate Network (WiFi/BT/Ethernet) state which can be ON, OFF - //[ESP115]pwd= - case 115: - response = ESP115(cmd_params, auth_type, output); - break; -#endif // WIFI_FEATURE|| ETH_FEATURE || BT_FEATURE - -#ifdef HTTP_FEATURE - // Set HTTP state which can be ON, OFF - //[ESP120]pwd= - case 120: - response = ESP120(cmd_params, auth_type, output); - break; - // Set HTTP port - //[ESP121]pwd= - case 121: - response = ESP121(cmd_params, auth_type, output); - break; -#endif // HTTP_FEATURE -#ifdef TELNET_FEATURE - // Set TELNET state which can be ON, OFF - //[ESP130]pwd= - case 130: - response = ESP130(cmd_params, auth_type, output); - break; - // Set TELNET port - //[ESP131]pwd= - case 131: - response = ESP131(cmd_params, auth_type, output); - break; -#endif // TELNET_FEATURE -#ifdef TIMESTAMP_FEATURE - // Sync / Set / Get current time - //[ESP140] - // pwd= - case 140: - response = ESP140(cmd_params, auth_type, output); - break; -#endif // TIMESTAMP_FEATURE - // Get/Set display/set boot delay in ms / Verbose boot - //[ESP150][pwd=] - case 150: - response = ESP150(cmd_params, auth_type, output); - break; -#ifdef WS_DATA_FEATURE - // Set WebSocket state which can be ON, OFF - //[ESP160]pwd= - case 160: - response = ESP160(cmd_params, auth_type, output); - break; - // Set WebSocket port - //[ESP161]pwd= - case 161: - response = ESP161(cmd_params, auth_type, output); - break; -#endif // WS_DATA_FEATURE -#ifdef CAMERA_DEVICE - // Get/Set Camera command value / list all values in JSON/plain - //[ESP170]label= 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 - case 170: - response = ESP170(cmd_params, auth_type, output); - break; - // Save frame to target path and filename (default target = today date, - // default name=timestamp.jpg) [ESP171]path= filename= pwd= - case 171: - response = ESP171(cmd_params, auth_type, output); - break; -#endif // CAMERA_DEVICE -#ifdef FTP_FEATURE - // Set Ftp state which can be ON, OFF - //[ESP180]pwd= - case 180: - response = ESP180(cmd_params, auth_type, output); - break; - // Set/get ftp ports - //[ESP181]ctrl= active= passive= pwd= - case 181: - response = ESP181(cmd_params, auth_type, output); - break; -#endif // FTP_FEATURE -#ifdef WEBDAV_FEATURE - // Set webdav state which can be ON, OFF - //[ESP190]pwd= - case 190: - response = ESP190(cmd_params, auth_type, output); - break; - // Set/get webdav port - //[ESP191]ctrl= active= passive= pwd= - case 191: - response = ESP191(cmd_params, auth_type, output); - break; -#endif // WEBDAV_FEATURE -#if defined(SD_DEVICE) - // Get/Set SD Card Status - //[ESP200] json= pwd= - case 200: - response = ESP200(cmd_params, auth_type, output); - break; -#if SD_DEVICE != ESP_SDIO - // Get/Set SD card Speed factor 1 2 4 6 8 16 32 - //[ESP202]SPEED=pwd= - case 202: - response = ESP202(cmd_params, auth_type, output); - break; -#endif // SD_DEVICE != ESP_SDIO -#ifdef SD_UPDATE_FEATURE - // Get/Set SD Check at boot state which can be ON, OFF - //[ESP402]pwd= - case 402: - response = ESP402(cmd_params, auth_type, output); - break; -#endif // #ifdef SD_UPDATE_FEATURE -#endif // SD_DEVICE -#ifdef DIRECT_PIN_FEATURE - // Get/Set pin value - //[ESP201]P V [PULLUP=YES RAW=YES]pwd= - case 201: - response = ESP201(cmd_params, auth_type, output); - break; -#endif // DIRECT_PIN_FEATURE -#ifdef SENSOR_DEVICE - // Get SENSOR Value / type/Set SENSOR type - //[ESP210] - case 210: - response = ESP210(cmd_params, auth_type, output); - break; -#endif // #ifdef SENSOR_DEVICE -#if defined(DISPLAY_DEVICE) - // Output to esp screen status - //[ESP214]pwd= - case 214: - response = ESP214(cmd_params, auth_type, output); - break; -#if defined(DISPLAY_TOUCH_DRIVER) - // Touch Calibration - //[ESP215][pwd=] - case 215: - response = ESP215(cmd_params, auth_type, output); - break; -#endif // DISPLAY_TOUCH_DRIVER -#ifdef BUZZER_DEVICE - // Play sound - //[ESP250]F= D= [pwd=] - case 250: - response = ESP250(cmd_params, auth_type, output); - break; -#endif // BUZZER_DEVICE -#endif // DISPLAY_DEVICE - // Show pins - //[ESP220][pwd=] - case 220: - response = ESP220(cmd_params, auth_type, output); - break; - // Delay command - //[ESP290][pwd=] - case 290: - response = ESP290(cmd_params, auth_type, output); - break; - // Get full ESP3D settings - //[ESP400] - case 400: - response = ESP400(cmd_params, auth_type, output); - break; - // Set EEPROM setting - //[ESP401]P= T= V= pwd= - case 401: - response = ESP401(cmd_params, auth_type, output); - break; -#if defined(WIFI_FEATURE) - // Get available AP list (limited to 30) - // output is JSON or plain text according parameter - //[ESP410] - case 410: - response = ESP410(cmd_params, auth_type, output); - break; -#endif // WIFI_FEATURE - // Get ESP current status - // output is JSON or plain text according parameter - //[ESP420] - case 420: - response = ESP420(cmd_params, auth_type, output); - break; - // Set ESP State - // cmd are RESTART / RESET - //[ESP444] - case 444: - response = ESP444(cmd_params, auth_type, output); - break; -#ifdef MDNS_FEATURE - // Get ESP3D list - //[ESP450] pwd= - case 450: - response = ESP450(cmd_params, auth_type, output); - break; -#endif // MDNS_FEATURE -#ifdef AUTHENTICATION_FEATURE - // Change admin password - //[ESP550]pwd= - case 550: - response = ESP550(cmd_params, auth_type, output); - break; - // Change user password - //[ESP555]pwd= - case 555: - response = ESP555(cmd_params, auth_type, output); - break; -#endif // AUTHENTICATION_FEATURE -#if defined(NOTIFICATION_FEATURE) - // Send Notification - //[ESP600][pwd=] - case 600: - response = ESP600(cmd_params, auth_type, output); - break; - // Set/Get Notification settings - //[ESP610]type= T1= T2= - // TS= [pwd=] Get will give type and settings only - // not the protected T1/T2 - case 610: - response = ESP610(cmd_params, auth_type, output); - break; - // Send Notification using URL - //[ESP620]URL= [pwd=] - case 620: - response = ESP620(cmd_params, auth_type, output); - break; -#endif // NOTIFICATION_FEATURE -#if defined(FILESYSTEM_FEATURE) - // Format ESP Filesystem - //[ESP710]FORMAT pwd= - case 710: - response = ESP710(cmd_params, auth_type, output); - break; - // List ESP Filesystem - //[ESP720] pwd= - case 720: - response = ESP720(cmd_params, auth_type, output); - break; - // Action on ESP Filesystem - // rmdir / remove / mkdir / exists - //[ESP730]= pwd= - case 730: - response = ESP730(cmd_params, auth_type, output); - break; -#endif // FILESYSTEM_FEATURE -#if defined(SD_DEVICE) - // Format ESP Filesystem - //[ESP715]FORMATSD pwd= - case 715: - response = ESP715(cmd_params, auth_type, output); - break; -#endif // SD_DEVICE -#if defined(GCODE_HOST_FEATURE) - // Open local file - //[ESP700] - case 700: - response = ESP700(cmd_params, auth_type, output); - break; - // Get Status and Control ESP700 stream - //[ESP701]action= - case 701: - response = ESP701(cmd_params, auth_type, output); - break; -#endif // GCODE_HOST_FEATURE -#if defined(SD_DEVICE) - // List SD Filesystem - //[ESP740] pwd= - case 740: - response = ESP740(cmd_params, auth_type, output); - break; - // Action on SD Filesystem - // rmdir / remove / mkdir / exists - //[ESP750]= pwd= - case 750: - response = ESP750(cmd_params, auth_type, output); - break; -#endif // SD_DEVICE -#if defined(GLOBAL_FILESYSTEM_FEATURE) - // List Global Filesystem - //[ESP780] pwd= - case 780: - response = ESP780(cmd_params, auth_type, output); - break; - // Action on Global Filesystem - // rmdir / remove / mkdir / exists - //[ESP790]= pwd= - case 790: - response = ESP790(cmd_params, auth_type, output); - break; -#endif // GLOBAL_FILESYSTEM_FEATURE - // Get fw version firmare target and fw version - // eventually set time with pc time - // output is JSON or plain text according parameter - //[ESP800] - case 800: - response = ESP800(cmd_params, auth_type, output); - break; - -#if COMMUNICATION_PROTOCOL != SOCKET_SERIAL - // Get state / Set Enable / Disable Serial Communication - //[ESP900] - case 900: - response = ESP900(cmd_params, auth_type, output); - break; - // Get / Set Serial Baud Rate - //[ESP901] json= pwd= - case 901: - response = ESP901(cmd_params, auth_type, output); - break; -#endif // COMMUNICATION_PROTOCOL != SOCKET_SERIAL -#ifdef BUZZER_DEVICE - // Get state / Set Enable / Disable buzzer - //[ESP910] - case 910: - response = ESP910(cmd_params, auth_type, output); - break; -#endif // BUZZER_DEVICE - case 920: - // Get state / Set state of output message clients - //[ESP910]=[pwd=] - response = ESP920(cmd_params, auth_type, output); - break; -#if defined(ESP_SERIAL_BRIDGE_OUTPUT) - // Get state / Set Enable / Disable Serial Bridge Communication - //[ESP930] - case 930: - response = ESP930(cmd_params, auth_type, output); - break; - // Get / Set Serial Bridge Baud Rate - //[ESP931] json= pwd= - case 931: - response = ESP931(cmd_params, auth_type, output); - break; -#endif // defined(ESP_SERIAL_BRIDGE_OUTPUT) -#if defined(ARDUINO_ARCH_ESP32) && \ - (CONFIG_IDF_TARGET_ESP32S3 || CONFIG_IDF_TARGET_ESP32S2 || \ - CONFIG_IDF_TARGET_ESP32C3) - case 999: - // Set quiet boot if strapping pin is High - //[ESP999] [pwd=] - response = ESP999(cmd_params, auth_type, output); - break; -#endif // ARDUINO_ARCH_ESP32 - default: - output->printERROR("Invalid Command"); - response = false; - } - return response; -} - -bool Commands::_dispatchSetting( - bool json, const char *filter, ESP3DSettingIndex index, const char *help, - const char **optionValues, const char **optionLabels, uint32_t maxsize, - uint32_t minsize, uint32_t minsize2, uint8_t precision, const char *unit, - bool needRestart, ESP3DOutput *output, bool isFirst) { - String tmpstr; - String value; - char out_str[255]; - tmpstr.reserve( - 350); // to save time and avoid several memories allocation delay - const ESP3DSettingDescription *elementSetting = - Settings_ESP3D::getSettingPtr(index); - if (!elementSetting) { - return false; - } - switch (elementSetting->type) { - case ESP3DSettingType::byte_t: - value = String(Settings_ESP3D::read_byte(index)); - break; - case ESP3DSettingType::integer_t: - value = String(Settings_ESP3D::read_uint32(index)); - break; - case ESP3DSettingType::ip_t: - value = Settings_ESP3D::read_IP_String(index); - break; - case ESP3DSettingType::float_t: - // TODO Add float support ? - value = "Not supported"; - log_esp3d_e("Float not supported"); - return false; - break; - case ESP3DSettingType::mask: - // TODO Add Mask support ? - value = "Not supported"; - log_esp3d_e("Mask not supported"); - return false; - break; - case ESP3DSettingType::bitsfield: - // TODO Add bitfield support ? - value = "Not supported"; - log_esp3d_e("Bitsfield not supported"); - return false; - break; - case ESP3DSettingType::string_t: - // String - if (index == ESP_AP_PASSWORD || index == ESP_STA_PASSWORD || -#ifdef NOTIFICATION_FEATURE - index == ESP_NOTIFICATION_TOKEN1 || - index == ESP_NOTIFICATION_TOKEN2 || -#endif // NOTIFICATION_FEATURE - - index == ESP_USER_PWD || index == ESP_ADMIN_PWD) { // hide passwords - // using ******** - value = HIDDEN_PASSWORD; - } else { - value = Settings_ESP3D::read_string(index); - } - break; - default: - value = "Not supported"; - log_esp3d_e("Type not supported"); - return false; - break; - } - if (json) { - if (!isFirst) { - tmpstr += ","; - } - tmpstr += "{\"F\":\""; - tmpstr += filter; - tmpstr += "\",\"P\":\""; - tmpstr += String(static_cast(index)); - tmpstr += "\",\"T\":\""; - // Limited support already done for above so even not supported we can - // define it once will be enabled - switch (elementSetting->type) { - case ESP3DSettingType::byte_t: - tmpstr += "B"; - break; - case ESP3DSettingType::integer_t: - tmpstr += "I"; - break; - case ESP3DSettingType::ip_t: - tmpstr += "A"; - break; - case ESP3DSettingType::float_t: - tmpstr += "F"; - break; - case ESP3DSettingType::mask: - tmpstr += "M"; - break; - case ESP3DSettingType::bitsfield: - tmpstr += "X"; - break; - default: - tmpstr += "S"; - } - tmpstr += "\",\"V\":\""; - tmpstr += value; - tmpstr += "\",\"H\":\""; - tmpstr += help; - tmpstr += "\""; - if (needRestart) { - tmpstr += ",\"R\":\"1\""; - } - if (optionValues && optionLabels) { - tmpstr += ",\"O\":["; - for (uint8_t i = 0; i < maxsize; i++) { - if (i > 0) { - tmpstr += ","; - } - tmpstr += "{\""; - // be sure we have same size for both array to avoid overflow - tmpstr += optionLabels[i]; - tmpstr += "\":\""; - tmpstr += optionValues[i]; - tmpstr += "\"}"; - } - tmpstr += "]"; - } - if (unit) { - tmpstr += ",\"R\":\""; - tmpstr += unit; - tmpstr += "\""; - } - if (precision != ((uint8_t)-1)) { - tmpstr += ",\"E\":\""; - tmpstr += String(precision); - tmpstr += "\""; - } - if (maxsize != (uint32_t)-1 && !optionValues) { - tmpstr += ",\"S\":\""; - tmpstr += String(maxsize); - tmpstr += "\""; - } - if (minsize != (uint32_t)-1) { - tmpstr += ",\"M\":\""; - tmpstr += String(minsize); - tmpstr += "\""; - } - if (minsize2 != (uint32_t)-1) { - tmpstr += ",\"MS\":\""; - tmpstr += String(minsize2); - tmpstr += "\""; - } - tmpstr += "}"; - } else { - tmpstr = filter; - tmpstr += "/"; - tmpstr += help; - tmpstr += ": "; - tmpstr += value; - tmpstr += "\n"; - } - output->print(tmpstr.c_str()); - return true; -} \ No newline at end of file diff --git a/esp3d/src/core/commands.h b/esp3d/src/core/commands.h deleted file mode 100644 index 379c36d6..00000000 --- a/esp3d/src/core/commands.h +++ /dev/null @@ -1,264 +0,0 @@ -/* - commands.h - ESP3D commands 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 COMMANDS_H -#define COMMANDS_H -#include - -#include "../modules/authentication/authentication_service.h" - -class ESP3DOutput; - -class Commands { - public: - Commands(); - ~Commands(); - void process(uint8_t* sbuf, size_t len, ESP3DOutput* output, - level_authenticate_type auth = LEVEL_GUEST, - ESP3DOutput* outputonly = nullptr, uint8_t outputignore = 0); - bool is_esp_command(uint8_t* sbuf, size_t len); - bool execute_internal_command(int cmd, const char* cmd_params, - level_authenticate_type auth_level, - ESP3DOutput* output); - int get_space_pos(const char* string, uint from = 0); - const char* get_param(const char* cmd_params, const char* label); - const char* get_label(const char* cmd_params, const char* labelseparator, - uint8_t startindex = 0); - const char* clean_param(const char* cmd_params); - const char* format_response(uint cmdID, bool isjson = false, bool isok = true, - const char* message = ""); - bool has_tag(const char* cmd_params, const char* tag); - bool ESP0(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#if defined(WIFI_FEATURE) - bool ESP100(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP101(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // WIFI_FEATURE -#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) - bool ESP102(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP103(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // WIFI_FEATURE ||ETH_FEATURE -#if defined(WIFI_FEATURE) || defined(BLUETOOTH_FEATURE) || defined(ETH_FEATURE) - bool ESP104(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // WIFI_FEATURE || BLUETOOTH_FEATURE || ETH_FEATURE -#if defined(WIFI_FEATURE) - bool ESP105(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP106(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP107(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP108(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // WIFI_FEATURE -#if defined(WIFI_FEATURE) || defined(BLUETOOTH_FEATURE) || defined(ETH_FEATURE) - bool ESP110(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // WIFI_FEATURE || BLUETOOTH_FEATURE || ETH_FEATURE -#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) - bool ESP111(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // WIFI_FEATURE || ETH_FEATURE -#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BT_FEATURE) - bool ESP112(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP114(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP115(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // WIFI_FEATURE || BLUETOOTH_FEATURE || ETH_FEATURE -#if defined(HTTP_FEATURE) - bool ESP120(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP121(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // HTTP_FEATURE -#if defined(TELNET_FEATURE) - bool ESP130(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP131(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // TELNET_FEATURE -#if defined(TIMESTAMP_FEATURE) - bool ESP140(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // TIMESTAMP_FEATURE - bool ESP150(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#if defined(WS_DATA_FEATURE) - bool ESP160(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP161(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // WS_DATA_FEATURE -#if defined(CAMERA_DEVICE) - bool ESP170(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP171(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // CAMERA_DEVICE -#if defined(FTP_FEATURE) - bool ESP180(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP181(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // FTP_FEATURE -#if defined(WEBDAV_FEATURE) - bool ESP190(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP191(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // WEBDAV_FEATURE -#if defined(SD_DEVICE) - bool ESP200(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#if SD_DEVICE != ESP_SDIO - bool ESP202(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // SD_DEVICE != ESP_SDIO -#ifdef SD_UPDATE_FEATURE - bool ESP402(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // SD_UPDATE_FEATURE -#endif // SD_DEVICE -#ifdef DIRECT_PIN_FEATURE - bool ESP201(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // DIRECT_PIN_FEATURE -#if defined(DISPLAY_DEVICE) - bool ESP214(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#if defined(DISPLAY_TOUCH_DRIVER) - bool ESP215(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // DISPLAY_TOUCH_DRIVER -#endif // DISPLAY_DEVICE -#ifdef SENSOR_DEVICE - bool ESP210(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // SENSOR_DEVICE - bool ESP220(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP290(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP400(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP401(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#if defined(WIFI_FEATURE) - bool ESP410(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // WIFI_FEATURE - bool ESP420(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP444(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#ifdef MDNS_FEATURE - bool ESP450(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // MDNS_FEATURE -#if defined(AUTHENTICATION_FEATURE) - bool ESP550(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP555(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // AUTHENTICATION_FEATURE -#if defined(NOTIFICATION_FEATURE) - bool ESP600(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP610(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP620(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // NOTIFICATION_FEATURE -#if defined(GCODE_HOST_FEATURE) - bool ESP700(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP701(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // GCODE_HOST_FEATURE -#if defined(FILESYSTEM_FEATURE) - bool ESP710(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP720(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP730(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // FILESYSTEM_FEATURE -#if defined(SD_DEVICE) - bool ESP715(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP750(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP740(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // SD_DEVICE -#if defined(GLOBAL_FILESYSTEM_FEATURE) - bool ESP780(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP790(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // GLOBAL_FILESYSTEM_FEATURE - bool ESP800(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#if COMMUNICATION_PROTOCOL != SOCKET_SERIAL - bool ESP900(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP901(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // COMMUNICATION_PROTOCOL != SOCKET_SERIAL - bool ESP920(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#if defined(ESP_SERIAL_BRIDGE_OUTPUT) - bool ESP930(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP931(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // defined (ESP_SERIAL_BRIDGE_OUTPUT) -#ifdef BUZZER_DEVICE - bool ESP910(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); - bool ESP250(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // BUZZER_DEVICE -#if defined(ARDUINO_ARCH_ESP32) && \ - (CONFIG_IDF_TARGET_ESP32S3 || CONFIG_IDF_TARGET_ESP32S2 || \ - CONFIG_IDF_TARGET_ESP32C3) - bool ESP999(const char* cmd_params, level_authenticate_type auth_level, - ESP3DOutput* output); -#endif // ARDUINO_ARCH_ESP32 - - private: - bool _dispatchSetting(bool json, const char* filter, ESP3DSettingIndex index, - const char* help, const char** optionValues, - const char** optionLabels, uint32_t maxsize, - uint32_t minsize, uint32_t minsize2, uint8_t precision, - const char* unit, bool needRestart, ESP3DOutput* output, - bool isFirst = false); -}; - -extern Commands esp3d_commands; - -#endif // COMMANDS_H diff --git a/esp3d/src/core/espcmd/ESP0.cpp b/esp3d/src/core/commands/ESP0.cpp similarity index 74% rename from esp3d/src/core/espcmd/ESP0.cpp rename to esp3d/src/core/commands/ESP0.cpp index 75e537cc..beb0b0f1 100644 --- a/esp3d/src/core/espcmd/ESP0.cpp +++ b/esp3d/src/core/commands/ESP0.cpp @@ -18,9 +18,8 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" -#include "../commands.h" -#include "../esp3doutput.h" -#include "../settings_esp3d.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" const char* help[] = { "[ESP] (id) - display this help", #if defined(WIFI_FEATURE) @@ -46,7 +45,7 @@ const char* help[] = { "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", + "[ESP111](OUTPUT=PRINT)(ALL) display current IP and network informations", #endif // WIFI_FEATURE || ETH_FEATURE #if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BT_FEATURE) "[ESP112](Hostname) - display/set Hostname", @@ -129,12 +128,14 @@ const char* help[] = { "[ESP450]display ESP3D list on network", #endif // MDNS_FEATURE #if defined(AUTHENTICATION_FEATURE) + "[ESP500]display authentication level", + "[ESP510](timeout) - set/display session time out", "[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) " + "[ESP610]type=(NONE/PUSHOVER/EMAIL/LINE/TELEGRAM/IFTTT/HOMEASSISTANT) (T1=xxx) (T2=xxx) " "(TS=xxx) - display/set Notification settings", "[ESP620]URL=http://XXXXXX - send GET notification", #endif // NOTIFICATION_FEATURE @@ -172,10 +173,8 @@ const char* help[] = { #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", #if defined(ESP_SERIAL_BRIDGE_OUTPUT) - "[ESP930](ON/OFF/CLOSE) - display/set serial bridge state", + "[ESP930](ENABLE/DISABLE/CLOSE) - display/set serial bridge state", "[ESP931] - display/set serial bridge baud rate", #endif // defined(ESP_SERIAL_BRIDGE_OUTPUT) #if defined(ARDUINO_ARCH_ESP32) && \ @@ -183,193 +182,232 @@ const char* help[] = { CONFIG_IDF_TARGET_ESP32C3) "[ESP999](QUIETBOOT) [pwd=] - set quiet boot mode", #endif // ARDUINO_ARCH_ESP32 - ""}; -const uint cmdlist[] = {0, +}; +const uint cmdlist[] = { + 0, #if defined(WIFI_FEATURE) - 100, 101, + 100, 101, #endif // WIFI_FEATURE #if defined(WIFI_FEATURE) || defined(ETH_FEATURE) - 102, 103, + 102, 103, #endif // WIFI_FEATURE || ETH_FEATURE #if defined(WIFI_FEATURE) || defined(BLUETOOTH_FEATURE) || defined(ETH_FEATURE) - 104, + 104, #endif // WIFI_FEATURE || BLUETOOTH_FEATURE || ETH_FEATURE #if defined(WIFI_FEATURE) - 105, 106, 107, 108, + 105, 106, 107, 108, #endif // WIFI_FEATURE #if defined(WIFI_FEATURE) || defined(BLUETOOTH_FEATURE) || defined(ETH_FEATURE) - 110, + 110, #endif // WIFI_FEATURE || BLUETOOTH_FEATURE || ETH_FEATURE #if defined(WIFI_FEATURE) || defined(ETH_FEATURE) - 111, + 111, #endif // WIFI_FEATURE || ETH_FEATURE #if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BT_FEATURE) - 112, 114, 115, + 112, 114, 115, #endif // WIFI_FEATURE || ETH_FEATURE || BT_FEATURE #if defined(HTTP_FEATURE) - 120, 121, + 120, 121, #endif // HTTP_FEATURE #if defined(TELNET_FEATURE) - 130, 131, + 130, 131, #endif // TELNET_FEATURE #if defined(TIMESTAMP_FEATURE) - 140, + 140, #endif // TIMESTAMP_FEATURE - 150, + 150, #if defined(WS_DATA_FEATURE) - 160, 161, + 160, 161, #endif // WS_DATA_FEATURE #if defined(CAMERA_DEVICE) - 170, 171, + 170, 171, #endif // CAMERA_DEVICE #if defined(FTP_FEATURE) - 180, 181, + 180, 181, #endif // FTP_FEATURE #if defined(WEBDAV_FEATURE) - 190, 191, + 190, 191, #endif // WEBDAV_FEATURE #if defined(SD_DEVICE) - 200, + 200, #endif // SD_DEVICE #ifdef DIRECT_PIN_FEATURE - 201, + 201, #endif // DIRECT_PIN_FEATURE #if defined(SD_DEVICE) && SD_DEVICE != ESP_SDIO - 202, + 202, #endif // SD_DEVICE #ifdef SENSOR_DEVICE - 210, + 210, #endif // SENSOR_DEVICE #if defined(DISPLAY_DEVICE) - 214, + 214, #if defined(DISPLAY_TOUCH_DRIVER) - 215, + 215, #endif // DISPLAY_TOUCH_DRIVER #endif // DISPLAY_DEVICE - 220, + 220, #ifdef BUZZER_DEVICE - 250, + 250, #endif // BUZZER_DEVICE - 290, 400, 401, + 290, 400, 401, +#ifdef SD_UPDATE_FEATURE + 402, +#endif // SD_UPDATE_FEATURE #if defined(WIFI_FEATURE) - 410, + 410, #endif // WIFI_FEATURE - 420, 444, + 420, 444, #ifdef MDNS_FEATURE - 450, + 450, #endif // MDNS_FEATURE #if defined(AUTHENTICATION_FEATURE) - 550, 555, + 500, 510, 550, 555, #endif // AUTHENTICATION_FEATURE #if defined(NOTIFICATION_FEATURE) - 600, 610, 620, + 600, 610, 620, #endif // NOTIFICATION_FEATURE #if defined(GCODE_HOST_FEATURE) - 700, 701, + 700, 701, #endif // GCODE_HOST_FEATURE #if defined(FILESYSTEM_FEATURE) - 710, + 710, #endif // FILESYSTEM_FEATURE #if defined(SD_DEVICE) - 715, + 715, #endif // SD_DEVICE #if defined(FILESYSTEM_FEATURE) - 720, 730, + 720, 730, #endif // FILESYSTEM_FEATURE #if defined(SD_DEVICE) - 740, 750, + 740, 750, #endif // SD_DEVICE #if defined(GLOBAL_FILESYSTEM_FEATURE) - 780, 790, + 780, 790, #endif // GLOBAL_FILESYSTEM_FEATURE - 800, + 800, #if COMMUNICATION_PROTOCOL != SOCKET_SERIAL - 900, 901, + 900, 901, #endif // COMMUNICATION_PROTOCOL != SOCKET_SERIAL #ifdef BUZZER_DEVICE - 910, + 910, #endif // BUZZER_DEVICE - 920, #if defined(ESP_SERIAL_BRIDGE_OUTPUT) - 930, 935, + 930, 931, #endif // defined(ESP_SERIAL_BRIDGE_OUTPUT) #if defined(ARDUINO_ARCH_ESP32) && \ (CONFIG_IDF_TARGET_ESP32S3 || CONFIG_IDF_TARGET_ESP32S2 || \ CONFIG_IDF_TARGET_ESP32C3) - 999, + 999, #endif // ARDUINO_ARCH_ESP32 && CONFIG_IDF_TARGET_ESP32S3 || // CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3 - 0}; +}; // ESP3D Help //[ESP0] or [ESP] -bool Commands::ESP0(const char* cmd_params, level_authenticate_type auth_type, - ESP3DOutput* output) { - bool noError = true; - String parameter; +void ESP3DCommands::ESP0(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + msg->target = target; + msg->origin = ESP3DClientType::command; + String tmpstr; 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) { + const uint cmdlistNb = sizeof(cmdlist) / sizeof(uint); + bool json = hasTag(msg, cmd_params_pos, "json"); + if (cmdNb != cmdlistNb) { + esp3d_log("Help corrupted: %d vs %d", cmdNb, cmdlistNb); + msg->type = ESP3DMessageType::unique; + if (!dispatch(msg, "Help corrupted")) { + esp3d_log_e("Error sending command to clients"); + } + return; + } + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + // use msg for first answer if (json) { - output->print("{\"cmd\":\"0\",\"status\":\"ok\",\"data\":["); + tmpstr = "{\"cmd\":\"0\",\"status\":\"ok\",\"data\":["; } else { - output->printMSGLine("[List of ESP3D commands]"); + tmpstr = "[List of ESP3D commands]\n"; + } + msg->type = ESP3DMessageType::head; + if (!dispatch(msg, tmpstr.c_str())) { + esp3d_log_e("Error sending command to clients"); + return; + } + yield(); + for (uint i = 0; i < cmdNb; i++) { + if (json) { + tmpstr = "{\"id\":\""; + tmpstr += String(cmdlist[i]); + tmpstr += "\",\"help\":\""; + tmpstr += help[i]; + tmpstr += "\"}"; + if (i < cmdNb - 1 && (cmdNb - 1) > 0) { + tmpstr += ","; + } + } else { + tmpstr = help[i]; + tmpstr += "\n"; + } + + if (!dispatch(tmpstr.c_str(), target, requestId, + ESP3DMessageType::core)) { + esp3d_log_e("Error sending answer to clients"); + return; + } + esp3d_log("Help sent: %d", i); + + yield(); } - 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(","); + if (json) { + if (!dispatch("]}", target, requestId, ESP3DMessageType::tail)) { + esp3d_log_e("Error sending answer to clients"); + return; + } + } else { + if (!dispatch("ok\n", target, requestId, ESP3DMessageType::tail)) { + esp3d_log_e("Error sending answer to clients"); + return; + } + } + } else { + uint cmdval = atoi(tmpstr.c_str()); + for (uint i = 0; i < cmdNb; i++) { + if (cmdlist[i] == cmdval) { + if (json) { + tmpstr = "{\"cmd\":\"0\",\"status\":\"ok\",\"data\":{\"id\":\""; + tmpstr += String(cmdval); + tmpstr += "\",\"help\":\""; + tmpstr += help[i]; + tmpstr += "\"}}"; + } else { + tmpstr = help[i]; + tmpstr += "\n"; } - } else { - output->printMSGLine(help[i]); + msg->type = ESP3DMessageType::unique; + if (!dispatch(msg, tmpstr.c_str())) { + return; + } + return; } } if (json) { - output->printLN("]}"); + tmpstr = + "{\"cmd\":\"0\",\"status\":\"error\",\"data\":\"This command is not " + "supported: "; + tmpstr += String(cmdval); + tmpstr += "\"}"; + } else { + tmpstr = "This command is not supported: "; + tmpstr += String(cmdval); + tmpstr += "\n"; } - } 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()); - } + msg->type = ESP3DMessageType::unique; + if (!dispatch(msg, tmpstr.c_str())) { + return; } } - return noError; } diff --git a/esp3d/src/core/commands/ESP100.cpp b/esp3d/src/core/commands/ESP100.cpp new file mode 100644 index 00000000..6051d024 --- /dev/null +++ b/esp3d/src/core/commands/ESP100.cpp @@ -0,0 +1,86 @@ +/* + ESP100.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(WIFI_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/wifi/wificonfig.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 100 +// STA SSID +//[ESP100][json=no] [pwd=] +void ESP3DCommands::ESP100(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + const ESP3DSettingDescription* settingPtr = + ESP3DSettings::getSettingPtr(ESP_STA_SSID); + if (settingPtr) { + ok_msg = ESP3DSettings::readString(ESP_STA_SSID); + } else { + hasError = true; + error_msg = "This setting is unknown"; + } + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + esp3d_log( + "got %s param for a value of %s, is valid %d", tmpstr.c_str(), + tmpstr.c_str(), + ESP3DSettings::isValidStringSetting(tmpstr.c_str(), ESP_STA_SSID)); + if (ESP3DSettings::isValidStringSetting(tmpstr.c_str(), ESP_STA_SSID)) { + esp3d_log("Value %s is valid", tmpstr.c_str()); + if (!ESP3DSettings::writeString(ESP_STA_SSID, tmpstr.c_str())) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid parameter"; + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // WIFI_FEATURE diff --git a/esp3d/src/core/commands/ESP101.cpp b/esp3d/src/core/commands/ESP101.cpp new file mode 100644 index 00000000..e3d92f43 --- /dev/null +++ b/esp3d/src/core/commands/ESP101.cpp @@ -0,0 +1,78 @@ +/* + ESP101.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(WIFI_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/wifi/wificonfig.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 101 +// STA Password +//[ESP101] [json=no] [pwd=] +void ESP3DCommands::ESP101(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + bool clearSetting = hasTag(msg, cmd_params_pos, "NOPASSWORD"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + hasError = true; + error_msg = "Password not displayable"; + } else { + if (clearSetting) { + esp3d_log("NOPASSWORD flag detected, set string to empty string"); + tmpstr = ""; + } + esp3d_log( + "got %s param for a value of %s, is valid %d", tmpstr.c_str(), + tmpstr.c_str(), + ESP3DSettings::isValidStringSetting(tmpstr.c_str(), ESP_STA_PASSWORD)); + if (ESP3DSettings::isValidStringSetting(tmpstr.c_str(), ESP_STA_PASSWORD)) { + esp3d_log("Value %s is valid", tmpstr.c_str()); + if (!ESP3DSettings::writeString(ESP_STA_PASSWORD, tmpstr.c_str())) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid parameter"; + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} +#endif // WIFI_FEATURE diff --git a/esp3d/src/core/commands/ESP102.cpp b/esp3d/src/core/commands/ESP102.cpp new file mode 100644 index 00000000..731d20b6 --- /dev/null +++ b/esp3d/src/core/commands/ESP102.cpp @@ -0,0 +1,100 @@ +/* + ESP102.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) +#include "../../modules/network/netconfig.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#if defined(WIFI_FEATURE) +#include "../../modules/wifi/wificonfig.h" +#endif // WIFI_FEATURE +#if defined(ETH_FEATURE) +#include "../../modules/ethernet/ethconfig.h" +#endif // ETH_FEATURE +#include "../../modules/authentication/authentication_service.h" +#define COMMAND_ID 102 +// Change STA IP mode (DHCP/STATIC) +//[ESP102][json=no] [pwd=] +void ESP3DCommands::ESP102(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; + uint8_t byteValue = (uint8_t)-1; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + byteValue = ESP3DSettings::readByte(ESP_STA_IP_MODE); + if (byteValue == static_cast(DHCP_MODE)) { + ok_msg = "DHCP"; + } else if (byteValue == static_cast(STATIC_IP_MODE)) { + ok_msg = "STATIC"; + } else { + ok_msg = "Unknown:" + String(byteValue); + } + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + if (tmpstr == "DHCP") { + byteValue = static_cast(DHCP_MODE); + } else if (tmpstr == "STATIC") { + byteValue = static_cast(STATIC_IP_MODE); + } else { + byteValue = (uint8_t)-1; // unknow flag so put outof range value + } + esp3d_log("got %s param for a value of %d, is valid %d", tmpstr.c_str(), + byteValue, + ESP3DSettings::isValidByteSetting(byteValue, ESP_STA_IP_MODE)); + if (ESP3DSettings::isValidByteSetting(byteValue, ESP_STA_IP_MODE)) { + esp3d_log("Value %d is valid", byteValue); + if (!ESP3DSettings::writeByte(ESP_STA_IP_MODE, byteValue)) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid parameter"; + } + } + + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // WIFI_FEATURE || ETH_FEATURE diff --git a/esp3d/src/core/commands/ESP103.cpp b/esp3d/src/core/commands/ESP103.cpp new file mode 100644 index 00000000..4820c148 --- /dev/null +++ b/esp3d/src/core/commands/ESP103.cpp @@ -0,0 +1,124 @@ +/* + ESP103.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) +#include "../../modules/network/netconfig.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#if defined(WIFI_FEATURE) +#include "../../modules/wifi/wificonfig.h" +#endif // WIFI_FEATURE +#if defined(ETH_FEATURE) +#include "../../modules/ethernet/ethconfig.h" +#endif // ETH_FEATURE +#include "../../modules/authentication/authentication_service.h" +#define COMMAND_ID 103 +// Change STA IP/Mask/GW +//[ESP103]IP= MSK= GW= DNS= [json=no] [pwd= +void ESP3DCommands::ESP103(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; + const char* cmdList[] = {"IP=", "MSK=", "GW=", "DNS="}; + uint8_t cmdListSize = sizeof(cmdList) / sizeof(char*); + const ESP3DSettingIndex settingIndex[] = { + ESP_STA_IP_VALUE, ESP_STA_MASK_VALUE, ESP_STA_GATEWAY_VALUE, + ESP_STA_DNS_VALUE}; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + if (json) { + ok_msg = "{\"ip\":\""; + } else { + ok_msg = "IP: "; + } + ok_msg += ESP3DSettings::readIPString(ESP_STA_IP_VALUE); + if (json) { + ok_msg += "\",\"gw\":\""; + } else { + ok_msg += ", GW: "; + } + ok_msg += ESP3DSettings::readIPString(ESP_STA_GATEWAY_VALUE); + if (json) { + ok_msg += "\",\"msk\":\""; + } else { + ok_msg += ", MSK: "; + } + ok_msg += ESP3DSettings::readIPString(ESP_STA_MASK_VALUE); + if (json) { + ok_msg += "\",\"dns\":\""; + } else { + ok_msg += ", DNS: "; + } + ok_msg += ESP3DSettings::readIPString(ESP_STA_DNS_VALUE); + if (json) { + ok_msg += "\"}"; + } + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + bool hasParam = false; + for (uint8_t i = 0; i < cmdListSize; i++) { + tmpstr = get_param(msg, cmd_params_pos, cmdList[i]); + if (tmpstr.length() != 0) { + hasParam = true; + if (ESP3DSettings::isValidIPStringSetting(tmpstr.c_str(), + settingIndex[i])) { + esp3d_log("Value %s is valid", tmpstr.c_str()); + if (!ESP3DSettings::writeIPString(settingIndex[i], tmpstr.c_str())) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid parameter"; + } + } + } + if (!hasParam && !hasError) { + hasError = true; + error_msg = "Invalid parameter"; + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // WIFI_FEATURE || ETH_FEATURE diff --git a/esp3d/src/core/commands/ESP104.cpp b/esp3d/src/core/commands/ESP104.cpp new file mode 100644 index 00000000..651aa05d --- /dev/null +++ b/esp3d/src/core/commands/ESP104.cpp @@ -0,0 +1,111 @@ +/* + ESP104.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(WIFI_FEATURE) || defined(BLUETOOTH_FEATURE) || defined(ETH_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/network/netconfig.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 104 +// Set STA fallback mode state at boot which can be BT, WIFI-SETUP, OFF +//[ESP104] json= pwd= +void ESP3DCommands::ESP104(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; + uint8_t byteValue = (uint8_t)-1; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + byteValue = ESP3DSettings::readByte(ESP_STA_FALLBACK_MODE); +#if defined(BLUETOOTH_FEATURE) + if (byteValue == (uint8_t)ESP_BT) { + ok_msg = "BT"; + } else +#endif // BLUETOOTH_FEATURE +#if defined(WIFI_FEATURE) + if (byteValue == (uint8_t)ESP_AP_SETUP) { + ok_msg = "CONFIG"; + } else +#endif // WIFI_FEATURE + if (byteValue == (uint8_t)ESP_NO_NETWORK) { + ok_msg = "OFF"; + } else { + ok_msg = "Unknown"; + } + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE +#if defined(BLUETOOTH_FEATURE) + if (tmpstr == "BT") { + byteValue = (uint8_t)ESP_BT; + } else +#endif // BLUETOOTH_FEATURE +#if defined(WIFI_FEATURE) + if (tmpstr == "CONFIG") { + byteValue = (uint8_t)ESP_AP_SETUP; + } else +#endif // WIFI_FEATURE + if (tmpstr == "OFF") { + byteValue = (uint8_t)ESP_NO_NETWORK; + } else { + byteValue = (uint8_t)-1; // unknow flag so put outof range value + } + esp3d_log( + "got %s param for a value of %d, is valid %d", tmpstr.c_str(), + byteValue, + ESP3DSettings::isValidByteSetting(byteValue, ESP_STA_FALLBACK_MODE)); + if (ESP3DSettings::isValidByteSetting(byteValue, ESP_STA_FALLBACK_MODE)) { + esp3d_log("Value %d is valid", byteValue); + if (!ESP3DSettings::writeByte(ESP_STA_FALLBACK_MODE, byteValue)) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid parameter"; + } + } + + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // WIFI_FEATURE diff --git a/esp3d/src/core/commands/ESP105.cpp b/esp3d/src/core/commands/ESP105.cpp new file mode 100644 index 00000000..52052d7a --- /dev/null +++ b/esp3d/src/core/commands/ESP105.cpp @@ -0,0 +1,85 @@ +/* + ESP105.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(WIFI_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/wifi/wificonfig.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 105 +// AP SSID +//[ESP105] [json=no] [pwd=] +void ESP3DCommands::ESP105(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + const ESP3DSettingDescription* settingPtr = + ESP3DSettings::getSettingPtr(ESP_AP_SSID); + if (settingPtr) { + ok_msg = ESP3DSettings::readString(ESP_AP_SSID); + } else { + hasError = true; + error_msg = "This setting is unknown"; + } + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + esp3d_log("got %s param for a value of %s, is valid %d", tmpstr.c_str(), + tmpstr.c_str(), + ESP3DSettings::isValidStringSetting(tmpstr.c_str(), ESP_AP_SSID)); + if (ESP3DSettings::isValidStringSetting(tmpstr.c_str(), ESP_AP_SSID)) { + esp3d_log("Value %s is valid", tmpstr.c_str()); + if (!ESP3DSettings::writeString(ESP_AP_SSID, tmpstr.c_str())) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid parameter"; + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // WIFI_FEATURE diff --git a/esp3d/src/core/commands/ESP106.cpp b/esp3d/src/core/commands/ESP106.cpp new file mode 100644 index 00000000..a0839e2a --- /dev/null +++ b/esp3d/src/core/commands/ESP106.cpp @@ -0,0 +1,85 @@ +/* + ESP106.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(WIFI_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/wifi/wificonfig.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 106 +// AP Password +//[ESP106] [json=no] [pwd=] +void ESP3DCommands::ESP106(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool clearSetting = hasTag(msg, cmd_params_pos, "NOPASSWORD"); + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + hasError = true; + error_msg = "Password not displayable"; + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + if (clearSetting) { + esp3d_log("NOPASSWORD flag detected, set string to empty string"); + tmpstr = ""; + } + esp3d_log( + "got %s param for a value of %s, is valid %d", tmpstr.c_str(), + tmpstr.c_str(), + ESP3DSettings::isValidStringSetting(tmpstr.c_str(), ESP_AP_PASSWORD)); + if (ESP3DSettings::isValidStringSetting(tmpstr.c_str(), ESP_AP_PASSWORD)) { + esp3d_log("Value %s is valid", tmpstr.c_str()); + if (!ESP3DSettings::writeString(ESP_AP_PASSWORD, tmpstr.c_str())) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid parameter"; + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // WIFI_FEATURE diff --git a/esp3d/src/core/commands/ESP107.cpp b/esp3d/src/core/commands/ESP107.cpp new file mode 100644 index 00000000..d77c9c12 --- /dev/null +++ b/esp3d/src/core/commands/ESP107.cpp @@ -0,0 +1,78 @@ +/* + ESP107.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(WIFI_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/network/netconfig.h" +#include "../../modules/wifi/wificonfig.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 107 +// Change AP IP +//[ESP107] [json=no] pwd= +void ESP3DCommands::ESP107(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + ok_msg = ESP3DSettings::readIPString(ESP_AP_IP_VALUE); + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + if (ESP3DSettings::isValidIPStringSetting(tmpstr.c_str(), + ESP_AP_IP_VALUE)) { + esp3d_log("Value %s is valid", tmpstr.c_str()); + if (!ESP3DSettings::writeIPString(ESP_AP_IP_VALUE, tmpstr.c_str())) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid parameter"; + } + } + + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // WIFI_FEATURE diff --git a/esp3d/src/core/commands/ESP108.cpp b/esp3d/src/core/commands/ESP108.cpp new file mode 100644 index 00000000..f8d08406 --- /dev/null +++ b/esp3d/src/core/commands/ESP108.cpp @@ -0,0 +1,82 @@ +/* + ESP108.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(WIFI_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/wifi/wificonfig.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 108 +// Change AP channel +//[ESP108] [json=no] [pwd=] +void ESP3DCommands::ESP108(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; + uint8_t byteValue = 0; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + byteValue = ESP3DSettings::readByte(ESP_AP_CHANNEL); + ok_msg = String(byteValue); + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + byteValue = atoi(tmpstr.c_str()); + esp3d_log("got %s param for a value of %d, is valid %d", tmpstr.c_str(), + byteValue, + ESP3DSettings::isValidByteSetting(byteValue, ESP_AP_CHANNEL)); + if (ESP3DSettings::isValidByteSetting(byteValue, ESP_AP_CHANNEL)) { + esp3d_log("Value %d is valid", byteValue); + if (!ESP3DSettings::writeByte(ESP_AP_CHANNEL, byteValue)) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid parameter"; + } + } + + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // WIFI_FEATURE diff --git a/esp3d/src/core/commands/ESP110.cpp b/esp3d/src/core/commands/ESP110.cpp new file mode 100644 index 00000000..a808fbbc --- /dev/null +++ b/esp3d/src/core/commands/ESP110.cpp @@ -0,0 +1,127 @@ +/* + ESP110.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(WIFI_FEATURE) || defined(BLUETOOTH_FEATURE) || defined(ETH_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/network/netconfig.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 110 +// Set radio state at boot which can be BT, WIFI-STA, WIFI-AP, ETH-STA, OFF +//[ESP110] json= pwd= +void ESP3DCommands::ESP110(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; + uint8_t byteValue = (uint8_t)-1; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + byteValue = ESP3DSettings::readByte(ESP_RADIO_MODE); + if (byteValue == ESP_BT) { + ok_msg = "BT"; + } else +#if defined(WIFI_FEATURE) + if (byteValue == ESP_WIFI_AP) { + ok_msg = "WIFI-AP"; + } else if (byteValue == ESP_WIFI_STA) { + ok_msg = "WIFI-STA"; + } else if (byteValue == ESP_AP_SETUP) { + ok_msg = "WIFI-SETUP"; + } else if (byteValue == ESP_ETH_STA) { + ok_msg = "ETH-STA"; + } else +#endif // WIFI_FEATURE + if (byteValue == ESP_NO_NETWORK) { + ok_msg = "OFF"; + } else { + ok_msg = "Unknown"; + } + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr.toUpperCase(); + if (tmpstr == "BT") { + byteValue = ESP_BT; + } else +#if defined(WIFI_FEATURE) + if (tmpstr == "WIFI-AP") { + byteValue = ESP_WIFI_AP; + } else if (tmpstr == "WIFI-STA") { + byteValue = ESP_WIFI_STA; + } else if (tmpstr == "WIFI-SETUP") { + byteValue = ESP_AP_SETUP; + } else +#endif // WIFI_FEATURE +#if defined(ETH_FEATURE) + if (tmpstr == "ETH-STA") { + byteValue = ESP_ETH_STA; + } else +#endif // ETH_FEATURE + if (tmpstr == "OFF") { + byteValue = ESP_NO_NETWORK; + } else { + byteValue = (uint8_t)-1; // unknow flag so put outof range value + } + esp3d_log("got %s param for a value of %d, is valid %d", tmpstr.c_str(), + byteValue, + ESP3DSettings::isValidByteSetting(byteValue, ESP_RADIO_MODE)); + if (ESP3DSettings::isValidByteSetting(byteValue, ESP_RADIO_MODE)) { + esp3d_log("Value %d is valid", byteValue); + if (!ESP3DSettings::writeByte(ESP_RADIO_MODE, byteValue)) { + hasError = true; + error_msg = "Set value failed"; + } else { + if (!NetConfig::begin()) { + hasError = true; + error_msg = "Cannot setup network"; + } + } + } else { + hasError = true; + error_msg = "Invalid parameter"; + } + } + + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // WIFI_FEATURE diff --git a/esp3d/src/core/commands/ESP111.cpp b/esp3d/src/core/commands/ESP111.cpp new file mode 100644 index 00000000..33aad028 --- /dev/null +++ b/esp3d/src/core/commands/ESP111.cpp @@ -0,0 +1,110 @@ +/* + ESP111.cpp - ESP3D command 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 +*/ +// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 +#include "../../include/esp3d_config.h" +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/network/netconfig.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 111 +// Get current IP +//[ESP111] OUTPUT=PRINTER ALL [json=no] +void ESP3DCommands::ESP111(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + bool respjson = json; + bool showAll = hasTag(msg, cmd_params_pos, "ALL"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + + tmpstr = get_param(msg, cmd_params_pos, "OUTPUT="); + if (tmpstr == "PRINTER") { + msg->target = ESP3DClientType::remote_screen; + json = false; + } + if (!showAll) { + ok_msg = NetConfig::localIP().c_str(); + } else { + if (json) { + ok_msg = "{\"ip\":\""; + } else { + ok_msg = "IP: "; + } + ok_msg += NetConfig::localIP().c_str(); + if (json) { + ok_msg += "\",\"gw\":\""; + } else { + ok_msg += "\nGW: "; + } + ok_msg += NetConfig::localGW().c_str(); + if (json) { + ok_msg += "\",\"msk\":\""; + } else { + ok_msg += "\nMSK: "; + } + ok_msg += NetConfig::localMSK().c_str(); + if (json) { + ok_msg += "\",\"dns\":\""; + } else { + ok_msg += "\nDNS: "; + } + ok_msg += NetConfig::localDNS().c_str(); + if (json) { + ok_msg += "\"}"; + } + } + + if (msg->target == ESP3DClientType::remote_screen) { + if (respjson) { + tmpstr = "{\"cmd\":\"111\",\"status\":\"ok\",\"data\":\"ok\"}"; + } else { + tmpstr = "ok\n"; + } + // send response to original client + if (!dispatch(tmpstr.c_str(), target, msg->request_id, + ESP3DMessageType::unique)) { + esp3d_log_e("Error sending response to original client"); + } + } + + // Printer does not support json just normal serial + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // WIFI_FEATURE diff --git a/esp3d/src/core/commands/ESP112.cpp b/esp3d/src/core/commands/ESP112.cpp new file mode 100644 index 00000000..9458a56f --- /dev/null +++ b/esp3d/src/core/commands/ESP112.cpp @@ -0,0 +1,87 @@ +/* + ESP112.cpp - ESP3D command 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 +*/ +#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 "../esp3d_commands.h" +#include "../esp3d_settings.h" + +// Get/Set hostname +//[ESP112] [json=no] pwd= +#define COMMAND_ID 112 +void ESP3DCommands::ESP112(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; + +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + const ESP3DSettingDescription* settingPtr = + ESP3DSettings::getSettingPtr(ESP_HOSTNAME); + if (settingPtr) { + ok_msg = ESP3DSettings::readString(ESP_HOSTNAME); + } else { + hasError = true; + error_msg = "This setting is unknown"; + } + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + esp3d_log( + "got %s param for a value of %s, is valid %d", tmpstr.c_str(), + tmpstr.c_str(), + ESP3DSettings::isValidStringSetting(tmpstr.c_str(), ESP_HOSTNAME)); + if (ESP3DSettings::isValidStringSetting(tmpstr.c_str(), ESP_HOSTNAME)) { + esp3d_log("Value %s is valid", tmpstr.c_str()); + if (!ESP3DSettings::writeString(ESP_HOSTNAME, tmpstr.c_str())) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid parameter"; + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // WIFI_FEATURE || ETH_FEATURE || BT_FEATURE diff --git a/esp3d/src/core/commands/ESP114.cpp b/esp3d/src/core/commands/ESP114.cpp new file mode 100644 index 00000000..78d973dc --- /dev/null +++ b/esp3d/src/core/commands/ESP114.cpp @@ -0,0 +1,94 @@ +/* + ESP114.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BT_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +// Get/Set Boot radio state which can be ON, OFF +//[ESP114] json= pwd= +#define COMMAND_ID 114 +void ESP3DCommands::ESP114(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; + uint8_t byteValue = (uint8_t)-1; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + byteValue = ESP3DSettings::readByte(ESP_BOOT_RADIO_STATE); + if (byteValue == (uint8_t)ESP3DState::off) { + ok_msg = "OFF"; + } else if (byteValue == (uint8_t)ESP3DState::on) { + ok_msg = "ON"; + } else { + ok_msg = "Unknown"; + } + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + if (tmpstr == "OFF") { + byteValue = (uint8_t)ESP3DState::off; + } else if (tmpstr == "ON") { + byteValue = (uint8_t)ESP3DState::on; + } else { + byteValue = (uint8_t)-1; // unknow flag so put outof range value + } + esp3d_log( + "got %s param for a value of %d, is valid %d", tmpstr.c_str(), + byteValue, + ESP3DSettings::isValidByteSetting(byteValue, ESP_BOOT_RADIO_STATE)); + if (ESP3DSettings::isValidByteSetting(byteValue, ESP_BOOT_RADIO_STATE)) { + esp3d_log("Value %d is valid", byteValue); + if (!ESP3DSettings::writeByte(ESP_BOOT_RADIO_STATE, byteValue)) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid parameter"; + } + } + + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BT_FEATURE) \ No newline at end of file diff --git a/esp3d/src/core/commands/ESP115.cpp b/esp3d/src/core/commands/ESP115.cpp new file mode 100644 index 00000000..1d61320c --- /dev/null +++ b/esp3d/src/core/commands/ESP115.cpp @@ -0,0 +1,86 @@ +/* + ESP115.cpp - ESP3D command 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 +*/ +#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 "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 115 +// Get/Set immediate Network (WiFi/BT/Ethernet) state which can be ON, OFF +//[ESP115] json= pwd= +void ESP3DCommands::ESP115(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + + uint8_t current_radio_mode = NetConfig::getMode(); + if (tmpstr.length() == 0) { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + if (current_radio_mode == ESP_NO_NETWORK) { + ok_msg = "OFF"; + } else { + ok_msg = "ON"; + } + } else { + if (tmpstr == "OFF") { + if (current_radio_mode != ESP_NO_NETWORK) { + NetConfig::end(); + } + } else if (tmpstr == "ON") { + if (current_radio_mode == ESP_NO_NETWORK) { + if (!NetConfig::begin()) { + hasError = true; + error_msg = "Fail to start network"; + } + } + } else { + hasError = true; + error_msg = "Invalid parameter"; + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // WIFI_FEATURE || ETH_FEATURE || BT_FEATURE diff --git a/esp3d/src/core/commands/ESP120.cpp b/esp3d/src/core/commands/ESP120.cpp new file mode 100644 index 00000000..64a4077e --- /dev/null +++ b/esp3d/src/core/commands/ESP120.cpp @@ -0,0 +1,79 @@ +/* + ESP120.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(HTTP_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 120 +// Set HTTP state which can be ON, OFF +//[ESP120] json= pwd= +void ESP3DCommands::ESP120(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + ESP3DState setting_http_mode = + (ESP3DState)ESP3DSettings::readByte(ESP_HTTP_ON); + if (tmpstr.length() == 0) { + if (setting_http_mode == ESP3DState::off) { + ok_msg = "OFF"; + } else { + ok_msg = "ON"; + } + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + if (tmpstr == "OFF" || tmpstr == "ON") { + if (!ESP3DSettings::writeByte(ESP_HTTP_ON, tmpstr == "OFF" ? 0 : 1)) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid parameter"; + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // HTTP_FEATURE diff --git a/esp3d/src/core/commands/ESP121.cpp b/esp3d/src/core/commands/ESP121.cpp new file mode 100644 index 00000000..9d099d59 --- /dev/null +++ b/esp3d/src/core/commands/ESP121.cpp @@ -0,0 +1,81 @@ +/* + ESP121.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(HTTP_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 121 +// Set HTTP port +//[ESP121] json= pwd= +void ESP3DCommands::ESP121(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; + uint32_t intValue = 0; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + intValue = ESP3DSettings::readUint32(ESP_HTTP_PORT); + ok_msg = String(intValue); + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + intValue = atoi(tmpstr.c_str()); + esp3d_log("got %s param for a value of %ld, is valid %d", tmpstr.c_str(), + intValue, + ESP3DSettings::isValidIntegerSetting(intValue, ESP_HTTP_PORT)); + if (ESP3DSettings::isValidIntegerSetting(intValue, ESP_HTTP_PORT)) { + esp3d_log("Value %ld is valid", intValue); + if (!ESP3DSettings::writeUint32(ESP_HTTP_PORT, intValue)) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid parameter"; + } + } + + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // HTTP_FEATURE diff --git a/esp3d/src/core/commands/ESP130.cpp b/esp3d/src/core/commands/ESP130.cpp new file mode 100644 index 00000000..9c7f7459 --- /dev/null +++ b/esp3d/src/core/commands/ESP130.cpp @@ -0,0 +1,89 @@ +/* + ESP130.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(TELNET_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/telnet/telnet_server.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 130 +// Set TELNET state which can be ON, OFF, CLOSE +//[ESP130] json= pwd= +void ESP3DCommands::ESP130(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + bool closeClients = hasTag(msg, cmd_params_pos, "CLOSE"); + bool stateON = hasTag(msg, cmd_params_pos, "ON"); + bool stateOFF = hasTag(msg, cmd_params_pos, "OFF"); + bool has_param = false; + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + ESP3DState setting_mode = (ESP3DState)ESP3DSettings::readByte(ESP_TELNET_ON); + if (tmpstr.length() == 0) { + if (setting_mode == ESP3DState::off) { + ok_msg = "OFF"; + } else { + ok_msg = "ON"; + } + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + if (stateON || stateOFF) { + if (!ESP3DSettings::writeByte(ESP_TELNET_ON, stateOFF ? 0 : 1)) { + hasError = true; + error_msg = "Set value failed"; + } + has_param = true; + } + if (closeClients) { + has_param = true; + telnet_server.closeClient(); + } + if (!has_param) { + hasError = true; + error_msg = "Invalid parameter"; + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // TELNET_FEATURE diff --git a/esp3d/src/core/commands/ESP131.cpp b/esp3d/src/core/commands/ESP131.cpp new file mode 100644 index 00000000..4da1e6ae --- /dev/null +++ b/esp3d/src/core/commands/ESP131.cpp @@ -0,0 +1,81 @@ +/* + ESP131.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(TELNET_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 131 +// Set TELNET port +//[ESP131] json= pwd= +void ESP3DCommands::ESP131(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; + uint32_t intValue = 0; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + intValue = ESP3DSettings::readUint32(ESP_TELNET_PORT); + ok_msg = String(intValue); + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + intValue = atoi(tmpstr.c_str()); + esp3d_log("got %s param for a value of %ld, is valid %d", tmpstr.c_str(), + intValue, + ESP3DSettings::isValidIntegerSetting(intValue, ESP_TELNET_PORT)); + if (ESP3DSettings::isValidIntegerSetting(intValue, ESP_TELNET_PORT)) { + esp3d_log("Value %ld is valid", intValue); + if (!ESP3DSettings::writeUint32(ESP_TELNET_PORT, intValue)) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid parameter"; + } + } + + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // TELNET_FEATURE diff --git a/esp3d/src/core/commands/ESP140.cpp b/esp3d/src/core/commands/ESP140.cpp new file mode 100644 index 00000000..9b2d1e7a --- /dev/null +++ b/esp3d/src/core/commands/ESP140.cpp @@ -0,0 +1,180 @@ +/* + ESP140.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(TIMESTAMP_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/time/time_service.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 140 +// Sync / Set / Get current time +//[ESP140] +// NOW json= pwd= +void ESP3DCommands::ESP140(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + bool sync = hasTag(msg, cmd_params_pos, "sync"); + bool now = hasTag(msg, cmd_params_pos, "now"); + String tmpstr; + const char* cmdList[] = {"srv1", "srv2", "srv3", "tzone", "ntp", "time"}; + uint8_t cmdListSize = sizeof(cmdList) / sizeof(char*); + const ESP3DSettingIndex settingIndex[] = { + ESP_TIME_SERVER1, ESP_TIME_SERVER2, ESP_TIME_SERVER3, + ESP_TIME_ZONE, ESP_INTERNET_TIME, (ESP3DSettingIndex)-1, + }; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + if (json) { + ok_msg = "{"; + } else { + ok_msg = ""; + } + // no need to show time right now + for (uint8_t i = 0; i < cmdListSize - 2; i++) { + if (json) { + if (i > 0) { + ok_msg += ","; + } + ok_msg += "\""; + } else { + if (i > 0) { + ok_msg += ", "; + } + } + ok_msg += cmdList[i]; + + if (json) { + ok_msg += "\":\""; + } else { + ok_msg += ": "; + } + ok_msg += ESP3DSettings::readString(settingIndex[i]); + if (json) { + ok_msg += "\""; + } else { + } + } + if (json) { + ok_msg += ",\"ntp\":\""; + } else { + ok_msg += ", ntp: "; + } + ok_msg += ESP3DSettings::readByte(ESP_INTERNET_TIME) ? "yes" : "no"; + if (json) { + ok_msg += "\""; + } else { + } + + if (json) { + ok_msg += "}"; + } + } else { + bool hasParam = false; + String tmpkey; + for (uint8_t i = 0; i < cmdListSize; i++) { + tmpkey = cmdList[i]; + tmpkey += "="; + tmpstr = get_param(msg, cmd_params_pos, tmpkey.c_str()); + if (tmpstr.length() != 0) { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + hasParam = true; + if (settingIndex[i] == (ESP3DSettingIndex)-1) { + // set time + if (!timeService.setTime(tmpstr.c_str())) { + hasError = true; + error_msg = "Set time failed"; + } + } else if (settingIndex[i] == ESP_INTERNET_TIME) { + tmpstr.toLowerCase(); + if (tmpstr == "yes" || tmpstr == "no" || tmpstr == "1" || + tmpstr == "0" || tmpstr == "true" || tmpstr == "false") { + uint8_t val = 0; + if (tmpstr == "yes" || tmpstr == "1" || tmpstr == "true") { + val = 1; + } + if (!ESP3DSettings::writeByte(settingIndex[i], val)) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid token parameter"; + } + + } else { + if (ESP3DSettings::isValidStringSetting(tmpstr.c_str(), + settingIndex[i])) { + esp3d_log("Value %s is valid", tmpstr.c_str()); + if (!ESP3DSettings::writeString(settingIndex[i], tmpstr.c_str())) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid token parameter"; + esp3d_log_e("Value %s is invalid", tmpstr.c_str()); + } + } + } + } + if (!hasError && now) { + ok_msg = timeService.getCurrentTime(); + ok_msg += " ("; + ok_msg += timeService.getTimeZone(); + ok_msg += ")"; + hasParam = true; + } + if (!hasError && sync) { + // apply changes without restarting the board + timeService.begin(); + hasParam = true; + } + if (!hasParam && !hasError) { + hasError = true; + error_msg = "Invalid parameter"; + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // TIMESTAMP_FEATURE diff --git a/esp3d/src/core/commands/ESP150.cpp b/esp3d/src/core/commands/ESP150.cpp new file mode 100644 index 00000000..a860e093 --- /dev/null +++ b/esp3d/src/core/commands/ESP150.cpp @@ -0,0 +1,123 @@ +/* + ESP150.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#include "../../modules/authentication/authentication_service.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 150 +// Get/Set display/set boot delay in ms / Verbose boot +//[ESP150][pwd=] +void ESP3DCommands::ESP150(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + String tmpstr; + bool json = hasTag(msg, cmd_params_pos, "json"); + bool hasParam = false; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + if (json) { + ok_msg = "{\"delay\":\""; + } else { + ok_msg = "delay="; + } + ok_msg += String(ESP3DSettings::readUint32(ESP_BOOT_DELAY)); + if (json) { + ok_msg += "\",\"verbose\":\""; + } else { + ok_msg += ", verbose="; + } + ok_msg += ESP3DSettings::isVerboseBoot(true) ? "ON" : "OFF"; + if (json) { + ok_msg += "\"}"; + } + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_param(msg, cmd_params_pos, "delay="); + if (tmpstr.length() != 0) { + hasParam = true; + if (ESP3DSettings::isValidIntegerSetting(tmpstr.toInt(), + ESP_BOOT_DELAY)) { + if (!ESP3DSettings::writeUint32(ESP_BOOT_DELAY, tmpstr.toInt())) { + hasError = true; + error_msg = "Set delay failed"; + esp3d_log_e("%s", error_msg.c_str()); + } + } else { + hasError = true; + error_msg = "Incorrect delay"; + esp3d_log_e("%s", error_msg.c_str()); + } + } + if (!hasError) { + tmpstr = get_param(msg, cmd_params_pos, "verbose="); + if (tmpstr.length() != 0) { + hasParam = true; + tmpstr.toUpperCase(); + if (tmpstr == "ON" || tmpstr == "OFF" || tmpstr == "1" || + tmpstr == "0" || tmpstr == "TRUE" || tmpstr == "FALSE" || + tmpstr == "YES" || tmpstr == "NO") { + uint8_t val = 0; + if (tmpstr == "ON" || tmpstr == "1" || tmpstr == "TRUE" || + tmpstr == "YES") { + val = 1; + } + if (!ESP3DSettings::writeByte(ESP_VERBOSE_BOOT, val)) { + hasError = true; + error_msg = "Set delay failed"; + esp3d_log_e("%s", error_msg.c_str()); + } + } else { + hasError = true; + error_msg = "Incorrect verbose setting"; + esp3d_log_e("%s", error_msg.c_str()); + } + } + } + if (!hasError && !hasParam) { + hasError = true; + error_msg = "Incorrect parameter"; + esp3d_log_e("%s", error_msg.c_str()); + } + } + + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} diff --git a/esp3d/src/core/commands/ESP160.cpp b/esp3d/src/core/commands/ESP160.cpp new file mode 100644 index 00000000..4c928423 --- /dev/null +++ b/esp3d/src/core/commands/ESP160.cpp @@ -0,0 +1,90 @@ +/* + ESP160.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(WS_DATA_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/websocket/websocket_server.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 160 +// Set WebSocket state which can be ON, OFF, CLOSE +//[ESP160] json= pwd= +void ESP3DCommands::ESP160(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + bool closeClients = hasTag(msg, cmd_params_pos, "CLOSE"); + bool stateON = hasTag(msg, cmd_params_pos, "ON"); + bool stateOFF = hasTag(msg, cmd_params_pos, "OFF"); + bool has_param = false; + String tmpstr; +#ifdef AUTHENTICATION_FEATURE + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + ESP3DState setting_mode = + (ESP3DState)ESP3DSettings::readByte(ESP_WEBSOCKET_ON); + if (tmpstr.length() == 0) { + if (setting_mode == ESP3DState::off) { + ok_msg = "OFF"; + } else { + ok_msg = "ON"; + } + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + if (stateON || stateOFF) { + if (!ESP3DSettings::writeByte(ESP_WEBSOCKET_ON, stateOFF ? 0 : 1)) { + hasError = true; + error_msg = "Set value failed"; + } + has_param = true; + } + if (closeClients) { + has_param = true; + websocket_data_server.closeClients(); + } + if (!has_param) { + hasError = true; + error_msg = "Invalid parameter"; + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // WS_DATA_FEATURE diff --git a/esp3d/src/core/commands/ESP161.cpp b/esp3d/src/core/commands/ESP161.cpp new file mode 100644 index 00000000..b0f6f5ee --- /dev/null +++ b/esp3d/src/core/commands/ESP161.cpp @@ -0,0 +1,82 @@ +/* + ESP161.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(WS_DATA_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 161 +// Set Websocket port +//[ESP161] json= pwd= +void ESP3DCommands::ESP161(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; + uint32_t intValue = 0; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + intValue = ESP3DSettings::readUint32(ESP_WEBSOCKET_PORT); + ok_msg = String(intValue); + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + intValue = atoi(tmpstr.c_str()); + esp3d_log( + "got %s param for a value of %ld, is valid %d", tmpstr.c_str(), + intValue, + ESP3DSettings::isValidIntegerSetting(intValue, ESP_WEBSOCKET_PORT)); + if (ESP3DSettings::isValidIntegerSetting(intValue, ESP_WEBSOCKET_PORT)) { + esp3d_log("Value %ld is valid", intValue); + if (!ESP3DSettings::writeUint32(ESP_WEBSOCKET_PORT, intValue)) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid parameter"; + } + } + + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // WS_DATA_FEATURE diff --git a/esp3d/src/core/commands/ESP170.cpp b/esp3d/src/core/commands/ESP170.cpp new file mode 100644 index 00000000..afba2086 --- /dev/null +++ b/esp3d/src/core/commands/ESP170.cpp @@ -0,0 +1,303 @@ +/* + ESP122.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(CAMERA_DEVICE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/camera/camera.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" +#include "esp_camera.h" + +#define COMMAND_ID 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 +void ESP3DCommands::ESP170(int cmd_params_pos, ESP3DMessage* msg) { + const char* camcmd = [] = { + "framesize", + "quality", + "contrast", + "brightness", + "saturation", + "sharpness", + "special_effect", + "wb_mode", + "awb", + "awb_gain", + "aec", + "aec2", + "ae_level", + "aec_value", + "agc", + "agc_gain", + "gainceiling", + "bpc", + "wpc", + "raw_gma", + "lenc", + "vflip", + "hmirror", + "dcw", + "colorbar", +#if CAM_LED_PIN != -1 + "light", +#endif // CAM_LED_PIN + }; + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; +#if AUTHENTICATION_FEATURE + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + if (!esp3d_camera.started()) { + hasError = true; + error_msg = "No camera initialized"; + esp3d_log_e("%s", error_msg.c_str()); + } else { + tmpstr = get_clean_param(msg, cmd_params_pos); + sensor_t* s = esp_camera_sensor_get(); + if (s == nullptr) { + hasError = true; + error_msg = "No camera settings available"; + esp3d_log_e("%s", error_msg.c_str()); + } else { + if (tmpstr.length() == 0) { + if (json) { + tmpstr = "{\"cmd\":\"170\",\"status\":\"ok\",\"data\":["; + + } else { + tmpstr = "Camera:\n"; + } + msg->type = ESP3DMessageType::head; + if (!dispatch(msg, tmpstr.c_str())) { + esp3d_log_e("Error sending response to clients"); + return; + } + // now send all settings one by one + // framesize + if (!dispatchIdValue(json, "framesize", + String(status.framesize).c_str(), target, + requestId, true)) { + return; + } + + // quality + if (!dispatchIdValue(json, "quality", String(status.quality).c_str(), + target, requestId)) { + return; + } + + // brightness + if (!dispatchIdValue(json, "brightness", + String(status.brightness).c_str(), target, + requestId)) { + return; + } + + // contrast + if (!dispatchIdValue(json, "contrast", String(status.contrast).c_str(), + target, requestId)) { + return; + } + + // saturation + if (!dispatchIdValue(json, "saturation", + String(status.saturation).c_str(), target, + requestId)) { + return; + + // sharpness + if (!dispatchIdValue(json, "sharpness", + String(status.sharpness).c_str(), target, + requestId)) { + return; + } + + // special_effect + if (!dispatchIdValue(json, "special_effect", + String(status.special_effect).c_str(), target, + requestId)) { + return; + } + + // wb_mode + if (!dispatchIdValue(json, "wb_mode", String(status.wb_mode).c_str(), + target, requestId)) { + return; + } + + // awb + if (!dispatchIdValue(json, "awb", String(status.awb).c_str(), target, + requestId)) { + return; + } + + // awb_gain + if (!dispatchIdValue(json, "awb_gain", + String(status.awb_gain).c_str(), target, + requestId)) { + return; + } + + // aec + if (!dispatchIdValue(json, "aec", String(status.aec).c_str(), target, + requestId)) { + return; + } + // aec2 + if (!dispatchIdValue(json, "aec2", String(status.aec2).c_str(), + target, requestId)) { + return; + } + // ae_level + if (!dispatchIdValue(json, "ae_level", + String(status.ae_level).c_str(), target, + requestId)) { + return; + } + // aec_value + if (!dispatchIdValue(json, "aec_value", + String(status.aec_value).c_str(), target, + requestId)) { + return; + } + // agc + if (!dispatchIdValue(json, "agc", String(status.agc).c_str(), target, + requestId)) { + return; + } + // agc_gain + if (!dispatchIdValue(json, "agc_gain", + String(status.agc_gain).c_str(), target, + requestId)) { + return; + } + // gainceiling + if (!dispatchIdValue(json, "gainceiling", + String(status.gainceiling).c_str(), target, + requestId)) { + return; + } + // bpc + if (!dispatchIdValue(json, "bpc", String(status.bpc).c_str(), target, + requestId)) { + return; + } + // wpc + if (!dispatchIdValue(json, "wpc", String(status.wpc).c_str(), target, + requestId)) { + return; + } + // raw_gma + if (!dispatchIdValue(json, "raw_gma", String(status.raw_gma).c_str(), + target, requestId)) { + return; + } + // lenc + if (!dispatchIdValue(json, "lenc", String(status.lenc).c_str(), + target, requestId)) { + return; + } + // vflip + if (!dispatchIdValue(json, "vflip", String(status.vflip).c_str(), + target, requestId)) { + return; + } + // hmirror + if (!dispatchIdValue(json, "hmirror", String(status.hmirror).c_str(), + target, requestId)) { + return; + } + // dcw + if (!dispatchIdValue(json, "dcw", String(status.dcw).c_str(), target, + requestId)) { + return; + } + // colorbar + if (!dispatchIdValue(json, "colorbar", + String(status.colorbar).c_str(), target, + requestId)) { + return; + } +#if CAM_LED_PIN != -1 + // light + if (!dispatchIdValue( + json, "light", + String(digitalRead(CAM_LED_PIN) == HIGH ? 1 : 0).c_str(), + target, requestId)) { + return; + } +#endif // CAM_LED_PIN + } + if (json) { + if (!dispatch("]}", target, requestId, ESP3DMessageType::tail)) { + esp3d_log_e("Error sending answer to clients"); + } + } else { + { + tmpstr = "ok\n"; + if (!dispatch(tmpstr.c_str(), target, requestId, + ESP3DMessageType::tail)) { + esp3d_log_e("Error sending answer to clients"); + } + } + } + return; + } else { + size_t s = sizeof(camcmd) / sizeof(const char*); + for (size_t i = 0; i < s; i++) { + String label = camcmd[i]; + label += "="; + tmpstr = get_param(msg, cmd_params_pos, label.c_str()); + if (tmpstr.length() > 0) { + int r = esp3d_camera.command(camcmd[i], tmpstr.c_str()); + if (r == -1) { + hasError = true; + error_msg = "Unknow command"; + esp3d_log_e("%s", error_msg.c_str()); + } else if (r == 1) { + hasError = true; + error_msg = "Invalid value"; + esp3d_log_e("%s", error_msg.c_str()); + } else { + ok_msg = "ok"; + } + } + } + } + } + } + + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // CAMERA_DEVICE diff --git a/esp3d/src/core/commands/ESP171.cpp b/esp3d/src/core/commands/ESP171.cpp new file mode 100644 index 00000000..37cc29d9 --- /dev/null +++ b/esp3d/src/core/commands/ESP171.cpp @@ -0,0 +1,108 @@ +/* + ESP122.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(CAMERA_DEVICE) +#include + +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/camera/camera.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" +#include "esp_camera.h" + +#define COMMAND_ID 171 +// Save frame to target path and filename (default target = today date, default +// name=timestamp.jpg) +//[ESP171]path= filename= pwd= +void ESP3DCommands::ESP171(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok Snapshot taken"; + String path; + String filename; + String tmpstr; + bool json = hasTag(msg, cmd_params_pos, "json"); + +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + if (!esp3d_camera.started()) { + hasError = true; + error_msg = "No camera initialized"; + esp3d_log_e("%s", error_msg.c_str()); + } else { + tmpstr = get_param(msg, cmd_params_pos, "path="); + if (tmpstr.length() != 0) { + // get path + path = tmpstr; + } + tmpstr = get_param(msg, cmd_params_pos, "filename="); + if (tmpstr.length() != 0) { + // get filename + filename = tmpstr; + } + // 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"; + } + if (!esp3d_camera.handle_snap(nullptr, path.c_str(), filename.c_str())) { + hasError = true; + error_msg = "Error taking snapshot"; + esp3d_log_e("%s", error_msg.c_str()); + } + } + + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // CAMERA_DEVICE diff --git a/esp3d/src/core/commands/ESP180.cpp b/esp3d/src/core/commands/ESP180.cpp new file mode 100644 index 00000000..951c20f3 --- /dev/null +++ b/esp3d/src/core/commands/ESP180.cpp @@ -0,0 +1,89 @@ +/* + ESP130.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(FTP_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/ftp/FtpServer.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 180 +// Set ftp state which can be ON, OFF, CLOSE +//[ESP180] json= pwd= +void ESP3DCommands::ESP180(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + bool closeClients = hasTag(msg, cmd_params_pos, "CLOSE"); + bool stateON = hasTag(msg, cmd_params_pos, "ON"); + bool stateOFF = hasTag(msg, cmd_params_pos, "OFF"); + bool has_param = false; + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + ESP3DState setting_mode = (ESP3DState)ESP3DSettings::readByte(ESP_FTP_ON); + if (tmpstr.length() == 0) { + if (setting_mode == ESP3DState::off) { + ok_msg = "OFF"; + } else { + ok_msg = "ON"; + } + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + if (stateON || stateOFF) { + if (!ESP3DSettings::writeByte(ESP_FTP_ON, stateOFF ? 0 : 1)) { + hasError = true; + error_msg = "Set value failed"; + } + has_param = true; + } + if (closeClients) { + has_param = true; + ftp_server.closeClient(); + } + if (!has_param) { + hasError = true; + error_msg = "Invalid parameter"; + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // FTP_FEATURE diff --git a/esp3d/src/core/commands/ESP181.cpp b/esp3d/src/core/commands/ESP181.cpp new file mode 100644 index 00000000..f0c5aafd --- /dev/null +++ b/esp3d/src/core/commands/ESP181.cpp @@ -0,0 +1,151 @@ +/* + ESP181.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(FTP_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 181 +// Set/Get Ftp ports +//[ESP181]ctrl= active= passive= json= pwd= +void ESP3DCommands::ESP181(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + bool has_param = false; + String tmpstr; + uint32_t intValue = 0; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + if (json) { + ok_msg = "{\"ctrl\":\""; + } else { + ok_msg = "ctrl="; + } + intValue = ESP3DSettings::readUint32(ESP_FTP_CTRL_PORT); + ok_msg += String(intValue); + if (json) { + ok_msg += "\",\"active\":\""; + } else { + ok_msg += ", active="; + } + intValue = ESP3DSettings::readUint32(ESP_FTP_DATA_ACTIVE_PORT); + ok_msg += String(intValue); + if (json) { + ok_msg += "\",\"passive\":\""; + } else { + ok_msg += ", passive="; + } + intValue = ESP3DSettings::readUint32(ESP_FTP_DATA_PASSIVE_PORT); + ok_msg += String(intValue); + if (json) { + ok_msg += "\"}"; + } + + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_param(msg, cmd_params_pos, "ctrl="); + if (tmpstr.length() > 0) { + has_param = true; + intValue = atoi(tmpstr.c_str()); + if (ESP3DSettings::isValidIntegerSetting(intValue, ESP_FTP_CTRL_PORT)) { + esp3d_log("Value %ld is valid", intValue); + if (!ESP3DSettings::writeUint32(ESP_FTP_CTRL_PORT, intValue)) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid parameter ctrl"; + } + } + + if (!hasError) { + tmpstr = get_param(msg, cmd_params_pos, "active="); + if (tmpstr.length() > 0) { + has_param = true; + intValue = atoi(tmpstr.c_str()); + if (ESP3DSettings::isValidIntegerSetting(intValue, + ESP_FTP_DATA_ACTIVE_PORT)) { + esp3d_log("Value %ld is valid", intValue); + if (!ESP3DSettings::writeUint32(ESP_FTP_DATA_ACTIVE_PORT, intValue)) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid parameter active"; + } + } + } + + if (!hasError) { + tmpstr = get_param(msg, cmd_params_pos, "passive="); + if (tmpstr.length() > 0) { + has_param = true; + intValue = atoi(tmpstr.c_str()); + if (ESP3DSettings::isValidIntegerSetting(intValue, + ESP_FTP_DATA_PASSIVE_PORT)) { + esp3d_log("Value %ld is valid", intValue); + if (!ESP3DSettings::writeUint32(ESP_FTP_DATA_PASSIVE_PORT, + intValue)) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid parameter passive"; + } + } + } + if (!hasError && !has_param) { + hasError = true; + error_msg = "Invalid parameter"; + esp3d_log_e("%s", error_msg.c_str()); + } + } + + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // TELNET_FEATURE diff --git a/esp3d/src/core/commands/ESP190.cpp b/esp3d/src/core/commands/ESP190.cpp new file mode 100644 index 00000000..0058edee --- /dev/null +++ b/esp3d/src/core/commands/ESP190.cpp @@ -0,0 +1,89 @@ +/* + ESP190.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(WEBDAV_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/webdav/webdav_server.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 190 +// Set WebDav state which can be ON, OFF, CLOSE +//[ESP190] json= pwd= +void ESP3DCommands::ESP190(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + bool closeClients = hasTag(msg, cmd_params_pos, "CLOSE"); + bool stateON = hasTag(msg, cmd_params_pos, "ON"); + bool stateOFF = hasTag(msg, cmd_params_pos, "OFF"); + bool has_param = false; + String tmpstr; +#ifdef AUTHENTICATION_FEATURE + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + ESP3DState setting_mode = (ESP3DState)ESP3DSettings::readByte(ESP_WEBDAV_ON); + if (tmpstr.length() == 0) { + if (setting_mode == ESP3DState::off) { + ok_msg = "OFF"; + } else { + ok_msg = "ON"; + } + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + if (stateON || stateOFF) { + if (!ESP3DSettings::writeByte(ESP_WEBDAV_ON, stateOFF ? 0 : 1)) { + hasError = true; + error_msg = "Set value failed"; + } + has_param = true; + } + if (closeClients) { + has_param = true; + webdav_server.closeClient(); + } + if (!has_param) { + hasError = true; + error_msg = "Invalid parameter"; + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // WEBDAV_FEATURE diff --git a/esp3d/src/core/commands/ESP191.cpp b/esp3d/src/core/commands/ESP191.cpp new file mode 100644 index 00000000..46eb4897 --- /dev/null +++ b/esp3d/src/core/commands/ESP191.cpp @@ -0,0 +1,81 @@ +/* + ESP191.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(WEBDAV_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 191 +// Set webdav port +//[ESP191] json= pwd= +void ESP3DCommands::ESP191(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; + uint32_t intValue = 0; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + intValue = ESP3DSettings::readUint32(ESP_WEBDAV_PORT); + ok_msg = String(intValue); + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + intValue = atoi(tmpstr.c_str()); + esp3d_log("got %s param for a value of %ld, is valid %d", tmpstr.c_str(), + intValue, + ESP3DSettings::isValidIntegerSetting(intValue, ESP_WEBDAV_PORT)); + if (ESP3DSettings::isValidIntegerSetting(intValue, ESP_WEBDAV_PORT)) { + esp3d_log("Value %ld is valid", intValue); + if (!ESP3DSettings::writeUint32(ESP_WEBDAV_PORT, intValue)) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid parameter"; + } + } + + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // WEBDAV_FEATURE diff --git a/esp3d/src/core/commands/ESP200.cpp b/esp3d/src/core/commands/ESP200.cpp new file mode 100644 index 00000000..0312ca59 --- /dev/null +++ b/esp3d/src/core/commands/ESP200.cpp @@ -0,0 +1,78 @@ +/* + ESP200.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(SD_DEVICE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/filesystem/esp_sd.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 200 +// Get SD Card Status +//[ESP200] json= pwd= +void ESP3DCommands::ESP200(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool releasesd = hasTag(msg, cmd_params_pos, "RELEASESD"); + bool refreshsd = hasTag(msg, cmd_params_pos, "REFRESH"); + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + if (releasesd) { + ESP_SD::releaseFS(); + ok_msg = "SD card released"; + } + + if (!ESP_SD::accessFS()) { + if (ESP_SD::getState() == ESP_SDCARD_BUSY) { + ok_msg = "Busy"; + } else { + ok_msg = "Not available"; + } + } else { + int8_t state = ESP_SD::getState(true); + if (state == ESP_SDCARD_IDLE) { + ok_msg = "SD card ok"; + if (refreshsd) { + ESP_SD::refreshStats(true); + } + } + ESP_SD::releaseFS(); + } + + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // SD_DEVICE diff --git a/esp3d/src/core/commands/ESP201.cpp b/esp3d/src/core/commands/ESP201.cpp new file mode 100644 index 00000000..c0999157 --- /dev/null +++ b/esp3d/src/core/commands/ESP201.cpp @@ -0,0 +1,138 @@ +/* + ESP201.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(DIRECT_PIN_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../esp3d_commands.h" +#include "../esp3d_hal.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 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 +void ESP3DCommands::ESP201(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + String P = get_param(msg, cmd_params_pos, "P="); + String V = get_param(msg, cmd_params_pos, "V="); + bool isPULLUP = hasTag(msg, cmd_params_pos, "PULLUP"); + bool isRAW = hasTag(msg, cmd_params_pos, "RAW"); + bool isANALOG = hasTag(msg, cmd_params_pos, "ANALOG"); + int analog_range = 255; + String ANALOG_RANGE = get_param(msg, cmd_params_pos, "ANALOG_RANGE="); + if (ANALOG_RANGE.length() > 0) { + analog_range = ANALOG_RANGE.toInt(); + } + bool found = false; + get_param(msg, cmd_params_pos, "PULLUP=", &found); + if (!found && !isPULLUP) { + esp3d_log("Missing PULLUP parameter"); + isPULLUP = true; // default value + } + found = false; + int value = 0; + get_param(msg, cmd_params_pos, "RAW=", &found); + if (!found && !isRAW) { + esp3d_log("Missing RAW parameter"); + isRAW = true; // default value + } + found = false; + get_param(msg, cmd_params_pos, "ANALOG=", &found); + if (!found && !isANALOG) { + esp3d_log("Missing ANALOG parameter"); + isANALOG = false; // default value + } + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + if (P.length() == 0) { + hasError = true; + error_msg = "Missing pin"; + esp3d_log_e("%s", error_msg.c_str()); + } else { + int pin = P.toInt(); + esp3d_log("P=%d V=%s RAW=%d PULLUP=%d ANALOG=%d RANGE=%d", pin, V.c_str(), + isRAW, isPULLUP, isANALOG, analog_range); + if (!ESP3DHal::is_pin_usable(pin)) { + hasError = true; + error_msg = "Invalid pin"; + esp3d_log_e("%s", error_msg.c_str()); + } else { + if (V.length() > 0) { // Set + value = V.toInt(); + ESP3DHal::pinMode(pin, OUTPUT); + if (isANALOG) { + if ((value >= 0) || (value <= analog_range + 1)) { + ESP3DHal::analogRange(analog_range); + ESP3DHal::analogWriteFreq(1000); + analogWrite(pin, value); + } else { + hasError = true; + error_msg = "Invalid value"; + esp3d_log_e("%s", error_msg.c_str()); + } + } else { + if ((value == 0) || (value == 1)) { + digitalWrite(pin, (value == 0) ? LOW : HIGH); + } else { + hasError = true; + error_msg = "Invalid value"; + esp3d_log_e("%s", error_msg.c_str()); + } + } + } else { // Get + if (isANALOG) { + value = ESP3DHal::analogRead(pin); + } else { + if (!isRAW) { + if (isPULLUP) { + ESP3DHal::pinMode(pin, INPUT_PULLUP); + } else { + ESP3DHal::pinMode(pin, INPUT); + } + } + value = digitalRead(pin); + ok_msg = String(value); + } + } + } + } + + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // DIRECT_PIN_FEATURE diff --git a/esp3d/src/core/commands/ESP202.cpp b/esp3d/src/core/commands/ESP202.cpp new file mode 100644 index 00000000..73dbc99d --- /dev/null +++ b/esp3d/src/core/commands/ESP202.cpp @@ -0,0 +1,85 @@ +/* + ESP202.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(SD_DEVICE) && SD_DEVICE != ESP_SDIO +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/filesystem/esp_sd.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 202 +// Get/Set SD card Speed factor 1 2 4 6 8 16 32 +//[ESP202]SPEED= json= pwd= +void ESP3DCommands::ESP202(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + String speed = get_param(msg, cmd_params_pos, "SPEED="); + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + + if (speed.length() == 0) { // Get + esp3d_log("Reading SD speed divider"); + uint8_t s = ESP3DSettings::readByte(ESP_SD_SPEED_DIV); + esp3d_log("SD speed divider is %d", s); + ok_msg = String(s); + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + // Set + esp3d_log("Setting SD speed divider"); + uint8_t s = speed.toInt(); + if (ESP3DSettings::isValidByteSetting(s, ESP_SD_SPEED_DIV)) { + if (!ESP3DSettings::writeByte(ESP_SD_SPEED_DIV, s)) { + hasError = true; + error_msg = "Set failed"; + esp3d_log_e("Error setting SD speed divider"); + } else { + ESP_SD::setSPISpeedDivider(s); + } + } else { + hasError = true; + error_msg = "Invalid parameter"; + } + } + + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // SD_DEVICE diff --git a/esp3d/src/core/commands/ESP210.cpp b/esp3d/src/core/commands/ESP210.cpp new file mode 100644 index 00000000..c25d8fcc --- /dev/null +++ b/esp3d/src/core/commands/ESP210.cpp @@ -0,0 +1,134 @@ +/* + ESP210.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(SENSOR_DEVICE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/sensor/sensor.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 210 +// Get Sensor Value / type/Set Sensor type +//[ESP210] json= pwd= +void ESP3DCommands::ESP210(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + String stype = get_param(msg, cmd_params_pos, "type="); + String sint = get_param(msg, cmd_params_pos, "interval="); + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + if (stype.length() == 0 && sint.length() == 0) { // Get + 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 += "}"; + } + ok_msg = s; + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + // Set + if (stype.length() != 0) { + stype.toUpperCase(); + int8_t v = -1; + if (stype == "NONE") { + v = 0; + } else if (esp3d_sensor.isModelValid( + esp3d_sensor.getIDFromString(stype.c_str()))) { + v = esp3d_sensor.getIDFromString(stype.c_str()); + } else { + hasError = true; + error_msg = "Invalid parameter"; + esp3d_log_e("%s", error_msg.c_str()); + } + if (v != -1) { + if (!ESP3DSettings::writeByte(ESP_SENSOR_TYPE, v)) { + hasError = true; + error_msg = "Set failed"; + esp3d_log_e("%s", error_msg.c_str()); + } + if (!esp3d_sensor.begin()) { + hasError = true; + error_msg = "Starting failed"; + esp3d_log_e("%s", error_msg.c_str()); + } + } else { + hasError = true; + error_msg = "Invalid type"; + esp3d_log_e("%s", error_msg.c_str()); + } + } + if (!hasError && sint.length() != 0 && + ESP3DSettings::isValidIntegerSetting(sint.toInt(), + ESP_SENSOR_INTERVAL)) { + if (!ESP3DSettings::writeUint32(ESP_SENSOR_INTERVAL, sint.toInt())) { + hasError = true; + error_msg = "Set failed"; + esp3d_log_e("%s", error_msg.c_str()); + } else { + esp3d_sensor.setInterval(sint.toInt()); + } + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} +#endif // SENSOR_DEVICE diff --git a/esp3d/src/core/espcmd/ESP214.cpp b/esp3d/src/core/commands/ESP214.cpp similarity index 50% rename from esp3d/src/core/espcmd/ESP214.cpp rename to esp3d/src/core/commands/ESP214.cpp index f12cb6df..dca8338c 100644 --- a/esp3d/src/core/espcmd/ESP214.cpp +++ b/esp3d/src/core/commands/ESP214.cpp @@ -21,46 +21,36 @@ #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 "../esp3d_commands.h" +#include "../esp3d_settings.h" -#define COMMANDID 214 +#define COMMAND_ID 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 -#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; +void ESP3DCommands::ESP214(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; } -#else - (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"); + tmpstr = get_clean_param(msg, cmd_params_pos); + esp3d_display.setStatus(tmpstr.c_str()); + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); } - 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 // DISPLAY_DEVICE diff --git a/esp3d/src/core/commands/ESP215.cpp b/esp3d/src/core/commands/ESP215.cpp new file mode 100644 index 00000000..8a12caf8 --- /dev/null +++ b/esp3d/src/core/commands/ESP215.cpp @@ -0,0 +1,78 @@ +/* + ESP215.cpp - ESP3D command 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 +*/ +#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 "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 215 +// Touch Calibration +//[ESP215] json= [pwd=] +void ESP3DCommands::ESP215(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + bool calibrate = hasTag(msg, cmd_params_pos, "CALIBRATE"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + const ESP3DSettingDescription* settingPtr = + ESP3DSettings::getSettingPtr(ESP_CALIBRATION); + if (settingPtr) { + ok_msg = + ESP3DSettings::readByte(ESP_CALIBRATION) == 1 ? "Done" : "Not done"; + } else { + hasError = true; + error_msg = "This setting is unknown"; + esp3d_log_e("%s", error_msg.c_str()); + } + } else { + tmpstr.toUpperCase(); + if (!calibrate) { + hasError = true; + error_msg = "Missing parameter"; + esp3d_log_e("%s", error_msg.c_str()); + } else { + ok_msg = "ok - Please follow screen instructions"; + esp3d_display.startCalibration(); + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // DISPLAY_DEVICE && DISPLAY_TOUCH_DRIVER diff --git a/esp3d/src/core/commands/ESP220.cpp b/esp3d/src/core/commands/ESP220.cpp new file mode 100644 index 00000000..62282294 --- /dev/null +++ b/esp3d/src/core/commands/ESP220.cpp @@ -0,0 +1,194 @@ +/* + ESP220.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#include "../../modules/authentication/authentication_service.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 220 + +// Get ESP pins definition +// output is JSON or plain text according parameter +//[ESP220]json= +void ESP3DCommands::ESP220(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + String tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() != 0) { + hasError = true; + error_msg = "This command doesn't take parameters"; + esp3d_log_e("%s", error_msg.c_str()); + } else { + ok_msg = ""; + if (json) { + ok_msg = "{\"cmd\":\"220\",\"status\":\"ok\",\"data\":["; + } else { + ok_msg = "Pins:\n"; + } + msg->type = ESP3DMessageType::head; + if (!dispatch(msg, ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + return; + } + bool isFirst = true; + bool hasPin = false; +#if defined(SD_DEVICE) && SD_DEVICE != ESP_SDIO + + // SD CS + tmpstr = String(ESP_SD_CS_PIN == -1 ? SS : ESP_SD_CS_PIN); + if (!dispatchIdValue(json, " SD CS", tmpstr.c_str(), target, requestId, + isFirst)) { + return; + } + isFirst = false; + hasPin = true; + // SD MOSI + tmpstr = String(ESP_SD_MOSI_PIN == -1 ? MOSI : ESP_SD_MOSI_PIN); + if (!dispatchIdValue(json, " SD MOSI", tmpstr.c_str(), target, requestId, + isFirst)) { + return; + } + + // SD MISO + tmpstr = String(ESP_SD_MISO_PIN == -1 ? MISO : ESP_SD_MISO_PIN); + if (!dispatchIdValue(json, " SD MISO", tmpstr.c_str(), target, requestId, + isFirst)) { + return; + } + + // SD SCK + tmpstr = String(ESP_SD_SCK_PIN == -1 ? SCK : ESP_SD_SCK_PIN); + if (!dispatchIdValue(json, " SD SCK", tmpstr.c_str(), target, requestId, + isFirst)) { + return; + } + + // SD DETECT + tmpstr = String(ESP_SD_DETECT_PIN); + if (!dispatchIdValue(json, " SD DETECT", tmpstr.c_str(), target, requestId, + isFirst)) { + return; + } +#if ESP_SD_DETECT_PIN != -1 + // SD DETECT STATE + tmpstr = String(ESP_SD_DETECT_VALUE); + if (!dispatchIdValue(json, " SD DETECT STATE", tmpstr.c_str(), target, + requestId, isFirst)) { + return; + } +#endif // ESP_SD_DETECT_PIN !=-1 +#endif // defined(SD_DEVICE) && SD_DEVICE != ESP_SDIO +#if SD_DEVICE_CONNECTION == ESP_SHARED_SD && defined(ESP_FLAG_SHARED_SD_PIN) + // SD SWITCH + tmpstr = String(ESP_FLAG_SHARED_SD_PIN); + if (!dispatchIdValue(json, " SD SWITCH", tmpstr.c_str(), target, requestId, + isFirst)) { + return; + } + hasPin = true; +#endif // SD_DEVICE_CONNECTION == ESP_SHARED_SD +#ifdef BUZZER_DEVICE + // BUZZER + tmpstr = String(ESP3D_BUZZER_PIN); + if (!dispatchIdValue(json, " BUZZER", tmpstr.c_str(), target, requestId, + isFirst)) { + return; + } + hasPin = true; +#endif // BUZZER_DEVICE +#if defined(PIN_RESET_FEATURE) && defined(ESP3D_RESET_PIN) && \ + ESP3D_RESET_PIN != -1 + // RESET + tmpstr = String(ESP3D_RESET_PIN); + if (!dispatchIdValue(json, " RESET", tmpstr.c_str(), target, requestId, + isFirst)) { + return; + } + hasPin = true; +#endif // PIN_RESET_FEATURE +#ifdef SENSOR_DEVICE + // SENSOR + tmpstr = String(ESP3D_SENSOR_PIN); + if (!dispatchIdValue(json, " SENSOR", tmpstr.c_str(), target, requestId, + isFirst)) { + return; + } + hasPin = true; +#endif // SENSOR_DEVICE +#ifdef DISPLAY_DEVICE +#if (DISPLAY_DEVICE == OLED_I2C_SSD1306) || \ + (DISPLAY_DEVICE == OLED_I2C_SSDSH1106) + // SDA + tmpstr = String(ESP_SDA_PIN); + if (!dispatchIdValue(json, " SDA", tmpstr.c_str(), target, requestId, + isFirst)) { + return; + } + // SCL + tmpstr = String(ESP_SCL_PIN); + if (!dispatchIdValue(json, " SCL", tmpstr.c_str(), target, requestId, + isFirst)) { + return; + } + hasPin = true; +#endif //(DISPLAY_DEVICE == OLED_I2C_SSD1306) || (DISPLAY_DEVICE == + // OLED_I2C_SSDSH1106) +#endif // DISPLAY_DEVICE + if (!hasPin) { + tmpstr = "NO PIN"; + if (!dispatchIdValue(json, " PIN", tmpstr.c_str(), target, requestId, + isFirst)) { + return; + } + } + if (json) { + if (!dispatch("]}", target, requestId, ESP3DMessageType::tail)) { + esp3d_log_e("Error sending answer to clients"); + } + } else { + { + tmpstr = "ok\n"; + if (!dispatch(tmpstr.c_str(), target, requestId, + ESP3DMessageType::tail)) { + esp3d_log_e("Error sending answer to clients"); + } + } + } + return; + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} diff --git a/esp3d/src/core/commands/ESP250.cpp b/esp3d/src/core/commands/ESP250.cpp new file mode 100644 index 00000000..e17a8ea1 --- /dev/null +++ b/esp3d/src/core/commands/ESP250.cpp @@ -0,0 +1,75 @@ +/* + ESP250.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(BUZZER_DEVICE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/buzzer/buzzer.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 250 +// Play sound +//[ESP250]F= D= json= [pwd=] +void ESP3DCommands::ESP250(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + String F = get_param(msg, cmd_params_pos, "F="); + String D = get_param(msg, cmd_params_pos, "D="); + int freq = -1; + int duration = 0; + if (F.length() > 0) { + freq = F.toInt(); + } + if (D.length() > 0) { + duration = D.toInt(); + } + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + + if (freq == -1 && duration == 0) { + esp3d_buzzer.beep(); + } else { + if (freq == -1) { + freq = 1000; + } + if (duration != 0) { + esp3d_buzzer.beep(freq, duration); + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // BUZZER_DEVICE diff --git a/esp3d/src/core/commands/ESP290.cpp b/esp3d/src/core/commands/ESP290.cpp new file mode 100644 index 00000000..f26e0f4a --- /dev/null +++ b/esp3d/src/core/commands/ESP290.cpp @@ -0,0 +1,57 @@ +/* + ESP290.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#include "../../modules/authentication/authentication_service.h" +#include "../esp3d_commands.h" + +// Delay command +//[ESP290] json= [pwd=] +#define COMMAND_ID 290 +void ESP3DCommands::ESP290(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + hasError = true; + error_msg = "Missing parameter"; + esp3d_log_e("%s", error_msg.c_str()); + } else { + ESP3DHal::wait(tmpstr.toInt()); + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} diff --git a/esp3d/src/core/commands/ESP400.cpp b/esp3d/src/core/commands/ESP400.cpp new file mode 100644 index 00000000..b34b5761 --- /dev/null +++ b/esp3d/src/core/commands/ESP400.cpp @@ -0,0 +1,489 @@ +/* + ESP400.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" +#if COMMUNICATION_PROTOCOL != SOCKET_SERIAL +#include "../../modules/serial/serial_service.h" +#endif // COMMUNICATION_PROTOCOL != SOCKET_SERIAL +#include "../../modules/authentication/authentication_service.h" +#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 COMMAND_ID 400 + +const char* YesNoLabels[] = {"no", "yes"}; +const char* YesNoValues[] = {"0", "1"}; +const char* RadioModeLabels[] = {"none" +#ifdef WIFI_FEATURE + , + "sta", + "ap", + "setup" +#endif // WIFI_FEATURE +#ifdef BLUETOOTH_FEATURE + , + "bt" +#endif // BLUETOOTH_FEATURE +#ifdef ETH_FEATURE + , + "eth-sta" +#endif // ETH_FEATURE +}; +const char* RadioModeValues[] = {"0" +#ifdef WIFI_FEATURE + , + "1", + "2", + "5" +#endif // WIFI_FEATURE + +#ifdef BLUETOOTH_FEATURE + , + "3" + +#endif // BLUETOOTH_FEATURE + +#ifdef ETH_FEATURE + , + "4" +#endif // ETH_FEATURE +}; + +const char* FallbackLabels[] = {"none" +#ifdef WIFI_FEATURE + , + "setup" +#endif // WIFI_FEATURE +#ifdef BLUETOOTH_FEATURE + , + "bt" +#endif // BLUETOOTH_FEATURE +}; +const char* FallbackValues[] = {"0" +#ifdef WIFI_FEATURE + , + "5" +#endif // WIFI_FEATURE +#ifdef BLUETOOTH_FEATURE + , + "3" +#endif // BLUETOOTH_FEATURE +}; + +const char* FirmwareLabels[] = {"Unknown", "Grbl", "Marlin", "Smoothieware", + "Repetier"}; + +const char* FirmwareValues[] = {"0", "10", "20", "40", "50"}; +#ifdef NOTIFICATION_FEATURE +const char* NotificationsLabels[] = {"none", "pushover", "email", + "line", "telegram", "ifttt", "home-assistant"}; + +const char* NotificationsValues[] = {"0", "1", "2", "3", "4", "5", "6"}; +#endif // NOTIFICATION_FEATURE + +const char* IpModeLabels[] = {"static", "dhcp"}; +const char* IpModeValues[] = {"0", "1"}; + +const char* SupportedApChannelsStr[] = {"1", "2", "3", "4", "5", "6", "7", + "8", "9", "10", "11", "12", "13", "14"}; + +const char* SupportedBaudListSizeStr[] = { + "9600", "19200", "38400", "57600", "74880", "115200", + "230400", "250000", "500000", "921600", "1958400"}; + +#ifdef SENSOR_DEVICE + +const char* SensorLabels[] = {"none" +#if SENSOR_DEVICE == DHT11_DEVICE || SENSOR_DEVICE == DHT22_DEVICE + , + "DHT11", + "DHT22" + +#endif // SENSOR_DEVICE == DHT11_DEVICE || SENSOR_DEVICE == DHT22_DEVICE +#if SENSOR_DEVICE == ANALOG_DEVICE + , + "Analog" +#endif // SENSOR_DEVICE == ANALOG_DEVICE +#if SENSOR_DEVICE == BMP280_DEVICE || SENSOR_DEVICE == BME280_DEVICE + , + "BMP280", + "BME280" +#endif // SENSOR_DEVICE == BMP280_DEVICE || SENSOR_DEVICE == BME280_DEVICE +}; +const char* SensorValues[] = {"0" +#if SENSOR_DEVICE == DHT11_DEVICE || SENSOR_DEVICE == DHT22_DEVICE + , + "1", + "2" +#endif // SENSOR_DEVICE == DHT11_DEVICE || SENSOR_DEVICE == DHT22_DEVICE + +#if SENSOR_DEVICE == ANALOG_DEVICE + , + "3" +#endif // SENSOR_DEVICE == ANALOG_DEVICE +#if SENSOR_DEVICE == BMP280_DEVICE || SENSOR_DEVICE == BME280_DEVICE + , + "4", + "5" +#endif // SENSOR_DEVICE == BMP280_DEVICE || SENSOR_DEVICE == BME280_DEVICE + +}; + +#endif // SENSOR_DEVICE + +#ifdef SD_DEVICE +#if SD_DEVICE != ESP_SDIO +const char* SupportedSPIDividerStr[] = {"1", "2", "4", "6", "8", "16", "32"}; +const uint8_t SupportedSPIDividerStrSize = + sizeof(SupportedSPIDividerStr) / sizeof(char*); +#endif // SD_DEVICE != ESP_SDIO +#endif // SD_DEVICE + +// Get full ESP3D settings +//[ESP400] +void ESP3DCommands::ESP400(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + if (json) { + tmpstr = "{\"cmd\":\"400\",\"status\":\"ok\",\"data\":["; + + } else { + tmpstr = "Settings:\n"; + } + msg->type = ESP3DMessageType::head; + if (!dispatch(msg, tmpstr.c_str())) { + esp3d_log_e("Error sending response to clients"); + return; + } + +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BT_FEATURE) + // Hostname network/network + dispatchSetting(json, "network/network", ESP_HOSTNAME, "hostname", NULL, NULL, + 32, 1, 1, -1, NULL, true, target, requestId, true); +#endif // WIFI_FEATURE || ETH_FEATURE || BT_FEATURE + + // radio mode network/network + dispatchSetting(json, "network/network", ESP_RADIO_MODE, "radio mode", + RadioModeValues, RadioModeLabels, + sizeof(RadioModeValues) / sizeof(char*), -1, -1, -1, NULL, + true, target, requestId); + + // Radio State at Boot + dispatchSetting(json, "network/network", ESP_BOOT_RADIO_STATE, "radio_boot", + YesNoValues, YesNoLabels, sizeof(YesNoValues) / sizeof(char*), + -1, -1, -1, NULL, true, target, requestId); +#ifdef WIFI_FEATURE + // STA SSID network/sta + dispatchSetting(json, "network/sta", ESP_STA_SSID, "SSID", nullptr, nullptr, + 32, 1, 1, -1, nullptr, true, target, requestId); + + // STA Password network/sta + dispatchSetting(json, "network/sta", ESP_STA_PASSWORD, "pwd", nullptr, + nullptr, 64, 8, 0, -1, nullptr, true, target, requestId); + +#endif // WIFI_FEATURE +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) + // STA IP mode + dispatchSetting(json, "network/sta", ESP_STA_IP_MODE, "ip mode", IpModeValues, + IpModeLabels, sizeof(IpModeLabels) / sizeof(char*), -1, -1, + -1, nullptr, true, target, requestId); + // STA static IP + dispatchSetting(json, "network/sta", ESP_STA_IP_VALUE, "ip", nullptr, nullptr, + -1, -1, -1, -1, nullptr, true, target, requestId); + + // STA static Gateway + dispatchSetting(json, "network/sta", ESP_STA_GATEWAY_VALUE, "gw", nullptr, + nullptr, -1, -1, -1, -1, nullptr, true, target, requestId); + // STA static Mask + dispatchSetting(json, "network/sta", ESP_STA_MASK_VALUE, "msk", nullptr, + nullptr, -1, -1, -1, -1, nullptr, true, target, requestId); + // STA static DNS + dispatchSetting(json, "network/sta", ESP_STA_DNS_VALUE, "DNS", nullptr, + nullptr, -1, -1, -1, -1, nullptr, true, target, requestId); + +#endif // WIFI_FEATURE || ETH_FEATURE + +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BT_FEATURE) + // Sta fallback mode + dispatchSetting(json, "network/sta", ESP_STA_FALLBACK_MODE, + "sta fallback mode", FallbackValues, FallbackLabels, + sizeof(FallbackValues) / sizeof(char*), -1, -1, -1, nullptr, + true, target, requestId); +#endif // WIFI_FEATURE || ETH_FEATURE || BT_FEATURE +#if defined(WIFI_FEATURE) + // AP SSID network/ap + dispatchSetting(json, "network/ap", ESP_AP_SSID, "SSID", nullptr, nullptr, 32, + 1, 1, -1, nullptr, true, target, requestId); + + // AP password + dispatchSetting(json, "network/ap", ESP_AP_PASSWORD, "pwd", nullptr, nullptr, + 64, 8, 0, -1, nullptr, true, target, requestId); + // AP static IP + dispatchSetting(json, "network/ap", ESP_AP_IP_VALUE, "ip", nullptr, nullptr, + -1, -1, -1, -1, nullptr, true, target, requestId); + + // AP Channel + dispatchSetting(json, "network/ap", ESP_AP_CHANNEL, "channel", + SupportedApChannelsStr, SupportedApChannelsStr, + sizeof(SupportedApChannelsStr) / sizeof(char*), -1, -1, -1, + nullptr, true, target, requestId); +#endif // WIFI_FEATURE + +#ifdef AUTHENTICATION_FEATURE + // Admin password + dispatchSetting(json, "security/security", ESP_ADMIN_PWD, "adm pwd", nullptr, + nullptr, 20, 0, -1, -1, nullptr, true, target, requestId); + // User password + dispatchSetting(json, "security/security", ESP_USER_PWD, "user pwd", nullptr, + nullptr, 20, 0, -1, -1, nullptr, true, target, requestId); + + // session timeout + dispatchSetting(json, "security/security", ESP_SESSION_TIMEOUT, + "session timeout", nullptr, nullptr, 255, 0, -1, -1, nullptr, + true, target, requestId); + +#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL + // Secure Serial + dispatchSetting(json, "security/security", ESP_SECURE_SERIAL, "serial", + YesNoValues, YesNoLabels, sizeof(YesNoValues) / sizeof(char*), + -1, -1, -1, nullptr, true, target, requestId); + +#endif // COMMUNICATION_PROTOCOL +#endif // AUTHENTICATION_FEATURE +#ifdef HTTP_FEATURE + // HTTP On service/http + dispatchSetting(json, "service/http", ESP_HTTP_ON, "enable", YesNoValues, + YesNoLabels, sizeof(YesNoValues) / sizeof(char*), -1, -1, -1, + nullptr, true, target, requestId); + // HTTP port + dispatchSetting(json, "service/http", ESP_HTTP_PORT, "port", nullptr, nullptr, + 65535, 1, -1, -1, nullptr, true, target, requestId); +#endif // HTTP_FEATURE + +#ifdef TELNET_FEATURE + // TELNET On service/telnet + dispatchSetting(json, "service/telnetp", ESP_TELNET_ON, "enable", YesNoValues, + YesNoLabels, sizeof(YesNoValues) / sizeof(char*), -1, -1, -1, + nullptr, true, target, requestId); + + // TELNET Port + dispatchSetting(json, "service/telnetp", ESP_TELNET_PORT, "port", nullptr, + nullptr, 65535, 1, -1, -1, nullptr, true, target, requestId); +#endif // TELNET_FEATURE + +#ifdef WS_DATA_FEATURE + // Websocket On service + dispatchSetting(json, "service/websocketp", ESP_WEBSOCKET_ON, "enable", + YesNoValues, YesNoLabels, sizeof(YesNoValues) / sizeof(char*), + -1, -1, -1, nullptr, true, target, requestId); + + // Websocket Port + dispatchSetting(json, "service/websocketp", ESP_WEBSOCKET_PORT, "port", + nullptr, nullptr, 65535, 1, -1, -1, nullptr, true, target, + requestId); +#endif // WS_DATA_FEATURE + +#ifdef WEBDAV_FEATURE + // WebDav On service + dispatchSetting(json, "service/webdavp", ESP_WEBDAV_ON, "enable", YesNoValues, + YesNoLabels, sizeof(YesNoValues) / sizeof(char*), -1, -1, -1, + nullptr, true, target, requestId); + + // WebDav Port + dispatchSetting(json, "service/webdavp", ESP_WEBDAV_PORT, "port", nullptr, + nullptr, 65535, 1, -1, -1, nullptr, true, target, requestId); +#endif // WEBDAV_FEATURE + +#ifdef FTP_FEATURE + // FTP On service/ftp + dispatchSetting(json, "service/ftp", ESP_FTP_ON, "enable", YesNoValues, + YesNoLabels, sizeof(YesNoValues) / sizeof(char*), -1, -1, -1, + nullptr, true, target, requestId); + + // FTP Ports + // CTRL Port + dispatchSetting(json, "service/ftp", ESP_FTP_CTRL_PORT, "control port", + nullptr, nullptr, 65535, 1, -1, -1, nullptr, true, target, + requestId); + + // Active Port + dispatchSetting(json, "service/ftp", ESP_FTP_DATA_ACTIVE_PORT, "active port", + nullptr, nullptr, 65535, 1, -1, -1, nullptr, true, target, + requestId); + + // Passive Port + dispatchSetting(json, "service/ftp", ESP_FTP_DATA_PASSIVE_PORT, + "passive port", nullptr, nullptr, 65535, 1, -1, -1, nullptr, + true, target, requestId); +#endif // FTP_FEATURE + +#if defined(ESP_SERIAL_BRIDGE_OUTPUT) + // Serial bridge On service + dispatchSetting(json, "service/serial_bridge", ESP_SERIAL_BRIDGE_ON, "enable", + YesNoValues, YesNoLabels, sizeof(YesNoValues) / sizeof(char*), + -1, -1, -1, nullptr, true, target, requestId); + + // Baud Rate + dispatchSetting(json, "service/serial_bridge", ESP_SERIAL_BRIDGE_BAUD, "baud", + SupportedBaudListSizeStr, SupportedBaudListSizeStr, + sizeof(SupportedBaudListSizeStr) / sizeof(char*), -1, -1, -1, + nullptr, true, target, requestId); +#endif // ESP_SERIAL_BRIDGE_OUTPUT + +#ifdef TIMESTAMP_FEATURE + + // Internet Time + dispatchSetting(json, "service/time", ESP_INTERNET_TIME, "i-time", + YesNoValues, YesNoLabels, sizeof(YesNoValues) / sizeof(char*), + -1, -1, -1, nullptr, true, target, requestId); + + // Time zone + dispatchSetting(json, "service/time", ESP_TIME_ZONE, "tzone", + SupportedTimeZones, SupportedTimeZones, + SupportedTimeZonesSize, -1, -1, -1, nullptr, true, target, + requestId); + + // Time Server1 + dispatchSetting(json, "service/time", ESP_TIME_SERVER1, "t-server", nullptr, + nullptr, 127, 0, -1, -1, nullptr, true, target, requestId); + + // Time Server2 + dispatchSetting(json, "service/time", ESP_TIME_SERVER2, "t-server", nullptr, + nullptr, 127, 0, -1, -1, nullptr, true, target, requestId); + + // Time Server3 + dispatchSetting(json, "service/time", ESP_TIME_SERVER3, "t-server", nullptr, + nullptr, 127, 0, -1, -1, nullptr, true, target, requestId); +#endif // TIMESTAMP_FEATURE + +#ifdef NOTIFICATION_FEATURE + // Auto notification + dispatchSetting(json, "service/notification", ESP_AUTO_NOTIFICATION, + "auto notif", YesNoValues, YesNoLabels, + sizeof(YesNoValues) / sizeof(char*), -1, -1, -1, nullptr, + true, target, requestId); + + // Notification type + dispatchSetting(json, "service/notification", ESP_NOTIFICATION_TYPE, + "notification", NotificationsValues, NotificationsLabels, + sizeof(NotificationsValues) / sizeof(char*), -1, -1, -1, + nullptr, true, target, requestId); + + // Token 1 + dispatchSetting(json, "service/notification", ESP_NOTIFICATION_TOKEN1, "t1", + nullptr, nullptr, 250, 0, -1, -1, nullptr, true, target, + requestId); + + // Token 2 + dispatchSetting(json, "service/notification", ESP_NOTIFICATION_TOKEN2, "t2", + nullptr, nullptr, 63, 0, -1, -1, nullptr, true, target, + requestId); + + // Notifications Settings + dispatchSetting(json, "service/notification", ESP_NOTIFICATION_SETTINGS, "ts", + nullptr, nullptr, 128, 0, -1, -1, nullptr, true, target, + requestId); +#endif // NOTIFICATION_FEATURE + +#ifdef BUZZER_DEVICE + // Buzzer state + dispatchSetting(json, "device/device", ESP_BUZZER, "buzzer", YesNoValues, + YesNoLabels, sizeof(YesNoValues) / sizeof(char*), -1, -1, -1, + nullptr, true, target, requestId); +#endif // BUZZER_DEVICE + +#ifdef SENSOR_DEVICE + // Sensor type + dispatchSetting(json, "device/sensor", ESP_SENSOR_TYPE, "type", SensorValues, + SensorLabels, sizeof(SensorValues) / sizeof(char*), -1, -1, + -1, nullptr, true, target, requestId); + + // Sensor interval + dispatchSetting(json, "device/sensor", ESP_SENSOR_INTERVAL, "intervalms", + nullptr, nullptr, 60000, 0, -1, -1, nullptr, true, target, + requestId); + +#endif // SENSOR_DEVICE +#if defined(SD_DEVICE) +#if SD_DEVICE != ESP_SDIO + // SPI SD Divider + dispatchSetting(json, "device/sd", ESP_SD_SPEED_DIV, "speedx", + SupportedSPIDividerStr, SupportedSPIDividerStr, + SupportedSPIDividerStrSize, -1, -1, -1, nullptr, true, target, + requestId); +#endif // SD_DEVICE != ESP_SDIO +#ifdef SD_UPDATE_FEATURE + // SD CHECK UPDATE AT BOOT feature + dispatchSetting(json, "device/sd", ESP_SD_CHECK_UPDATE_AT_BOOT, "SD updater", + YesNoValues, YesNoLabels, sizeof(YesNoValues) / sizeof(char*), + -1, -1, -1, nullptr, true, target, requestId); +#endif // SD_UPDATE_FEATURE +#endif // SD_DEVICE + +#if !defined(FIXED_FW_TARGET) + // Target FW + dispatchSetting(json, "system/system", ESP_TARGET_FW, "targetfw", + FirmwareValues, FirmwareLabels, + sizeof(FirmwareValues) / sizeof(char*), -1, -1, -1, nullptr, + true, target, requestId); +#endif // FIXED_FW_TARGET +#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL + // Baud Rate + dispatchSetting(json, "system/system", ESP_BAUD_RATE, "baud", + SupportedBaudListSizeStr, SupportedBaudListSizeStr, + sizeof(SupportedBaudListSizeStr) / sizeof(char*), -1, -1, -1, + nullptr, true, target, requestId); +#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == + // MKS_SERIAL + + // Start delay + dispatchSetting(json, "system/boot", ESP_BOOT_DELAY, "bootdelay", nullptr, + nullptr, 40000, 0, -1, -1, nullptr, true, target, requestId); + + // Verbose boot + dispatchSetting(json, "system/boot", ESP_VERBOSE_BOOT, "verbose", YesNoValues, + YesNoLabels, sizeof(YesNoValues) / sizeof(char*), -1, -1, -1, + nullptr, true, target, requestId); + + if (json) { + if (!dispatch("]}", target, requestId, ESP3DMessageType::tail)) { + esp3d_log_e("Error sending response to clients"); + } + } else { + if (!dispatch("ok\n", target, requestId, ESP3DMessageType::tail)) { + esp3d_log_e("Error sending response to clients"); + } + } +} diff --git a/esp3d/src/core/commands/ESP401.cpp b/esp3d/src/core/commands/ESP401.cpp new file mode 100644 index 00000000..5e305457 --- /dev/null +++ b/esp3d/src/core/commands/ESP401.cpp @@ -0,0 +1,255 @@ +/* + ESP401.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#include "../../modules/authentication/authentication_service.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 401 +#if COMMUNICATION_PROTOCOL != SOCKET_SERIAL || defined(ESP_SERIAL_BRIDGE_OUTPUT) +#include "../../modules/serial/serial_service.h" +#endif // COMMUNICATION_PROTOCOL != SOCKET_SERIAL +#ifdef SENSOR_DEVICE +#include "../../modules/sensor/sensor.h" +#endif // SENSOR_DEVICE +#ifdef BUZZER_DEVICE +#include "../../modules/buzzer/buzzer.h" +#endif // BUZZER_DEVICE +#ifdef TIMESTAMP_FEATURE +#include "../../modules/time/time_service.h" +#endif // TIMESTAMP_FEATURE +#ifdef NOTIFICATION_FEATURE +#include "../../modules/notifications/notifications_service.h" +#endif // NOTIFICATION_FEATURE +#ifdef SD_DEVICE +#include "../../modules/filesystem/esp_sd.h" +#endif // SD_DEVICE +// Set EEPROM setting +//[ESP401]P= T= V= json= pwd= +void ESP3DCommands::ESP401(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + String spos = get_param(msg, cmd_params_pos, "P="); + bool foundV = false; + String sval = get_param(msg, cmd_params_pos, "V=", &foundV); + String styp = get_param(msg, cmd_params_pos, "T="); + + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + + if (spos.length() == 0) { + error_msg = "Invalid parameter P"; + hasError = true; + } else if (styp.length() == 0) { + error_msg = "Invalid parameter T"; + hasError = true; + } else if (sval.length() == 0 && !foundV) { + error_msg = "Invalid parameter V"; + hasError = true; + } else { + if (!(styp == "B" || styp == "S" || styp == "A" || styp == "I")) { + error_msg = "Invalid value for T"; + hasError = true; + } + } + if (!hasError) { + switch (styp[0]) { + case 'B': // Byte value + if (ESP3DSettings::isValidByteSetting((uint8_t)sval.toInt(), + spos.toInt())) { + if (!ESP3DSettings::writeByte(spos.toInt(), (uint8_t)sval.toInt())) { + error_msg = "Set failed"; + hasError = true; + esp3d_log_e("Set failed"); + } + } else { + error_msg = "Invalid value for T"; + hasError = true; + esp3d_log_e("Invalid value for T"); + } + break; + case 'I': // Integer value + if (ESP3DSettings::isValidIntegerSetting(sval.toInt(), spos.toInt())) { + if (!ESP3DSettings::writeUint32(spos.toInt(), sval.toInt())) { + error_msg = "Set failed"; + hasError = true; + esp3d_log_e("Set failed"); + } + } else { + error_msg = "Invalid value for T"; + hasError = true; + esp3d_log_e("Invalid value for T"); + } + break; + case 'S': // String value + if (ESP3DSettings::isValidStringSetting(sval.c_str(), spos.toInt())) { + if (!ESP3DSettings::writeString(spos.toInt(), sval.c_str())) { + error_msg = "Set failed"; + hasError = true; + esp3d_log_e("Set failed"); + } + } else { + error_msg = "Invalid value for T"; + hasError = true; + esp3d_log_e("Invalid value for T"); + } + break; + case 'A': // IP address + if (ESP3DSettings::isValidIPStringSetting(sval.c_str(), spos.toInt())) { + if (!ESP3DSettings::writeIPString(spos.toInt(), sval.c_str())) { + error_msg = "Set failed"; + hasError = true; + } + } else { + error_msg = "Invalid value for T"; + hasError = true; + esp3d_log_e("Invalid value for T"); + } + break; + default: + error_msg = "Invalid value for T"; + hasError = true; + break; + } + + if (!hasError) { + switch (spos.toInt()) { +#if defined(ESP_SERIAL_BRIDGE_OUTPUT) + case ESP_SERIAL_BRIDGE_ON: + if (!serial_bridge_service.started()) { + serial_bridge_service.begin(ESP_SERIAL_BRIDGE_OUTPUT); + } + break; +#endif // ESP_SERIAL_BRIDGE_OUTPUT + case ESP_VERBOSE_BOOT: + ESP3DSettings::isVerboseBoot(true); + break; + case ESP_TARGET_FW: + ESP3DSettings::GetFirmwareTarget(true); + break; +#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL + case ESP_SECURE_SERIAL: + esp3d_serial_service.setParameters(); + break; +#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == + // MKS_SERIAL +#ifdef AUTHENTICATION_FEATURE + case ESP_SESSION_TIMEOUT: + AuthenticationService::setSessionTimeout(1000 * 60 * sval.toInt()); + break; +#endif // AUTHENTICATION_FEATURE +#ifdef SD_DEVICE + case ESP_SD_SPEED_DIV: + ESP_SD::setSPISpeedDivider(sval.toInt()); + break; +#endif // SD_DEVICE +#ifdef TIMESTAMP_FEATURE + case ESP_INTERNET_TIME: + timeService.begin(); + break; +#endif // TIMESTAMP_FEATURE +#ifdef NOTIFICATION_FEATURE + case ESP_AUTO_NOTIFICATION: + notificationsservice.setAutonotification((sval.toInt() == 0) ? false + : true); + break; +#endif // NOTIFICATION_FEATURE +#ifdef SENSOR_DEVICE + case ESP_SENSOR_TYPE: + esp3d_sensor.begin(); + break; +#endif // SENSOR_DEVICE +#ifdef BUZZER_DEVICE + case ESP_BUZZER: + if (sval.toInt() == 1) { + esp3d_buzzer.begin(); + } else if (sval.toInt() == 0) { + esp3d_buzzer.end(); + } + break; +#endif // BUZZER_DEVICE +#ifdef SENSOR_DEVICE + case ESP_SENSOR_INTERVAL: + esp3d_sensor.setInterval(sval.toInt()); + break; +#endif // SENSOR_DEVICE +#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL + case ESP_BAUD_RATE: + esp3d_serial_service.updateBaudRate(sval.toInt()); + break; +#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == + // MKS_SERIAL +#if defined(ESP_SERIAL_BRIDGE_OUTPUT) + case ESP_SERIAL_BRIDGE_BAUD: + serial_bridge_service.updateBaudRate(sval.toInt()); + break; +#endif // defined(ESP_SERIAL_BRIDGE_OUTPUT) +#ifdef AUTHENTICATION_FEATURE + case ESP_ADMIN_PWD: + case ESP_USER_PWD: + AuthenticationService::update(); + break; +#endif // AUTHENTICATION_FEATURE + default: + break; + } + } + } + + if (!hasError) { + if (json) { + ok_msg = spos; + } else { + ok_msg = "ok"; + } + } else { + if (json) { + String tmp = "{\"error\":\""; + tmp += error_msg; + tmp += "\""; + if (spos.length() > 0) { + tmp += ",\"position\":\""; + tmp += spos; + tmp += "\""; + } + tmp += "}"; + error_msg = tmp; + } else { + error_msg += spos.length() > 0 ? " for P=" + spos : ""; + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} diff --git a/esp3d/src/core/commands/ESP402.cpp b/esp3d/src/core/commands/ESP402.cpp new file mode 100644 index 00000000..957132f6 --- /dev/null +++ b/esp3d/src/core/commands/ESP402.cpp @@ -0,0 +1,80 @@ +/* + ESP402.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(SD_UPDATE_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +// Set SD Check at boot state which can be ON, OFF +//[ESP402] json= pwd= +#define COMMAND_ID 402 +void ESP3DCommands::ESP402(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + ESP3DState setting_http_mode = + (ESP3DState)ESP3DSettings::readByte(ESP_SD_CHECK_UPDATE_AT_BOOT); + if (tmpstr.length() == 0) { + if (setting_http_mode == ESP3DState::off) { + ok_msg = "OFF"; + } else { + ok_msg = "ON"; + } + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + if (tmpstr == "OFF" || tmpstr == "ON") { + if (!ESP3DSettings::writeByte(ESP_SD_CHECK_UPDATE_AT_BOOT, + tmpstr == "OFF" ? 0 : 1)) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid parameter"; + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // SD_UPDATE_FEATURE diff --git a/esp3d/src/core/commands/ESP410.cpp b/esp3d/src/core/commands/ESP410.cpp new file mode 100644 index 00000000..17d5a600 --- /dev/null +++ b/esp3d/src/core/commands/ESP410.cpp @@ -0,0 +1,158 @@ +/* + ESP410.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(WIFI_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/wifi/wificonfig.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" +#include "../esp3d_string.h" + +// Get available AP list (limited to 30) +// output is JSON or plain text according parameter +//[ESP410]json= +#define COMMAND_ID 410 +void ESP3DCommands::ESP410(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() != 0) { + hasError = true; + error_msg = "This command doesn't take parameters"; + esp3d_log_e("%s", error_msg.c_str()); + + } else { + if (WiFi.getMode() == WIFI_STA || WiFi.getMode() == WIFI_AP) { + uint8_t currentmode = WiFi.getMode(); + int n = 0; + uint8_t total = 0; + if (json) { + tmpstr = "{\"cmd\":\"410\",\"status\":\"ok\",\"data\":["; + + } else { + tmpstr = "Start Scan\n"; + } + msg->type = ESP3DMessageType::head; + if (!dispatch(msg, tmpstr.c_str())) { + esp3d_log_e("Error sending response to clients"); + return; + } + // Set Sta Mode if necessary + if (currentmode == WIFI_AP) { + WiFi.mode(WIFI_AP_STA); + } + // Scan + n = WiFi.scanNetworks(); + + for (int i = 0; i < n; ++i) { + tmpstr = ""; + if (WiFi.RSSI(i) >= MIN_RSSI) { + if (total > 0) { + if (json) { + tmpstr += ","; + } + } + total++; + if (json) { + tmpstr += "{\"SSID\":\""; + tmpstr += esp3d_string::encodeString(WiFi.SSID(i).c_str()); + } else { + tmpstr += WiFi.SSID(i).c_str(); + } + if (json) { + tmpstr += "\",\"SIGNAL\":\""; + } else { + tmpstr += "\t"; + } + tmpstr += String(WiFiConfig::getSignal(WiFi.RSSI(i))); + if (!json) { + tmpstr += "%"; + } + if (json) { + tmpstr += "\",\"IS_PROTECTED\":\""; + } + if (WiFi.encryptionType(i) == ENC_TYPE_NONE) { + if (json) { + tmpstr += "0"; + } else { + tmpstr += "\tOpen"; + } + } else { + if (json) { + tmpstr += "1"; + } else { + tmpstr += "\tSecure"; + } + } + if (json) { + tmpstr += "\"}"; + } else { + tmpstr += "\n"; + } + if (!dispatch(tmpstr.c_str(), target, requestId, + ESP3DMessageType::core)) { + esp3d_log_e("Error sending answer to clients"); + } + } + } + + // Restore mode + if (currentmode == WIFI_AP) { + WiFi.mode((WiFiMode_t)currentmode); + } + WiFi.scanDelete(); + if (json) { + tmpstr = "]}"; + } else { + tmpstr = "End Scan\n"; + } + if (!dispatch(tmpstr.c_str(), target, requestId, + ESP3DMessageType::tail)) { + esp3d_log_e("Error sending answer to clients"); + } + return; + } else { + hasError = true; + error_msg = "WiFi not enabled"; + esp3d_log_e("%s", error_msg.c_str()); + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // WIFI_FEATURE diff --git a/esp3d/src/core/commands/ESP420.cpp b/esp3d/src/core/commands/ESP420.cpp new file mode 100644 index 00000000..aa5f39b9 --- /dev/null +++ b/esp3d/src/core/commands/ESP420.cpp @@ -0,0 +1,735 @@ +/* + ESP420.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#include "../../modules/authentication/authentication_service.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" +#include "../esp3d_string.h" + +#if COMMUNICATION_PROTOCOL != SOCKET_SERIAL || defined(ESP_SERIAL_BRIDGE_OUTPUT) +#include "../../modules/serial/serial_service.h" +#endif // COMMUNICATION_PROTOCOL != SOCKET_SERIAL +#ifdef FILESYSTEM_FEATURE +#include "../../modules/filesystem/esp_filesystem.h" +#endif // FILESYSTEM_FEATURE +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BLUETOOTH_FEATURE) +#include "../../modules/network/netconfig.h" +#if defined(WIFI_FEATURE) +#include "../../modules/wifi/wificonfig.h" +#endif // WIFI_FEATURE +#if defined(ETH_FEATURE) +#include "../../modules/ethernet/ethconfig.h" +#endif // ETH_FEATURE +#if defined(BLUETOOTH_FEATURE) +#include "../../modules/bluetooth/BT_service.h" +#endif // BLUETOOTH_FEATURE +#endif // WIFI_FEATURE || ETH_FEATURE || BLUETOOTH_FEATURE +#ifdef HTTP_FEATURE +#include "../../modules/http/http_server.h" +#endif // HTTP_FEATURE +#ifdef TELNET_FEATURE +#include "../../modules/telnet/telnet_server.h" +#endif // TELNET_FEATURE +#ifdef FTP_FEATURE +#include "../../modules/ftp/FtpServer.h" +#endif // FTP_FEATURE +#ifdef WS_DATA_FEATURE +#include "../../modules/websocket/websocket_server.h" +#endif // WS_DATA_FEATURE +#ifdef WEBDAV_FEATURE +#include "../../modules/webdav/webdav_server.h" +#endif // WEBDAV_FEATURE +#if defined(TIMESTAMP_FEATURE) +#include "../../modules/time/time_service.h" +#endif // TIMESTAMP_FEATURE +#if defined(SENSOR_DEVICE) +#include "../../modules/sensor/sensor.h" +#endif // SENSOR_DEVICE +#ifdef NOTIFICATION_FEATURE +#include "../../modules/notifications/notifications_service.h" +#endif // NOTIFICATION_FEATURE +#ifdef BUZZER_DEVICE +#include "../../modules/buzzer/buzzer.h" +#endif // BUZZER_DEVICE +#ifdef CAMERA_DEVICE +#include "../../modules/camera/camera.h" +#endif // CAMERA_DEVICE +#ifdef SD_DEVICE +#include "../../modules/filesystem/esp_sd.h" +#endif // SD_DEVICE +#if defined(DISPLAY_DEVICE) +#include "../../modules/display/display.h" +#endif // DISPLAY_DEVICE +#define COMMAND_ID 420 +#if defined(AUTHENTICATION_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#endif // AUTHENTICATION_FEATURE + +// Get ESP current status +// output is JSON or plain text according parameter +//[ESP420]json= +void ESP3DCommands::ESP420(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool json = hasTag(msg, cmd_params_pos, "json"); + bool addPreTag = hasTag(msg, cmd_params_pos, "addPreTag"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + if (json) { + tmpstr = "{\"cmd\":\"420\",\"status\":\"ok\",\"data\":["; + + } else { + if (addPreTag) { + tmpstr = "
\n";
+    } else {
+      tmpstr = "Configuration:\n";
+    }
+  }
+  msg->type = ESP3DMessageType::head;
+  if (!dispatch(msg, tmpstr.c_str())) {
+    esp3d_log_e("Error sending response to clients");
+    return;
+  }
+  // First entry
+
+  // Chip ID
+  tmpstr = ESP3DHal::getChipID();
+  if (!dispatchIdValue(json, "chip id", tmpstr.c_str(), target, requestId,
+                       true)) {
+    return;
+  }
+
+  // CPU Freq
+  tmpstr = String(ESP.getCpuFreqMHz());
+  tmpstr += "Mhz";
+  if (!dispatchIdValue(json, "CPU Freq", tmpstr.c_str(), target, requestId,
+                       false)) {
+    return;
+  }
+
+  // CPU Temp
+  if (ESP3DHal::has_temperature_sensor()) {
+    tmpstr = String(ESP3DHal::temperature(), 1);
+    tmpstr += "C";
+    if (!dispatchIdValue(json, "CPU Temp", tmpstr.c_str(), target, requestId,
+                         false)) {
+      return;
+    }
+  }
+
+  // Free Memory
+  tmpstr = esp3d_string::formatBytes(ESP.getFreeHeap());
+
+#ifdef ARDUINO_ARCH_ESP32
+#ifdef BOARD_HAS_PSRAM
+  tmpstr += " - PSRAM:";
+  tmpstr += esp3d_string::formatBytes(ESP.getFreePsram());
+#endif  // BOARD_HAS_PSRAM
+#endif  // ARDUINO_ARCH_ESP32
+  if (!dispatchIdValue(json, "free mem", tmpstr.c_str(), target, requestId,
+                       false)) {
+    return;
+  }
+
+  // SDK Version
+  tmpstr = ESP.getSdkVersion();
+  if (!dispatchIdValue(json, "SDK", tmpstr.c_str(), target, requestId, false)) {
+    return;
+  }
+
+  // Flash size
+  tmpstr = esp3d_string::formatBytes(ESP.getFlashChipSize());
+  if (!dispatchIdValue(json, "flash size", tmpstr.c_str(), target, requestId,
+                       false)) {
+    return;
+  }
+
+#if (defined(WIFI_FEATURE) || defined(ETH_FEATURE)) && \
+    (defined(OTA_FEATURE) || defined(WEB_UPDATE_FEATURE))
+  // update space
+  tmpstr = esp3d_string::formatBytes(ESP_FileSystem::max_update_size());
+  if (!dispatchIdValue(json, "size for update", tmpstr.c_str(), target,
+                       requestId, false)) {
+    return;
+  }
+#endif  // WIFI_FEATURE || ETH_FEATURE
+
+#if defined(FILESYSTEM_FEATURE)
+  // FileSystem type
+  tmpstr = ESP_FileSystem::FilesystemName();
+  if (!dispatchIdValue(json, "FS type", tmpstr.c_str(), target, requestId,
+                       false)) {
+    return;
+  }
+  // FileSystem capacity
+  tmpstr = esp3d_string::formatBytes(ESP_FileSystem::usedBytes());
+  tmpstr += "/";
+  tmpstr += esp3d_string::formatBytes(ESP_FileSystem::totalBytes());
+  if (!dispatchIdValue(json, "FS usage", tmpstr.c_str(), target, requestId,
+                       false)) {
+    return;
+  }
+#endif  // FILESYSTEM_FEATURE
+#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL
+  // baud rate
+  tmpstr = String(esp3d_serial_service.baudRate());
+  if (!dispatchIdValue(json, "baud", tmpstr.c_str(), target, requestId,
+                       false)) {
+    return;
+  }
+#endif  // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL ==
+        // MKS_SERIAL
+#if defined(WIFI_FEATURE)
+  if (WiFi.getMode() != WIFI_OFF) {
+    // sleep mode
+    tmpstr = WiFiConfig::getSleepModeString();
+    if (!dispatchIdValue(json, "sleep mode", tmpstr.c_str(), target, requestId,
+                         false)) {
+      return;
+    }
+  }
+#endif  // WIFI_FEATURE
+#if defined(WIFI_FEATURE)
+  // Wifi enabled
+  tmpstr = (WiFi.getMode() == WIFI_OFF) ? "OFF" : "ON";
+  if (!dispatchIdValue(json, "wifi", tmpstr.c_str(), target, requestId,
+                       false)) {
+    return;
+  }
+#endif  // WIFI_FEATURE
+#if defined(ETH_FEATURE)
+  // Ethernet enabled
+  tmpstr = (EthConfig::started()) ? "ON" : "OFF";
+  if (!dispatchIdValue(json, "ethernet", tmpstr.c_str(), target, requestId,
+                       false)) {
+    return;
+  }
+#endif  // ETH_FEATURE
+
+#if defined(BLUETOOTH_FEATURE)
+  // BT enabled
+  tmpstr = (bt_service.started()) ? "ON" : "OFF";
+  if (!dispatchIdValue(json, "bt", tmpstr.c_str(), target, requestId, false)) {
+    return;
+  }
+#endif  // BLUETOOTH_FEATURE
+#if defined(WIFI_FEATURE) || defined(ETH_FEATURE)
+  // Hostname
+  tmpstr = NetConfig::hostname();
+  if (!dispatchIdValue(json, "hostname", tmpstr.c_str(), target, requestId,
+                       false)) {
+    return;
+  }
+
+#if defined(HTTP_FEATURE)
+  if (HTTP_Server::started()) {
+    // http port
+    tmpstr = String(HTTP_Server::port());
+    if (!dispatchIdValue(json, "HTTP port", tmpstr.c_str(), target, requestId,
+                         false)) {
+      return;
+    }
+  }
+#endif  // HTTP_FEATURE
+#if defined(TELNET_FEATURE)
+  if (telnet_server.started()) {
+    // telnet port
+    tmpstr = String(telnet_server.port());
+    if (!dispatchIdValue(json, "Telnet port", tmpstr.c_str(), target, requestId,
+                         false)) {
+      return;
+    }
+  }
+
+  if (telnet_server.isConnected()) {
+    // telnet client IP
+    tmpstr = telnet_server.clientIPAddress();
+    if (!dispatchIdValue(json, "Telnet Client", tmpstr.c_str(), target,
+                         requestId, false)) {
+      return;
+    }
+  }
+
+#endif  // TELNET_FEATURE
+#if defined(WEBDAV_FEATURE)
+  if (webdav_server.started()) {
+    // WebDav port
+    tmpstr = String(webdav_server.port());
+    if (!dispatchIdValue(json, "WebDav port", tmpstr.c_str(), target, requestId,
+                         false)) {
+      return;
+    }
+  }
+#endif  // WEBDAV_FEATURE
+#if defined(FTP_FEATURE)
+  if (ftp_server.started()) {
+    // ftp ports
+    tmpstr = String(ftp_server.ctrlport());
+    tmpstr += ",";
+    tmpstr += String(ftp_server.dataactiveport());
+    tmpstr += ",";
+    tmpstr += String(ftp_server.datapassiveport());
+    if (!dispatchIdValue(json, "Ftp ports", tmpstr.c_str(), target, requestId,
+                         false)) {
+      return;
+    }
+  }
+#endif  // FTP_FEATURE
+#if defined(WS_DATA_FEATURE)
+  if (websocket_data_server.started()) {
+    // websocket port
+    tmpstr = String(websocket_data_server.port());
+    if (!dispatchIdValue(json, "Websocket port", tmpstr.c_str(), target,
+                         requestId, false)) {
+      return;
+    }
+  }
+#endif  // WS_DATA_FEATURE
+#if defined(CAMERA_DEVICE)
+  if (esp3d_camera.started()) {
+    // camera name
+    tmpstr = esp3d_camera.GetModelString();
+    tmpstr += "(";
+    tmpstr += esp3d_camera.GetModel();
+    tmpstr += ")";
+    if (!dispatchIdValue(json, "camera name", tmpstr.c_str(), target, requestId,
+                         false)) {
+      return;
+    }
+  }
+#endif  // CAMERA_DEVICE
+#endif  // #if defined(WIFI_FEATURE) || defined(ETH_FEATURE)
+
+#if defined(DISPLAY_DEVICE)
+  tmpstr = esp3d_display.getModelString();
+  if (!dispatchIdValue(json, "display", tmpstr.c_str(), target, requestId,
+                       false)) {
+    return;
+  }
+#endif  // DISPLAY_DEVICE
+
+#if defined(BLUETOOTH_FEATURE)
+  if (bt_service.started()) {
+    // BT mode
+    tmpstr = BTService::macAddress();
+    if (!dispatchIdValue(json, "bt", tmpstr.c_str(), target, requestId,
+                         false)) {
+      return;
+    }
+    // BT status
+    tmpstr = (bt_service.isConnected()) ? "connected" : "disconnected";
+    if (bt_service.isConnected()) {
+      tmpstr += " (client: ";
+      tmpstr += BTService::clientmacAddress();
+      tmpstr += ")";
+    }
+    if (!dispatchIdValue(json, "BT Status", tmpstr.c_str(), target, requestId,
+                         false)) {
+      return;
+    }
+  }
+#endif  // BLUETOOTH_FEATURE
+#if defined(ETH_FEATURE)
+  if (EthConfig::started()) {
+    // Ethernet mode
+    tmpstr = ETH.macAddress();
+    if (!dispatchIdValue(json, "ethernet", tmpstr.c_str(), target, requestId,
+                         false)) {
+      return;
+    }
+    // Ethernet cable
+    tmpstr = (EthConfig::linkUp()) ? "connected" : "disconnected";
+
+    if (EthConfig::linkUp()) {
+      tmpstr += " (";
+      tmpstr += ETH.linkSpeed();
+      tmpstr += "Mbps)";
+    }
+    if (!dispatchIdValue(json, "cable", tmpstr.c_str(), target, requestId,
+                         false)) {
+      return;
+    }
+    // IP mode
+    tmpstr = (NetConfig::isIPModeDHCP(ESP_ETH_STA)) ? "dhcp" : "static";
+    if (!dispatchIdValue(json, "ip mode", tmpstr.c_str(), target, requestId,
+                         false)) {
+      return;
+    }
+    // IP value
+    tmpstr = ETH.localIP().toString();
+    if (!dispatchIdValue(json, "ip", tmpstr.c_str(), target, requestId,
+                         false)) {
+      return;
+    }
+    // GW value
+    tmpstr = ETH.gatewayIP().toString();
+    if (!dispatchIdValue(json, "gw", tmpstr.c_str(), target, requestId,
+                         false)) {
+      return;
+    }
+    // Mask value
+    tmpstr = ETH.subnetMask().toString();
+    if (!dispatchIdValue(json, "msk", tmpstr.c_str(), target, requestId,
+                         false)) {
+      return;
+    }
+    // DNS value
+    tmpstr = ETH.dnsIP().toString();
+    if (!dispatchIdValue(json, "DNS", tmpstr.c_str(), target, requestId,
+                         false)) {
+      return;
+    }
+  }
+#endif  // ETH_FEATURE
+#if defined(WIFI_FEATURE)
+  if (WiFi.getMode() != WIFI_OFF) {
+    // WiFi Mode
+    tmpstr = (WiFi.getMode() == WIFI_STA)      ? "sta"
+             : (WiFi.getMode() == WIFI_AP)     ? "ap"
+             : (WiFi.getMode() == WIFI_AP_STA) ? "mixed"
+                                               : "unknown";
+    if (!dispatchIdValue(json, "wifi mode", tmpstr.c_str(), target, requestId,
+                         false)) {
+      return;
+    }
+    // WiFi mac
+    tmpstr = (WiFi.getMode() == WIFI_STA)  ? WiFi.macAddress()
+             : (WiFi.getMode() == WIFI_AP) ? WiFi.softAPmacAddress()
+             : (WiFi.getMode() == WIFI_AP_STA)
+                 ? WiFi.macAddress() + "/" + WiFi.softAPmacAddress()
+                 : "unknown";
+    if (!dispatchIdValue(json, "mac", tmpstr.c_str(), target, requestId,
+                         false)) {
+      return;
+    }
+
+    // WiFi Station
+    if (WiFi.getMode() == WIFI_STA) {
+      // Connected to SSID
+      tmpstr = (WiFi.isConnected()) ? WiFi.SSID() : "";
+      if (!dispatchIdValue(json, "SSID", tmpstr.c_str(), target, requestId,
+                           false)) {
+        return;
+      }
+      if (WiFi.isConnected()) {  // in case query come from serial
+        // Signal strength
+        tmpstr = WiFiConfig::getSignal(WiFi.RSSI(), false);
+        tmpstr += "%";
+        if (!dispatchIdValue(json, "signal", tmpstr.c_str(), target, requestId,
+                             false)) {
+          return;
+        }
+        // Phy Mode
+        tmpstr = WiFiConfig::getPHYModeString(WIFI_STA);
+        if (!dispatchIdValue(json, "phy mode", tmpstr.c_str(), target,
+                             requestId, false)) {
+          return;
+        }
+        // Channel
+        tmpstr = String(WiFi.channel());
+        if (!dispatchIdValue(json, "channel", tmpstr.c_str(), target, requestId,
+                             false)) {
+          return;
+        }
+        // IP Mode
+        tmpstr = (NetConfig::isIPModeDHCP(ESP_WIFI_STA)) ? "dhcp" : "static";
+        if (!dispatchIdValue(json, "ip mode", tmpstr.c_str(), target, requestId,
+                             false)) {
+          return;
+        }
+        // IP value
+        tmpstr = WiFi.localIP().toString();
+        if (!dispatchIdValue(json, "ip", tmpstr.c_str(), target, requestId,
+                             false)) {
+          return;
+        }
+        // Gateway value
+        tmpstr = WiFi.gatewayIP().toString();
+        if (!dispatchIdValue(json, "gw", tmpstr.c_str(), target, requestId,
+                             false)) {
+          return;
+        }
+        // Mask value
+        tmpstr = WiFi.subnetMask().toString();
+        if (!dispatchIdValue(json, "msk", tmpstr.c_str(), target, requestId,
+                             false)) {
+          return;
+        }
+        // DNS value
+        tmpstr = WiFi.dnsIP().toString();
+        if (!dispatchIdValue(json, "DNS", tmpstr.c_str(), target, requestId,
+                             false)) {
+          return;
+        }
+      }
+      // Disabled Mode
+      tmpstr = "OFF";
+      if (!dispatchIdValue(json, "ap", tmpstr.c_str(), target, requestId,
+                           false)) {
+        return;
+      }
+      // Disabled Mode
+      tmpstr = WiFi.softAPmacAddress();
+      if (!dispatchIdValue(json, "mac", tmpstr.c_str(), target, requestId,
+                           false)) {
+        return;
+      }
+    } else if (WiFi.getMode() == WIFI_AP) {
+      // AP SSID
+      tmpstr = WiFiConfig::AP_SSID();
+      if (!dispatchIdValue(json, "SSID", tmpstr.c_str(), target, requestId,
+                           false)) {
+        return;
+      }
+      // AP Visibility
+      tmpstr = (WiFiConfig::is_AP_visible()) ? "yes" : "no";
+      if (!dispatchIdValue(json, "visible", tmpstr.c_str(), target, requestId,
+                           false)) {
+        return;
+      }
+      // AP Authentication
+      tmpstr = WiFiConfig::AP_Auth_String();
+      if (!dispatchIdValue(json, "authentication", tmpstr.c_str(), target,
+                           requestId, false)) {
+        return;
+      }
+      // DHCP Server
+      tmpstr = (NetConfig::isDHCPServer(ESP_WIFI_AP)) ? "ON" : "OFF";
+      if (!dispatchIdValue(json, "DHCP Server", tmpstr.c_str(), target,
+                           requestId, false)) {
+        return;
+      }
+      // IP Value
+      tmpstr = WiFi.softAPIP().toString();
+      if (!dispatchIdValue(json, "ip", tmpstr.c_str(), target, requestId,
+                           false)) {
+        return;
+      }
+      // Gateway Value
+      tmpstr = WiFiConfig::AP_Gateway_String();
+      if (!dispatchIdValue(json, "gw", tmpstr.c_str(), target, requestId,
+                           false)) {
+        return;
+      }
+      // Mask Value
+      tmpstr = WiFiConfig::AP_Mask_String();
+      if (!dispatchIdValue(json, "msk", tmpstr.c_str(), target, requestId,
+                           false)) {
+        return;
+      }
+      // Connected clients
+      const char* entry = NULL;
+      uint8_t nb = 0;
+      entry = WiFiConfig::getConnectedSTA(&nb, true);
+
+      tmpstr = String(nb);
+      if (!dispatchIdValue(json, "clients", tmpstr.c_str(), target, requestId,
+                           false)) {
+        return;
+      }
+      for (uint8_t i = 0; i < nb; i++) {
+        // Client
+        tmpstr = entry;
+        String label = "# " + String(i);
+        if (!dispatchIdValue(json, label.c_str(), tmpstr.c_str(), target,
+                             requestId, false)) {
+          return;
+        }
+        entry = WiFiConfig::getConnectedSTA();
+      }
+
+      // Disabled Mode
+      tmpstr = "OFF";
+      if (!dispatchIdValue(json, "sta", tmpstr.c_str(), target, requestId,
+                           false)) {
+        return;
+      }
+      // Disabled Mode
+      tmpstr = WiFi.macAddress();
+      if (!dispatchIdValue(json, "mac", tmpstr.c_str(), target, requestId,
+                           false)) {
+        return;
+      }
+    }
+  }
+#endif  // WIFI_FEATURE
+
+#if defined(TIMESTAMP_FEATURE)
+  // NTP enabled
+  tmpstr = (timeService.started()) ? "ON" : "OFF";
+  if (!dispatchIdValue(json, "ntp", tmpstr.c_str(), target, requestId, false)) {
+    return;
+  }
+#endif  // TIMESTAMP_FEATURE
+
+#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL
+  // serial enabled
+  tmpstr = (esp3d_serial_service.started()) ? "ON" : "OFF";
+  if (!dispatchIdValue(json, "serial", tmpstr.c_str(), target, requestId,
+                       false)) {
+    return;
+  }
+#endif  // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL ==
+        // MKS_SERIAL
+#if defined(AUTHENTICATION_FEATURE)
+  // authentication enabled
+  tmpstr = "ON";
+#else
+  tmpstr = "OFF";
+#endif  // AUTHENTICATION_FEATURE
+  if (!dispatchIdValue(json, "authentication", tmpstr.c_str(), target,
+                       requestId, false)) {
+    return;
+  }
+
+#if defined(NOTIFICATION_FEATURE)
+  // notification enabled
+  tmpstr = (notificationsservice.started()) ? "ON" : "OFF";
+  if (notificationsservice.started()) {
+    tmpstr += " (";
+    tmpstr += notificationsservice.getTypeString();
+    tmpstr += ")";
+  }
+  if (!dispatchIdValue(json, "notification", tmpstr.c_str(), target, requestId,
+                       false)) {
+    return;
+  }
+#endif  // NOTIFICATION_FEATURE
+#if defined(SD_DEVICE)
+  // SD enabled
+  tmpstr = (ESP3DSettings::GetSDDevice() == ESP_DIRECT_SD)   ? "direct "
+           : (ESP3DSettings::GetSDDevice() == ESP_SHARED_SD) ? "shared "
+                                                             : "none ";
+  tmpstr += "(";
+  tmpstr += ESP_SD::FilesystemName();
+  tmpstr += ")";
+  if (!dispatchIdValue(json, "sd", tmpstr.c_str(), target, requestId, false)) {
+    return;
+  }
+
+#ifdef SD_UPDATE_FEATURE
+  // SD updater enabled
+  tmpstr =
+      ESP3DSettings::readByte(ESP_SD_CHECK_UPDATE_AT_BOOT) != 0 ? "ON" : "OFF";
+  if (!dispatchIdValue(json, "SD updater", tmpstr.c_str(), target, requestId,
+                       false)) {
+    return;
+  }
+#endif  // SD_UPDATE_FEATURE
+
+#endif  // SD_DEVICE
+#if defined(SENSOR_DEVICE)
+  // sensor enabled
+  tmpstr = (esp3d_sensor.started()) ? "ON" : "OFF";
+  if (esp3d_sensor.started()) {
+    tmpstr += " (";
+    tmpstr += esp3d_sensor.GetCurrentModelString();
+    tmpstr += ")";
+  }
+  if (!dispatchIdValue(json, "sensor", tmpstr.c_str(), target, requestId,
+                       false)) {
+    return;
+  }
+#endif  // SENSOR_DEVICE
+#if defined(BUZZER_DEVICE)
+  // buzzer enabled
+  tmpstr = (esp3d_buzzer.started()) ? "ON" : "OFF";
+  if (!dispatchIdValue(json, "buzzer", tmpstr.c_str(), target, requestId,
+                       false)) {
+    return;
+  }
+#endif  // BUZZER_DEVICE
+#if defined(CAMERA_DEVICE)
+  // camera enabled
+  tmpstr = (esp3d_camera.started()) ? "ON" : "OFF";
+  if (esp3d_camera.started()) {
+    tmpstr += " (";
+
+    tmpstr += esp3d_camera.GetModelString();
+    tmpstr += ")";
+  }
+  if (!dispatchIdValue(json, "camera", tmpstr.c_str(), target, requestId,
+                       false)) {
+    return;
+  }
+#endif  // CAMERA_DEVICE
+
+// Serial mode
+#if COMMUNICATION_PROTOCOL == MKS_SERIAL
+  tmpstr = "MKS";
+  if (!dispatchIdValue(json, "serial", tmpstr.c_str(), target, requestId,
+                       false)) {
+    return;
+  }
+#endif  // COMMUNICATION_PROTOCOL == MKS_SERIAL
+
+  // Target Firmware
+  tmpstr = ESP3DSettings::GetFirmwareTargetShortName();
+  if (!dispatchIdValue(json, "targetfw", tmpstr.c_str(), target, requestId,
+                       false)) {
+    return;
+  }
+
+  // FW version
+
+  tmpstr = "";
+#if defined(SHORT_BUILD_VERSION)
+  tmpstr += SHORT_BUILD_VERSION "-";
+#endif  // SHORT_BUILD_VERSION
+  tmpstr += FW_VERSION;
+
+  if (!dispatchIdValue(json, "FW ver", tmpstr.c_str(), target, requestId,
+                       false)) {
+    return;
+  }
+
+  // FW architecture
+  tmpstr = ESP3DSettings::TargetBoard();
+  if (!dispatchIdValue(json, "FW arch", tmpstr.c_str(), target, requestId,
+                       false)) {
+    return;
+  }
+
+  // end of list
+  if (json) {
+    if (!dispatch("]}", target, requestId, ESP3DMessageType::tail)) {
+      esp3d_log_e("Error sending answer to clients");
+    }
+  } else {
+    {
+      if (addPreTag) {
+        tmpstr = "
\n"; + } else { + tmpstr = "ok\n"; + } + if (!dispatch(tmpstr.c_str(), target, requestId, + ESP3DMessageType::tail)) { + esp3d_log_e("Error sending answer to clients"); + } + } + } +} diff --git a/esp3d/src/core/commands/ESP444.cpp b/esp3d/src/core/commands/ESP444.cpp new file mode 100644 index 00000000..5d2acc9d --- /dev/null +++ b/esp3d/src/core/commands/ESP444.cpp @@ -0,0 +1,83 @@ +/* + ESP444.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#include "../../modules/authentication/authentication_service.h" +#include "../esp3d.h" +#include "../esp3d_commands.h" + +// Set ESP State +// cmd are RESTART / RESET +//[ESP444] json= +#define COMMAND_ID 444 +void ESP3DCommands::ESP444(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; + bool isRestart = hasTag(msg, cmd_params_pos, "RESTART"); + bool isReset = hasTag(msg, cmd_params_pos, "RESET"); + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = ""; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + if (isReset) { + Esp3D::reset(); + esp3d_log("Resetting settings"); + } + + if (!(isRestart || isReset)) { + hasError = true; + esp3d_log_e("%s", error_msg.c_str()); + } else { + if (isReset) { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + ok_msg += "Reset done"; + } + if (isRestart) { + if (ok_msg.length() > 0) { + ok_msg += ", "; + } + ok_msg += "Now restarting..."; + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + return; + } + if (isRestart) { + ESP3DHal::wait(100); + Esp3D::restart_esp(); + } +} diff --git a/esp3d/src/core/commands/ESP450.cpp b/esp3d/src/core/commands/ESP450.cpp new file mode 100644 index 00000000..cd468c02 --- /dev/null +++ b/esp3d/src/core/commands/ESP450.cpp @@ -0,0 +1,142 @@ +/* + ESP410.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(MDNS_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/mDNS/mDNS.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +// Get available ESP3D list +// output is JSON or plain text according parameter +//[ESP4\50]json= +#define COMMAND_ID 450 +void ESP3DCommands::ESP450(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; + +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + + if (!(WiFi.getMode() == WIFI_STA || WiFi.getMode() == WIFI_AP)) { + tmpstr = "Network not enabled"; + dispatchAnswer(msg, COMMAND_ID, json, true, tmpstr.c_str()); + return; + } + + if (json) { + tmpstr = "{\"cmd\":\"450\",\"status\":\"ok\",\"data\":["; + + } else { + tmpstr = "Start Scan\n"; + } + msg->type = ESP3DMessageType::head; + if (!dispatch(msg, tmpstr.c_str())) { + esp3d_log_e("Error sending response to clients"); + return; + } + + uint16_t count = esp3d_mDNS.servicesCount(); + uint16_t nbListed = 0; + esp3d_log("Total : %d", count); + for (uint16_t i = 0; i < count; i++) { + if (strlen(esp3d_mDNS.answerHostname(i)) == 0) { + continue; + } + // Currently esp3d support only IPV4 and only one address per device + + tmpstr = ""; + + if (json) { + if (nbListed > 0) { + tmpstr += ","; + } + + tmpstr += "{\"Hostname\":\""; + } + tmpstr += esp3d_mDNS.answerHostname(i); + if (json) { + tmpstr += "\",\"IP\":\""; + } else { + tmpstr += " ("; + } + tmpstr += esp3d_mDNS.answerIP(i); + if (json) { + tmpstr += "\",\"port\":\""; + tmpstr += String(esp3d_mDNS.answerPort(i)); + tmpstr += "\",\"TxT\":["; + + } else { + tmpstr += ":"; + tmpstr += String(esp3d_mDNS.answerPort(i)); + tmpstr += ") "; + } + uint16_t nbtxt = esp3d_mDNS.answerTxtCount(i); + for (uint8_t t = 0; t < nbtxt; t++) { + if (t != 0) { + tmpstr += ","; + } + if (json) { + tmpstr += "{\"key\":\""; + } + tmpstr += esp3d_mDNS.answerTxtKey(i, t); + if (json) { + tmpstr += "\",\"value\":\""; + } else { + tmpstr += "="; + } + tmpstr += esp3d_mDNS.answerTxt(i, t); + if (json) { + tmpstr += "\"}"; + } + } + + if (json) { + tmpstr += "]}"; + } else { + tmpstr += "\n"; + } + if (!dispatch(tmpstr.c_str(), target, requestId, ESP3DMessageType::core)) { + esp3d_log_e("Error sending answer to clients"); + } + + nbListed++; + } + + // end of list + if (json) { + tmpstr = "]}"; + } else { + tmpstr = "End Scan\n"; + } + if (!dispatch(tmpstr.c_str(), target, requestId, ESP3DMessageType::tail)) { + esp3d_log_e("Error sending answer to clients"); + } +} + +#endif // MDNS_FEATURE diff --git a/esp3d/src/core/commands/ESP500.cpp b/esp3d/src/core/commands/ESP500.cpp new file mode 100644 index 00000000..7aafdc13 --- /dev/null +++ b/esp3d/src/core/commands/ESP500.cpp @@ -0,0 +1,67 @@ +/* + ESP550.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(AUTHENTICATION_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 500 +// Get connection status +//[ESP500] json= pwd= +void ESP3DCommands::ESP500(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + + String tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + switch (msg->authentication_level) { + case ESP3DAuthenticationLevel::admin: + ok_msg = "admin"; + break; + case ESP3DAuthenticationLevel::user: + ok_msg = "user"; + break; + case ESP3DAuthenticationLevel::not_authenticated: + ok_msg = "Not authenticated"; + break; + default: + ok_msg = "guest"; + break; + } + } else { + esp3d_log_e("Got %s", tmpstr.c_str()); + hasError = true; + } + + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // AUTHENTICATION_FEATURE diff --git a/esp3d/src/core/commands/ESP510.cpp b/esp3d/src/core/commands/ESP510.cpp new file mode 100644 index 00000000..e2f79d65 --- /dev/null +++ b/esp3d/src/core/commands/ESP510.cpp @@ -0,0 +1,83 @@ +/* + ESP550.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(AUTHENTICATION_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 510 +// set/display session time out +//[ESP510] json= pwd= +void ESP3DCommands::ESP510(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + const ESP3DSettingDescription* settingPtr = + ESP3DSettings::getSettingPtr(ESP_SESSION_TIMEOUT); + if (settingPtr) { + ok_msg = String(ESP3DSettings::readByte(ESP_SESSION_TIMEOUT)); + } else { + hasError = true; + error_msg = "This setting is unknown"; + } + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + if (ESP3DSettings::isValidByteSetting((uint8_t)tmpstr.toInt(), + ESP_SESSION_TIMEOUT)) { + esp3d_log("Value %s is valid", tmpstr.c_str()); + if (!ESP3DSettings::writeByte(ESP_SESSION_TIMEOUT, + (uint8_t)tmpstr.toInt())) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid parameter"; + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // AUTHENTICATION_FEATURE diff --git a/esp3d/src/core/commands/ESP550.cpp b/esp3d/src/core/commands/ESP550.cpp new file mode 100644 index 00000000..fc8add1f --- /dev/null +++ b/esp3d/src/core/commands/ESP550.cpp @@ -0,0 +1,79 @@ +/* + ESP550.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(AUTHENTICATION_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 550 +// Change admin password +//[ESP550] json= pwd= +void ESP3DCommands::ESP550(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + const ESP3DSettingDescription* settingPtr = + ESP3DSettings::getSettingPtr(ESP_ADMIN_PWD); + if (settingPtr) { + ok_msg = ESP3DSettings::readString(ESP_ADMIN_PWD); + } else { + hasError = true; + error_msg = "This setting is unknown"; + } + } else { + esp3d_log( + "got %s param for a value of %s, is valid %d", tmpstr.c_str(), + tmpstr.c_str(), + ESP3DSettings::isValidStringSetting(tmpstr.c_str(), ESP_ADMIN_PWD)); + if (ESP3DSettings::isValidStringSetting(tmpstr.c_str(), ESP_ADMIN_PWD)) { + esp3d_log("Value %s is valid", tmpstr.c_str()); + if (!ESP3DSettings::writeString(ESP_ADMIN_PWD, tmpstr.c_str())) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid parameter"; + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // AUTHENTICATION_FEATURE diff --git a/esp3d/src/core/commands/ESP555.cpp b/esp3d/src/core/commands/ESP555.cpp new file mode 100644 index 00000000..d320fc54 --- /dev/null +++ b/esp3d/src/core/commands/ESP555.cpp @@ -0,0 +1,79 @@ +/* + ESP555.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(AUTHENTICATION_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +// Change user password +//[ESP555] json= pwd= +#define COMMAND_ID 555 +void ESP3DCommands::ESP555(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + const ESP3DSettingDescription* settingPtr = + ESP3DSettings::getSettingPtr(ESP_USER_PWD); + if (settingPtr) { + ok_msg = ESP3DSettings::readString(ESP_USER_PWD); + } else { + hasError = true; + error_msg = "This setting is unknown"; + } + } else { + esp3d_log( + "got %s param for a value of %s, is valid %d", tmpstr.c_str(), + tmpstr.c_str(), + ESP3DSettings::isValidStringSetting(tmpstr.c_str(), ESP_USER_PWD)); + if (ESP3DSettings::isValidStringSetting(tmpstr.c_str(), ESP_USER_PWD)) { + esp3d_log("Value %s is valid", tmpstr.c_str()); + if (!ESP3DSettings::writeString(ESP_USER_PWD, tmpstr.c_str())) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid parameter"; + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // AUTHENTICATION_FEATURE diff --git a/esp3d/src/core/commands/ESP600.cpp b/esp3d/src/core/commands/ESP600.cpp new file mode 100644 index 00000000..cc4efc4c --- /dev/null +++ b/esp3d/src/core/commands/ESP600.cpp @@ -0,0 +1,66 @@ +/* + ESP600.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(NOTIFICATION_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/notifications/notifications_service.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 600 +// Send Notification +//[ESP600]msg json= pwd= +void ESP3DCommands::ESP600(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + hasError = true; + error_msg = "Message is missing"; + esp3d_log_e("%s", error_msg.c_str()); + } else { + if (!notificationsservice.sendMSG(ESP_NOTIFICATION_TITLE, tmpstr.c_str())) { + hasError = true; + error_msg = "Send notification failed"; + esp3d_log_e("%s", error_msg.c_str()); + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // NOTIFICATION_FEATURE diff --git a/esp3d/src/core/commands/ESP610.cpp b/esp3d/src/core/commands/ESP610.cpp new file mode 100644 index 00000000..ffd91fed --- /dev/null +++ b/esp3d/src/core/commands/ESP610.cpp @@ -0,0 +1,139 @@ +/* + ESP610.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(NOTIFICATION_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/notifications/notifications_service.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 610 +// Set/Get Notification settings +//[ESP610] +// Get will give type and settings +// but not T1/T2 chich are protected +void ESP3DCommands::ESP610(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; + const char* cmdList[] = {"type=", "T1=", "T2=", "TS="}; + uint8_t cmdListSize = sizeof(cmdList) / sizeof(char*); + const char* notificationStr[] = {"NONE", "PUSHOVER", "EMAIL", + "LINE", "TELEGRAM", "IFTTT", "HOMEASSISTANT"}; + uint8_t notificationStrSize = sizeof(notificationStr) / sizeof(char*); + const ESP3DSettingIndex settingIndex[] = { + ESP_NOTIFICATION_TYPE, ESP_NOTIFICATION_TOKEN1, ESP_NOTIFICATION_TOKEN2, + ESP_NOTIFICATION_SETTINGS}; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + if (json) { + ok_msg = "{\"type\":\""; + } else { + ok_msg = "type: "; + } + uint8_t Ntype = ESP3DSettings::readByte(ESP_NOTIFICATION_TYPE); + ok_msg += Ntype < notificationStrSize ? notificationStr[Ntype] : "Unknown"; + + if (json) { + ok_msg += "\",\"TS\":\""; + } else { + ok_msg += ", TS: "; + } + ok_msg += ESP3DSettings::readString(ESP_NOTIFICATION_SETTINGS); + + if (json) { + ok_msg += "\"}"; + } + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + bool hasParam = false; + for (uint8_t i = 0; i < cmdListSize; i++) { + bool isPresent = false; + tmpstr = get_param(msg, cmd_params_pos, cmdList[i], &isPresent); + if (tmpstr.length() != 0 || isPresent) { + hasParam = true; + if (i > 0) { + if (ESP3DSettings::isValidStringSetting(tmpstr.c_str(), + settingIndex[i])) { + esp3d_log("Value %s is valid", tmpstr.c_str()); + if (!ESP3DSettings::writeString(settingIndex[i], tmpstr.c_str())) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid parameter"; + } + } else { + tmpstr.toUpperCase(); + int id = -1; + for (uint8_t j = 0; j < notificationStrSize; j++) { + if (tmpstr == notificationStr[j]) { + id = j; + break; + } + } + if (id != -1) { + if (!ESP3DSettings::writeByte(ESP_NOTIFICATION_TYPE, id)) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid parameter"; + esp3d_log_e("%s", error_msg.c_str()); + } + } + } + } + if (!hasParam && !hasError) { + hasError = true; + error_msg = "Invalid parameter"; + } + if (!hasError) { + notificationsservice.begin(); + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // NOTIFICATION_FEATURE diff --git a/esp3d/src/core/commands/ESP620.cpp b/esp3d/src/core/commands/ESP620.cpp new file mode 100644 index 00000000..0b65253f --- /dev/null +++ b/esp3d/src/core/commands/ESP620.cpp @@ -0,0 +1,66 @@ +/* + ESP620.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(NOTIFICATION_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/notifications/notifications_service.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 620 +// Send Notification using encoded URL +//[ESP620]URL= json=[pwd=] +void ESP3DCommands::ESP620(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_param(msg, cmd_params_pos, "URL="); + if (tmpstr.length() == 0) { + hasError = true; + error_msg = "URL is missing"; + } else { + if (notificationsservice.GET(tmpstr.c_str())) { + ok_msg = "Notification sent"; + } else { + hasError = true; + error_msg = "Send notification failed"; + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // NOTIFICATION_FEATURE diff --git a/esp3d/src/core/commands/ESP700.cpp b/esp3d/src/core/commands/ESP700.cpp new file mode 100644 index 00000000..fe018120 --- /dev/null +++ b/esp3d/src/core/commands/ESP700.cpp @@ -0,0 +1,81 @@ +/* + ESP700.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(GCODE_HOST_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/gcode_host/gcode_host.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 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 + +// process local file +//[ESP700] +void ESP3DCommands::ESP700(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + hasError = true; + error_msg = "Missing parameter"; + esp3d_log_e("%s", error_msg.c_str()); + } else { + if (esp3d_gcode_host.getStatus() == HOST_NO_STREAM) { + if (esp3d_gcode_host.processFile(tmpstr.c_str(), + msg->authentication_level)) { + esp3d_log("Processing %s", parameter.c_str()); + } else { + hasError = true; + error_msg = "Error processing file"; + esp3d_log_e("%s", error_msg.c_str()); + } + } else { + hasError = true; + error_msg = "Streaming already in progress"; + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // GCODE_HOST_FEATURE diff --git a/esp3d/src/core/commands/ESP701.cpp b/esp3d/src/core/commands/ESP701.cpp new file mode 100644 index 00000000..6ddf0d0f --- /dev/null +++ b/esp3d/src/core/commands/ESP701.cpp @@ -0,0 +1,146 @@ +/* + ESP701.cpp - ESP3D command 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 +*/ +// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 +#include "../../include/esp3d_config.h" +#if defined(GCODE_HOST_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/gcode_host/gcode_host.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 701 + +// Query and Control ESP700 stream +//[ESP701]action= CLEAR_ERROR +void ESP3DCommands::ESP701(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + bool hasClearError = hasTag(msg, cmd_params_pos, "CLEAR_ERROR"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + // give status + switch (esp3d_gcode_host.getStatus()) { + case HOST_START_STREAM: + case HOST_READ_LINE: + case HOST_PROCESS_LINE: + case HOST_WAIT4_ACK: + // TODO add % of progress and filename if any + // totalSize / processedSize / fileName + if (json) { + ok_msg = "{\"status\":\"processing\",\"total\":\"" + + String(esp3d_gcode_host.totalSize()) + + "\",\"processed\":\"" + + String(esp3d_gcode_host.processedSize()) + "\",\"type\":\"" + + String(esp3d_gcode_host.getFSType()); + if (esp3d_gcode_host.getFSType() != TYPE_SCRIPT_STREAM) { + ok_msg += "\",\"name\":\"" + String(esp3d_gcode_host.fileName()); + } + ok_msg += "\"}"; + } else { + ok_msg = "processing"; + } + break; + case HOST_PAUSE_STREAM: + ok_msg = "pause"; + break; + case HOST_NO_STREAM: + esp3d_log("No stream %d", esp3d_gcode_host.getErrorNum()); + if (esp3d_gcode_host.getErrorNum() != ERROR_NO_ERROR) { + hasError = true; + if (json) { + error_msg = "{\"status\":\"no stream\",\"code\":\"" + + String(esp3d_gcode_host.getErrorNum()) + "\"}"; + } else { + error_msg = "no stream, last error " + + String(esp3d_gcode_host.getErrorNum()); + } + } else { + ok_msg = "no stream"; + } + break; + default: + error_msg = String(esp3d_gcode_host.getStatus()); + hasError = true; + break; + } + + } else { + tmpstr = get_param(msg, cmd_params_pos, "action="); + if (tmpstr.length() == 0) { + hasError = true; + error_msg = "Missing parameter"; + esp3d_log_e("%s", error_msg.c_str()); + } else { + tmpstr.toUpperCase(); + if (tmpstr != "PAUSE" && tmpstr != "ABORT" && tmpstr != "RESUME") { + hasError = true; + error_msg = "Unknown action"; + esp3d_log_e("%s", error_msg.c_str()); + } else { + if (tmpstr == "PAUSE") { + if (esp3d_gcode_host.pause()) { + ok_msg = "Stream paused"; + } else { + hasError = true; + error_msg = "No stream to pause"; + } + } else if (tmpstr == "RESUME") { + if (esp3d_gcode_host.resume()) { + ok_msg = "Stream resumed"; + } else { + error_msg = "No stream to resume"; + hasError = true; + } + } else if (tmpstr == "ABORT") { + if (esp3d_gcode_host.abort()) { + ok_msg = "Stream aborted"; + } else { + error_msg = "No stream to abort"; + hasError = true; + } + } + } + if (hasClearError) { + esp3d_gcode_host.setErrorNum(ERROR_NO_ERROR); + } + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // GCODE_HOST_FEATURE diff --git a/esp3d/src/core/commands/ESP710.cpp b/esp3d/src/core/commands/ESP710.cpp new file mode 100644 index 00000000..010e6a1e --- /dev/null +++ b/esp3d/src/core/commands/ESP710.cpp @@ -0,0 +1,88 @@ +/* + ESP710.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(FILESYSTEM_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/filesystem/esp_filesystem.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 710 +// Format ESP Filesystem +//[ESP710]FORMATFS json= pwd= +void ESP3DCommands::ESP710(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + bool formatfs = hasTag(msg, cmd_params_pos, "FORMATFS"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + ESP3DMessage* endMsg = nullptr; + if (tmpstr.length() == 0) { + hasError = true; + error_msg = "Missing parameter"; + esp3d_log_e("%s", error_msg.c_str()); + + } else { + if (formatfs) { + ok_msg = "Starting formating..."; + endMsg = ESP3DMessageManager::copyMsgInfos(*msg); + } else { + hasError = true; + error_msg = "Invalid parameter"; + esp3d_log_e("%s", error_msg.c_str()); + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } + if (!hasError && formatfs) { + ESP_FileSystem::accessFS(); + bool success = ESP_FileSystem::format(); + if (success) { + ok_msg = "Formating done"; + } else { + hasError = true; + error_msg = "Formating failed"; + esp3d_log_e("%s", error_msg.c_str()); + } + if (!dispatchAnswer(endMsg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } + ESP_FileSystem::releaseFS(); + } +} + +#endif // FILESYSTEM_FEATURE diff --git a/esp3d/src/core/commands/ESP715.cpp b/esp3d/src/core/commands/ESP715.cpp new file mode 100644 index 00000000..84f34aa6 --- /dev/null +++ b/esp3d/src/core/commands/ESP715.cpp @@ -0,0 +1,102 @@ +/* + ESP715.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(SD_DEVICE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/filesystem/esp_sd.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 715 +// Format SD Filesystem +//[ESP715]FORMATSD json= pwd= +void ESP3DCommands::ESP715(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + bool formatsd = hasTag(msg, cmd_params_pos, "FORMATSD"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + ESP3DMessage* endMsg = nullptr; + if (tmpstr.length() == 0) { + hasError = true; + error_msg = "Missing parameter"; + esp3d_log_e("%s", error_msg.c_str()); + + } else { + if (formatsd) { + if (ESP_SD::getState() != ESP_SDCARD_BUSY) { + ok_msg = "Starting formating..."; + endMsg = ESP3DMessageManager::copyMsgInfos(*msg); + } else { + hasError = true; + error_msg = "SD card busy"; + esp3d_log_e("%s", error_msg.c_str()); + } + } else { + hasError = true; + error_msg = "Invalid parameter"; + esp3d_log_e("%s", error_msg.c_str()); + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } + if (!hasError && formatsd) { + if (ESP_SD::accessFS()) { + ESP_SD::setState(ESP_SDCARD_BUSY); + bool success = ESP_SD::format(); + if (success) { + ok_msg = "Formating done"; + } else { + hasError = true; + error_msg = "Formating failed"; + esp3d_log_e("%s", error_msg.c_str()); + } + + ESP_SD::releaseFS(); + } else { + hasError = true; + error_msg = "SD not available"; + esp3d_log_e("%s", error_msg.c_str()); + } + + if (!dispatchAnswer(endMsg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } + } +} + +#endif // SD_DEVICE diff --git a/esp3d/src/core/commands/ESP720.cpp b/esp3d/src/core/commands/ESP720.cpp new file mode 100644 index 00000000..1406ac29 --- /dev/null +++ b/esp3d/src/core/commands/ESP720.cpp @@ -0,0 +1,233 @@ +/* + ESP720.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(FILESYSTEM_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/filesystem/esp_filesystem.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" +#include "../esp3d_string.h" + +#ifdef FILESYSTEM_TIMESTAMP_FEATURE +#include "../../modules/time/time_service.h" +#endif // FILESYSTEM_TIMESTAMP_FEATURE +#define COMMAND_ID 720 +// List ESP Filesystem +//[ESP720] json= pwd= +void ESP3DCommands::ESP720(int cmd_params_pos, ESP3DMessage* msg) { + bool hasError = false; + String error_msg = "Path inccorrect"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; + // prepare answer msg + msg->target = msg->origin; + msg->origin = ESP3DClientType::command; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + + ESP3DMessage msgInfo; + ESP3DMessageManager::copyMsgInfos(&msgInfo, *msg); + tmpstr = get_clean_param(msg, cmd_params_pos); + + if (tmpstr.length() == 0) { + tmpstr = "/"; + } + + if (ESP_FileSystem::accessFS()) { + ESP_File f; + f = ESP_FileSystem::open(tmpstr.c_str(), ESP_FILE_READ); + if (f) { + if (json) { + ok_msg = "{\"cmd\":\"720\",\"status\":\"ok\",\"data\":{\"path\":\""; + ok_msg += tmpstr.c_str(); + ok_msg += "\",\"files\":["; + + } else { + ok_msg = "Directory on Flash : "; + ok_msg += tmpstr.c_str(); + ok_msg += "\n"; + } + msg->type = ESP3DMessageType::head; + if (!dispatch(msg, ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + hasError = true; + } + + if (!hasError) { + uint nbDirs = 0; + uint nbFiles = 0; + size_t totalSpace = ESP_FileSystem::totalBytes(); + size_t usedSpace = ESP_FileSystem::usedBytes(); + size_t freeSpace = ESP_FileSystem::freeBytes(); + + ESP_File sub; + sub = f.openNextFile(); + while (sub && !hasError) { + if (sub.isDirectory()) { + ok_msg = ""; + nbDirs++; + if (json) { + ok_msg = ""; + if (nbDirs > 1) { + ok_msg += ","; + } + ok_msg += "{\"name\":\""; + ok_msg += sub.name(); + ok_msg += "\",\"size\":\"-1\"}"; + } else { + ok_msg = "[DIR] \t"; + ok_msg += sub.name(); + } + if (!json) { + ok_msg += "\n"; + } + ESP3DMessage* newMsg = ESP3DMessageManager::copyMsgInfos(msgInfo); + if (newMsg) { + newMsg->type = ESP3DMessageType::core; + if (!dispatch(newMsg, ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + hasError = true; + } + } else { + esp3d_log_e("Error creating message"); + hasError = true; + } + } + sub.close(); + sub = f.openNextFile(); + } + f.close(); + f = ESP_FileSystem::open(tmpstr.c_str(), ESP_FILE_READ); + // Check files + sub = f.openNextFile(); + while (sub && !hasError) { + if (!sub.isDirectory()) { + nbFiles++; + String time = ""; + ok_msg = ""; +#ifdef FILESYSTEM_TIMESTAMP_FEATURE + time = timeService.getDateTime((time_t)sub.getLastWrite()); +#endif // FILESYSTEM_TIMESTAMP_FEATURE + if (json) { + ok_msg = ""; + if (nbDirs > 0 || nbFiles > 1) { + ok_msg += ","; + } + ok_msg += "{\"name\":\""; + ok_msg += sub.name(); + ok_msg += "\",\"size\":\""; + ok_msg += esp3d_string::formatBytes(sub.size()); + if (time.length() > 0) { + ok_msg += "\",\"time\":\""; + ok_msg += time; + } + ok_msg += "\"}"; + } else { + ok_msg += " \t "; + ok_msg += sub.name(); + ok_msg += " \t"; + ok_msg += esp3d_string::formatBytes(sub.size()); + ok_msg += " \t"; + ok_msg += time; + } + if (!json) { + ok_msg += "\n"; + } + ESP3DMessage* newMsg = ESP3DMessageManager::copyMsgInfos(msgInfo); + if (newMsg) { + newMsg->type = ESP3DMessageType::core; + if (!dispatch(newMsg, ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + hasError = true; + } + } else { + esp3d_log_e("Error creating message"); + hasError = true; + } + } + sub.close(); + sub = f.openNextFile(); + } + // end of json + if (json) { + ok_msg = "], \"total\":\""; + ok_msg += esp3d_string::formatBytes(totalSpace); + ok_msg += "\",\"used\":\""; + ok_msg += esp3d_string::formatBytes(usedSpace); + ok_msg += "\",\"occupation\":\""; + if (totalSpace == 0) { + totalSpace = 1; + } + uint occupation = round(100.0 * usedSpace / totalSpace); + if ((occupation < 1) && (usedSpace > 0)) { + occupation = 1; + } + ok_msg += String(occupation); + ok_msg += "\"}}"; + + } else { + ok_msg = "Files: "; + ok_msg += String(nbFiles); + ok_msg += ", Dirs :"; + ok_msg += String(nbDirs); + ok_msg += "\nTotal: "; + ok_msg += esp3d_string::formatBytes(totalSpace); + ok_msg += ", Used: "; + ok_msg += esp3d_string::formatBytes(usedSpace); + ok_msg += ", Available: "; + ok_msg += esp3d_string::formatBytes(freeSpace); + ok_msg += "\n"; + } + + ESP3DMessage* newMsg = ESP3DMessageManager::copyMsgInfos(msgInfo); + newMsg->type = ESP3DMessageType::tail; + if (!dispatch(newMsg, ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } + f.close(); + } + } else { + hasError = true; + error_msg = "Invalid directory"; + esp3d_log_e("%s", error_msg.c_str()); + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } + } + ESP_FileSystem::releaseFS(); + } else { + hasError = true; + error_msg = "FS not available"; + esp3d_log_e("%s", error_msg.c_str()); + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } + } +} + +#endif // FILESYSTEM_FEATURE diff --git a/esp3d/src/core/commands/ESP730.cpp b/esp3d/src/core/commands/ESP730.cpp new file mode 100644 index 00000000..f0c7973c --- /dev/null +++ b/esp3d/src/core/commands/ESP730.cpp @@ -0,0 +1,116 @@ +/* + ESP730.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(FILESYSTEM_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/filesystem/esp_filesystem.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 730 +// Action on ESP Filesystem +// rmdir / remove / mkdir / exists / create +//[ESP730]= json= pwd= +void ESP3DCommands::ESP730(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; + const char* cmdList[] = {"rmdir=", "remove=", "mkdir=", "exists=", "create="}; + uint8_t cmdListSize = sizeof(cmdList) / sizeof(char*); +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + uint8_t i; + for (i = 0; i < cmdListSize && !hasError; i++) { + tmpstr = get_param(msg, cmd_params_pos, cmdList[i]); + if (tmpstr.length() != 0) { + break; + } + } + if (i >= cmdListSize || tmpstr.length() == 0) { + hasError = true; + } else { + if (ESP_FileSystem::accessFS()) { + switch (i) { + case 0: + if (!ESP_FileSystem::rmdir(tmpstr.c_str())) { + hasError = true; + error_msg = "rmdir failed"; + } + break; + case 1: + if (!ESP_FileSystem::remove(tmpstr.c_str())) { + hasError = true; + error_msg = "remove failed"; + } + break; + case 2: + if (!ESP_FileSystem::mkdir(tmpstr.c_str())) { + hasError = true; + error_msg = "mkdir failed"; + } + break; + case 3: + if (ESP_FileSystem::exists(tmpstr.c_str())) { + ok_msg = "yes"; + } else { + ok_msg = "no"; + } + break; + case 4: { + ESP_File f = ESP_FileSystem::open(tmpstr.c_str(), ESP_FILE_WRITE); + if (f.isOpen()) { + f.close(); + } else { + hasError = true; + error_msg = "creation failed"; + } + } break; + default: + hasError = true; + error_msg = "Invalid parameters"; + break; + } + ESP_FileSystem::releaseFS(); + } else { + hasError = true; + error_msg = "Flash not available"; + esp3d_log_e("%s", error_msg.c_str()); + } + } + + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // FILESYSTEM_FEATURE diff --git a/esp3d/src/core/commands/ESP740.cpp b/esp3d/src/core/commands/ESP740.cpp new file mode 100644 index 00000000..e6f8e6e6 --- /dev/null +++ b/esp3d/src/core/commands/ESP740.cpp @@ -0,0 +1,248 @@ +/* + ESP740.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(SD_DEVICE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/filesystem/esp_sd.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" +#include "../esp3d_string.h" + +#ifdef SD_TIMESTAMP_FEATURE +#include "../../modules/time/time_service.h" +#endif // SD_TIMESTAMP_FEATURE +#define COMMAND_ID 740 +// List SD Filesystem +//[ESP740] json= pwd= +void ESP3DCommands::ESP740(int cmd_params_pos, ESP3DMessage* msg) { + bool hasError = false; + String error_msg = "Path inccorrect"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; + // prepare answer msg + msg->target = msg->origin; + msg->origin = ESP3DClientType::command; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + + ESP3DMessage msgInfo; + ESP3DMessageManager::copyMsgInfos(&msgInfo, *msg); + tmpstr = get_clean_param(msg, cmd_params_pos); + + if (tmpstr.length() == 0) { + tmpstr = "/"; + } + + if (ESP_SD::accessFS()) { + if (ESP_SD::getState(true) == ESP_SDCARD_NOT_PRESENT) { + hasError = true; + error_msg = "No SD card"; + esp3d_log_e("%s", error_msg.c_str()); + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } + } else { + ESP_SD::setState(ESP_SDCARD_BUSY); + ESP_SDFile f; + f = ESP_SD::open(tmpstr.c_str(), ESP_FILE_READ); + if (f) { + if (json) { + ok_msg = "{\"cmd\":\"740\",\"status\":\"ok\",\"data\":{\"path\":\""; + ok_msg += tmpstr.c_str(); + ok_msg += "\",\"files\":["; + + } else { + ok_msg = "Directory on SD : "; + ok_msg += tmpstr.c_str(); + ok_msg += "\n"; + } + msg->type = ESP3DMessageType::head; + if (!dispatch(msg, ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + hasError = true; + } + if (ESP_SD::getState(true) == ESP_SDCARD_NOT_PRESENT) { + hasError = true; + error_msg = "No SD card"; + esp3d_log_e("%s", error_msg.c_str()); + } + if (!hasError) { + uint nbDirs = 0; + uint nbFiles = 0; + uint64_t totalSpace = ESP_SD::totalBytes(); + uint64_t usedSpace = ESP_SD::usedBytes(); + uint64_t freeSpace = ESP_SD::freeBytes(); + + ESP_SDFile sub; + sub = f.openNextFile(); + while (sub && !hasError) { + if (sub.isDirectory()) { + ok_msg = ""; + nbDirs++; + if (json) { + ok_msg = ""; + if (nbDirs > 1) { + ok_msg += ","; + } + ok_msg += "{\"name\":\""; + ok_msg += sub.name(); + ok_msg += "\",\"size\":\"-1\"}"; + } else { + ok_msg = "[DIR] \t"; + ok_msg += sub.name(); + } + if (!json) { + ok_msg += "\n"; + } + ESP3DMessage* newMsg = ESP3DMessageManager::copyMsgInfos(msgInfo); + if (newMsg) { + newMsg->type = ESP3DMessageType::core; + if (!dispatch(newMsg, ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + hasError = true; + } + } else { + esp3d_log_e("Error creating message"); + hasError = true; + } + } + sub.close(); + sub = f.openNextFile(); + } + f.close(); + f = ESP_SD::open(tmpstr.c_str(), ESP_FILE_READ); + // Check files + sub = f.openNextFile(); + while (sub && !hasError) { + if (!sub.isDirectory()) { + nbFiles++; + String time = ""; + ok_msg = ""; +#ifdef SD_TIMESTAMP_FEATURE + time = timeService.getDateTime((time_t)sub.getLastWrite()); +#endif // SD_TIMESTAMP_FEATURE + if (json) { + ok_msg = ""; + if (nbDirs > 0 || nbFiles > 1) { + ok_msg += ","; + } + ok_msg += "{\"name\":\""; + ok_msg += sub.name(); + ok_msg += "\",\"size\":\""; + ok_msg += esp3d_string::formatBytes(sub.size()); + if (time.length() > 0) { + ok_msg += "\",\"time\":\""; + ok_msg += time; + } + ok_msg += "\"}"; + } else { + ok_msg += " \t "; + ok_msg += sub.name(); + ok_msg += " \t"; + ok_msg += esp3d_string::formatBytes(sub.size()); + ok_msg += " \t"; + ok_msg += time; + } + if (!json) { + ok_msg += "\n"; + } + ESP3DMessage* newMsg = ESP3DMessageManager::copyMsgInfos(msgInfo); + if (newMsg) { + newMsg->type = ESP3DMessageType::core; + if (!dispatch(newMsg, ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + hasError = true; + } + } else { + esp3d_log_e("Error creating message"); + hasError = true; + } + } + sub.close(); + sub = f.openNextFile(); + } + // end of json + if (json) { + ok_msg = "], \"total\":\""; + ok_msg += esp3d_string::formatBytes(totalSpace); + ok_msg += "\",\"used\":\""; + ok_msg += esp3d_string::formatBytes(usedSpace); + ok_msg += "\",\"occupation\":\""; + if (totalSpace == 0) { + totalSpace = 1; + } + uint occupation = round(100.0 * usedSpace / totalSpace); + if ((occupation < 1) && (usedSpace > 0)) { + occupation = 1; + } + ok_msg += String(occupation); + ok_msg += "\"}}"; + + } else { + ok_msg = "Files: "; + ok_msg += String(nbFiles); + ok_msg += ", Dirs :"; + ok_msg += String(nbDirs); + ok_msg += "\nTotal: "; + ok_msg += esp3d_string::formatBytes(totalSpace); + ok_msg += ", Used: "; + ok_msg += esp3d_string::formatBytes(usedSpace); + ok_msg += ", Available: "; + ok_msg += esp3d_string::formatBytes(freeSpace); + ok_msg += "\n"; + } + + ESP3DMessage* newMsg = ESP3DMessageManager::copyMsgInfos(msgInfo); + newMsg->type = ESP3DMessageType::tail; + if (!dispatch(newMsg, ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } + f.close(); + } + } else { + hasError = true; + error_msg = "Invalid directory"; + esp3d_log_e("%s", error_msg.c_str()); + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } + } + } + ESP_SD::releaseFS(); + } else { + hasError = true; + error_msg = "FS not available"; + esp3d_log_e("%s", error_msg.c_str()); + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } + } +} + +#endif // SD_DEVICE diff --git a/esp3d/src/core/commands/ESP750.cpp b/esp3d/src/core/commands/ESP750.cpp new file mode 100644 index 00000000..f4fc127b --- /dev/null +++ b/esp3d/src/core/commands/ESP750.cpp @@ -0,0 +1,122 @@ +/* + ESP750.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(SD_DEVICE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/filesystem/esp_sd.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 750 +// Action on SD Filesystem +// rmdir / remove / mkdir / exists /create +//[ESP750]= json= pwd= +void ESP3DCommands::ESP750(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; + const char* cmdList[] = {"rmdir=", "remove=", "mkdir=", "exists=", "create="}; + uint8_t cmdListSize = sizeof(cmdList) / sizeof(char*); +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + uint8_t i; + for (i = 0; i < cmdListSize && !hasError; i++) { + tmpstr = get_param(msg, cmd_params_pos, cmdList[i]); + if (tmpstr.length() != 0) { + break; + } + } + if (i >= cmdListSize || tmpstr.length() == 0) { + hasError = true; + } else { + if (ESP_SD::accessFS()) { + if (ESP_SD::getState(true) == ESP_SDCARD_NOT_PRESENT) { + hasError = true; + error_msg = "No SD card"; + esp3d_log_e("%s", error_msg.c_str()); + } else { + switch (i) { + case 0: + if (!ESP_SD::rmdir(tmpstr.c_str())) { + hasError = true; + error_msg = "rmdir failed"; + } + break; + case 1: + if (!ESP_SD::remove(tmpstr.c_str())) { + hasError = true; + error_msg = "remove failed"; + } + break; + case 2: + if (!ESP_SD::mkdir(tmpstr.c_str())) { + hasError = true; + error_msg = "mkdir failed"; + } + break; + case 3: + if (ESP_SD::exists(tmpstr.c_str())) { + ok_msg = "yes"; + } else { + ok_msg = "no"; + } + break; + case 4: { + ESP_SDFile f = ESP_SD::open(tmpstr.c_str(), ESP_FILE_WRITE); + if (f.isOpen()) { + f.close(); + } else { + hasError = true; + error_msg = "creation failed"; + } + } break; + default: + hasError = true; + error_msg = "Invalid parameters"; + break; + } + } + ESP_SD::releaseFS(); + } else { + hasError = true; + error_msg = "Flash not available"; + esp3d_log_e("%s", error_msg.c_str()); + } + } + + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // SD_DEVICE diff --git a/esp3d/src/core/commands/ESP780.cpp b/esp3d/src/core/commands/ESP780.cpp new file mode 100644 index 00000000..a5273a63 --- /dev/null +++ b/esp3d/src/core/commands/ESP780.cpp @@ -0,0 +1,234 @@ +/* + ESP780.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(GLOBAL_FILESYSTEM_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/filesystem/esp_globalFS.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" +#include "../esp3d_string.h" + +#if defined(SD_TIMESTAMP_FEATURE) || defined(FILESYSTEM_TIMESTAMP_FEATURE) +#include "../../modules/time/time_service.h" +#endif // SD_TIMESTAMP_FEATURE || FILESYSTEM_TIMESTAMP_FEATURE +#define COMMAND_ID 780 +// List Global Filesystem +//[ESP780] json= pwd= +void ESP3DCommands::ESP780(int cmd_params_pos, ESP3DMessage* msg) { + bool hasError = false; + String error_msg = "Path inccorrect"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; + // prepare answer msg + msg->target = msg->origin; + msg->origin = ESP3DClientType::command; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + + ESP3DMessage msgInfo; + ESP3DMessageManager::copyMsgInfos(&msgInfo, *msg); + tmpstr = get_clean_param(msg, cmd_params_pos); + + if (tmpstr.length() == 0) { + tmpstr = "/"; + } + uint8_t fsType = ESP_GBFS::getFSType(tmpstr.c_str()); + + if (fsType != FS_UNKNOWN && ESP_GBFS::accessFS(fsType)) { + ESP_GBFile f; + f = ESP_GBFS::open(tmpstr.c_str(), ESP_FILE_READ); + if (f) { + if (json) { + ok_msg = "{\"cmd\":\"780\",\"status\":\"ok\",\"data\":{\"path\":\""; + ok_msg += tmpstr.c_str(); + ok_msg += "\",\"files\":["; + + } else { + ok_msg = "Directory on Global FS : "; + ok_msg += tmpstr.c_str(); + ok_msg += "\n"; + } + msg->type = ESP3DMessageType::head; + if (!dispatch(msg, ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + hasError = true; + } + + if (!hasError) { + uint nbDirs = 0; + uint nbFiles = 0; + size_t totalSpace = ESP_GBFS::totalBytes(); + size_t usedSpace = ESP_GBFS::usedBytes(); + size_t freeSpace = ESP_GBFS::freeBytes(); + + ESP_GBFile sub; + sub = f.openNextFile(); + while (sub && !hasError) { + if (sub.isDirectory()) { + ok_msg = ""; + nbDirs++; + if (json) { + ok_msg = ""; + if (nbDirs > 1) { + ok_msg += ","; + } + ok_msg += "{\"name\":\""; + ok_msg += sub.name(); + ok_msg += "\",\"size\":\"-1\"}"; + } else { + ok_msg = "[DIR] \t"; + ok_msg += sub.name(); + } + if (!json) { + ok_msg += "\n"; + } + ESP3DMessage* newMsg = ESP3DMessageManager::copyMsgInfos(msgInfo); + if (newMsg) { + newMsg->type = ESP3DMessageType::core; + if (!dispatch(newMsg, ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + hasError = true; + } + } else { + esp3d_log_e("Error creating message"); + hasError = true; + } + } + sub.close(); + sub = f.openNextFile(); + } + f.close(); + f = ESP_GBFS::open(tmpstr.c_str(), ESP_FILE_READ); + // Check files + sub = f.openNextFile(); + while (sub && !hasError) { + if (!sub.isDirectory()) { + nbFiles++; + String time = ""; + ok_msg = ""; +#ifdef FILESYSTEM_TIMESTAMP_FEATURE + time = timeService.getDateTime((time_t)sub.getLastWrite()); +#endif // FILESYSTEM_TIMESTAMP_FEATURE + if (json) { + ok_msg = ""; + if (nbDirs > 0 || nbFiles > 1) { + ok_msg += ","; + } + ok_msg += "{\"name\":\""; + ok_msg += sub.name(); + ok_msg += "\",\"size\":\""; + ok_msg += esp3d_string::formatBytes(sub.size()); + if (time.length() > 0) { + ok_msg += "\",\"time\":\""; + ok_msg += time; + } + ok_msg += "\"}"; + } else { + ok_msg += " \t "; + ok_msg += sub.name(); + ok_msg += " \t"; + ok_msg += esp3d_string::formatBytes(sub.size()); + ok_msg += " \t"; + ok_msg += time; + } + if (!json) { + ok_msg += "\n"; + } + ESP3DMessage* newMsg = ESP3DMessageManager::copyMsgInfos(msgInfo); + if (newMsg) { + newMsg->type = ESP3DMessageType::core; + if (!dispatch(newMsg, ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + hasError = true; + } + } else { + esp3d_log_e("Error creating message"); + hasError = true; + } + } + sub.close(); + sub = f.openNextFile(); + } + // end of json + if (json) { + ok_msg = "], \"total\":\""; + ok_msg += esp3d_string::formatBytes(totalSpace); + ok_msg += "\",\"used\":\""; + ok_msg += esp3d_string::formatBytes(usedSpace); + ok_msg += "\",\"occupation\":\""; + if (totalSpace == 0) { + totalSpace = 1; + } + uint occupation = round(100.0 * usedSpace / totalSpace); + if ((occupation < 1) && (usedSpace > 0)) { + occupation = 1; + } + ok_msg += String(occupation); + ok_msg += "\"}}"; + + } else { + ok_msg = "Files: "; + ok_msg += String(nbFiles); + ok_msg += ", Dirs :"; + ok_msg += String(nbDirs); + ok_msg += "\nTotal: "; + ok_msg += esp3d_string::formatBytes(totalSpace); + ok_msg += ", Used: "; + ok_msg += esp3d_string::formatBytes(usedSpace); + ok_msg += ", Available: "; + ok_msg += esp3d_string::formatBytes(freeSpace); + ok_msg += "\n"; + } + + ESP3DMessage* newMsg = ESP3DMessageManager::copyMsgInfos(msgInfo); + newMsg->type = ESP3DMessageType::tail; + if (!dispatch(newMsg, ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } + f.close(); + } + } else { + hasError = true; + error_msg = "Invalid directory"; + esp3d_log_e("%s", error_msg.c_str()); + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } + } + ESP_GBFS::releaseFS(fsType); + } else { + hasError = true; + error_msg = "FS not available"; + esp3d_log_e("%s", error_msg.c_str()); + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } + } +} + +#endif // GLOBAL_FILESYSTEM_FEATURE diff --git a/esp3d/src/core/commands/ESP790.cpp b/esp3d/src/core/commands/ESP790.cpp new file mode 100644 index 00000000..cc244650 --- /dev/null +++ b/esp3d/src/core/commands/ESP790.cpp @@ -0,0 +1,117 @@ +/* + ESP790.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(GLOBAL_FILESYSTEM_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/filesystem/esp_globalFS.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 790 +// Action on Global Filesystem +// rmdir / remove / mkdir / exists /create +//[ESP790]= json= pwd= +void ESP3DCommands::ESP790(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; + const char* cmdList[] = {"rmdir=", "remove=", "mkdir=", "exists=", "create="}; + uint8_t cmdListSize = sizeof(cmdList) / sizeof(char*); +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + uint8_t i; + for (i = 0; i < cmdListSize && !hasError; i++) { + tmpstr = get_param(msg, cmd_params_pos, cmdList[i]); + if (tmpstr.length() != 0) { + break; + } + } + if (i >= cmdListSize || tmpstr.length() == 0) { + hasError = true; + } else { + uint8_t fsType = ESP_GBFS::getFSType(tmpstr.c_str()); + if (fsType != FS_UNKNOWN && ESP_GBFS::accessFS(fsType)) { + switch (i) { + case 0: + if (!ESP_GBFS::rmdir(tmpstr.c_str())) { + hasError = true; + error_msg = "rmdir failed"; + } + break; + case 1: + if (!ESP_GBFS::remove(tmpstr.c_str())) { + hasError = true; + error_msg = "remove failed"; + } + break; + case 2: + if (!ESP_GBFS::mkdir(tmpstr.c_str())) { + hasError = true; + error_msg = "mkdir failed"; + } + break; + case 3: + if (ESP_GBFS::exists(tmpstr.c_str())) { + ok_msg = "yes"; + } else { + ok_msg = "no"; + } + break; + case 4: { + ESP_GBFile f = ESP_GBFS::open(tmpstr.c_str(), ESP_FILE_WRITE); + if (f.isOpen()) { + f.close(); + } else { + hasError = true; + error_msg = "creation failed"; + } + } break; + default: + hasError = true; + error_msg = "Invalid parameters"; + break; + } + + ESP_GBFS::releaseFS(fsType); + } else { + hasError = true; + error_msg = "FS not available"; + esp3d_log_e("%s", error_msg.c_str()); + } + } + + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} +#endif // GLOBAL_FILESYSTEM_FEATURE diff --git a/esp3d/src/core/commands/ESP800.cpp b/esp3d/src/core/commands/ESP800.cpp new file mode 100644 index 00000000..74c35f31 --- /dev/null +++ b/esp3d/src/core/commands/ESP800.cpp @@ -0,0 +1,299 @@ +/* + ESP800.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/network/netconfig.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#ifdef FILESYSTEM_FEATURE +#include "../../modules/filesystem/esp_filesystem.h" +#endif // FILESYSTEM_FEATURE +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BLUETOOTH_FEATURE) +#include "../../modules/network/netconfig.h" +#if defined(WIFI_FEATURE) +#include "../../modules/wifi/wificonfig.h" +#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 +#ifdef TIMESTAMP_FEATURE +#include "../../modules/time/time_service.h" +#endif // TIMESTAMP_FEATURE +#ifdef CAMERA_DEVICE +#include "../../modules/camera/camera.h" +#endif // CAMERA_DEVICE +#define COMMAND_ID 800 +// get fw capabilities +// eventually set time with pc time +// output is JSON or plain text according parameter +//[ESP800]json= +// +void ESP3DCommands::ESP800(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + msg->target = target; + msg->origin = ESP3DClientType::command; + String timestr = "none"; +#if defined(TIMESTAMP_FEATURE) + String timeparam = get_param(msg, cmd_params_pos, "time="); + String tzparam = get_param(msg, cmd_params_pos, "tz="); +#endif // TIMESTAMP_FEATURE + String setupparam = get_param(msg, cmd_params_pos, "setup="); + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE +#if defined(TIMESTAMP_FEATURE) + // set time if internet time is not enabled + if (!timeService.isInternetTime()) { + if (tzparam.length() > 0) { + if (!timeService.setTimeZone(tzparam.c_str())) { + // not blocking error + esp3d_log_e("Error setting timezone"); + timestr = "Failed to set timezone"; + } else { + timestr = "Manual"; + } + } else { + timestr = "Not set"; + } + if (timeparam.length() > 0) { + if (!timeService.setTime(timeparam.c_str())) { + // not blocking error + esp3d_log_e("Error setting time"); + timestr = "Failed to set time"; + } + } + } else { + if (timeService.started()) { + timestr = "Auto"; + } else { + timestr = "Failed to set"; + } + } +#else + timestr = "none"; +#endif // ESP3D_TIMESTAMP_FEATURE + if (setupparam.length() > 0) { + if (!ESP3DSettings::writeByte(ESP_SETUP, setupparam == "1" ? 1 : 0)) { + // not blocking error + esp3d_log_e("Error writing setup state"); + } + } + if (json) { + tmpstr = "{\"cmd\":\"800\",\"status\":\"ok\",\"data\":{"; + + } else { + tmpstr = "Capabilities:\n"; + } + msg->type = ESP3DMessageType::head; + if (!dispatch(msg, tmpstr.c_str())) { + esp3d_log_e("Error sending response to clients"); + return; + } + // list capabilities + tmpstr = ""; +#if defined(SHORT_BUILD_VERSION) + tmpstr += SHORT_BUILD_VERSION; + tmpstr += "-"; +#endif // SHORT_BUILD_VERSION + tmpstr += FW_VERSION; + // FW version + if (!dispatchKeyValue(json, "FWVersion", tmpstr.c_str(), target, requestId, + false, true)) { + return; + } + // FW Target + tmpstr = ESP3DSettings::GetFirmwareTargetShortName(); + if (!dispatchKeyValue(json, "FWTarget", tmpstr.c_str(), target, requestId)) { + return; + } + + // FW ID + tmpstr = ESP3DSettings::GetFirmwareTarget(); + if (!dispatchKeyValue(json, "FWTargetID", tmpstr.c_str(), target, + requestId)) { + return; + } + + // Setup done + tmpstr = ESP3DSettings::readByte(ESP_SETUP) == 0 ? "Enabled" : "Disabled"; + if (!dispatchKeyValue(json, "Setup", tmpstr.c_str(), target, requestId)) { + return; + } + + // SD connection + if (ESP3DSettings::GetSDDevice() == ESP_DIRECT_SD) { + tmpstr = "direct"; + } else if (ESP3DSettings::GetSDDevice() == ESP_SHARED_SD) { + tmpstr = "shared"; + } else { + tmpstr = "none"; + } + if (!dispatchKeyValue(json, "SDConnection", tmpstr.c_str(), target, + requestId)) { + return; + } + + // Serial protocol +#if COMMUNICATION_PROTOCOL == MKS_SERIAL + tmpstr = "MKS"; +#endif // COMMUNICATION_PROTOCOL == MKS_SERIAL +#if COMMUNICATION_PROTOCOL == RAW_SERIAL + tmpstr = "Raw"; +#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL +#if COMMUNICATION_PROTOCOL == SOCKET_SERIAL + tmpstr = "Socket"; +#endif // COMMUNICATION_PROTOCOL == SOCKET_SERIAL + if (!dispatchKeyValue(json, "SerialProtocol", tmpstr.c_str(), target, + requestId)) { + return; + } + + // Authentication +#if defined(AUTHENTICATION_FEATURE) + tmpstr = "Enabled"; +#else + tmpstr = "Disabled"; +#endif // AUTHENTICATION_FEATURE + if (!dispatchKeyValue(json, "Authentication", tmpstr.c_str(), target, + requestId)) { + return; + } + + // Web Communication +#if (defined(WIFI_FEATURE) || defined(ETH_FEATURE)) && defined(HTTP_FEATURE) +#if defined(ASYNCWEBSERVER_FEATURE) + tmpstr = "Asynchronous"; +#else + tmpstr = "Synchronous"; +#endif // ASYNCWEBSERVER_FEATURE + if (!dispatchKeyValue(json, "WebCommunication", tmpstr.c_str(), target, + requestId)) { + return; + } + // WebSocket IP + tmpstr = NetConfig::localIP().c_str(); + if (!dispatchKeyValue(json, "WebSocketIP", tmpstr.c_str(), target, + requestId)) { + return; + } + // WebSocket Port +#if defined(ASYNCWEBSERVER_FEATURE) + tmpstr = HTTP_Server::port(); +#else + tmpstr = websocket_terminal_server.getPort(); +#endif // ASYNCWEBSERVER_FEATURE + if (!dispatchKeyValue(json, "WebSocketPort", tmpstr.c_str(), target, + requestId)) { + return; + } +#endif // (WIFI_FEATURE) || ETH_FEATURE) && HTTP_FEATURE) +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BT_FEATURE) + // Hostname + tmpstr = NetConfig::hostname(); + if (!dispatchKeyValue(json, "Hostname", tmpstr.c_str(), target, requestId)) { + return; + } +#endif // WIFI_FEATURE|| ETH_FEATURE || BT_FEATURE +#if defined(WIFI_FEATURE) + if (WiFiConfig::started()) { + // WiFi mode + tmpstr = (WiFi.getMode() == WIFI_AP) ? "AP" : "STA"; + if (!dispatchKeyValue(json, "WiFiMode", tmpstr.c_str(), target, + requestId)) { + return; + } + } +#endif // WIFI_FEATURE +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) +// Update +#if defined(WEB_UPDATE_FEATURE) + if (ESP_FileSystem::max_update_size() != 0) { + tmpstr = "Enabled"; + } else { + tmpstr = "Disabled"; + } +#else + tmpstr = "Disabled"; +#endif // WEB_UPDATE_FEATURE + if (!dispatchKeyValue(json, "WebUpdate", tmpstr.c_str(), target, requestId)) { + return; + } +#endif // WIFI_FEATURE|| ETH_FEATURE + // FS +#if defined(FILESYSTEM_FEATURE) + tmpstr = ESP_FileSystem::FilesystemName(); +#else + tmpstr = "none"; +#endif // FILESYSTEM_FEATURE + if (!dispatchKeyValue(json, "FlashFileSystem", tmpstr.c_str(), target, + requestId)) { + return; + } + // Host path + tmpstr = ESP3D_HOST_PATH; + if (!dispatchKeyValue(json, "HostPath", tmpstr.c_str(), target, requestId)) { + return; + } + // time server +#if defined(TIMESTAMP_FEATURE) + tmpstr = timestr; +#else + tmpstr = "none"; +#endif // TIMESTAMP_FEATURE + if (!dispatchKeyValue(json, "Time", tmpstr.c_str(), target, requestId)) { + return; + } + +#ifdef CAMERA_DEVICE + // camera ID + tmpstr = esp3d_camera.GetModel(); + if (!dispatchKeyValue(json, "CameraID", tmpstr.c_str(), target, requestId)) { + return; + } + // camera Name + tmpstr = esp3d_camera.GetModelString(); + if (!dispatchKeyValue(json, "CameraName", tmpstr.c_str(), target, + requestId)) { + return; + } +#endif // CAMERA_DEVICE + + // end of list + if (json) { + if (!dispatch("}}", target, requestId, ESP3DMessageType::tail)) { + esp3d_log_e("Error sending answer to clients"); + } + } else { + { + if (!dispatch("ok\n", target, requestId, ESP3DMessageType::tail)) { + esp3d_log_e("Error sending answer to clients"); + } + } + } +} diff --git a/esp3d/src/core/commands/ESP900.cpp b/esp3d/src/core/commands/ESP900.cpp new file mode 100644 index 00000000..9cd45ed2 --- /dev/null +++ b/esp3d/src/core/commands/ESP900.cpp @@ -0,0 +1,79 @@ +/* + ESP900.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if COMMUNICATION_PROTOCOL != SOCKET_SERIAL +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/serial/serial_service.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 900 +// Get state / Set Enable / Disable Serial Communication +//[ESP900] json= [pwd=] +void ESP3DCommands::ESP900(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + bool enabled = hasTag(msg, cmd_params_pos, "ENABLE"); + bool disabled = hasTag(msg, cmd_params_pos, "DISABLE"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + if (esp3d_serial_service.started()) { + ok_msg = "ENABLED"; + } else { + ok_msg = "DISABLED"; + } + ok_msg += " - Serial" + String(esp3d_serial_service.serialIndex()); + } else { + if (enabled || disabled) { + if (enabled) { + if (!esp3d_serial_service.begin(ESP_SERIAL_OUTPUT)) { + hasError = true; + error_msg = "Cannot enable serial communication"; + } + } else { + esp3d_serial_service.end(); + } + } else { + hasError = true; + error_msg = "Invalid parameters"; + esp3d_log_e("%s", error_msg.c_str()); + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} +#endif \ No newline at end of file diff --git a/esp3d/src/core/commands/ESP901.cpp b/esp3d/src/core/commands/ESP901.cpp new file mode 100644 index 00000000..21fb4a6c --- /dev/null +++ b/esp3d/src/core/commands/ESP901.cpp @@ -0,0 +1,86 @@ +/* + ESP901.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if COMMUNICATION_PROTOCOL != SOCKET_SERIAL +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/serial/serial_service.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 901 +// Set Serial baudrate +//[ESP901] json= pwd= +void ESP3DCommands::ESP901(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + const ESP3DSettingDescription* settingPtr = + ESP3DSettings::getSettingPtr(ESP_BAUD_RATE); + if (settingPtr) { + ok_msg = String(ESP3DSettings::readUint32(ESP_BAUD_RATE)); + } else { + hasError = true; + error_msg = "This setting is unknown"; + } + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + esp3d_log( + "got %s param for a value of %s, is valid %d", tmpstr.c_str(), + tmpstr.c_str(), + ESP3DSettings::isValidIntegerSetting(tmpstr.toInt(), ESP_BAUD_RATE)); + if (ESP3DSettings::isValidIntegerSetting(tmpstr.toInt(), ESP_BAUD_RATE)) { + esp3d_log("Value %s is valid", tmpstr.c_str()); + if (!ESP3DSettings::writeUint32(ESP_BAUD_RATE, tmpstr.toInt())) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid parameter"; + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // COMMUNICATION_PROTOCOL != SOCKET_SERIAL diff --git a/esp3d/src/core/commands/ESP910.cpp b/esp3d/src/core/commands/ESP910.cpp new file mode 100644 index 00000000..0bcbac94 --- /dev/null +++ b/esp3d/src/core/commands/ESP910.cpp @@ -0,0 +1,79 @@ +/* + ESP910.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(BUZZER_DEVICE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/buzzer/buzzer.h" +#include "../esp3d_commands.h" +#include "../esp3d_message.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 910 +// Get state / Set Enable / Disable buzzer +//[ESP910][pwd=] +void ESP3DCommands::ESP910(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + bool enabled = hasTag(msg, cmd_params_pos, "ENABLE"); + bool disabled = hasTag(msg, cmd_params_pos, "DISABLE"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + if (esp3d_buzzer.started()) { + ok_msg = "ENABLED"; + } else { + ok_msg = "DISABLED"; + } + } else { + if (enabled || disabled) { + if (enabled) { + if (!esp3d_buzzer.begin()) { + hasError = true; + error_msg = "Cannot enable buzzer"; + } + } else { + esp3d_buzzer.end(); + } + } else { + hasError = true; + error_msg = "Invalid parameters"; + esp3d_log_e("%s", error_msg.c_str()); + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} +#endif // BUZZER_DEVICE diff --git a/esp3d/src/core/commands/ESP930.cpp b/esp3d/src/core/commands/ESP930.cpp new file mode 100644 index 00000000..eaf07312 --- /dev/null +++ b/esp3d/src/core/commands/ESP930.cpp @@ -0,0 +1,95 @@ +/* + ESP930.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(ESP_SERIAL_BRIDGE_OUTPUT) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/serial/serial_service.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 930 +// Set Bridge Serial state which can be ON, OFF, CLOSE +//[ESP930] json= pwd= +void ESP3DCommands::ESP930(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + bool enabled = hasTag(msg, cmd_params_pos, "ENABLE"); + bool disabled = hasTag(msg, cmd_params_pos, "DISABLE"); + bool close = hasTag(msg, cmd_params_pos, "CLOSE"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + if (ESP3DSettings::readByte(ESP_SERIAL_BRIDGE_ON) == 1) { + ok_msg = "ENABLED"; + } else { + ok_msg = "DISABLED"; + } + ok_msg += " - Serial" + String(serial_bridge_service.serialIndex()); + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + if (enabled || disabled || close) { + if (disabled || enabled) { + if (!ESP3DSettings::writeByte(ESP_SERIAL_BRIDGE_ON, + (enabled) ? 1 : 0)) { + hasError = true; + error_msg = "Set failed"; + } + } + if (enabled && !serial_bridge_service.started()) { + if (!serial_bridge_service.begin(ESP_SERIAL_BRIDGE_OUTPUT)) { + hasError = true; + error_msg = "Cannot enable serial bridge communication"; + } + } + if (close) { + serial_bridge_service.end(); + } + } else { + hasError = true; + error_msg = "Invalid parameters"; + esp3d_log_e("%s", error_msg.c_str()); + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // TELNET_FEATURE diff --git a/esp3d/src/core/commands/ESP931.cpp b/esp3d/src/core/commands/ESP931.cpp new file mode 100644 index 00000000..043cb729 --- /dev/null +++ b/esp3d/src/core/commands/ESP931.cpp @@ -0,0 +1,87 @@ +/* + ESP931.cpp - ESP3D command 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 +*/ +#include "../../include/esp3d_config.h" +#if defined(ESP_SERIAL_BRIDGE_OUTPUT) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/serial/serial_service.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" + +#define COMMAND_ID 931 +// Set Serial bridge baudrate +//[ESP931] json= pwd= +void ESP3DCommands::ESP931(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == ESP3DAuthenticationLevel::guest) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + const ESP3DSettingDescription* settingPtr = + ESP3DSettings::getSettingPtr(ESP_SERIAL_BRIDGE_BAUD); + if (settingPtr) { + ok_msg = String(ESP3DSettings::readUint32(ESP_SERIAL_BRIDGE_BAUD)); + } else { + hasError = true; + error_msg = "This setting is unknown"; + } + } else { +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; + } +#endif // AUTHENTICATION_FEATURE + esp3d_log("got %s param for a value of %s, is valid %d", tmpstr.c_str(), + tmpstr.c_str(), + ESP3DSettings::isValidIntegerSetting(tmpstr.toInt(), + ESP_SERIAL_BRIDGE_BAUD)); + if (ESP3DSettings::isValidIntegerSetting(tmpstr.toInt(), + ESP_SERIAL_BRIDGE_BAUD)) { + esp3d_log("Value %s is valid", tmpstr.c_str()); + if (!ESP3DSettings::writeUint32(ESP_SERIAL_BRIDGE_BAUD, tmpstr.toInt())) { + hasError = true; + error_msg = "Set value failed"; + } + } else { + hasError = true; + error_msg = "Invalid parameter"; + } + } + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } +} + +#endif // ESP_SERIAL_BRIDGE_OUTPUT diff --git a/esp3d/src/core/espcmd/ESP999.cpp b/esp3d/src/core/commands/ESP999.cpp similarity index 51% rename from esp3d/src/core/espcmd/ESP999.cpp rename to esp3d/src/core/commands/ESP999.cpp index 45516224..59e54091 100644 --- a/esp3d/src/core/espcmd/ESP999.cpp +++ b/esp3d/src/core/commands/ESP999.cpp @@ -19,63 +19,54 @@ */ #include "../../include/esp3d_config.h" #include "../../modules/authentication/authentication_service.h" -#include "../commands.h" -#include "../esp3doutput.h" -#include "../settings_esp3d.h" +#include "../esp3d_commands.h" +#include "../esp3d_settings.h" #if defined(ARDUINO_ARCH_ESP32) && \ (CONFIG_IDF_TARGET_ESP32S3 || CONFIG_IDF_TARGET_ESP32S2 || \ CONFIG_IDF_TARGET_ESP32C3) #include -#define COMMANDID 999 +#define COMMAND_ID 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 -#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; +void ESP3DCommands::ESP999(int cmd_params_pos, ESP3DMessage* msg) { + ESP3DClientType target = msg->origin; + ESP3DRequest requestId = msg->request_id; + (void)requestId; + msg->target = target; + msg->origin = ESP3DClientType::command; + bool hasError = false; + String error_msg = "Invalid parameters"; + String ok_msg = "ok"; + bool json = hasTag(msg, cmd_params_pos, "json"); + bool quietboot = hasTag(msg, cmd_params_pos, "QUIETBOOT"); + String tmpstr; +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level != ESP3DAuthenticationLevel::admin) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + dispatchAuthenticationError(msg, COMMAND_ID, json); + return; } -#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 + tmpstr = get_clean_param(msg, cmd_params_pos); + if (tmpstr.length() == 0) { + hasError = true; + error_msg = "Missing parameter" + } else { + if (quietboot) { 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"); + hasError = true; + error_msg = "Set failed(May be already set?)"; } - } - } - if (json) { - output->printLN(response.c_str()); - } else { - if (noError) { - output->printMSG(response.c_str()); } else { - output->printERROR(response.c_str(), errorCode); + hasError = true; } } - return noError; + if (!dispatchAnswer(msg, COMMAND_ID, json, hasError, + hasError ? error_msg.c_str() : ok_msg.c_str())) { + esp3d_log_e("Error sending response to clients"); + } } #endif // defined(ARDUINO_ARCH_ESP32) && (CONFIG_IDF_TARGET_ESP32S3 || diff --git a/esp3d/src/core/esp3d.cpp b/esp3d/src/core/esp3d.cpp index 86bdb324..e19b0016 100644 --- a/esp3d/src/core/esp3d.cpp +++ b/esp3d/src/core/esp3d.cpp @@ -27,7 +27,7 @@ #include "esp3d.h" #include "../include/esp3d_config.h" -#include "settings_esp3d.h" +#include "esp3d_settings.h" #if COMMUNICATION_PROTOCOL != SOCKET_SERIAL || ESP_SERIAL_BRIDGE_OUTPUT #include "../modules/serial/serial_service.h" @@ -57,7 +57,7 @@ #include "../modules/update/update_service.h" #endif // SD_UPDATE_FEATURE #include "../modules/boot_delay/boot_delay.h" -#include "esp3doutput.h" +#include "esp3d_message.h" bool Esp3D::restart = false; @@ -70,17 +70,16 @@ Esp3D::~Esp3D() { end(); } // Begin which setup everything bool Esp3D::begin() { BootDelay bd; - Hal::begin(); - LOG_ESP3D_INIT + ESP3DHal::begin(); + ESP3D_LOG_INIT_FN #if COMMUNICATION_PROTOCOL == SOCKET_SERIAL Serial2Socket.enable(); #endif // COMMUNICATION_PROTOCOL == SOCKET_SERIAL - // init output - ESP3DOutput::isOutput(ESP_ALL_CLIENTS, true); bool res = true; #if defined(CONNECTED_DEVICES_FEATURE) + esp3d_log("Starting Devices feature"); if (!DevicesServices::begin()) { - log_esp3d_e("Error setup connected devices"); + esp3d_log_e("Error setup connected devices"); res = false; } #endif // CONNECTED_DEVICES_FEATURE @@ -88,14 +87,14 @@ bool Esp3D::begin() { bd.begin(); #ifdef SD_UPDATE_FEATURE if (update_service.begin()) { - log_esp3d("Need restart due to update"); + esp3d_log("Need restart due to update"); // no need to continue as there was an update restart_now(); } #endif // SD_UPDATE_FEATURE - log_esp3d("Mode %d", WiFi.getMode()); - if (!Settings_ESP3D::begin()) { - log_esp3d("Need reset settings"); + esp3d_log("Mode %d", WiFi.getMode()); + if (!ESP3DSettings::begin()) { + esp3d_log("Need reset settings"); reset(); // Restart ESP3D restart_now(); @@ -103,8 +102,8 @@ bool Esp3D::begin() { // BT do not start automaticaly so should be OK #if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL // Serial service - if (!serial_service.begin(ESP_SERIAL_OUTPUT)) { - log_esp3d_e("Error with serial service"); + if (!esp3d_serial_service.begin(ESP_SERIAL_OUTPUT)) { + esp3d_log_e("Error with serial service"); res = false; } #endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == @@ -112,26 +111,28 @@ bool Esp3D::begin() { // Serial bridge #if defined(ESP_SERIAL_BRIDGE_OUTPUT) if (!serial_bridge_service.begin(ESP_SERIAL_BRIDGE_OUTPUT)) { - log_esp3d_e("Error with serial bridge service"); + esp3d_log_e("Error with serial bridge service"); res = false; } #endif // ESP_SERIAL_BRIDGE_OUTPUT // Setup Filesystem #if defined(FILESYSTEM_FEATURE) + esp3d_log("Starting Filesystem feature"); if (!ESP_FileSystem::begin()) { - log_esp3d_e("Error with filesystem service"); + esp3d_log_e("Error with filesystem service"); res = false; } #endif // FILESYSTEM_FEATURE #ifdef DISPLAY_DEVICE esp3d_display.showScreenID(MAIN_SCREEN); - log_esp3d("Main screen"); + esp3d_log("Main screen"); #endif // DISPLAY_DEVICE // Setup Network #if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BLUETOOTH_FEATURE) - if (Settings_ESP3D::read_byte(ESP_BOOT_RADIO_STATE) == 1) { + esp3d_log("Starting Netconfig feature"); + if (ESP3DSettings::readByte(ESP_BOOT_RADIO_STATE) == 1) { if (!NetConfig::begin()) { - log_esp3d_e("Error setup network"); + esp3d_log_e("Error setup network"); res = false; } } @@ -145,6 +146,7 @@ bool Esp3D::begin() { esp3d_gcode_host.processFile(ESP_AUTOSTART_SCRIPT_FILE); #endif // ESP_AUTOSTART_FEATURE #endif // GCODE_HOST_FEATURE + esp3d_log("Esp3d Started"); _started = true; return res; } @@ -159,7 +161,7 @@ void Esp3D::handle() { restart_now(); } #if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - serial_service.handle(); + esp3d_serial_service.handle(); #endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == // MKS_SERIAL #if defined(ESP_SERIAL_BRIDGE_OUTPUT) @@ -197,7 +199,7 @@ bool Esp3D::end() { ESP_FileSystem::end(); #endif // FILESYSTEM_FEATURE #if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - serial_service.end(); + esp3d_serial_service.end(); #endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == // MKS_SERIAL return true; @@ -207,20 +209,20 @@ bool Esp3D::end() { bool Esp3D::reset() { bool resetOk = true; #if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - if (!serial_service.reset()) { + if (!esp3d_serial_service.reset()) { resetOk = false; - log_esp3d_e("Reset serial error"); + esp3d_log_e("Reset serial error"); } #endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == // MKS_SERIAL #if defined(ESP_SERIAL_BRIDGE_OUTPUT) if (!serial_bridge_service.reset()) { resetOk = false; - log_esp3d_e("Reset serial bridge error"); + esp3d_log_e("Reset serial bridge error"); } #endif // ESP_SERIAL_BRIDGE_OUTPUT - if (!Settings_ESP3D::reset()) { - log_esp3d_e("Reset settings error"); + if (!ESP3DSettings::reset()) { + esp3d_log_e("Reset settings error"); resetOk = false; } return resetOk; @@ -235,19 +237,19 @@ void Esp3D::restart_now() { #if defined(ETH_FEATURE) && defined(ESP3D_ETH_PHY_POWER_PIN) digitalWrite(ESP3D_ETH_PHY_POWER_PIN, LOW); #endif // ESP3D_ETH_PHY_POWER_PIN - log_esp3d("Restarting"); + esp3d_log("Restarting"); #if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - if (!serial_service.started()) { - serial_service.begin(ESP_SERIAL_OUTPUT); + if (!esp3d_serial_service.started()) { + esp3d_serial_service.begin(ESP_SERIAL_OUTPUT); } - serial_service.flush(); + esp3d_serial_service.flush(); #endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == // MKS_SERIAL #if defined(FILESYSTEM_FEATURE) ESP_FileSystem::end(); #endif // FILESYSTEM_FEATURE #if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - serial_service.swap(); + esp3d_serial_service.swap(); #endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == // MKS_SERIAL ESP.restart(); diff --git a/esp3d/src/core/benchmark.cpp b/esp3d/src/core/esp3d_benchmark.cpp similarity index 98% rename from esp3d/src/core/benchmark.cpp rename to esp3d/src/core/esp3d_benchmark.cpp index 885be153..303991fe 100644 --- a/esp3d/src/core/benchmark.cpp +++ b/esp3d/src/core/esp3d_benchmark.cpp @@ -20,7 +20,7 @@ #include "../include/esp3d_config.h" #if defined(ESP_BENCHMARK_FEATURE) -#include "benchmark.h" +#include "esp3d_benchmark.h" #include "../modules/websocket/websocket_server.h" void report_esp3d(const char * format, ...) { diff --git a/esp3d/src/core/benchmark.h b/esp3d/src/core/esp3d_benchmark.h similarity index 100% rename from esp3d/src/core/benchmark.h rename to esp3d/src/core/esp3d_benchmark.h diff --git a/esp3d/src/core/esp3d_client_types.h b/esp3d/src/core/esp3d_client_types.h new file mode 100644 index 00000000..b253ebc8 --- /dev/null +++ b/esp3d/src/core/esp3d_client_types.h @@ -0,0 +1,52 @@ +/* + esp3d_client_types + + Copyright (c) 2022 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 library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +enum class ESP3DClientType : uint8_t { + no_client = 0, + serial = 1, + usb_serial = 2, + stream = 3, + telnet = 4, + http = 5, + webui_websocket = 6, + websocket = 7, + rendering = 8, // Target only (same as esp_screen) + bluetooth = 9, + socket_serial = 10, + echo_serial = 11, // target only + serial_bridge = 12, + remote_screen = 13, // target only = M117 + mks_serial = 14, + command, // origin only + system, // origin only + all_clients +}; + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/esp3d/src/core/esp3d_commands.cpp b/esp3d/src/core/esp3d_commands.cpp new file mode 100644 index 00000000..bf032222 --- /dev/null +++ b/esp3d/src/core/esp3d_commands.cpp @@ -0,0 +1,1541 @@ +/* + commands.cpp - ESP3D commands 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 +*/ +// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 +#include "esp3d_commands.h" + +#include "../include/esp3d_config.h" +#include "esp3d.h" +#include "esp3d_settings.h" + +#if defined(ESP_LOG_FEATURE) +const char * esp3dclientstr[]={ + "no_client", + "serial", + "usb_serial", + "stream", + "telnet", + "http", + "webui_websocket", + "websocket", + "rendering", + "bluetooth", + "socket_serial", + "echo_serial", + "serial_bridge", + "remote_screen", + "mks_serial", + "command", + "system", + "all_clients" +}; +#define GETCLIENTSTR(id) static_cast(id)>=0 && static_cast(id)<=static_cast(ESP3DClientType::all_clients)?esp3dclientstr[static_cast(id)] :"Out of index" + +const char * esp3dmsgstr[] = { + "head", "core", "tail", "unique" +}; +#define GETMSGTYPESTR(id) static_cast(id)>=0 && static_cast(id)<=static_cast(ESP3DMessageType::unique)?esp3dmsgstr[static_cast(id)] :"Out of index" + +#endif // defined(ESP_LOG_FEATURE) + + +#if COMMUNICATION_PROTOCOL == MKS_SERIAL +#include "../modules/mks/mks_service.h" +#endif // COMMUNICATION_PROTOCOL == MKS_SERIAL + +#include "../modules/serial/serial_service.h" + +#if defined(TELNET_FEATURE) +#include "../modules/telnet/telnet_server.h" +#endif // TELNET_FEATURE + +#if defined(HTTP_FEATURE) || defined(WS_DATA_FEATURE) +#include "../modules/websocket/websocket_server.h" +#endif // HTTP_FEATURE || WS_DATA_FEATURE + +#if defined(HTTP_FEATURE) +#include "../modules/http/http_server.h" +#endif // HTTP_FEATURE + +#ifdef BLUETOOTH_FEATURE +#include "../modules/bluetooth/BT_service.h" +#endif // BLUETOOTH_FEATURE + +#if defined(ESP3DLIB_ENV) && COMMUNICATION_PROTOCOL == SOCKET_SERIAL +#include "../modules/serial2socket/serial2socket.h" +#endif // defined(ESP3DLIB_ENV) && COMMUNICATION_PROTOCOL == SOCKET_SERIAL + +#if defined(DISPLAY_DEVICE) +#include "../modules/display/display.h" +#endif // DISPLAY_DEVICE + +ESP3DCommands esp3d_commands; + +ESP3DCommands::ESP3DCommands() { +#if COMMUNICATION_PROTOCOL == RAW_SERIAL + _output_client = ESP3DClientType::serial; +#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL +#if COMMUNICATION_PROTOCOL == MKS_SERIAL + _output_client = ESP3DClientType::mks_serial; +#endif // COMMUNICATION_PROTOCOL == MKS_SERIAL +#if COMMUNICATION_PROTOCOL == SOCKET_SERIAL + _output_client = ESP3DClientType::socket_serial; +#endif // +} + +ESP3DCommands::~ESP3DCommands() {} + +bool ESP3DCommands::isRealTimeCommand(char *cmd, size_t len) { return false; } + +// check if current line is an [ESPXXX] command +bool ESP3DCommands::is_esp_command(uint8_t *sbuf, size_t len) { + // TODO + // M117 should be handled here and transfered to [ESP214] if it is an host + if (len < 5) { + return false; + } + if ((char(sbuf[0]) == '[') && (char(sbuf[1]) == 'E') && + (char(sbuf[2]) == 'S') && (char(sbuf[3]) == 'P') && + ((char(sbuf[4]) == ']') || (char(sbuf[5]) == ']') || + (char(sbuf[6]) == ']') || (char(sbuf[7]) == ']'))) { + return true; + } + // echo command header on some targeted firmware + if (len >= 14) { + if ((char(sbuf[0]) == 'e') && (char(sbuf[1]) == 'c') && + (char(sbuf[2]) == 'h') && (char(sbuf[3]) == 'o') && + (char(sbuf[4]) == ':') && (char(sbuf[5]) == ' ') && + (char(sbuf[6]) == '[') && (char(sbuf[7]) == 'E') && + (char(sbuf[8]) == 'S') && (char(sbuf[9]) == 'P') && + ((char(sbuf[4]) == ']') || (char(sbuf[5]) == ']') || + (char(sbuf[6]) == ']') || (char(sbuf[7]) == ']'))) { + return true; + } + } + return false; +} + +const char *ESP3DCommands::format_response(uint cmdID, bool isjson, bool isok, + const char *message) { + static String res; + res = ""; + if (!isjson) { + res += message; + } else { + res = "{\"cmd\":\""; + res += String(cmdID); + res += "\",\"status\":\""; + if (isok) { + res += "ok"; + } else { + res += "error"; + } + res += "\",\"data\":"; + if (message[0] != '{') { + res += "\""; + } + res += message; + if (message[0] != '{') { + res += "\""; + } + res += "}"; + } + return res.c_str(); +} + +bool ESP3DCommands::hasTag(ESP3DMessage *msg, uint start, const char *label) { + if (!msg) { + esp3d_log_e("no msg for tag %s", label); + return false; + } + String lbl = label; + // esp3d_log("checking message for tag %s", label); + uint lenLabel = strlen(label); + lbl += "="; + lbl = get_param(msg, start, lbl.c_str()); + if (lbl.length() != 0) { + // esp3d_log("Label is used with parameter %s", lbl.c_str()); + // make result uppercase + lbl.toUpperCase(); + return (lbl == "YES" || lbl == "1" || lbl == "TRUE"); + } + bool prevCharIsEscaped = false; + bool prevCharIsspace = true; + // esp3d_log("Checking label as tag"); + for (uint i = start; i < msg->size; i++) { + char c = char(msg->data[i]); + // esp3d_log("%c", c); + if (c == label[0] && prevCharIsspace) { + uint p = 0; + while (i < msg->size && p < lenLabel && c == label[p]) { + i++; + p++; + if (i < msg->size) { + c = char(msg->data[i]); + // esp3d_log("%c vs %c", c, char(msg->data[i])); + } + } + if (p == lenLabel) { + // end of params + if (i == msg->size || std::isspace(c)) { + // esp3d_log("label %s found", label); + return true; + } + } + if (std::isspace(c) && !prevCharIsEscaped) { + prevCharIsspace = true; + } + if (c == '\\') { + prevCharIsEscaped = true; + } else { + prevCharIsEscaped = false; + } + } + } + // esp3d_log("label %s not found", label); + return false; +} + +const char *ESP3DCommands::get_param(ESP3DMessage *msg, uint start, + const char *label, bool *found) { + if (!msg) { + esp3d_log_e("no message"); + return ""; + } + return get_param((const char *)msg->data, msg->size, start, label, found); +} + +const char *ESP3DCommands::get_param(const char *data, uint size, uint start, + const char *label, bool *found) { + esp3d_log("get_param %s", label); + int startPos = -1; + uint lenLabel = strlen(label); + static String value; + bool prevCharIsEscaped = false; + bool prevCharIsspace = true; + value = ""; + uint startp = start; + if (found) { + *found = false; + } + while (char(data[startp]) == ' ' && startp < size) { + startp++; + } + for (uint i = startp; i < size; i++) { + char c = char(data[i]); + if (c == label[0] && startPos == -1 && prevCharIsspace) { + uint p = 0; + while (i < size && p < lenLabel && c == label[p]) { + i++; + p++; + if (i < size) { + c = char(data[i]); + } + } + if (p == lenLabel) { + startPos = i; + if (found) { + *found = true; + } + } + } + if (std::isspace(c) && !prevCharIsEscaped) { + prevCharIsspace = true; + } + if (startPos > -1 && i < size) { + if (c == '\\') { + prevCharIsEscaped = true; + } + if (std::isspace(c) && !prevCharIsEscaped) { + return value.c_str(); + } + + if (c != '\\') { + value += c; + prevCharIsEscaped = false; + } + } + } + esp3d_log("found *%s*", value.c_str()); + return value.c_str(); +} + +const char *ESP3DCommands::get_clean_param(ESP3DMessage *msg, uint start) { + if (!msg) { + esp3d_log_e("no message"); + return ""; + } + static String value; + bool prevCharIsEscaped = false; + uint startp = start; + while (char(msg->data[startp]) == ' ' && startp < msg->size) { + startp++; + } + value = ""; + for (uint i = startp; i < msg->size; i++) { + char c = char(msg->data[i]); + if (c == '\\') { + prevCharIsEscaped = true; + } + if (std::isspace(c) && !prevCharIsEscaped) { + esp3d_log("testing *%s*", value.c_str()); + if (value == "json" || value.startsWith("json=") || + value.startsWith("pwd=")) { + esp3d_log("clearing *%s*", value.c_str()); + value = ""; + } else { + esp3d_log("returning *%s*", value.c_str()); + return value.c_str(); + } + } + if (c != '\\') { + if ((std::isspace(c) && prevCharIsEscaped) || !std::isspace(c)) { + value += c; + } + prevCharIsEscaped = false; + } + } + esp3d_log("testing *%s*", value.c_str()); + // for empty value + if (value == "json" || value.startsWith("json=") || + value.startsWith("pwd=")) { + esp3d_log("clearing *%s*", value.c_str()); + value = ""; + } + esp3d_log("returning *%s*", value.c_str()); + return value.c_str(); +} + +bool ESP3DCommands::has_param(ESP3DMessage *msg, uint start) { + return strlen(get_clean_param(msg, start)) != 0; +} + +void ESP3DCommands::execute_internal_command(int cmd, int cmd_params_pos, + ESP3DMessage *msg) { + if (!msg) { + esp3d_log_e("no msg for cmd %d", cmd); + return; + } +#ifdef AUTHENTICATION_FEATURE + String pwd = get_param(msg, cmd_params_pos, "pwd="); + if (pwd.length() != 0 && (msg->origin == ESP3DClientType::serial || + msg->origin == ESP3DClientType::serial_bridge || + msg->origin == ESP3DClientType::telnet || + msg->origin == ESP3DClientType::websocket || + msg->origin == ESP3DClientType::bluetooth)) { + msg->authentication_level = + AuthenticationService::getAuthenticatedLevel(pwd.c_str(), msg); + // update authentication level for current client + switch (msg->origin) { + case ESP3DClientType::serial: + esp3d_serial_service.setAuthentication(msg->authentication_level); + break; +#if defined(ESP_SERIAL_BRIDGE_OUTPUT) + case ESP3DClientType::serial_bridge: + serial_bridge_service.setAuthentication(msg->authentication_level); + break; +#endif // ESP_SERIAL_BRIDGE_OUTPUT +#if defined(TELNET_FEATURE) + case ESP3DClientType::telnet: + telnet_server.setAuthentication(msg->authentication_level); + break; +#endif // TELNET_FEATURE +#if defined(WS_DATA_FEATURE) + case ESP3DClientType::websocket: + websocket_data_server.setAuthentication(msg->authentication_level); + break; +#endif // WS_DATA_FEATURE +#ifdef BLUETOOTH_FEATURE + case ESP3DClientType::bluetooth: + bt_service.setAuthentication(msg->authentication_level); + break; +#endif // BLUETOOTH_FEATURE + default: + break; + } + } + +#endif // AUTHENTICATION_FEATURE + switch (cmd) { + // ESP3D Help + //[ESP0] or [ESP] + case 0: + ESP0(cmd_params_pos, msg); + break; + +#if defined(WIFI_FEATURE) + // STA SSID + //[ESP100][pwd=] + case 100: + ESP100(cmd_params_pos, msg); + break; + // STA Password + //[ESP101][pwd=] + case 101: + ESP101(cmd_params_pos, msg); + break; +#endif // WIFI_FEATURE +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) + // Change STA IP mode (DHCP/STATIC) + //[ESP102]pwd= + case 102: + ESP102(cmd_params_pos, msg); + break; + // Change STA IP/Mask/GW + //[ESP103]IP= MSK= GW= pwd= + case 103: + ESP103(cmd_params_pos, msg); + break; +#endif // WIFI_FEATURE ||ETH_FEATURE +#if defined(WIFI_FEATURE) || defined(BLUETOOTH_FEATURE) || defined(ETH_FEATURE) + // Set fallback mode which can be BT, WIFI-AP, OFF + //[ESP104]pwd= + case 104: + ESP104(cmd_params_pos, msg); + break; +#endif // WIFI_FEATURE || BLUETOOTH_FEATURE || ETH_FEATURE) +#if defined(WIFI_FEATURE) + // AP SSID + //[ESP105][pwd=] + case 105: + ESP105(cmd_params_pos, msg); + break; + // AP Password + //[ESP106][pwd=] + case 106: + ESP106(cmd_params_pos, msg); + break; + // Change AP IP + //[ESP107] pwd= + case 107: + ESP107(cmd_params_pos, msg); + break; + // Change AP channel + //[ESP108]pwd= + case 108: + ESP108(cmd_params_pos, msg); + break; +#endif // WIFI_FEATURE + +#if defined(WIFI_FEATURE) || defined(BLUETOOTH_FEATURE) || defined(ETH_FEATURE) + // Set radio state at boot which can be BT, WIFI-STA, WIFI-AP, ETH-STA, + // OFF + //[ESP110]pwd= + case 110: + ESP110(cmd_params_pos, msg); + break; +#endif // WIFI_FEATURE || BLUETOOTH_FEATURE || ETH_FEATURE) + +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) + // Get current IP + //[ESP111] + case 111: + ESP111(cmd_params_pos, msg); + break; +#endif // WIFI_FEATURE || ETH_FEATURE) + +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BT_FEATURE) + // Get/Set hostname + //[ESP112] pwd= + case 112: + ESP112(cmd_params_pos, msg); + break; + // Get/Set boot Network (WiFi/BT/Ethernet) state which can be ON, OFF + //[ESP114]pwd= + case 114: + ESP114(cmd_params_pos, msg); + break; + // Get/Set immediate Network (WiFi/BT/Ethernet) state which can be ON, OFF + //[ESP115]pwd= + case 115: + ESP115(cmd_params_pos, msg); + break; +#endif // WIFI_FEATURE|| ETH_FEATURE || BT_FEATURE + +#ifdef HTTP_FEATURE + // Set HTTP state which can be ON, OFF + //[ESP120]pwd= + case 120: + ESP120(cmd_params_pos, msg); + break; + // Set HTTP port + //[ESP121]pwd= + case 121: + ESP121(cmd_params_pos, msg); + break; +#endif // HTTP_FEATURE +#ifdef TELNET_FEATURE + // Set TELNET state which can be ON, OFF + //[ESP130]pwd= + case 130: + ESP130(cmd_params_pos, msg); + break; + // Set TELNET port + //[ESP131]pwd= + case 131: + ESP131(cmd_params_pos, msg); + break; +#endif // TELNET_FEATURE +#ifdef TIMESTAMP_FEATURE + // Sync / Set / Get current time + //[ESP140] + // pwd= + case 140: + ESP140(cmd_params_pos, msg); + break; +#endif // TIMESTAMP_FEATURE + // Get/Set display/set boot delay in ms / Verbose boot + //[ESP150]pwd= + case 150: + ESP150(cmd_params_pos, msg); + break; +#ifdef WS_DATA_FEATURE + // Set WebSocket state which can be ON, OFF + //[ESP160]pwd= + case 160: + ESP160(cmd_params_pos, msg); + break; + // Set WebSocket port + //[ESP161]pwd= + case 161: + ESP161(cmd_params_pos, msg); + break; +#endif // WS_DATA_FEATURE +#ifdef CAMERA_DEVICE + // Get/Set Camera command value / list all values in JSON/plain + //[ESP170]label= 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 + case 170: + ESP170(cmd_params_pos, msg); + break; + // Save frame to target path and filename (default target = todaydate, + // default name=timestamp.jpg) [ESP171]path= + // filename = < target + // filename> pwd= + case 171: + ESP171(cmd_params_pos, msg); + break; +#endif // CAMERA_DEVICE +#ifdef FTP_FEATURE + // Set Ftp state which can be ON, OFF + //[ESP180]pwd= + case 180: + ESP180(cmd_params_pos, msg); + break; + // Set/get ftp ports + //[ESP181]ctrl= active= passive= pwd= + // case 181: + ESP181(cmd_params_pos, msg); + break; +#endif // FTP_FEATURE +#ifdef WEBDAV_FEATURE + // Set webdav state which can be ON, OFF + //[ESP190]pwd= + case 190: + ESP190(cmd_params_pos, msg); + break; + // Set/get webdav port + //[ESP191]ctrl= active= passive= pwd= + // case 191: + ESP191(cmd_params_pos, msg); + break; +#endif // WEBDAV_FEATURE +#if defined(SD_DEVICE) + // Get/Set SD Card Status + //[ESP200] json= pwd= + case 200: + ESP200(cmd_params_pos, msg); + break; +#if SD_DEVICE != ESP_SDIO + // Get/Set SD card Speed factor 1 2 4 6 8 16 32 + //[ESP202]SPEED=pwd= + case 202: + ESP202(cmd_params_pos, msg); + break; +#endif // SD_DEVICE != ESP_SDIO +#ifdef SD_UPDATE_FEATURE + // Get/Set SD Check at boot state which can be ON, OFF + //[ESP402]pwd= + case 402: + ESP402(cmd_params_pos, msg); + break; +#endif // #ifdef SD_UPDATE_FEATURE +#endif // SD_DEVICE +#ifdef DIRECT_PIN_FEATURE + // Get/Set pin value + //[ESP201]P V [PULLUP=YES RAW=YES]pwd= + case 201: + ESP201(cmd_params_pos, msg); + break; +#endif // DIRECT_PIN_FEATURE +#ifdef SENSOR_DEVICE + // Get SENSOR Value / type/Set SENSOR type + //[ESP210] + case 210: + ESP210(cmd_params_pos, msg); + break; +#endif // #ifdef SENSOR_DEVICE +#if defined(DISPLAY_DEVICE) + // Output to esp screen status + //[ESP214]pwd= + case 214: + ESP214(cmd_params_pos, msg); + break; +#if defined(DISPLAY_TOUCH_DRIVER) + // Touch Calibration + //[ESP215][pwd=] + case 215: + ESP215(cmd_params_pos, msg); + break; +#endif // DISPLAY_TOUCH_DRIVER +#ifdef BUZZER_DEVICE + // Play sound + //[ESP250]F= D= [pwd=] + case 250: + ESP250(cmd_params_pos, msg); + break; +#endif // BUZZER_DEVICE +#endif // DISPLAY_DEVICE + // Show pins + //[ESP220][pwd=] + case 220: + ESP220(cmd_params_pos, msg); + break; + // Delay command + //[ESP290][pwd=] + case 290: + ESP290(cmd_params_pos, msg); + break; + // Get full ESP3D settings + //[ESP400] + case 400: + ESP400(cmd_params_pos, msg); + break; + // Set EEPROM setting + //[ESP401]P= T= V= pwd= + case 401: + ESP401(cmd_params_pos, msg); + break; +#if defined(WIFI_FEATURE) + // Get available AP list (limited to 30) + // msg is JSON or plain text according parameter + //[ESP410] + case 410: + ESP410(cmd_params_pos, msg); + break; +#endif // WIFI_FEATURE + // Get ESP current status + // msg is JSON or plain text according parameter + //[ESP420] + case 420: + ESP420(cmd_params_pos, msg); + break; + // Set ESP State + // cmd are RESTART / RESET + //[ESP444] + case 444: + ESP444(cmd_params_pos, msg); + break; +#ifdef MDNS_FEATURE + // Get ESP3D list + //[ESP450] pwd= + case 450: + ESP450(cmd_params_pos, msg); + break; +#endif // MDNS_FEATURE +#ifdef AUTHENTICATION_FEATURE + // Get current authentication level + //[ESP500] json= pwd= + case 500: + ESP500(cmd_params_pos, msg); + break; + // set/display session time out + //[ESP510] json= pwd= + case 510: + ESP510(cmd_params_pos, msg); + break; + // Change admin password + //[ESP550]pwd= + case 550: + ESP550(cmd_params_pos, msg); + break; + // Change user password + //[ESP555]pwd= + case 555: + ESP555(cmd_params_pos, msg); + break; +#endif // AUTHENTICATION_FEATURE +#if defined(NOTIFICATION_FEATURE) + // Send Notification + //[ESP600][pwd=] + case 600: + ESP600(cmd_params_pos, msg); + break; + // Set/Get Notification settings + //[ESP610]type= T1= T2= + // TS= pwd= Get will give type and settings only + // not the protected T1/T2 + case 610: + ESP610(cmd_params_pos, msg); + break; + // Send Notification using URL + //[ESP620]URL= pwd= + case 620: + ESP620(cmd_params_pos, msg); + break; +#endif // NOTIFICATION_FEATURE +#if defined(FILESYSTEM_FEATURE) + // Format ESP Filesystem + //[ESP710]FORMAT pwd= + case 710: + ESP710(cmd_params_pos, msg); + break; + // List ESP Filesystem + //[ESP720] pwd= + case 720: + ESP720(cmd_params_pos, msg); + break; + // Action on ESP Filesystem + // rmdir / remove / mkdir / exists + //[ESP730]= pwd= + case 730: + ESP730(cmd_params_pos, msg); + break; +#endif // FILESYSTEM_FEATURE +#if defined(SD_DEVICE) + // Format ESP Filesystem + //[ESP715]FORMATSD pwd= + case 715: + ESP715(cmd_params_pos, msg); + break; +#endif // SD_DEVICE +#if defined(GCODE_HOST_FEATURE) + // Open local file + //[ESP700] + case 700: + ESP700(cmd_params_pos, msg); + break; + // Get Status and Control ESP700 stream + //[ESP701]action= + case 701: + ESP701(cmd_params_pos, msg); + break; +#endif // GCODE_HOST_FEATURE +#if defined(SD_DEVICE) + // List SD Filesystem + //[ESP740] pwd= + case 740: + ESP740(cmd_params_pos, msg); + break; + // Action on SD Filesystem + // rmdir / remove / mkdir / exists + //[ESP750]= pwd= + case 750: + ESP750(cmd_params_pos, msg); + break; +#endif // SD_DEVICE +#if defined(GLOBAL_FILESYSTEM_FEATURE) + // List Global Filesystem + //[ESP780] pwd= + case 780: + ESP780(cmd_params_pos, msg); + break; + // Action on Global Filesystem + // rmdir / remove / mkdir / exists + //[ESP790]= pwd= + case 790: + ESP790(cmd_params_pos, msg); + break; +#endif // GLOBAL_FILESYSTEM_FEATURE + // Get fw version firmare target and fw version + // eventually set time with pc time + // output is JSON or plain text according parameter + //[ESP800] + case 800: + ESP800(cmd_params_pos, msg); + break; + +#if COMMUNICATION_PROTOCOL != SOCKET_SERIAL + // Get state / Set Enable / Disable Serial Communication + //[ESP900] + case 900: + ESP900(cmd_params_pos, msg); + break; + // Get / Set Serial Baud Rate + //[ESP901] json= pwd= + case 901: + ESP901(cmd_params_pos, msg); + break; +#endif // COMMUNICATION_PROTOCOL != SOCKET_SERIAL +#ifdef BUZZER_DEVICE + // Get state / Set Enable / Disable buzzer + //[ESP910] + case 910: + ESP910(cmd_params_pos, msg); + break; +#endif // BUZZER_DEVICE + +#if defined(ESP_SERIAL_BRIDGE_OUTPUT) + // Get state / Set Enable / Disable Serial Bridge Communication + //[ESP930] + case 930: + ESP930(cmd_params_pos, msg); + break; + // Get / Set Serial Bridge Baud Rate + //[ESP931] json= pwd= + case 931: + ESP931(cmd_params_pos, msg); + break; +#endif // defined(ESP_SERIAL_BRIDGE_OUTPUT) +#if defined(ARDUINO_ARCH_ESP32) && \ + (CONFIG_IDF_TARGET_ESP32S3 || CONFIG_IDF_TARGET_ESP32S2 || \ + CONFIG_IDF_TARGET_ESP32C3) + case 999: + // Set quiet boot if strapping pin is High + //[ESP999] [pwd=] + ESP999(cmd_params_pos, msg); + break; +#endif // ARDUINO_ARCH_ESP32 + + default: + msg->target = msg->origin; + esp3d_log("Invalid Command: %d", cmd); + if (hasTag(msg, cmd_params_pos, "json")) { + String tmpstr = "{\"cmd\":\"[ESP"; + tmpstr += String(cmd); + tmpstr += "]\",\"status\":\"error\",\"data\":\"Invalid Command\"}"; + if (!dispatch(msg, tmpstr.c_str())) { + esp3d_log_e("Out of memory"); + } + } else { + String tmpstr = "Invalid Command: [ESP"; + tmpstr += String(cmd); + tmpstr += "]\n"; + if (!dispatch(msg, tmpstr.c_str())) { + esp3d_log_e("Out of memory"); + } + } + } +} + +bool ESP3DCommands::dispatchSetting(bool json, const char *filter, + ESP3DSettingIndex index, const char *help, + const char **optionValues, + const char **optionLabels, uint32_t maxsize, + uint32_t minsize, uint32_t minsize2, + uint8_t precision, const char *unit, + bool needRestart, ESP3DClientType target, + ESP3DRequest requestId, bool isFirst) { + String tmpstr; + String value; + tmpstr.reserve( + 350); // to save time and avoid several memories allocation delay + const ESP3DSettingDescription *elementSetting = + ESP3DSettings::getSettingPtr(index); + if (!elementSetting) { + return false; + } + switch (elementSetting->type) { + case ESP3DSettingType::byte_t: + value = String(ESP3DSettings::readByte(index)); + break; + case ESP3DSettingType::integer_t: + value = String(ESP3DSettings::readUint32(index)); + break; + case ESP3DSettingType::ip_t: + value = ESP3DSettings::readIPString(index); + break; + case ESP3DSettingType::float_t: + // TODO Add float support ? + value = "Not supported"; + break; + case ESP3DSettingType::mask: + // TODO Add Mask support ? + value = "Not supported"; + break; + case ESP3DSettingType::bitsfield: + // TODO Add bitfield support ? + value = "Not supported"; + break; + default: // String + if (index == ESP_STA_PASSWORD || index == ESP_AP_PASSWORD || +#if ESP3D_NOTIFICATIONS_FEATURE + index == ESP_NOTIFICATION_TOKEN1 || + index == ESP_NOTIFICATION_TOKEN2 || +#endif // ESP3D_NOTIFICATIONS_FEATURE + + index == ESP_ADMIN_PWD || index == ESP_USER_PWD) { // hide passwords + // using ******** + value = HIDDEN_PASSWORD; + } else { + value = ESP3DSettings::readString(index); + } + } + if (json) { + if (!isFirst) { + tmpstr += ","; + } + tmpstr += "{\"F\":\""; + tmpstr += filter; + tmpstr += "\",\"P\":\""; + tmpstr += String(static_cast(index)); + tmpstr += "\",\"T\":\""; + switch (elementSetting->type) { + case ESP3DSettingType::byte_t: + tmpstr += "B"; + break; + case ESP3DSettingType::integer_t: + tmpstr += "I"; + break; + case ESP3DSettingType::ip_t: + tmpstr += "A"; + break; + case ESP3DSettingType::float_t: + tmpstr += "F"; + break; + case ESP3DSettingType::mask: + tmpstr += "M"; + break; + case ESP3DSettingType::bitsfield: + tmpstr += "X"; + break; + default: + tmpstr += "S"; + } + tmpstr += "\",\"V\":\""; + tmpstr += value; // TODO: need to encode string ? + tmpstr += "\",\"H\":\""; + tmpstr += help; + tmpstr += "\""; + if (needRestart) { + tmpstr += ",\"R\":\"1\""; + } + if (optionValues && optionLabels) { + tmpstr += ",\"O\":["; + for (uint8_t i = 0; i < maxsize; i++) { + if (i > 0) { + tmpstr += ","; + } + tmpstr += "{\""; + // be sure we have same size for both array to avoid overflow + tmpstr += optionLabels[i]; + tmpstr += "\":\""; + tmpstr += optionValues[i]; + tmpstr += "\"}"; + } + tmpstr += "]"; + } + if (unit) { + tmpstr += ",\"R\":\""; + tmpstr += unit; + tmpstr += "\""; + } + if (precision != ((uint8_t)-1)) { + tmpstr += ",\"E\":\""; + tmpstr += String(precision); + tmpstr += "\""; + } + if (maxsize != (uint32_t)-1 && !optionValues) { + tmpstr += ",\"S\":\""; + tmpstr += String(maxsize); + tmpstr += "\""; + } + if (minsize != (uint32_t)-1) { + tmpstr += ",\"M\":\""; + tmpstr += String(minsize); + tmpstr += "\""; + } + if (minsize2 != (uint32_t)-1) { + tmpstr += ",\"MS\":\""; + tmpstr += String(minsize2); + tmpstr += "\""; + } + tmpstr += "}"; + } else { + tmpstr = filter; + tmpstr += "/"; + tmpstr += help; + tmpstr += ": "; + tmpstr += value; + tmpstr += "\n"; + } + return dispatch(tmpstr.c_str(), target, requestId, ESP3DMessageType::core); +} + +bool ESP3DCommands::dispatchAuthenticationError(ESP3DMessage *msg, uint cmdid, + bool json) { + String tmpstr; + if (!msg) { + return false; + } +#if defined(HTTP_FEATURE) && defined(AUTHENTICATION_FEATURE) + if (msg->target == ESP3DClientType::http ) { + msg->authentication_level = ESP3DAuthenticationLevel::not_authenticated; + } +#endif // HTTP_FEATURE + // answer is one message, override for safety + msg->type = ESP3DMessageType::unique; + if (json) { + tmpstr = "{\"cmd\":\""; + tmpstr += String(cmdid); + tmpstr += + "\",\"status\":\"error\",\"data\":\"Wrong authentication level\"}"; + } else { + tmpstr = "Wrong authentication level\n"; + } + return dispatch(msg, tmpstr.c_str()); +} + +bool ESP3DCommands::dispatchAnswer(ESP3DMessage *msg, uint cmdid, bool json, + bool hasError, const char *answerMsg) { + String tmpstr; + if (!msg || !answerMsg) { + esp3d_log_e("no msg"); + return false; + } + // answer is one message, override for safety + msg->type = ESP3DMessageType::unique; + if (json) { + tmpstr = "{\"cmd\":\"" + String(cmdid) + "\",\"status\":\""; + + if (hasError) { + tmpstr += "error"; + } else { + tmpstr += "ok"; + } + tmpstr += "\",\"data\":"; + if (answerMsg[0] != '{') { + tmpstr += "\""; + } + tmpstr += answerMsg; + if (answerMsg[0] != '{') { + tmpstr += "\""; + } + tmpstr += "}\n"; + } else { + tmpstr = answerMsg; + tmpstr += "\n"; + } + return dispatch(msg, tmpstr.c_str()); +} + +bool ESP3DCommands::dispatchKeyValue(bool json, const char *key, + const char *value, ESP3DClientType target, + ESP3DRequest requestId, bool nested, + bool isFirst) { + String tmpstr = ""; + if (json) { + if (!isFirst) { + tmpstr += ","; + } + if (nested) { + tmpstr += "{"; + } + tmpstr += "\""; + } + tmpstr += key; + if (json) { + tmpstr += "\":\""; + } else { + tmpstr += ": "; + } + tmpstr += value; + if (json) { + tmpstr += "\""; + if (nested) { + tmpstr += "}"; + } + } else { + tmpstr += "\n"; + } + return dispatch(tmpstr.c_str(), target, requestId, ESP3DMessageType::core); +} + +bool ESP3DCommands::dispatchIdValue(bool json, const char *Id, + const char *value, ESP3DClientType target, + ESP3DRequest requestId, bool isFirst) { + String tmpstr = ""; + if (json) { + if (!isFirst) { + tmpstr += ","; + } + tmpstr += "{\"id\":\""; + } + tmpstr += Id; + if (json) { + tmpstr += "\",\"value\":\""; + } else { + tmpstr += ": "; + } + tmpstr += value; + if (json) { + tmpstr += "\"}"; + } else { + tmpstr += "\n"; + } + return dispatch(tmpstr.c_str(), target, requestId, ESP3DMessageType::core); +} + +bool ESP3DCommands::formatCommand(char *cmd, size_t len) { + if (isRealTimeCommand(cmd, len)) { + // TODO: what if is realtime command ? + return true; + } + uint sizestr = strlen(cmd); + if (len > sizestr + 2) { + cmd[sizestr] = '\n'; + cmd[sizestr + 1] = 0x0; + return true; + } + return false; +} + +void ESP3DCommands::process(ESP3DMessage *msg) { + static bool lastIsESP3D = false; + if (!msg) { + esp3d_log_e("no msg"); + return; + } + esp3d_log("Processing message %d", msg->size); + if (is_esp_command(msg->data, msg->size)) { + esp3d_log("Detected ESP command"); + lastIsESP3D = true; + uint cmdId = 0; + uint espcmdpos = 0; + bool startcmd = false; + bool endcmd = false; + for (uint i = 0; i < msg->size && espcmdpos == 0; i++) { + if (char(msg->data[i]) == ']') { // start command flag + endcmd = true; + espcmdpos = i + 1; + } else if (char(msg->data[i]) == '[') { // end command flag + startcmd = true; + } else if (startcmd && !endcmd && + std::isdigit(static_cast( + char(msg->data[i])))) { // command id + if (cmdId != 0) { + cmdId = (cmdId * 10); + } + cmdId += (msg->data[i] - 48); + } + } + // execute esp command + esp3d_log("Execute internal command %d", cmdId); + execute_internal_command(cmdId, espcmdpos, msg); + } else { + esp3d_log("Dispatch command, len %d, from %d(%s) to %d(%s)", msg->size, + static_cast(msg->origin), GETCLIENTSTR(msg->origin), static_cast(msg->target), GETCLIENTSTR(msg->target)); + + // Work around to avoid to dispatch single \n or \r to everyone as it is + // part of previous ESP3D command + if (msg->size == 1 && + ((char(msg->data[0]) == '\n') || (char(msg->data[0]) == '\r')) && + lastIsESP3D) { + lastIsESP3D = false; + // delete message + esp3d_log("Delete message"); + ESP3DMessageManager::deleteMsg(msg); + return; + } + lastIsESP3D = false; + dispatch(msg); + } +} +bool ESP3DCommands::dispatch(ESP3DMessage *msg, const char *sbuf) { + return dispatch(msg, (uint8_t *)sbuf, strlen(sbuf)); +} + +bool ESP3DCommands::dispatch(ESP3DMessage *msg, uint8_t *sbuf, size_t len) { + if (!msg) { + esp3d_log_e("no msg"); + return false; + } + if (!ESP3DMessageManager::setDataContent(msg, sbuf, len)) { + esp3d_log_e("set data content failed"); + ESP3DMessageManager::deleteMsg(msg); + return false; + } + return dispatch(msg); +} + +bool ESP3DCommands::dispatch(uint8_t *sbuf, size_t size, ESP3DClientType target, + ESP3DRequest requestId, ESP3DMessageType type, + ESP3DClientType origin, + ESP3DAuthenticationLevel authentication_level) { + ESP3DMessage *newMsgPtr = ESP3DMessageManager::newMsg(origin, target); + if (newMsgPtr) { + newMsgPtr->request_id = requestId; + newMsgPtr->type = type; + newMsgPtr->authentication_level = authentication_level; + return dispatch(newMsgPtr, sbuf, size); + } + esp3d_log_e("no newMsgPtr"); + return false; +} +bool ESP3DCommands::dispatch(const char *sbuf, ESP3DClientType target, + ESP3DRequest requestId, ESP3DMessageType type, + ESP3DClientType origin, + ESP3DAuthenticationLevel authentication_level) { + ESP3DMessage *newMsgPtr = ESP3DMessageManager::newMsg(origin, target); + if (newMsgPtr) { + newMsgPtr->request_id = requestId; + newMsgPtr->type = type; + newMsgPtr->authentication_level = authentication_level; + return dispatch(newMsgPtr, sbuf); + } + esp3d_log_e("no newMsgPtr"); + return false; +} + +ESP3DClientType ESP3DCommands::getOutputClient(bool fromSettings) { + // TODO: add setting for it when necessary + (void)fromSettings; + esp3d_log("OutputClient: %d %s", static_cast(_output_client), GETCLIENTSTR(_output_client)); + return _output_client; +} + +bool ESP3DCommands::dispatch(ESP3DMessage *msg) { + bool sendOk = true; + String tmp; + esp3d_log("Dispatch message origin %d(%s) to client %d(%s) , size: %d, type: %d(%s)", + static_cast(msg->origin), + esp3dclientstr[static_cast(msg->origin)], + static_cast(msg->target), GETCLIENTSTR(msg->target), + msg->size, static_cast(msg->type),GETMSGTYPESTR(msg->type)); + esp3d_log("Dispatch message data: %s", (const char *)msg->data); + if (!msg) { + esp3d_log_e("no msg"); + return false; + } + // currently only echo back no test done on success + // TODO check add is successful + switch (msg->target) { +#if COMMUNICATION_PROTOCOL == RAW_SERIAL + case ESP3DClientType::serial: + esp3d_log("Serial message"); + if (!esp3d_serial_service.dispatch(msg)) { + sendOk = false; + esp3d_log_e("Serial dispatch failed"); + } + break; +#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL + +#if COMMUNICATION_PROTOCOL == SOCKET_SERIAL + case ESP3DClientType::echo_serial: + esp3d_log("Echo serial message"); + MYSERIAL1.write(msg->data, msg->size); + if (msg->type == ESP3DMessageType::unique || msg->type == ESP3DMessageType::tail) { + if (msg->data[msg->size-1]!='\n'){ + MYSERIAL1.write('\n'); + } + } + ESP3DMessageManager::deleteMsg(msg); + break; + + case ESP3DClientType::socket_serial: + esp3d_log("Socket serial message"); + if (!Serial2Socket.dispatch(msg)) { + sendOk = false; + esp3d_log_e("Socket dispatch failed"); + } + break; +#endif // COMMUNICATION_PROTOCOL == SOCKET_SERIAL + +#if defined(ESP_SERIAL_BRIDGE_OUTPUT) + case ESP3DClientType::serial_bridge: + esp3d_log("Serial bridge message"); + if (!serial_bridge_service.dispatch(msg)) { + sendOk = false; + esp3d_log_e("Serial bridge dispatch failed"); + } + break; +#endif // ESP_SERIAL_BRIDGE_OUTPUT + +#ifdef WS_DATA_FEATURE + case ESP3DClientType::websocket: + esp3d_log("Websocket message"); + if (!websocket_data_server.dispatch(msg)) { + sendOk = false; + esp3d_log_e("Telnet dispatch failed"); + } + break; +#endif // WS_DATA_FEATURE + +#ifdef TELNET_FEATURE + case ESP3DClientType::telnet: + esp3d_log("Telnet message"); + if (!telnet_server.dispatch(msg)) { + sendOk = false; + esp3d_log_e("Telnet dispatch failed"); + } + break; +#endif // TELNET_FEATURE + +#ifdef BLUETOOTH_FEATURE + case ESP3DClientType::bluetooth: + esp3d_log("Bluetooth message"); + if (!bt_service.dispatch(msg)) { + sendOk = false; + esp3d_log_e("Bluetooth dispatch failed"); + } + break; +#endif // BLUETOOTH_FEATURE + +#ifdef HTTP_FEATURE + case ESP3DClientType::webui_websocket: + esp3d_log("Webui websocket message"); + if (!websocket_terminal_server.dispatch(msg)) { + sendOk = false; + esp3d_log_e("Webui websocket dispatch failed"); + } + break; + case ESP3DClientType::http: + esp3d_log("Http message"); + if (!HTTP_Server::dispatch(msg)) { + sendOk = false; + esp3d_log_e("Webui websocket dispatch failed"); + } + break; +#endif // HTTP_FEATURE +#if defined(DISPLAY_DEVICE) + case ESP3DClientType::rendering: + esp3d_log("Rendering message"); + if (!esp3d_display.dispatch(msg)) { + sendOk = false; + esp3d_log_e("Display dispatch failed"); + } + break; +#endif // defined(DISPLAY_DEVICE) + +#if COMMUNICATION_PROTOCOL == MKS_SERIAL + case ESP3DClientType::mks_serial: + esp3d_log("MKS Serial message"); + if (!MKSService::dispatch(msg)) { + sendOk = false; + esp3d_log_e("MKS Serial dispatch failed"); + } + break; +#endif // COMMUNICATION_PROTOCOL == MKS_SERIAL + +#ifdef PRINTER_HAS_DISPLAY + case ESP3DClientType::remote_screen: + esp3d_log("Remote screen message"); + // change target to output client + msg->target = getOutputClient(); + // change text to GCODE M117 + tmp = "M117 "; + tmp += (const char *)msg->data; + // replace end of line with space + tmp.replace("\n", " "); + tmp.replace("\r", ""); + tmp += "\n"; + if (ESP3DMessageManager::setDataContent(msg, (uint8_t *)tmp.c_str(), + tmp.length())) { + return dispatch(msg); + } + sendOk = false; + esp3d_log_e("Cannot set data content for remote screen"); + break; +#endif // PRINTER_HAS_DISPLAY + case ESP3DClientType::all_clients: + esp3d_log("All clients message"); + // Add each client one by one +#ifdef PRINTER_HAS_DISPLAY + if (msg->origin != ESP3DClientType::remote_screen && + msg->origin != getOutputClient()) { + if (msg->target == ESP3DClientType::all_clients) { + // become the reference message + msg->target = ESP3DClientType::remote_screen; + } else { + // duplicate message because current is already pending + ESP3DMessage *copy_msg = ESP3DMessageManager::copyMsg(*msg); + if (copy_msg) { + copy_msg->target = ESP3DClientType::remote_screen; + dispatch(copy_msg); + } else { + esp3d_log_e("Cannot duplicate message for remote screen"); + } + } + } +#endif // PRINTER_HAS_DISPLAY + +#if defined(DISPLAY_DEVICE) + if (msg->origin != ESP3DClientType::rendering && + msg->origin != getOutputClient()) { + if (msg->target == ESP3DClientType::all_clients) { + // become the reference message + msg->target = ESP3DClientType::rendering; + msg->request_id.id = ESP_OUTPUT_STATUS; + } else { + // duplicate message because current is already pending + ESP3DMessage *copy_msg = ESP3DMessageManager::copyMsg(*msg); + if (copy_msg) { + copy_msg->target = ESP3DClientType::rendering; + copy_msg->request_id.id = ESP_OUTPUT_STATUS; + dispatch(copy_msg); + } else { + esp3d_log_e("Cannot duplicate message for display"); + } + } + } +#endif // defined(DISPLAY_DEVICE) + +#if COMMUNICATION_PROTOCOL == SOCKET_SERIAL + if (msg->origin != ESP3DClientType::echo_serial && + msg->origin != ESP3DClientType::socket_serial) { + if (msg->target == ESP3DClientType::all_clients) { + // become the reference message + msg->target = ESP3DClientType::echo_serial; + } else { + // duplicate message because current is already pending + ESP3DMessage *copy_msg = ESP3DMessageManager::copyMsg(*msg); + if (copy_msg) { + copy_msg->target = ESP3DClientType::echo_serial; + dispatch(copy_msg); + } else { + esp3d_log_e("Cannot duplicate message for echo serial"); + } + } + } +#endif // COMMUNICATION_PROTOCOL == SOCKET_SERIAL + +#if defined(ESP_SERIAL_BRIDGE_OUTPUT) + if (msg->origin != ESP3DClientType::serial_bridge) { + if (msg->target == ESP3DClientType::all_clients) { + // become the reference message + msg->target = ESP3DClientType::serial_bridge; + } else { + // duplicate message because current is already pending + ESP3DMessage *copy_msg = ESP3DMessageManager::copyMsg(*msg); + if (copy_msg) { + copy_msg->target = ESP3DClientType::serial_bridge; + dispatch(copy_msg); + } else { + esp3d_log_e("Cannot duplicate message for serial bridge"); + } + } + } +#endif // ESP_SERIAL_BRIDGE_OUTPUT + +#ifdef BLUETOOTH_FEATURE + if (msg->origin != ESP3DClientType::bluetooth && bt_service.isConnected()) { + if (msg->target == ESP3DClientType::all_clients) { + // become the reference message + msg->target = ESP3DClientType::bluetooth; + } else { + // duplicate message because current is already pending + ESP3DMessage *copy_msg = ESP3DMessageManager::copyMsg(*msg); + if (copy_msg) { + copy_msg->target = ESP3DClientType::bluetooth; + dispatch(copy_msg); + } else { + esp3d_log_e("Cannot duplicate message for bluetooth"); + } + } + } +#endif // BLUETOOTH_FEATURE + +#ifdef TELNET_FEATURE + if (msg->origin != ESP3DClientType::telnet && telnet_server.isConnected()) { + if (msg->target == ESP3DClientType::all_clients) { + // become the reference message + msg->target = ESP3DClientType::telnet; + } else { + // duplicate message because current is already pending + ESP3DMessage *copy_msg = ESP3DMessageManager::copyMsg(*msg); + if (copy_msg) { + copy_msg->target = ESP3DClientType::telnet; + dispatch(copy_msg); + } else { + esp3d_log_e("Cannot duplicate message for telnet"); + } + } + } else{ + if (msg->origin != ESP3DClientType::telnet)esp3d_log("Telnet not connected"); + } +#endif // TELNET_FEATURE + +#ifdef HTTP_FEATURE // http cannot be in all client because it depend of any + // connection of the server + if (msg->origin != ESP3DClientType::webui_websocket && websocket_terminal_server.isConnected()) { + if (msg->target == ESP3DClientType::all_clients) { + // become the reference message + msg->target = ESP3DClientType::webui_websocket; + } else { + // duplicate message because current is already pending + ESP3DMessage *copy_msg = ESP3DMessageManager::copyMsg(*msg); + if (copy_msg) { + copy_msg->target = ESP3DClientType::webui_websocket; + dispatch(copy_msg); + } else { + esp3d_log_e("Cannot duplicate message for webui_websocket"); + } + } + } else { + if (msg->origin != ESP3DClientType::webui_websocket)esp3d_log("Webui websocket not connected"); + } +#endif // HTTP_FEATURE + +#ifdef WS_DATA_FEATURE + if (msg->origin != ESP3DClientType::websocket && websocket_data_server.isConnected()) { + if (msg->target == ESP3DClientType::all_clients) { + // become the reference message + msg->target = ESP3DClientType::websocket; + } else { + // duplicate message because current is already pending + ESP3DMessage *copy_msg = ESP3DMessageManager::copyMsg(*msg); + if (copy_msg) { + copy_msg->target = ESP3DClientType::websocket; + dispatch(copy_msg); + } else { + esp3d_log_e("Cannot duplicate message for websocket"); + } + } + } else { + if (msg->origin != ESP3DClientType::websocket)esp3d_log("Websocket not connected"); + } +#endif // WS_DATA_FEATURE + + //... + + // Send pending if any or cancel message is no client did handle it + if (msg->target == ESP3DClientType::all_clients) { + esp3d_log("No client handled message, send pending"); + sendOk = false; + } else { + return dispatch(msg); + } + break; + default: + esp3d_log_e("No valid target specified %d", + static_cast(msg->target)); + sendOk = false; + } + // clear message + if (!sendOk) { + esp3d_log_e("Send msg failed"); + ESP3DMessageManager::deleteMsg(msg); + } + return sendOk; +} diff --git a/esp3d/src/core/esp3d_commands.h b/esp3d/src/core/esp3d_commands.h new file mode 100644 index 00000000..924aa46f --- /dev/null +++ b/esp3d/src/core/esp3d_commands.h @@ -0,0 +1,230 @@ +/* + esp3d_commands.h - ESP3D commands 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 COMMANDS_H +#define COMMANDS_H +#include + +#include "../modules/authentication/authentication_service.h" +#include "esp3d_message.h" + +class ESP3DCommands { + public: + ESP3DCommands(); + ~ESP3DCommands(); + void process(ESP3DMessage* msg); + + bool is_esp_command(uint8_t* sbuf, size_t len); + + void execute_internal_command(int cmd, int cmd_params_pos, ESP3DMessage* msg); + + const char* get_param(ESP3DMessage* msg, uint start, const char* label, + bool* found = nullptr); + + const char* get_param(const char* data, uint size, uint start, + const char* label, bool* found = nullptr); + + const char* format_response(uint cmdID, bool isjson = false, bool isok = true, + const char* message = ""); + + bool hasTag(ESP3DMessage* msg, uint start, const char* label); + const char* get_clean_param(ESP3DMessage* msg, uint start); + bool has_param(ESP3DMessage* msg, uint start); + + void ESP0(int cmd_params_pos, ESP3DMessage* msg); +#if defined(WIFI_FEATURE) + void ESP100(int cmd_params_pos, ESP3DMessage* msg); + void ESP101(int cmd_params_pos, ESP3DMessage* msg); +#endif // WIFI_FEATURE +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) + void ESP102(int cmd_params_pos, ESP3DMessage* msg); + void ESP103(int cmd_params_pos, ESP3DMessage* msg); +#endif // WIFI_FEATURE ||ETH_FEATURE +#if defined(WIFI_FEATURE) || defined(BLUETOOTH_FEATURE) || defined(ETH_FEATURE) + void ESP104(int cmd_params_pos, ESP3DMessage* msg); +#endif // WIFI_FEATURE || BLUETOOTH_FEATURE || ETH_FEATURE +#if defined(WIFI_FEATURE) + void ESP105(int cmd_params_pos, ESP3DMessage* msg); + void ESP106(int cmd_params_pos, ESP3DMessage* msg); + void ESP107(int cmd_params_pos, ESP3DMessage* msg); + void ESP108(int cmd_params_pos, ESP3DMessage* msg); +#endif // WIFI_FEATURE +#if defined(WIFI_FEATURE) || defined(BLUETOOTH_FEATURE) || defined(ETH_FEATURE) + void ESP110(int cmd_params_pos, ESP3DMessage* msg); +#endif // WIFI_FEATURE || BLUETOOTH_FEATURE || ETH_FEATURE +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) + void ESP111(int cmd_params_pos, ESP3DMessage* msg); +#endif // WIFI_FEATURE || ETH_FEATURE +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BT_FEATURE) + void ESP112(int cmd_params_pos, ESP3DMessage* msg); + void ESP114(int cmd_params_pos, ESP3DMessage* msg); + void ESP115(int cmd_params_pos, ESP3DMessage* msg); +#endif // WIFI_FEATURE || BLUETOOTH_FEATURE || ETH_FEATURE +#if defined(HTTP_FEATURE) + void ESP120(int cmd_params_pos, ESP3DMessage* msg); + void ESP121(int cmd_params_pos, ESP3DMessage* msg); +#endif // HTTP_FEATURE +#if defined(TELNET_FEATURE) + void ESP130(int cmd_params_pos, ESP3DMessage* msg); + void ESP131(int cmd_params_pos, ESP3DMessage* msg); +#endif // TELNET_FEATURE +#if defined(TIMESTAMP_FEATURE) + void ESP140(int cmd_params_pos, ESP3DMessage* msg); +#endif // TIMESTAMP_FEATURE + void ESP150(int cmd_params_pos, ESP3DMessage* msg); +#if defined(WS_DATA_FEATURE) + void ESP160(int cmd_params_pos, ESP3DMessage* msg); + void ESP161(int cmd_params_pos, ESP3DMessage* msg); +#endif // WS_DATA_FEATURE +#if defined(CAMERA_DEVICE) + void ESP170(int cmd_params_pos, ESP3DMessage* msg); + void ESP171(int cmd_params_pos, ESP3DMessage* msg); +#endif // CAMERA_DEVICE +#if defined(FTP_FEATURE) + void ESP180(int cmd_params_pos, ESP3DMessage* msg); + void ESP181(int cmd_params_pos, ESP3DMessage* msg); +#endif // FTP_FEATURE +#if defined(WEBDAV_FEATURE) + void ESP190(int cmd_params_pos, ESP3DMessage* msg); + void ESP191(int cmd_params_pos, ESP3DMessage* msg); +#endif // WEBDAV_FEATURE +#if defined(SD_DEVICE) + void ESP200(int cmd_params_pos, ESP3DMessage* msg); +#if SD_DEVICE != ESP_SDIO + void ESP202(int cmd_params_pos, ESP3DMessage* msg); +#endif // SD_DEVICE != ESP_SDIO +#ifdef SD_UPDATE_FEATURE + void ESP402(int cmd_params_pos, ESP3DMessage* msg); +#endif // SD_UPDATE_FEATURE +#endif // SD_DEVICE +#ifdef DIRECT_PIN_FEATURE + void ESP201(int cmd_params_pos, ESP3DMessage* msg); +#endif // DIRECT_PIN_FEATURE +#if defined(DISPLAY_DEVICE) + void ESP214(int cmd_params_pos, ESP3DMessage* msg); +#if defined(DISPLAY_TOUCH_DRIVER) + void ESP215(int cmd_params_pos, ESP3DMessage* msg); +#endif // DISPLAY_TOUCH_DRIVER +#endif // DISPLAY_DEVICE +#ifdef SENSOR_DEVICE + void ESP210(int cmd_params_pos, ESP3DMessage* msg); +#endif // SENSOR_DEVICE + void ESP220(int cmd_params_pos, ESP3DMessage* msg); + void ESP290(int cmd_params_pos, ESP3DMessage* msg); + void ESP400(int cmd_params_pos, ESP3DMessage* msg); + void ESP401(int cmd_params_pos, ESP3DMessage* msg); +#if defined(WIFI_FEATURE) + void ESP410(int cmd_params_pos, ESP3DMessage* msg); +#endif // WIFI_FEATURE + void ESP420(int cmd_params_pos, ESP3DMessage* msg); + void ESP444(int cmd_params_pos, ESP3DMessage* msg); +#ifdef MDNS_FEATURE + void ESP450(int cmd_params_pos, ESP3DMessage* msg); +#endif // MDNS_FEATURE +#if defined(AUTHENTICATION_FEATURE) + void ESP500(int cmd_params_pos, ESP3DMessage* msg); + void ESP510(int cmd_params_pos, ESP3DMessage* msg); + void ESP550(int cmd_params_pos, ESP3DMessage* msg); + void ESP555(int cmd_params_pos, ESP3DMessage* msg); +#endif // AUTHENTICATION_FEATURE +#if defined(NOTIFICATION_FEATURE) + void ESP600(int cmd_params_pos, ESP3DMessage* msg); + void ESP610(int cmd_params_pos, ESP3DMessage* msg); + void ESP620(int cmd_params_pos, ESP3DMessage* msg); +#endif // NOTIFICATION_FEATURE +#if defined(GCODE_HOST_FEATURE) + void ESP700(int cmd_params_pos, ESP3DMessage* msg); + void ESP701(int cmd_params_pos, ESP3DMessage* msg); +#endif // GCODE_HOST_FEATURE +#if defined(FILESYSTEM_FEATURE) + void ESP710(int cmd_params_pos, ESP3DMessage* msg); + void ESP720(int cmd_params_pos, ESP3DMessage* msg); + void ESP730(int cmd_params_pos, ESP3DMessage* msg); +#endif // FILESYSTEM_FEATURE +#if defined(SD_DEVICE) + void ESP715(int cmd_params_pos, ESP3DMessage* msg); + void ESP750(int cmd_params_pos, ESP3DMessage* msg); + void ESP740(int cmd_params_pos, ESP3DMessage* msg); +#endif // SD_DEVICE +#if defined(GLOBAL_FILESYSTEM_FEATURE) + void ESP780(int cmd_params_pos, ESP3DMessage* msg); + void ESP790(int cmd_params_pos, ESP3DMessage* msg); +#endif // GLOBAL_FILESYSTEM_FEATURE + void ESP800(int cmd_params_pos, ESP3DMessage* msg); +#if COMMUNICATION_PROTOCOL != SOCKET_SERIAL + void ESP900(int cmd_params_pos, ESP3DMessage* msg); + void ESP901(int cmd_params_pos, ESP3DMessage* msg); +#endif // COMMUNICATION_PROTOCOL != SOCKET_SERIAL +#if defined(ESP_SERIAL_BRIDGE_OUTPUT) + void ESP930(int cmd_params_pos, ESP3DMessage* msg); + void ESP931(int cmd_params_pos, ESP3DMessage* msg); +#endif // defined (ESP_SERIAL_BRIDGE_OUTPUT) +#ifdef BUZZER_DEVICE + void ESP910(int cmd_params_pos, ESP3DMessage* msg); + void ESP250(int cmd_params_pos, ESP3DMessage* msg); +#endif // BUZZER_DEVICE +#if defined(ARDUINO_ARCH_ESP32) && \ + (CONFIG_IDF_TARGET_ESP32S3 || CONFIG_IDF_TARGET_ESP32S2 || \ + CONFIG_IDF_TARGET_ESP32C3) + void ESP999(int cmd_params_pos, ESP3DMessage* msg); +#endif // ARDUINO_ARCH_ESP32 + bool dispatch(const char* sbuf, ESP3DClientType target, + ESP3DRequest requestId, + ESP3DMessageType type = ESP3DMessageType::head, + ESP3DClientType origin = ESP3DClientType::command, + ESP3DAuthenticationLevel authentication_level = + ESP3DAuthenticationLevel::guest); + bool dispatch(ESP3DMessage* msg, const char* sbuf); + bool dispatch(ESP3DMessage* msg, uint8_t* sbuf, size_t len); + bool dispatch(ESP3DMessage* msg); + bool dispatchAnswer(ESP3DMessage* msg, uint cmdid, bool json, bool hasError, + const char* answerMsg); + bool dispatchIdValue(bool json, const char* Id, const char* value, + ESP3DClientType target, ESP3DRequest requestId, + bool isFirst = false); + bool dispatchKeyValue(bool json, const char* key, const char* value, + ESP3DClientType target, ESP3DRequest requestId, + bool nested = false, bool isFirst = false); + bool dispatch(uint8_t* sbuf, size_t size, ESP3DClientType target, + ESP3DRequest requestId, ESP3DMessageType type, + ESP3DClientType origin, + ESP3DAuthenticationLevel authentication_level); + bool dispatchSetting(bool json, const char* filter, ESP3DSettingIndex index, + const char* help, const char** optionValues, + const char** optionLabels, uint32_t maxsize, + uint32_t minsize, uint32_t minsize2, uint8_t precision, + const char* unit, bool needRestart, + ESP3DClientType target, ESP3DRequest requestId, + bool isFirst = false); + bool dispatchAuthenticationError(ESP3DMessage* msg, uint cmdid, bool json); + bool formatCommand(char* cmd, size_t len); + bool isRealTimeCommand(char* cmd, size_t len); + ESP3DClientType getOutputClient(bool fromSettings = false); + void setOutputClient(ESP3DClientType output_client) { + _output_client = output_client; + } + + private: + ESP3DClientType _output_client; +}; + +extern ESP3DCommands esp3d_commands; + +#endif // COMMANDS_H diff --git a/esp3d/src/core/hal.cpp b/esp3d/src/core/esp3d_hal.cpp similarity index 88% rename from esp3d/src/core/hal.cpp rename to esp3d/src/core/esp3d_hal.cpp index d35c9734..c6635066 100644 --- a/esp3d/src/core/hal.cpp +++ b/esp3d/src/core/esp3d_hal.cpp @@ -34,15 +34,15 @@ #include #include -TaskHandle_t Hal::xHandle = nullptr; +TaskHandle_t ESP3DHal::xHandle = nullptr; #endif // ARDUINO_ARCH_ESP32 -#include "esp3doutput.h" +#include "esp3d_message.h" -uint32_t Hal::_analogRange = 255; -uint32_t Hal::_analogWriteFreq = 1000; +uint32_t ESP3DHal::_analogRange = 255; +uint32_t ESP3DHal::_analogWriteFreq = 1000; -void Hal::pinMode(uint8_t pin, uint8_t mode) { +void ESP3DHal::pinMode(uint8_t pin, uint8_t mode) { #if defined(ARDUINO_ARCH_ESP8266) if ((pin == 16) && (mode == INPUT_PULLUP)) { ::pinMode(pin, INPUT_PULLDOWN_16); @@ -52,7 +52,7 @@ void Hal::pinMode(uint8_t pin, uint8_t mode) { ::pinMode(pin, mode); } -int Hal::analogRead(uint8_t pin) { +int ESP3DHal::analogRead(uint8_t pin) { #ifdef ARDUINO_ARCH_ESP8266 // only one ADC on ESP8266 A0 (void)pin; return ::analogRead(A0); @@ -61,7 +61,7 @@ int Hal::analogRead(uint8_t pin) { #endif } -bool Hal::analogWrite(uint8_t pin, uint value) { +bool ESP3DHal::analogWrite(uint8_t pin, uint value) { if (value > (_analogRange - 1)) { return false; } @@ -73,13 +73,13 @@ bool Hal::analogWrite(uint8_t pin, uint value) { #endif // ARDUINO_ARCH_ESP32 return true; } -void Hal::analogWriteFreq(uint32_t freq) { +void ESP3DHal::analogWriteFreq(uint32_t freq) { _analogWriteFreq = freq; #ifdef ARDUINO_ARCH_ESP8266 ::analogWriteFreq(_analogWriteFreq); #endif // ARDUINO_ARCH_ESP8266 } -void Hal::analogRange(uint32_t range) { +void ESP3DHal::analogRange(uint32_t range) { _analogRange = range; uint8_t resolution = 0; switch (_analogRange) { @@ -110,9 +110,9 @@ void Hal::analogRange(uint32_t range) { } // Setup -bool Hal::begin() { +bool ESP3DHal::begin() { #if defined(ARDUINO_ARCH_ESP32) && defined(CAMERA_DEVICE) - log_esp3d("Disable brown out"); + esp3d_log("Disable brown out"); WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); // disable brownout detector #endif // ARDUINO_ARCH_ESP32 && CAMERA_DEVICE // Clear all wifi state @@ -134,10 +134,10 @@ bool Hal::begin() { } // End ESP3D -void Hal::end() {} +void ESP3DHal::end() {} // Watchdog feeder -void Hal::wdtFeed() { +void ESP3DHal::wdtFeed() { #ifdef ARDUINO_ARCH_ESP8266 ESP.wdtFeed(); #endif // ARDUINO_ARCH_ESP8266 @@ -157,7 +157,7 @@ void Hal::wdtFeed() { #ifndef DISABLE_WDT_ESP3DLIB_TASK if (xHandle && esp_task_wdt_status(xHandle) == ESP_OK) { if (esp_task_wdt_reset() != ESP_OK) { - log_esp3d_e("WDT Reset failed"); + esp3d_log_e("WDT Reset failed"); } } #endif // DISABLE_WDT_ESP3DLIB_TASK @@ -165,7 +165,7 @@ void Hal::wdtFeed() { } // wait function -void Hal::wait(uint32_t milliseconds) { +void ESP3DHal::wait(uint32_t milliseconds) { #if defined(ASYNCWEBSERVER) uint32_t timeout = millis(); while ((millis() - timeout) < milliseconds) { @@ -179,7 +179,7 @@ void Hal::wait(uint32_t milliseconds) { #endif // !ASYNCWEBSERVER } -uint16_t Hal::getChipID() { +uint16_t ESP3DHal::getChipID() { #ifdef ARDUINO_ARCH_ESP8266 return ESP.getChipId(); #endif // ARDUINO_ARCH_ESP8266 @@ -188,7 +188,7 @@ uint16_t Hal::getChipID() { #endif // ARDUINO_ARCH_ESP32 } -bool Hal::has_temperature_sensor() { +bool ESP3DHal::has_temperature_sensor() { #ifdef ARDUINO_ARCH_ESP8266 return false; #endif // ARDUINO_ARCH_ESP8266 @@ -202,7 +202,7 @@ bool Hal::has_temperature_sensor() { #endif // ARDUINO_ARCH_ESP32 } -float Hal::temperature() { +float ESP3DHal::temperature() { #ifdef ARDUINO_ARCH_ESP8266 return 0.0; #endif // ARDUINO_ARCH_ESP8266 @@ -217,7 +217,7 @@ float Hal::temperature() { #endif // ARDUINO_ARCH_ESP32 } -bool Hal::is_pin_usable(uint pin) { +bool ESP3DHal::is_pin_usable(uint pin) { #ifdef ARDUINO_ARCH_ESP8266 if ((pin <= 5) || ((pin >= 12) && (pin <= 16))) { return true; diff --git a/esp3d/src/core/hal.h b/esp3d/src/core/esp3d_hal.h similarity index 95% rename from esp3d/src/core/hal.h rename to esp3d/src/core/esp3d_hal.h index 7e597a50..a1f017e5 100644 --- a/esp3d/src/core/hal.h +++ b/esp3d/src/core/esp3d_hal.h @@ -1,5 +1,5 @@ /* - hal.h - esp3d hal class + esp3d_hal.h - esp3d hal class Copyright (c) 2014 Luc Lebosse. All rights reserved. @@ -33,7 +33,7 @@ #endif // ARDUINO_ARCH_ESP32 #include -class Hal { +class ESP3DHal { public: static bool begin(); static void end(); @@ -65,7 +65,7 @@ class Esp3dTimout { uint64_t getTimeout() { return _timeout; }; private: - uint64_t _start; - uint64_t _timeout; + uint64_t _start = 0; + uint64_t _timeout = 0; }; #endif //_ESP3D_HAL_H diff --git a/esp3d/src/core/esp3d_log.cpp b/esp3d/src/core/esp3d_log.cpp new file mode 100644 index 00000000..7f6b5621 --- /dev/null +++ b/esp3d/src/core/esp3d_log.cpp @@ -0,0 +1,169 @@ +/* + esp3d_log.cpp - log esp3d 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 +*/ + +#include "../include/esp3d_config.h" +#if defined(ESP_LOG_FEATURE) +// telnet +#if ESP_LOG_FEATURE == LOG_OUTPUT_TELNET +#include "../modules/telnet/telnet_server.h" +Telnet_Server telnet_log; +#endif // ESP_LOG_FEATURE == LOG_OUTPUT_TELNET +// Websocket +#if ESP_LOG_FEATURE == LOG_OUTPUT_WEBSOCKET +#include "../modules/websocket/websocket_server.h" +WebSocket_Server websocket_log("log"); +#endif // ESP_LOG_FEATURE == LOG_OUTPUT_WEBSOCKET + +#ifndef LOG_ESP3D_BAUDRATE +#define LOG_ESP3D_BAUDRATE 115200 +#endif //~LOG_ESP3D_BAUDRATE + +#if defined(ARDUINO_ARCH_ESP8266) +// no need with latest esp8266 core +#define pathToFileName(p) p +#endif // ARDUINO_ARCH_ESP8266 + +// Serial +#if (ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL0) || \ + (ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL1) || \ + (ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL2) + +#ifndef ESP3DLIB_ENV +#if ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL0 +#define LOG_OUTPUT_SERIAL Serial +#endif // LOG_OUTPUT_SERIAL0 +#if ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL1 +#define LOG_OUTPUT_SERIAL Serial1 +#endif // LOG_OUTPUT_SERIAL1 +#if ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL2 +#define LOG_OUTPUT_SERIAL Serial2 +#endif // LOG_OUTPUT_SERIAL2 +#else +#define LOG_OUTPUT_SERIAL MYSERIAL1 +#endif // ESP3DLIB_ENV +#endif // ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL0 || ESP_LOG_FEATURE == + // LOG_OUTPUT_SERIAL1 || ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL2 + +void esp3d_logf(uint8_t level, const char* format, ...) { +#if (((ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL0) || \ + (ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL1) || \ + (ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL2)) && \ + !defined(ESP3DLIB_ENV)) + if (!LOG_OUTPUT_SERIAL.availableForWrite()) return; +#endif // ((ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL0) || (ESP_... +#if ESP_LOG_FEATURE == LOG_OUTPUT_TELNET + if (!telnet_log.started() || !telnet_log.isConnected()) { + return; + } +#endif // ESP_LOG_FEATURE == LOG_OUTPUT_TELNET +#if ESP_LOG_FEATURE == LOG_OUTPUT_WEBSOCKET + if (!websocket_log.started()) { + return; + } +#endif // ESP_LOG_FEATURE == LOG_OUTPUT_WEBSOCKET + + size_t len = 0; + char default_buffer[64]; + char* buffer_ptr = default_buffer; + va_list arg; + va_list copy; + va_start(arg, format); + va_copy(copy, arg); + + len = vsnprintf(NULL, 0, format, arg); + + va_end(copy); + if (len >= sizeof(default_buffer)) { + buffer_ptr = (char*)malloc((len + 1) * sizeof(char)); + if (buffer_ptr == NULL) { + return; + } + } + + len = vsnprintf(buffer_ptr, len + 1, format, arg); + +#if (((ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL0) || \ + (ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL1) || \ + (ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL2)) && \ + !defined(ESP3DLIB_ENV)) + LOG_OUTPUT_SERIAL.write((uint8_t*)buffer_ptr, strlen(buffer_ptr)); + LOG_OUTPUT_SERIAL.flush(); +#endif // ((ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL0) || (ESP_... + +#if ESP_LOG_FEATURE == LOG_OUTPUT_TELNET + telnet_log.writeBytes((uint8_t*)buffer_ptr, strlen(buffer_ptr)); +#endif // ESP_LOG_FEATURE == LOG_OUTPUT_TELNET +#if ESP_LOG_FEATURE == LOG_OUTPUT_WEBSOCKET + websocket_log.writeBytes((uint8_t*)buffer_ptr, strlen(buffer_ptr)); +#endif // ESP_LOG_FEATURE == LOG_OUTPUT_WEBSOCKET + + va_end(arg); + if (buffer_ptr != default_buffer) { + free(buffer_ptr); + } +} + +void esp3d_log_init() { +#if (ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL0) || \ + (ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL1) || \ + (ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL2) +#ifdef ARDUINO_ARCH_ESP8266 + LOG_OUTPUT_SERIAL.begin(LOG_ESP3D_BAUDRATE, SERIAL_8N1, SERIAL_FULL, + (ESP_LOG_TX_PIN == -1) ? 1 : ESP_LOG_TX_PIN); +#if ESP_LOG_RX_PIN != -1 + LOG_OUTPUT_SERIAL + .pins((ESP_LOG_TX_PIN == -1) ? 1 : ESP_LOG_TX_PIN, ESP_LOG_RX_PIN) +#endif // ESP_LOG_RX_PIN != -1 +#endif // ARDUINO_ARCH_ESP8266 +#if defined(ARDUINO_ARCH_ESP32) + LOG_OUTPUT_SERIAL.begin(LOG_ESP3D_BAUDRATE, SERIAL_8N1, + ESP_LOG_RX_PIN, ESP_LOG_TX_PIN); +#endif // ARDUINO_ARCH_ESP32 + +#endif // (ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL0) || (ESP_LOG_FEATURE == + // LOG_OUTPUT_SERIAL1)||(ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL2) +} + +void esp3d_network_log_init() { +#if ESP_LOG_FEATURE == LOG_OUTPUT_TELNET + telnet_log.begin(LOG_ESP3D_OUTPUT_PORT, true); +#endif // ESP_LOG_FEATURE == LOG_OUTPUT_TELNET +#if ESP_LOG_FEATURE == LOG_OUTPUT_WEBSOCKET + websocket_log.begin(LOG_ESP3D_OUTPUT_PORT); +#endif // ESP_LOG_FEATURE == LOG_OUTPUT_WEBSOCKET +} +void esp3d_network_log_handle() { +#if ESP_LOG_FEATURE == LOG_OUTPUT_TELNET + telnet_log.handle(); +#endif // ESP_LOG_FEATURE == LOG_OUTPUT_TELNET +#if ESP_LOG_FEATURE == LOG_OUTPUT_WEBSOCKET + websocket_log.handle(); +#endif // ESP_LOG_FEATURE == LOG_OUTPUT_WEBSOCKET +} +void esp3d_network_log_end() { +#if ESP_LOG_FEATURE == LOG_OUTPUT_TELNET + telnet_log.end(); +#endif // ESP_LOG_FEATURE == LOG_OUTPUT_TELNET +#if ESP_LOG_FEATURE == LOG_OUTPUT_WEBSOCKET + websocket_log.end(); +#endif // ESP_LOG_FEATURE == LOG_OUTPUT_WEBSOCKET +} + +#endif // ESP_LOG_FEATURE diff --git a/esp3d/src/core/esp3d_log.h b/esp3d/src/core/esp3d_log.h new file mode 100644 index 00000000..93cd1419 --- /dev/null +++ b/esp3d/src/core/esp3d_log.h @@ -0,0 +1,78 @@ +/* + esp3d_log.h - esp3d log functions + + 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 +*/ + +#pragma once + +#include "../include/esp3d_config.h" +#include "../include/esp3d_defines.h" +#if defined(ESP_LOG_FEATURE) +extern void esp3d_logf(uint8_t level, const char* format, ...); +extern void esp3d_network_log_init(); +extern void esp3d_network_log_handle(); +extern void esp3d_network_log_end(); + +extern void esp3d_log_init(); + +#if !defined(ESP3D_DEBUG_LEVEL) +#define ESP3D_DEBUG_LEVEL LOG_LEVEL_NONE +#endif // ESP3D_DEBUG_LEVEL +#if defined(ARDUINO_ARCH_ESP8266) +// no need with latest esp8266 core +#define pathToFileName(p) p +#endif // ARDUINO_ARCH_ESP8266 + +#if ESP3D_DEBUG_LEVEL >= LOG_LEVEL_VERBOSE +#define esp3d_log(format, ...) \ + esp3d_logf(LOG_LEVEL_VERBOSE, "[ESP3D-VERBOSE][%s:%u] %s(): " format "\r\n", \ + pathToFileName(__FILE__), __LINE__, __FUNCTION__, ##__VA_ARGS__) +#else +#define esp3d_log(format, ...) +#endif // ESP3D_DEBUG_LEVEL>= LOG_LEVEL_VERBOSE + +#if ESP3D_DEBUG_LEVEL >= LOG_LEVEL_DEBUG +#define esp3d_log_d(format, ...) \ + esp3d_logf(LOG_LEVEL_DEBUG, "[ESP3D-DEBUG][%s:%u] %s(): " format "\r\n", \ + pathToFileName(__FILE__), __LINE__, __FUNCTION__, ##__VA_ARGS__) +#else +#define esp3d_log_d(format, ...) +#endif // ESP3D_DEBUG_LEVEL>= LOG_LEVEL_DEBUG + +#if ESP3D_DEBUG_LEVEL >= LOG_LEVEL_ERROR +#define esp3d_log_e(format, ...) \ + esp3d_logf(LOG_LEVEL_ERROR, "[ESP3D-ERROR][%s:%u] %s(): " format "\r\n", \ + pathToFileName(__FILE__), __LINE__, __FUNCTION__, ##__VA_ARGS__) +#define ESP3D_LOG_INIT_FN esp3d_log_init(); +#define ESP3D_LOG_NETWORK_INIT_FN esp3d_network_log_init(); +#define ESP3D_LOG_NETWORK_HANDLE_FN esp3d_network_log_handle(); +#define ESP3D_LOG_NETWORK_END_FN esp3d_network_log_end(); +#else +#define esp3d_log_e(format, ...) +#endif // ESP3D_DEBUG_LEVEL >= LOG_LEVEL_ERROR + +#else +#define esp3d_log_e(format, ...) +#define esp3d_log_d(format, ...) +#define esp3d_log(format, ...) +#undef ESP3D_DEBUG_LEVEL +#define ESP3D_LOG_INIT_FN +#define ESP3D_LOG_NETWORK_INIT_FN +#define ESP3D_LOG_NETWORK_HANDLE_FN +#define ESP3D_LOG_NETWORK_END_FN +#endif // ESP_LOG_FEATURE \ No newline at end of file diff --git a/esp3d/src/core/esp3d_message.cpp b/esp3d/src/core/esp3d_message.cpp new file mode 100644 index 00000000..f3b48daa --- /dev/null +++ b/esp3d/src/core/esp3d_message.cpp @@ -0,0 +1,158 @@ +/* + esp3d_message.cpp - output 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 +*/ +// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 +#include "esp3d_message.h" + +#include "../include/esp3d_config.h" + +ESP3DRequest no_id{.id = 0}; + +#if defined(ESP_LOG_FEATURE) +int msg_counting = 0; +#endif // ESP_LOG_FEATURE + +bool ESP3DMessageManager::deleteMsg(ESP3DMessage* message) { + if (!message) return false; + if (message->data) { + free(message->data); + } + free(message); + message = NULL; +#if defined(ESP_LOG_FEATURE) + esp3d_log("Deletion : Now we have %ld msg", --msg_counting); +#endif // ESP_LOG_FEATURE + return true; +} + +ESP3DMessage* ESP3DMessageManager::newMsg() { + ESP3DMessage* newMsgPtr = (ESP3DMessage*)malloc(sizeof(ESP3DMessage)); + if (newMsgPtr) { +#if defined(ESP_LOG_FEATURE) + esp3d_log("Creation : Now we have %ld msg", ++msg_counting); +#endif // ESP_LOG_FEATURE + newMsgPtr->data = nullptr; + newMsgPtr->size = 0; + newMsgPtr->origin = ESP3DClientType::no_client; + newMsgPtr->target = ESP3DClientType::all_clients; + newMsgPtr->authentication_level = ESP3DAuthenticationLevel::guest; + newMsgPtr->request_id.id = millis(); + newMsgPtr->type = ESP3DMessageType::head; + } else { + esp3d_log_e("Out of memory"); + } + return newMsgPtr; +} + +ESP3DMessage* ESP3DMessageManager::newMsg(ESP3DRequest requestId) { + ESP3DMessage* newMsgPtr = newMsg(); + if (newMsgPtr) { + newMsgPtr->origin = ESP3DClientType::command; + newMsgPtr->request_id = requestId; + } + return newMsgPtr; +} + +bool ESP3DMessageManager::copyMsgInfos(ESP3DMessage* newMsgPtr, + ESP3DMessage msg) { + if (!newMsgPtr) { + return false; + } + newMsgPtr->origin = msg.origin; + newMsgPtr->target = msg.target; + newMsgPtr->authentication_level = msg.authentication_level; + newMsgPtr->request_id = msg.request_id; + newMsgPtr->type = msg.type; + return true; +} + +ESP3DMessage* ESP3DMessageManager::copyMsgInfos(ESP3DMessage msg) { + ESP3DMessage* newMsgPtr = newMsg(); + if (newMsgPtr) { + copyMsgInfos(newMsgPtr, msg); + } + return newMsgPtr; +} + +ESP3DMessage* ESP3DMessageManager::copyMsg(ESP3DMessage msg) { + ESP3DMessage* newMsgPtr = newMsg(msg.origin, msg.target, msg.data, msg.size, + msg.authentication_level); + if (newMsgPtr) { + newMsgPtr->request_id = msg.request_id; + newMsgPtr->type = msg.type; + } + return newMsgPtr; +} + +ESP3DMessage* ESP3DMessageManager::newMsg( + ESP3DClientType origin, ESP3DClientType target, const uint8_t* data, + size_t length, ESP3DAuthenticationLevel authentication_level) { + ESP3DMessage* newMsgPtr = newMsg(origin, target, authentication_level); + if (newMsgPtr) { + if (!setDataContent(newMsgPtr, data, length)) { + deleteMsg(newMsgPtr); + newMsgPtr = nullptr; + esp3d_log_e("newMsg failed for origin %d, target %d, data %s", + (uint8_t)origin, (uint8_t)target, + data ? (char*)data : "null"); + } + } + return newMsgPtr; +} + +ESP3DMessage* ESP3DMessageManager::newMsg( + ESP3DClientType origin, ESP3DClientType target, + ESP3DAuthenticationLevel authentication_level) { + ESP3DMessage* newMsgPtr = newMsg(); + if (newMsgPtr) { + newMsgPtr->origin = origin; + newMsgPtr->target = target; + newMsgPtr->authentication_level = authentication_level; + } + return newMsgPtr; +} + +bool ESP3DMessageManager::setDataContent(ESP3DMessage* msg, const uint8_t* data, + size_t length) { + if (!msg) { + esp3d_log_e("no valid msg container"); + return false; + } + if (!data || length == 0) { + esp3d_log_e("no data to set for %d origin, %d target", (uint8_t)msg->origin, + (uint8_t)msg->target); + return false; + } + if (msg->data) { + free(msg->data); + } + + // add some security in case data is called as string so add 1 byte for \0 + msg->data = (uint8_t*)malloc(sizeof(uint8_t) * (length + 1)); + if (msg->data) { + memcpy(msg->data, data, length); + msg->size = length; + msg->data[length] = + '\0'; // add some security in case data is called as string + esp3d_log("Data content set to %s", msg->data); + return true; + } + esp3d_log_e("Out of memory"); + return false; +} diff --git a/esp3d/src/core/esp3d_message.h b/esp3d/src/core/esp3d_message.h new file mode 100644 index 00000000..253c30c0 --- /dev/null +++ b/esp3d/src/core/esp3d_message.h @@ -0,0 +1,88 @@ +/* + esp3d_message.h - output 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 +*/ + +#define ESP_OUTPUT_IP_ADDRESS 0 +#define ESP_OUTPUT_STATUS 1 +#define ESP_OUTPUT_PROGRESS 2 +#define ESP_OUTPUT_STATE 3 + +#define ESP_STATE_DISCONNECTED 0 + +#ifndef _ESP3DOUTPUT_H +#define _ESP3DOUTPUT_H + +#include "../include/esp3d_config.h" + +#ifdef HTTP_FEATURE +#if defined(ARDUINO_ARCH_ESP32) +class WebServer; +#define WEBSERVER WebServer +#endif // ARDUINO_ARCH_ESP32 +#if defined(ARDUINO_ARCH_ESP8266) +#include +#define WEBSERVER ESP8266WebServer +#endif // ARDUINO_ARCH_ESP8266 +#endif // HTTP_FEATURE + +#include "../modules/authentication/authentication_level_types.h" +#include "esp3d_client_types.h" + +enum class ESP3DMessageType : uint8_t { head, core, tail, unique }; + +union ESP3DRequest { + uint id; + uint code; +#ifdef HTTP_FEATURE + WEBSERVER *http_request; +#endif // HTTP_FEATURE +}; + +extern ESP3DRequest no_id; + +struct ESP3DMessage { + uint8_t *data; + size_t size; + ESP3DClientType origin; + ESP3DClientType target; + ESP3DAuthenticationLevel authentication_level; + ESP3DRequest request_id; + ESP3DMessageType type; +}; + +class ESP3DMessageManager final { + public: + static ESP3DMessage *newMsg(); + static ESP3DMessage *newMsg(ESP3DRequest requestId); + static bool deleteMsg(ESP3DMessage *message); + static bool copyMsgInfos(ESP3DMessage *newMsgPtr, ESP3DMessage msg); + static ESP3DMessage *copyMsgInfos(ESP3DMessage msg); + static ESP3DMessage *copyMsg(ESP3DMessage msg); + static ESP3DMessage *newMsg(ESP3DClientType origin, ESP3DClientType target, + const uint8_t *data, size_t length, + ESP3DAuthenticationLevel authentication_level = + ESP3DAuthenticationLevel::guest); + static ESP3DMessage *newMsg(ESP3DClientType origin, ESP3DClientType target, + ESP3DAuthenticationLevel authentication_level = + ESP3DAuthenticationLevel::guest); + static bool setDataContent(ESP3DMessage *msg, const uint8_t *data, + size_t length); +}; + +#endif //_ESP3DOUTPUT_H diff --git a/esp3d/src/core/settings_esp3d.cpp b/esp3d/src/core/esp3d_settings.cpp similarity index 82% rename from esp3d/src/core/settings_esp3d.cpp rename to esp3d/src/core/esp3d_settings.cpp index b781f122..09691b73 100644 --- a/esp3d/src/core/settings_esp3d.cpp +++ b/esp3d/src/core/esp3d_settings.cpp @@ -19,11 +19,13 @@ */ #include "../include/esp3d_config.h" +#ifndef STRINGIFY #define STRINGIFY(x) #x +#endif // STRINGIFY #define STRING(x) STRINGIFY(x) #if defined(ESP_SAVE_SETTINGS) -#include "esp3doutput.h" -#include "settings_esp3d.h" +#include "esp3d_message.h" +#include "esp3d_settings.h" #if ESP_SAVE_SETTINGS == SETTINGS_IN_EEPROM #include @@ -53,7 +55,7 @@ #include "../modules/serial/serial_service.h" // Current Settings Version -#define CURRENT_SETTINGS_VERSION "ESP3D04" +#define CURRENT_SETTINGS_VERSION "ESP3D05" // boundaries #define MAX_SENSOR_INTERVAL 60000 @@ -65,7 +67,7 @@ #define MIN_BOOT_DELAY 0 #define MIN_NOTIFICATION_TOKEN_LENGTH 0 #define MIN_NOTIFICATION_SETTINGS_LENGTH 0 -#define MAX_NOTIFICATION_TOKEN_LENGTH 63 +#define MAX_NOTIFICATION_TOKEN_LENGTH 250 #define MAX_NOTIFICATION_SETTINGS_LENGTH 128 #define MAX_SERVER_ADDRESS_LENGTH 128 #define MAX_TIME_ZONE_LENGTH 6 @@ -140,16 +142,6 @@ #define DEFAULT_CALIBRATION_DONE "0" #define DEFAULT_SESSION_TIMEOUT "3" -// Default flags -#define DEFAULT_SERIAL_OUTPUT_FLAG "1" -#define DEFAULT_REMOTE_SCREEN_FLAG "1" -#define DEFAULT_WEBSOCKET_FLAG "1" -#define DEFAULT_TELNET_FLAG "1" -#define DEFAULT_BT_FLAG "1" -#define DEFAULT_SCREEN_FLAG "1" -#define DEFAULT_SERIAL_BRIDGE_FLAG "1" - -#ifdef WIFI_FEATURE // default string values #define DEFAULT_AP_SSID "ESP3D" #define DEFAULT_AP_PASSWORD "12345678" @@ -160,10 +152,8 @@ #define DEFAULT_STA_SSID "NETWORK_SSID" #define DEFAULT_STA_PASSWORD "12345678" #endif // STATION_WIFI_SSID && STATION_WIFI_PASSWORD -#endif // WIFI_FEATURE -#if defined(BLUETOOTH_FEATURE) || defined(WIFI_FEATURE) || defined(ETH_FEATURE) + #define DEFAULT_HOSTNAME "esp3d" -#endif // BLUETOOTH_FEATURE ||WIFI_FEATURE || ETH_FEATURE #define DEFAULT_ADMIN_PWD "admin" #define DEFAULT_USER_PWD "user" @@ -172,7 +162,7 @@ #define DEFAULT_TIME_SERVER2 "time.google.com" #define DEFAULT_TIME_SERVER3 "0.pool.ntp.org" -#define DEFAULT_SETTINGS_VERSION "ESP3D30" +#define DEFAULT_SETTINGS_VERSION "ESP3D31" // default IP values #define DEFAULT_STA_IP_VALUE "192.168.0.254" @@ -185,8 +175,8 @@ #define DEFAULT_AP_MASK_VALUE "255.255.255.0" #define DEFAULT_AP_DNS_VALUE DEFAULT_AP_IP_VALUE -uint8_t Settings_ESP3D::_FirmwareTarget = 0; -bool Settings_ESP3D::_isverboseboot = false; +uint8_t ESP3DSettings::_FirmwareTarget = 0; +bool ESP3DSettings::_isverboseboot = false; uint16_t ESP3DSettingsData[] = {ESP_RADIO_MODE, ESP_STA_PASSWORD, @@ -200,35 +190,28 @@ uint16_t ESP3DSettingsData[] = {ESP_RADIO_MODE, ESP_STA_MASK_VALUE, ESP_STA_DNS_VALUE, ESP_AP_IP_VALUE, + ESP_STA_IP_MODE, ESP_SETTINGS_VERSION, ESP_NOTIFICATION_TYPE, ESP_CALIBRATION, ESP_AP_CHANNEL, ESP_BUZZER, ESP_INTERNET_TIME, - ESP_SERIAL_FLAG, ESP_HTTP_ON, ESP_TELNET_ON, ESP_WEBSOCKET_ON, ESP_SD_SPEED_DIV, ESP_SENSOR_TYPE, ESP_TARGET_FW, - ESP_TIME_IS_DST, - ESP_REMOTE_SCREEN_FLAG, ESP_SD_MOUNT, ESP_SESSION_TIMEOUT, - ESP_WEBSOCKET_FLAG, ESP_SD_CHECK_UPDATE_AT_BOOT, ESP_SETUP, - ESP_TELNET_FLAG, - ESP_BT_FLAG, - ESP_SCREEN_FLAG, ESP_FTP_ON, ESP_AUTO_NOTIFICATION, ESP_VERBOSE_BOOT, ESP_WEBDAV_ON, ESP_SECURE_SERIAL, - ESP_SERIAL_BRIDGE_FLAG, ESP_SERIAL_BRIDGE_ON, ESP_HOSTNAME, ESP_ADMIN_PWD, @@ -270,20 +253,20 @@ const uint8_t SupportedApChannelsSize = sizeof(SupportedApChannels) / sizeof(uint8_t); #endif // WIFI_FEATURE -bool Settings_ESP3D::begin() { +bool ESP3DSettings::begin() { if (GetSettingsVersion() == -1) { return false; } // get target FW - Settings_ESP3D::GetFirmwareTarget(true); - Settings_ESP3D::isVerboseBoot(true); + ESP3DSettings::GetFirmwareTarget(true); + ESP3DSettings::isVerboseBoot(true); return true; } -bool Settings_ESP3D::isVerboseBoot(bool fromsettings) { +bool ESP3DSettings::isVerboseBoot(bool fromsettings) { #if COMMUNICATION_PROTOCOL != MKS_SERIAL if (fromsettings) { - _isverboseboot = read_byte(ESP_VERBOSE_BOOT); + _isverboseboot = readByte(ESP_VERBOSE_BOOT); } #else _isverboseboot = false; @@ -291,19 +274,19 @@ bool Settings_ESP3D::isVerboseBoot(bool fromsettings) { return _isverboseboot; } -uint8_t Settings_ESP3D::GetFirmwareTarget(bool fromsettings) { +uint8_t ESP3DSettings::GetFirmwareTarget(bool fromsettings) { #if defined(FIXED_FW_TARGET) (void)fromsettings; _FirmwareTarget = FIXED_FW_TARGET; #else if (fromsettings) { - _FirmwareTarget = read_byte(ESP_TARGET_FW); + _FirmwareTarget = readByte(ESP_TARGET_FW); } #endif // #if defined( FIXED_FW_TARGET ) return _FirmwareTarget; } -uint8_t Settings_ESP3D::GetSDDevice() { +uint8_t ESP3DSettings::GetSDDevice() { #ifdef SD_DEVICE return SD_DEVICE_CONNECTION; #else // !SD_DEVICE @@ -311,7 +294,7 @@ uint8_t Settings_ESP3D::GetSDDevice() { #endif // SD_DEVICE } -const char *Settings_ESP3D::GetFirmwareTargetShortName() { +const char *ESP3DSettings::GetFirmwareTargetShortName() { static String response; if (_FirmwareTarget == REPETIER) { @@ -330,17 +313,17 @@ const char *Settings_ESP3D::GetFirmwareTargetShortName() { return response.c_str(); } -uint8_t Settings_ESP3D::read_byte(int pos, bool *haserror) { +uint8_t ESP3DSettings::readByte(int pos, bool *haserror) { if (haserror) { *haserror = true; } - log_esp3d("read_byte %d", pos); + esp3d_log("readByte %d", pos); uint8_t value = getDefaultByteSetting(pos); - log_esp3d("default value %d", value); + esp3d_log("default value %d", value); #if ESP_SAVE_SETTINGS == SETTINGS_IN_EEPROM // check if parameters are acceptable if ((pos + 1 > EEPROM_SIZE)) { - log_esp3d_e("Error read byte %d", pos); + esp3d_log_e("Error read byte %d", pos); return value; } // read byte @@ -351,7 +334,7 @@ uint8_t Settings_ESP3D::read_byte(int pos, bool *haserror) { #if ESP_SAVE_SETTINGS == SETTINGS_IN_PREFERENCES Preferences prefs; if (!prefs.begin(NAMESPACE, true)) { - log_esp3d_e("Error opening %s", NAMESPACE); + esp3d_log_e("Error opening %s", NAMESPACE); return value; } String p = "P_" + String(pos); @@ -369,17 +352,17 @@ uint8_t Settings_ESP3D::read_byte(int pos, bool *haserror) { } // write a flag / byte -bool Settings_ESP3D::write_byte(int pos, const uint8_t value) { +bool ESP3DSettings::writeByte(int pos, const uint8_t value) { #if ESP_SAVE_SETTINGS == SETTINGS_IN_EEPROM // check if parameters are acceptable if (pos + 1 > EEPROM_SIZE) { - log_esp3d_e("Error read byte %d", pos); + esp3d_log_e("Error read byte %d", pos); return false; } EEPROM.begin(EEPROM_SIZE); EEPROM.write(pos, value); if (!EEPROM.commit()) { - log_esp3d_e("Error commit %d", pos); + esp3d_log_e("Error commit %d", pos); return false; } EEPROM.end(); @@ -387,21 +370,21 @@ bool Settings_ESP3D::write_byte(int pos, const uint8_t value) { #if ESP_SAVE_SETTINGS == SETTINGS_IN_PREFERENCES Preferences prefs; if (!prefs.begin(NAMESPACE, false)) { - log_esp3d_e("Error opening %s", NAMESPACE); + esp3d_log_e("Error opening %s", NAMESPACE); return false; } String p = "P_" + String(pos); uint8_t r = prefs.putChar(p.c_str(), value); prefs.end(); if (r == 0) { - log_esp3d_e("Error commit %s", p.c_str()); + esp3d_log_e("Error commit %s", p.c_str()); return false; } #endif // SETTINGS_IN_PREFERENCES return true; } -bool Settings_ESP3D::is_string(const char *s, uint len) { +bool ESP3DSettings::is_string(const char *s, uint len) { for (uint p = 0; p < len; p++) { if (!isPrintable(char(s[p]))) { return false; @@ -413,16 +396,16 @@ bool Settings_ESP3D::is_string(const char *s, uint len) { // read a string // a string is multibyte + \0, this is won't work if 1 char is multibyte like // chinese char -const char *Settings_ESP3D::read_string(int pos, bool *haserror) { +const char *ESP3DSettings::readString(int pos, bool *haserror) { const ESP3DSettingDescription *query = getSettingPtr(pos); if (haserror) { *haserror = true; } if (!query) { - log_esp3d_e("Error unknow entry %d", pos); + esp3d_log_e("Error unknow entry %d", pos); return ""; } - uint8_t size_max = query->size; + size_t size_max = query->size; #if ESP_SAVE_SETTINGS == SETTINGS_IN_EEPROM static char *byte_buffer = NULL; @@ -433,17 +416,17 @@ const char *Settings_ESP3D::read_string(int pos, bool *haserror) { } // check if parameters are acceptable if (pos + size_max + 1 > EEPROM_SIZE) { - log_esp3d_e("Error read string %d", pos); + esp3d_log_e("Error read string %d", pos); return ""; } byte_buffer = (char *)malloc(size_max + 1); if (!byte_buffer) { - log_esp3d_e("Error mem read string %d", pos); + esp3d_log_e("Error mem read string %d", pos); return ""; } EEPROM.begin(EEPROM_SIZE); byte b = 1; // non zero for the while loop below - int i = 0; + size_t i = 0; // read until max size is reached or \0 is found while (i < size_max && b != 0) { @@ -469,7 +452,7 @@ const char *Settings_ESP3D::read_string(int pos, bool *haserror) { static String res; if (!prefs.begin(NAMESPACE, true)) { - log_esp3d_e("Error opening %s", NAMESPACE); + esp3d_log_e("Error opening %s", NAMESPACE); return ""; } String p = "P_" + String(pos); @@ -481,7 +464,7 @@ const char *Settings_ESP3D::read_string(int pos, bool *haserror) { prefs.end(); if (res.length() > size_max) { - log_esp3d_e("String too long %d vs %d", res.length(), size_max); + esp3d_log_e("String too long %d vs %d", res.length(), size_max); res = res.substring(0, size_max - 1); } @@ -494,38 +477,38 @@ const char *Settings_ESP3D::read_string(int pos, bool *haserror) { } // write a string (array of byte with a 0x00 at the end) -bool Settings_ESP3D::write_string(int pos, const char *byte_buffer) { - int size_buffer = strlen(byte_buffer); +bool ESP3DSettings::writeString(int pos, const char *byte_buffer) { + size_t size_buffer = strlen(byte_buffer); const ESP3DSettingDescription *query = getSettingPtr(pos); if (!query) { - log_esp3d_e("Error unknow entry %d", pos); + esp3d_log_e("Error unknow entry %d", pos); return false; } - uint8_t size_max = query->size; + size_t size_max = query->size; // check if parameters are acceptable if (size_max == 0) { - log_esp3d_e("Error unknow entry %d", pos); + esp3d_log_e("Error unknow entry %d", pos); return false; } if (size_max < size_buffer) { - log_esp3d_e("Error string too long %d, %d", pos, size_buffer); + esp3d_log_e("Error string too long %d, %d", pos, size_buffer); return false; } #if ESP_SAVE_SETTINGS == SETTINGS_IN_EEPROM if (pos + size_buffer + 1 > EEPROM_SIZE || byte_buffer == NULL) { - log_esp3d_e("Error write string %d", pos); + esp3d_log_e("Error write string %d", pos); return false; } // copy the value(s) EEPROM.begin(EEPROM_SIZE); - for (int i = 0; i < size_buffer; i++) { + for (size_t i = 0; i < size_buffer; i++) { EEPROM.write(pos + i, byte_buffer[i]); } // 0 terminal EEPROM.write(pos + size_buffer, 0x00); if (!EEPROM.commit()) { - log_esp3d_e("Error commit %d", pos); + esp3d_log_e("Error commit %d", pos); return false; } EEPROM.end(); @@ -533,14 +516,14 @@ bool Settings_ESP3D::write_string(int pos, const char *byte_buffer) { #if ESP_SAVE_SETTINGS == SETTINGS_IN_PREFERENCES Preferences prefs; if (!prefs.begin(NAMESPACE, false)) { - log_esp3d_e("Error opening %s", NAMESPACE); + esp3d_log_e("Error opening %s", NAMESPACE); return false; } String p = "P_" + String(pos); uint8_t r = prefs.putString(p.c_str(), byte_buffer); prefs.end(); if (r != size_buffer) { - log_esp3d_e("Error commit %s", p.c_str()); + esp3d_log_e("Error commit %s", p.c_str()); return false; } #endif // SETTINGS_IN_PREFERENCES @@ -548,7 +531,7 @@ bool Settings_ESP3D::write_string(int pos, const char *byte_buffer) { } // read a uint32 -uint32_t Settings_ESP3D::read_uint32(int pos, bool *haserror) { +uint32_t ESP3DSettings::readUint32(int pos, bool *haserror) { if (haserror) { *haserror = true; } @@ -557,7 +540,7 @@ uint32_t Settings_ESP3D::read_uint32(int pos, bool *haserror) { // check if parameters are acceptable uint8_t size_buffer = sizeof(uint32_t); if (pos + size_buffer > EEPROM_SIZE) { - log_esp3d_e("Error read int %d", pos); + esp3d_log_e("Error read int %d", pos); return res; } uint8_t i = 0; @@ -572,7 +555,7 @@ uint32_t Settings_ESP3D::read_uint32(int pos, bool *haserror) { #if ESP_SAVE_SETTINGS == SETTINGS_IN_PREFERENCES Preferences prefs; if (!prefs.begin(NAMESPACE, true)) { - log_esp3d_e("Error opening %s", NAMESPACE); + esp3d_log_e("Error opening %s", NAMESPACE); return res; } String p = "P_" + String(pos); @@ -590,22 +573,22 @@ uint32_t Settings_ESP3D::read_uint32(int pos, bool *haserror) { } // read an IP -uint32_t Settings_ESP3D::read_IP(int pos, bool *haserror) { - return read_uint32(pos, haserror); +uint32_t ESP3DSettings::read_IP(int pos, bool *haserror) { + return readUint32(pos, haserror); } // read an IP -String Settings_ESP3D::read_IP_String(int pos, bool *haserror) { - return _IpToString(read_uint32(pos, haserror)); +String ESP3DSettings::readIPString(int pos, bool *haserror) { + return _IpToString(readUint32(pos, haserror)); } // write a uint32 -bool Settings_ESP3D::write_uint32(int pos, const uint32_t value) { +bool ESP3DSettings::writeUint32(int pos, const uint32_t value) { #if ESP_SAVE_SETTINGS == SETTINGS_IN_EEPROM uint8_t size_buffer = sizeof(uint32_t); // check if parameters are acceptable if (pos + size_buffer > EEPROM_SIZE) { - log_esp3d_e("Error invalid entry %d", pos); + esp3d_log_e("Error invalid entry %d", pos); return false; } EEPROM.begin(EEPROM_SIZE); @@ -614,7 +597,7 @@ bool Settings_ESP3D::write_uint32(int pos, const uint32_t value) { EEPROM.write(pos + i, ((uint8_t *)(&value))[i]); } if (!EEPROM.commit()) { - log_esp3d_e("Error commit %d", pos); + esp3d_log_e("Error commit %d", pos); return false; } EEPROM.end(); @@ -622,27 +605,22 @@ bool Settings_ESP3D::write_uint32(int pos, const uint32_t value) { #if ESP_SAVE_SETTINGS == SETTINGS_IN_PREFERENCES Preferences prefs; if (!prefs.begin(NAMESPACE, false)) { - log_esp3d_e("Error opening %s", NAMESPACE); + esp3d_log_e("Error opening %s", NAMESPACE); return false; } String p = "P_" + String(pos); uint8_t r = prefs.putUInt(p.c_str(), value); prefs.end(); if (r == 0) { - log_esp3d_e("Error commit %s", p.c_str()); + esp3d_log_e("Error commit %s", p.c_str()); return false; } #endif // SETTINGS_IN_PREFERENCES return true; } -// write a IP -bool Settings_ESP3D::write_IP(int pos, const uint32_t value) { - return write_uint32(pos, value); -} - // clear all entries -bool Settings_ESP3D::reset(bool networkonly) { +bool ESP3DSettings::reset(bool networkonly) { uint nb_settings = sizeof(ESP3DSettingsData) / sizeof(uint16_t); for (uint j = 0; j < nb_settings; j++) { uint16_t i = ESP3DSettingsData[j]; @@ -654,31 +632,31 @@ bool Settings_ESP3D::reset(bool networkonly) { if (query) { switch (query->type) { case ESP3DSettingType::string_t: - if (!Settings_ESP3D::write_string(i, query->default_val)) { - log_esp3d_e("Error reset string %d to %s", i, query->default_val); + if (!ESP3DSettings::writeString(i, query->default_val)) { + esp3d_log_e("Error reset string %d to %s", i, query->default_val); return false; } break; case ESP3DSettingType::byte_t: - if (!Settings_ESP3D::write_byte( + if (!ESP3DSettings::writeByte( i, (uint8_t)strtoul(query->default_val, NULL, 0))) { - log_esp3d_e("Error reset byte %d to %s", i, query->default_val); + esp3d_log_e("Error reset byte %d to %s", i, query->default_val); return false; } break; case ESP3DSettingType::integer_t: case ESP3DSettingType::ip_t: - if (!Settings_ESP3D::write_uint32(i, getDefaultIntegerSetting(i))) { - log_esp3d_e("Error reset uint32 %d to %s", i, query->default_val); + if (!ESP3DSettings::writeUint32(i, getDefaultIntegerSetting(i))) { + esp3d_log_e("Error reset uint32 %d to %s", i, query->default_val); return false; } break; default: - log_esp3d_e("Error unknow entry %d", i); + esp3d_log_e("Error unknow entry %d", i); break; } } else { - log_esp3d_e("Error unknow entry %d", i); + esp3d_log_e("Error unknow entry %d", i); } } return true; @@ -688,27 +666,28 @@ bool Settings_ESP3D::reset(bool networkonly) { // * -1 means no version detected // * 00 / 01 Not used // * 03 and up is version -int8_t Settings_ESP3D::GetSettingsVersion() { +int8_t ESP3DSettings::GetSettingsVersion() { int8_t v = -1; - String version = Settings_ESP3D::read_string(ESP_SETTINGS_VERSION); - if (!Settings_ESP3D::isValidStringSetting(version.c_str(), - ESP_SETTINGS_VERSION)) { - log_esp3d_e("Invalid Settings Version %s expected %s", version.c_str(), + + String version = ESP3DSettings::readString(ESP_SETTINGS_VERSION); + if (!ESP3DSettings::isValidStringSetting(version.c_str(), + ESP_SETTINGS_VERSION)) { + esp3d_log_e("Invalid Settings Version %s, should be %s", version.c_str(), DEFAULT_SETTINGS_VERSION); return v; } v = version.substring(5).toInt(); - log_esp3d("Settings Version %d", v); + esp3d_log("Settings Version %d", v); return v; } // write a IP from string -bool Settings_ESP3D::write_IP_String(int pos, const char *value) { - return write_uint32(pos, _stringToIP(value)); +bool ESP3DSettings::writeIPString(int pos, const char *value) { + return writeUint32(pos, _stringToIP(value)); } // Helper to convert IP string to int -uint32_t Settings_ESP3D::_stringToIP(const char *s) { +uint32_t ESP3DSettings::_stringToIP(const char *s) { uint32_t ip_int = 0; IPAddress ipaddr; if (ipaddr.fromString(s)) { @@ -718,13 +697,13 @@ uint32_t Settings_ESP3D::_stringToIP(const char *s) { } // Helper to convert int to IP string -String Settings_ESP3D::_IpToString(uint32_t ip_int) { +String ESP3DSettings::_IpToString(uint32_t ip_int) { static IPAddress ipaddr; ipaddr = ip_int; return ipaddr.toString(); } -const char *Settings_ESP3D::TargetBoard() { +const char *ESP3DSettings::TargetBoard() { #ifdef ARDUINO_ARCH_ESP32 #if CONFIG_IDF_TARGET_ESP32 #define TYPE_BOARD "ESP32" @@ -749,8 +728,8 @@ const char *Settings_ESP3D::TargetBoard() { #endif // ESP_SAVE_SETTINGS -bool Settings_ESP3D::isValidIPStringSetting(const char *value, - ESP3DSettingIndex settingElement) { +bool ESP3DSettings::isValidIPStringSetting(const char *value, + ESP3DSettingIndex settingElement) { const ESP3DSettingDescription *settingPtr = getSettingPtr(settingElement); if (!settingPtr) { return false; @@ -786,8 +765,8 @@ bool Settings_ESP3D::isValidIPStringSetting(const char *value, } return true; } -bool Settings_ESP3D::isValidStringSetting(const char *value, - ESP3DSettingIndex settingElement) { +bool ESP3DSettings::isValidStringSetting(const char *value, + ESP3DSettingIndex settingElement) { const ESP3DSettingDescription *settingPtr = getSettingPtr(settingElement); if (!(settingPtr->type == ESP3DSettingType::string_t)) { return false; @@ -798,7 +777,7 @@ bool Settings_ESP3D::isValidStringSetting(const char *value, return false; } // only printable char allowed - for (uint i = 0; i < strlen(value); i++) { + for (size_t i = 0; i < strlen(value); i++) { if (!isPrintable(value[i])) { return false; } @@ -809,7 +788,7 @@ bool Settings_ESP3D::isValidStringSetting(const char *value, break; case ESP_HOSTNAME: // only letter and digit - for (uint i = 0; i < strlen(value); i++) { + for (size_t i = 0; i < strlen(value); i++) { char c = value[i]; if (!(isdigit(c) || isalpha(c) || c == '-')) { return false; @@ -826,7 +805,7 @@ bool Settings_ESP3D::isValidStringSetting(const char *value, break; case ESP_ADMIN_PWD: case ESP_USER_PWD: - for (uint i = 0; i < strlen(value); i++) { + for (size_t i = 0; i < strlen(value); i++) { if (value[i] == ' ') { // no space allowed return false; } @@ -851,7 +830,7 @@ bool Settings_ESP3D::isValidStringSetting(const char *value, return true; // no more check for time server break; case ESP_TIME_ZONE: - if (len != settingPtr->size - 1) { + if (len != settingPtr->size) { return false; } for (uint8_t i = 0; i < SupportedTimeZonesSize; i++) { @@ -866,8 +845,8 @@ bool Settings_ESP3D::isValidStringSetting(const char *value, } return false; } -bool Settings_ESP3D::isValidIntegerSetting(uint32_t value, - ESP3DSettingIndex settingElement) { +bool ESP3DSettings::isValidIntegerSetting(uint32_t value, + ESP3DSettingIndex settingElement) { const ESP3DSettingDescription *settingPtr = getSettingPtr(settingElement); if (!settingPtr) { return false; @@ -876,6 +855,7 @@ bool Settings_ESP3D::isValidIntegerSetting(uint32_t value, return false; } switch (settingElement) { +#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL case ESP_SERIAL_BRIDGE_BAUD: case ESP_BAUD_RATE: for (uint8_t i = 0; i < SupportedBaudListSize; i++) { @@ -884,6 +864,7 @@ bool Settings_ESP3D::isValidIntegerSetting(uint32_t value, } } break; +#endif //#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL case ESP_WEBDAV_PORT: case ESP_HTTP_PORT: case ESP_TELNET_PORT: @@ -918,8 +899,8 @@ bool Settings_ESP3D::isValidIntegerSetting(uint32_t value, } return false; } -bool Settings_ESP3D::isValidByteSetting(uint8_t value, - ESP3DSettingIndex settingElement) { +bool ESP3DSettings::isValidByteSetting(uint8_t value, + ESP3DSettingIndex settingElement) { const ESP3DSettingDescription *settingPtr = getSettingPtr(settingElement); if (!settingPtr) { return false; @@ -931,20 +912,13 @@ bool Settings_ESP3D::isValidByteSetting(uint8_t value, switch (settingElement) { case ESP_BUZZER: case ESP_INTERNET_TIME: - case ESP_SERIAL_FLAG: - case ESP_REMOTE_SCREEN_FLAG: case ESP_HTTP_ON: case ESP_TELNET_ON: case ESP_WEBSOCKET_ON: - case ESP_WEBSOCKET_FLAG: case ESP_SD_CHECK_UPDATE_AT_BOOT: case ESP_SETUP: - case ESP_TELNET_FLAG: - case ESP_BT_FLAG: - case ESP_SCREEN_FLAG: case ESP_FTP_ON: case ESP_AUTO_NOTIFICATION: - case ESP_SERIAL_BRIDGE_FLAG: case ESP_SERIAL_BRIDGE_ON: case ESP_VERBOSE_BOOT: case ESP_WEBDAV_ON: @@ -961,7 +935,8 @@ bool Settings_ESP3D::isValidByteSetting(uint8_t value, if (value == ESP_NO_NOTIFICATION || value == ESP_PUSHOVER_NOTIFICATION || value == ESP_EMAIL_NOTIFICATION || value == ESP_LINE_NOTIFICATION || value == ESP_TELEGRAM_NOTIFICATION || - value == ESP_IFTTT_NOTIFICATION) { + value == ESP_IFTTT_NOTIFICATION || + value == ESP_HOMEASSISTANT_NOTIFICATION) { return true; } @@ -974,7 +949,7 @@ bool Settings_ESP3D::isValidByteSetting(uint8_t value, value == ESP_AP_SETUP #endif // WIFI_FEATURE #if defined(ETH_FEATURE) - || value == ESP_ETH + || value == ESP_ETH_STA #endif // ETH_FEATURE #if defined(BLUETOOTH_FEATURE) || value == ESP_BT @@ -1055,7 +1030,7 @@ bool Settings_ESP3D::isValidByteSetting(uint8_t value, return true; } -uint32_t Settings_ESP3D::getDefaultIntegerSetting( +uint32_t ESP3DSettings::getDefaultIntegerSetting( ESP3DSettingIndex settingElement) { const ESP3DSettingDescription *query = getSettingPtr(settingElement); if (query) { @@ -1065,13 +1040,14 @@ uint32_t Settings_ESP3D::getDefaultIntegerSetting( if (query->type == ESP3DSettingType::integer_t) return (uint32_t)strtoul(query->default_val, NULL, 0); else { - log_esp3d_e("Error invalid type %d for %d", query->type, settingElement); + esp3d_log_e("Error invalid type %d for %d", (uint)query->type, + (uint)settingElement); } } return 0; } -const char *Settings_ESP3D::getDefaultStringSetting( +const char *ESP3DSettings::getDefaultStringSetting( ESP3DSettingIndex settingElement) { const ESP3DSettingDescription *query = getSettingPtr(settingElement); if (query) { @@ -1079,27 +1055,28 @@ const char *Settings_ESP3D::getDefaultStringSetting( query->type == ESP3DSettingType::ip_t) return query->default_val; else { - log_esp3d_e("Error invalid type %d for %d", query->type, settingElement); + esp3d_log_e("Error invalid type %d for %d", (uint)query->type, + (uint)settingElement); } } return NULL; } -uint8_t Settings_ESP3D::getDefaultByteSetting( - ESP3DSettingIndex settingElement) { - log_esp3d("getDefaultByteSetting %d", settingElement); +uint8_t ESP3DSettings::getDefaultByteSetting(ESP3DSettingIndex settingElement) { + esp3d_log("getDefaultByteSetting %d", (uint)settingElement); const ESP3DSettingDescription *query = getSettingPtr(settingElement); if (query) { - log_esp3d("getDefaultByteSetting found"); + esp3d_log("getDefaultByteSetting found"); if (query->type == ESP3DSettingType::byte_t) { - log_esp3d("getDefaultByteSetting is %s", query->default_val); + esp3d_log("getDefaultByteSetting is %s", query->default_val); return (uint8_t)strtoul(query->default_val, NULL, 0); } else { - log_esp3d_e("Error invalid type %d for %d", query->type, settingElement); + esp3d_log_e("Error invalid type %d for %d", (uint)query->type, + (uint)settingElement); } } else { - log_esp3d_e("Error unknow entry %d", settingElement); + esp3d_log_e("Error unknow entry %d", (uint)settingElement); } return 0; } @@ -1107,7 +1084,7 @@ uint8_t Settings_ESP3D::getDefaultByteSetting( // get the description of a setting // Unlike esp32 esp8266 does not have lot of memory so we hard code the // settings and just generate one setting on demand -const ESP3DSettingDescription *Settings_ESP3D::getSettingPtr( +const ESP3DSettingDescription *ESP3DSettings::getSettingPtr( const ESP3DSettingIndex index) { static ESP3DSettingDescription setting; memset(&setting, 0, sizeof(setting)); @@ -1121,23 +1098,16 @@ const ESP3DSettingDescription *Settings_ESP3D::getSettingPtr( case ESP_AP_CHANNEL: case ESP_BUZZER: case ESP_INTERNET_TIME: - case ESP_SERIAL_FLAG: case ESP_HTTP_ON: case ESP_TELNET_ON: case ESP_WEBSOCKET_ON: case ESP_SD_SPEED_DIV: case ESP_SENSOR_TYPE: case ESP_TARGET_FW: - case ESP_TIME_IS_DST: - case ESP_REMOTE_SCREEN_FLAG: case ESP_SD_MOUNT: case ESP_SESSION_TIMEOUT: - case ESP_WEBSOCKET_FLAG: case ESP_SD_CHECK_UPDATE_AT_BOOT: case ESP_SETUP: - case ESP_TELNET_FLAG: - case ESP_BT_FLAG: - case ESP_SCREEN_FLAG: case ESP_FTP_ON: case ESP_AUTO_NOTIFICATION: case ESP_VERBOSE_BOOT: @@ -1145,7 +1115,6 @@ const ESP3DSettingDescription *Settings_ESP3D::getSettingPtr( case ESP_SECURE_SERIAL: case ESP_BOOT_RADIO_STATE: case ESP_STA_FALLBACK_MODE: - case ESP_SERIAL_BRIDGE_FLAG: case ESP_SERIAL_BRIDGE_ON: case ESP_STA_IP_MODE: setting.type = ESP3DSettingType::byte_t; // byte @@ -1210,23 +1179,16 @@ const ESP3DSettingDescription *Settings_ESP3D::getSettingPtr( case ESP_AP_CHANNEL: case ESP_BUZZER: case ESP_INTERNET_TIME: - case ESP_SERIAL_FLAG: case ESP_HTTP_ON: case ESP_TELNET_ON: case ESP_WEBSOCKET_ON: case ESP_SD_SPEED_DIV: case ESP_SENSOR_TYPE: case ESP_TARGET_FW: - case ESP_TIME_IS_DST: - case ESP_REMOTE_SCREEN_FLAG: case ESP_SD_MOUNT: case ESP_SESSION_TIMEOUT: - case ESP_WEBSOCKET_FLAG: case ESP_SD_CHECK_UPDATE_AT_BOOT: case ESP_SETUP: - case ESP_TELNET_FLAG: - case ESP_BT_FLAG: - case ESP_SCREEN_FLAG: case ESP_FTP_ON: case ESP_AUTO_NOTIFICATION: case ESP_VERBOSE_BOOT: @@ -1234,7 +1196,6 @@ const ESP3DSettingDescription *Settings_ESP3D::getSettingPtr( case ESP_SECURE_SERIAL: case ESP_BOOT_RADIO_STATE: case ESP_STA_FALLBACK_MODE: - case ESP_SERIAL_BRIDGE_FLAG: case ESP_SERIAL_BRIDGE_ON: case ESP_STA_IP_MODE: setting.size = 1; // 1 byte @@ -1292,6 +1253,8 @@ const ESP3DSettingDescription *Settings_ESP3D::getSettingPtr( // like chinese chars break; case ESP_NOTIFICATION_TOKEN1: + setting.size = 250; // 250 bytes + break; case ESP_NOTIFICATION_TOKEN2: setting.size = 63; // 63 bytes break; @@ -1337,9 +1300,6 @@ const ESP3DSettingDescription *Settings_ESP3D::getSettingPtr( case ESP_INTERNET_TIME: setting.default_val = DEFAULT_INTERNET_TIME; break; - case ESP_SERIAL_FLAG: - setting.default_val = DEFAULT_SERIAL_OUTPUT_FLAG; - break; case ESP_HTTP_ON: setting.default_val = DEFAULT_HTTP_ON; break; @@ -1358,36 +1318,18 @@ const ESP3DSettingDescription *Settings_ESP3D::getSettingPtr( case ESP_TARGET_FW: setting.default_val = STRING(DEFAULT_FW); break; - case ESP_TIME_IS_DST: - setting.default_val = DEFAULT_TIME_DST; - break; - case ESP_REMOTE_SCREEN_FLAG: - setting.default_val = DEFAULT_REMOTE_SCREEN_FLAG; - break; case ESP_SD_MOUNT: setting.default_val = DEFAULT_SD_MOUNT; break; case ESP_SESSION_TIMEOUT: setting.default_val = DEFAULT_SESSION_TIMEOUT; break; - case ESP_WEBSOCKET_FLAG: - setting.default_val = DEFAULT_WEBSOCKET_FLAG; - break; case ESP_SD_CHECK_UPDATE_AT_BOOT: setting.default_val = DEFAULT_SD_CHECK_UPDATE_AT_BOOT; break; case ESP_SETUP: setting.default_val = DEFAULT_SETUP; break; - case ESP_TELNET_FLAG: - setting.default_val = DEFAULT_TELNET_FLAG; - break; - case ESP_BT_FLAG: - setting.default_val = DEFAULT_BT_FLAG; - break; - case ESP_SCREEN_FLAG: - setting.default_val = DEFAULT_SCREEN_FLAG; - break; case ESP_FTP_ON: setting.default_val = DEFAULT_FTP_ON; break; @@ -1409,9 +1351,6 @@ const ESP3DSettingDescription *Settings_ESP3D::getSettingPtr( case ESP_STA_FALLBACK_MODE: setting.default_val = DEFAULT_STA_FALLBACK_MODE; break; - case ESP_SERIAL_BRIDGE_FLAG: - setting.default_val = DEFAULT_SERIAL_BRIDGE_FLAG; - break; case ESP_SERIAL_BRIDGE_ON: setting.default_val = DEFAULT_SERIAL_BRIDGE_ON; break; @@ -1513,13 +1452,13 @@ const ESP3DSettingDescription *Settings_ESP3D::getSettingPtr( setting.default_val = DEFAULT_WEBDAV_PORT; break; default: - log_esp3d_e("Invalid setting %d", index); + esp3d_log_e("Invalid setting %d", index); return NULL; break; } - log_esp3d("Got index %d:", setting.index); - log_esp3d("type %d:", setting.type); - log_esp3d("size %d:", setting.size); - log_esp3d("default_val %s:", setting.default_val); + esp3d_log("Got index %d:", setting.index); + esp3d_log("type %d:", setting.type); + esp3d_log("size %d:", setting.size); + esp3d_log("default_val %s:", setting.default_val); return &setting; } diff --git a/esp3d/src/core/settings_esp3d.h b/esp3d/src/core/esp3d_settings.h similarity index 83% rename from esp3d/src/core/settings_esp3d.h rename to esp3d/src/core/esp3d_settings.h index 31213eec..f142dcc4 100644 --- a/esp3d/src/core/settings_esp3d.h +++ b/esp3d/src/core/esp3d_settings.h @@ -1,6 +1,6 @@ /* - settings_esp3d.h - settings esp3d functions class + esp3d_settings.h - settings esp3d functions class Copyright (c) 2014 Luc Lebosse. All rights reserved. @@ -57,19 +57,18 @@ extern const uint8_t SupportedApChannels[]; extern const uint8_t SupportedApChannelsSize; #endif // WIFI_FEATURE -class Settings_ESP3D { +class ESP3DSettings { public: static bool begin(); - static uint8_t read_byte(int pos, bool *haserror = NULL); - static uint32_t read_uint32(int pos, bool *haserror = NULL); + static uint8_t readByte(int pos, bool *haserror = NULL); + static uint32_t readUint32(int pos, bool *haserror = NULL); static uint32_t read_IP(int pos, bool *haserror = NULL); - static String read_IP_String(int pos, bool *haserror = NULL); - static const char *read_string(int pos, bool *haserror = NULL); - static bool write_byte(int pos, const uint8_t value); - static bool write_string(int pos, const char *byte_buffer); - static bool write_uint32(int pos, const uint32_t value); - static bool write_IP(int pos, const uint32_t value); - static bool write_IP_String(int pos, const char *value); + static String readIPString(int pos, bool *haserror = NULL); + static const char *readString(int pos, bool *haserror = NULL); + static bool writeByte(int pos, const uint8_t value); + static bool writeString(int pos, const char *byte_buffer); + static bool writeUint32(int pos, const uint32_t value); + static bool writeIPString(int pos, const char *value); static bool reset(bool networkonly = false); static int8_t GetSettingsVersion(); static uint8_t GetFirmwareTarget(bool fromsettings = false); diff --git a/esp3d/src/core/esp3d_string.cpp b/esp3d/src/core/esp3d_string.cpp index 46eb1655..8f8e8881 100644 --- a/esp3d/src/core/esp3d_string.cpp +++ b/esp3d/src/core/esp3d_string.cpp @@ -60,7 +60,7 @@ void update_hash(uint8_t* data, size_t len, uint8_t* hash_buffer, static bool reverse = false; reverse = !reverse; int start_index = reverse ? hash_size : 0; - for (int i = 0; i < hash_size; i++) { + for (uint8_t i = 0; i < hash_size; i++) { int idx = reverse ? (start_index - i) % hash_size : (start_index + i) % hash_size; if (i >= len) { @@ -147,4 +147,35 @@ const char* esp3d_string::getContentType(const char* filename) { return "text/plain"; } return "application/octet-stream"; +} + +// tool function to avoid string corrupt JSON files +const char* esp3d_string::encodeString(const char* s) { + static String tmp; + tmp = s; + while (tmp.indexOf("'") != -1) { + tmp.replace("'", "'"); + } + while (tmp.indexOf("\"") != -1) { + tmp.replace("\"", """); + } + if (tmp == "") { + tmp = " "; + } + return tmp.c_str(); +} + +// helper to format size to readable string +const char* esp3d_string::formatBytes(uint64_t bytes) { + static String res; + if (bytes < 1024) { + res = String((uint16_t)bytes) + " B"; + } else if (bytes < (1024 * 1024)) { + res = String((float)(bytes / 1024.0), 2) + " KB"; + } else if (bytes < (1024 * 1024 * 1024)) { + res = String((float)(bytes / 1024.0 / 1024.0), 2) + " MB"; + } else { + res = String((float)(bytes / 1024.0 / 1024.0 / 1024.0), 2) + " GB"; + } + return res.c_str(); } \ No newline at end of file diff --git a/esp3d/src/core/esp3d_string.h b/esp3d/src/core/esp3d_string.h index fdfd9dda..2426adf8 100644 --- a/esp3d/src/core/esp3d_string.h +++ b/esp3d/src/core/esp3d_string.h @@ -25,6 +25,8 @@ namespace esp3d_string { const char* getTimeString(time_t time, bool isGMT); const char* generateUUID(const char* seed); const char* getContentType(const char* filename); +const char* encodeString(const char* s); +const char* formatBytes(uint64_t bytes); } // namespace esp3d_string #endif //_ESP3D_STRING_H diff --git a/esp3d/src/core/esp3doutput.cpp b/esp3d/src/core/esp3doutput.cpp deleted file mode 100644 index a1b6893b..00000000 --- a/esp3d/src/core/esp3doutput.cpp +++ /dev/null @@ -1,847 +0,0 @@ -/* - esp3d output.h - output 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 -*/ -// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 -#include "esp3doutput.h" - -#include "../include/esp3d_config.h" - -#if COMMUNICATION_PROTOCOL != SOCKET_SERIAL || defined(ESP_SERIAL_BRIDGE_OUTPUT) -#include "../modules/serial/serial_service.h" -#endif // COMMUNICATION_PROTOCOL != SOCKET_SERIAL -#if COMMUNICATION_PROTOCOL == SOCKET_SERIAL -#include "../modules/serial2socket/serial2socket.h" -#endif // COMMUNICATION_PROTOCOL == SOCKET_SERIAL -#include "settings_esp3d.h" -#if defined(HTTP_FEATURE) || defined(WS_DATA_FEATURE) -#include "../modules/websocket/websocket_server.h" -#endif // HTTP_FEATURE || WS_DATA_FEATURE -#if defined(BLUETOOTH_FEATURE) -#include "../modules/bluetooth/BT_service.h" -#endif // BLUETOOTH_FEATURE -#if defined(TELNET_FEATURE) -#include "../modules/telnet/telnet_server.h" -#endif // TELNET_FEATURE -#if COMMUNICATION_PROTOCOL == MKS_SERIAL -#include "../modules/mks/mks_service.h" -#endif // COMMUNICATION_PROTOCOL == MKS_SERIAL -#if defined(GCODE_HOST_FEATURE) -#include "../modules/gcode_host/gcode_host.h" -#endif // GCODE_HOST_FEATURE - -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || \ - COMMUNICATION_PROTOCOL == MKS_SERIAL || \ - COMMUNICATION_PROTOCOL == SOCKET_SERIAL -uint8_t ESP3DOutput::_serialoutputflags = 0; -#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == - // MKS_SERIAL || COMMUNICATION_PROTOCOL == SOCKET_SERIAL -#if defined(HAS_DISPLAY) || defined(HAS_SERIAL_DISPLAY) -uint8_t ESP3DOutput::_remotescreenoutputflags = 0; -#endif // HAS_DISPLAY || HAS_SERIAL_DISPLAY -#if defined(WS_DATA_FEATURE) -uint8_t ESP3DOutput::_websocketoutputflags = DEFAULT_WEBSOCKET_FLAG; -#endif // WS_DATA_FEATURE -#if defined(TELNET_FEATURE) -uint8_t ESP3DOutput::_telnetoutputflags = 0; -#endif // TELNET_FEATURE -#if defined(DISPLAY_DEVICE) -uint8_t ESP3DOutput::_screenoutputflags = DEFAULT_SCREEN_FLAG; -#endif // DISPLAY_DEVICE -#if defined(BLUETOOTH_FEATURE) -uint8_t ESP3DOutput::_BToutputflags = DEFAULT_BT_FLAG; -#endif // BLUETOOTH_FEATURE -#if defined(ESP_SERIAL_BRIDGE_OUTPUT) -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 -#if defined(ARDUINO_ARCH_ESP8266) -#include -#endif // ARDUINO_ARCH_ESP8266 -#endif // HTTP_FEATURE -#if defined(DISPLAY_DEVICE) -#include "../modules/display/display.h" -#endif // DISPLAY_DEVICE - -const uint8_t activeClients[] = { -#if !(defined(HAS_DISPLAY) || defined(HAS_SERIAL_DISPLAY)) && \ - (COMMUNICATION_PROTOCOL == RAW_SERIAL || \ - COMMUNICATION_PROTOCOL == MKS_SERIAL) - ESP_SERIAL_CLIENT, -#endif // ESP_SERIAL_CLIENT -#if defined(ESP_SERIAL_BRIDGE_OUTPUT) - ESP_SERIAL_BRIDGE_CLIENT, -#endif // ESP_SERIAL_BRIDGE_OUTPUT -#if defined(TELNET_FEATURE) - ESP_TELNET_CLIENT, -#endif // TELNET_FEATURE -#if defined(HTTP_FEATURE) - ESP_HTTP_CLIENT, -#endif // HTTP_FEATURE -#if defined(HAS_DISPLAY) || defined(HAS_SERIAL_DISPLAY) - ESP_REMOTE_SCREEN_CLIENT, -#endif // defined(HAS_DISPLAY) || defined(HAS_SERIAL_DISPLAY) -#if defined(BLUETOOTH_FEATURE) - ESP_BT_CLIENT, -#endif // BLUETOOTH_FEATURE -#if defined(DISPLAY_DEVICE) - ESP_SCREEN_CLIENT, -#endif // DISPLAY_DEVICE -#if defined(WS_DATA_FEATURE) - ESP_WEBSOCKET_CLIENT, -#endif // WS_DATA_FEATURE -#if COMMUNICATION_PROTOCOL == SOCKET_SERIAL - ESP_SOCKET_SERIAL_CLIENT, - ESP_ECHO_SERIAL_CLIENT, -#endif // COMMUNICATION_PROTOCOL == SOCKET_SERIAL - ESP_NO_CLIENT}; - -// tool function to avoid string corrupt JSON files -const char *ESP3DOutput::encodeString(const char *s) { - static String tmp; - tmp = s; - while (tmp.indexOf("'") != -1) { - tmp.replace("'", "'"); - } - while (tmp.indexOf("\"") != -1) { - tmp.replace("\"", """); - } - if (tmp == "") { - tmp = " "; - } - return tmp.c_str(); -} - -void ESP3DOutput::toScreen(uint8_t output_type, const char *s) { - switch (output_type) { - case ESP_OUTPUT_IP_ADDRESS: -#ifdef DISPLAY_DEVICE - esp3d_display.updateIP(); -#endif // DISPLAY_DEVICE - break; - case ESP_OUTPUT_STATUS: -#ifdef DISPLAY_DEVICE - esp3d_display.setStatus(s); -#endif // DISPLAY_DEVICE - break; - case ESP_OUTPUT_PROGRESS: -#ifdef DISPLAY_DEVICE - esp3d_display.progress((uint8_t)atoi(s)); -#endif // DISPLAY_DEVICE - break; - case ESP_OUTPUT_STATE: -#ifdef DISPLAY_DEVICE - switch (atoi(s)) { - case ESP_STATE_DISCONNECTED: - esp3d_display.setStatus("Disconnected"); - break; - default: - break; - } -#endif // DISPLAY_DEVICE - break; - default: - (void)s; - break; - } -} - -// constructor -ESP3DOutput::ESP3DOutput(uint8_t client) { - _client = client; - -#ifdef HTTP_FEATURE - _code = 200; - _headerSent = false; - _footerSent = false; - _webserver = nullptr; -#endif // HTTP_FEATURE -} - -uint8_t ESP3DOutput::client(uint8_t client) { - if (client != 0) { - _client = client; - } - return _client; -} - -#ifdef HTTP_FEATURE -// constructor -ESP3DOutput::ESP3DOutput(WEBSERVER *webserver) { - _client = ESP_HTTP_CLIENT; - _code = 200; - _headerSent = false; - _footerSent = false; - _webserver = webserver; -} -#endif // HTTP_FEATURE - -// destructor -ESP3DOutput::~ESP3DOutput() { flush(); } - -bool ESP3DOutput::isOutput(uint8_t flag, bool fromsettings) { - if (fromsettings) { -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || \ - COMMUNICATION_PROTOCOL == MKS_SERIAL || \ - COMMUNICATION_PROTOCOL == SOCKET_SERIAL - _serialoutputflags = Settings_ESP3D::read_byte(ESP_SERIAL_FLAG); -#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == - // MKS_SERIAL -#if defined(ESP_SERIAL_BRIDGE_OUTPUT) - _serialBridgeoutputflags = - Settings_ESP3D::read_byte(ESP_SERIAL_BRIDGE_FLAG); -#endif // ESP_SERIAL_BRIDGE_OUTPUT -#if defined(HAS_DISPLAY) || defined(HAS_SERIAL_DISPLAY) - _remotescreenoutputflags = - Settings_ESP3D::read_byte(ESP_REMOTE_SCREEN_FLAG); -#endif // defined(HAS_DISPLAY) || defined(HAS_SERIAL_DISPLAY) -#if defined(WS_DATA_FEATURE) - _websocketoutputflags = Settings_ESP3D::read_byte(ESP_WEBSOCKET_FLAG); -#endif // WS_DATA_FEATURE -#if defined(TELNET_FEATURE) - _telnetoutputflags = Settings_ESP3D::read_byte(ESP_TELNET_FLAG); -#endif // TELNET_FEATURE -#if defined(DISPLAY_DEVICE) - _screenoutputflags = Settings_ESP3D::read_byte(ESP_SCREEN_FLAG); -#endif // DISPLAY_DEVICE -#if defined(BLUETOOTH_FEATURE) - _BToutputflags = Settings_ESP3D::read_byte(ESP_BT_FLAG); -#endif // BLUETOOTH_FEATURE - } - switch (flag) { - case ESP_ECHO_SERIAL_CLIENT: - case ESP_SERIAL_CLIENT: -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || \ - COMMUNICATION_PROTOCOL == MKS_SERIAL || \ - COMMUNICATION_PROTOCOL == SOCKET_SERIAL - return _serialoutputflags; -#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == - // MKS_SERIAL - return 0; - case ESP_SERIAL_BRIDGE_CLIENT: -#if defined(ESP_SERIAL_BRIDGE_OUTPUT) - return _serialBridgeoutputflags; -#endif // ESP_SERIAL_BRIDGE_OUTPUT - return 0; - case ESP_REMOTE_SCREEN_CLIENT: -#if defined(HAS_DISPLAY) || defined(HAS_SERIAL_DISPLAY) - return _remotescreenoutputflags; -#endif // defined(HAS_DISPLAY) || defined(HAS_SERIAL_DISPLAY) - return 0; - case ESP_WEBSOCKET_CLIENT: -#if defined(WS_DATA_FEATURE) - return _websocketoutputflags; -#endif // WS_DATA_FEATURE - return 0; - case ESP_TELNET_CLIENT: -#if defined(TELNET_FEATURE) - return _telnetoutputflags; -#endif // TELNET_FEATURE - return 0; - case ESP_SCREEN_CLIENT: -#if defined(DISPLAY_DEVICE) - return _screenoutputflags; -#endif // DISPLAY_DEVICE - return 0; - case ESP_BT_CLIENT: -#if defined(BLUETOOTH_FEATURE) - return _BToutputflags; -#endif // BLUETOOTH_FEATURE - return 0; - default: - return true; - } -} - -size_t ESP3DOutput::dispatch(const uint8_t *sbuf, size_t len, - uint8_t ignoreClient) { - log_esp3d("Dispatch %d chars from client %d and ignore %d", len, _client, - ignoreClient); -#if defined(GCODE_HOST_FEATURE) - if (!(_client == ESP_STREAM_HOST_CLIENT || - ESP_STREAM_HOST_CLIENT == ignoreClient)) { - log_esp3d("Dispatch to gcode host"); - esp3d_gcode_host.push(sbuf, len); - } -#endif // GCODE_HOST_FEATURE -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - if (!(_client == ESP_SERIAL_CLIENT || ESP_SERIAL_CLIENT == ignoreClient)) { - if (isOutput(ESP_SERIAL_CLIENT)) { -#if COMMUNICATION_PROTOCOL == MKS_SERIAL - log_esp3d("Dispatch to gcode frame"); - MKSService::sendGcodeFrame((const char *)sbuf); -#else - log_esp3d("Dispatch to serial service"); - serial_service.write(sbuf, len); -#endif // COMMUNICATION_PROTOCOL == MKS_SERIAL - } - } -#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == - // MKS_SERIAL -#if COMMUNICATION_PROTOCOL == SOCKET_SERIAL - if (!(_client == ESP_SOCKET_SERIAL_CLIENT || - ESP_SOCKET_SERIAL_CLIENT == ignoreClient)) { - log_esp3d("Dispatch to serial socket client %d is %d, or is %d", _client, - ESP_SOCKET_SERIAL_CLIENT, ignoreClient); - Serial2Socket.push(sbuf, len); - } - if (!(_client == ESP_ECHO_SERIAL_CLIENT || - ESP_ECHO_SERIAL_CLIENT == ignoreClient || - _client == ESP_SOCKET_SERIAL_CLIENT)) { - log_esp3d("Dispatch to echo serial"); - MYSERIAL1.write(sbuf, len); - } -#endif // COMMUNICATION_PROTOCOL == SOCKET_SERIAL -#if defined(HTTP_FEATURE) // no need to block it never - if (!((_client == ESP_WEBSOCKET_TERMINAL_CLIENT) || - (_client == ESP_HTTP_CLIENT) || - (ESP_WEBSOCKET_TERMINAL_CLIENT == ignoreClient) || - (ESP_HTTP_CLIENT == ignoreClient))) { - if (websocket_terminal_server) { - log_esp3d("Dispatch websocket terminal"); - websocket_terminal_server.write(sbuf, len); - } - } -#endif // HTTP_FEATURE -#if defined(BLUETOOTH_FEATURE) - if (!(_client == ESP_BT_CLIENT || ESP_BT_CLIENT == ignoreClient)) { - if (isOutput(ESP_BT_CLIENT) && bt_service.started()) { - log_esp3d("Dispatch to bt"); - bt_service.write(sbuf, len); - } - } -#endif // BLUETOOTH_FEATURE -#if defined(ESP_SERIAL_BRIDGE_OUTPUT) - if (!(_client == ESP_SERIAL_BRIDGE_CLIENT || - ESP_SERIAL_BRIDGE_CLIENT == ignoreClient)) { - if (isOutput(ESP_SERIAL_BRIDGE_CLIENT) && serial_bridge_service.started()) { - log_esp3d("Dispatch to serial bridge"); - serial_bridge_service.write(sbuf, len); - } - } -#endif // ESP_SERIAL_BRIDGE_OUTPUT -#if defined(TELNET_FEATURE) - if (!(_client == ESP_TELNET_CLIENT || ESP_TELNET_CLIENT == ignoreClient)) { - if (isOutput(ESP_TELNET_CLIENT) && telnet_server.started()) { - log_esp3d("Dispatch to telnet"); - telnet_server.write(sbuf, len); - } - } -#endif // TELNET_FEATURE -#if defined(WS_DATA_FEATURE) - if (!(_client == ESP_WEBSOCKET_CLIENT || - ESP_WEBSOCKET_CLIENT == ignoreClient)) { - if (isOutput(ESP_WEBSOCKET_CLIENT) && websocket_data_server.started()) { - log_esp3d("Dispatch to websocket data server"); - websocket_data_server.write(sbuf, len); - } - } -#endif // WS_DATA_FEATURE - return len; -} - -// Flush -void ESP3DOutput::flush() { - if (!isOutput(_client)) { - return; - } - switch (_client) { -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - case ESP_SERIAL_CLIENT: - serial_service.flush(); - break; -#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == - // MKS_SERIAL -#ifdef HTTP_FEATURE - case ESP_HTTP_CLIENT: - if (_webserver) { - if (_headerSent && !_footerSent) { - _webserver->sendContent(""); - _footerSent = true; - } - } - break; -#endif // HTTP_FEATURE -#if defined(BLUETOOTH_FEATURE) - case ESP_BT_CLIENT: - bt_service.flush(); - break; -#endif // BLUETOOTH_FEATURE -#if defined(ESP_SERIAL_BRIDGE_OUTPUT) - case ESP_SERIAL_BRIDGE_CLIENT: - serial_bridge_service.flush(); - break; -#endif // ESP_SERIAL_BRIDGE_OUTPUT -#if defined(TELNET_FEATURE) - case ESP_TELNET_CLIENT: - telnet_server.flush(); - break; -#endif // TELNET_FEATURE - case ESP_ALL_CLIENTS: - // do nothing because there are side effects - break; - default: - break; - } -} - -size_t ESP3DOutput::printLN(const char *s) { - if (!isOutput(_client)) { - return 0; - } - switch (_client) { - case ESP_HTTP_CLIENT: - if (strlen(s) > 0) { - println(s); - return strlen(s) + 1; - } else { - println(" "); - return strlen(s) + 2; - } - return 0; - case ESP_TELNET_CLIENT: - print(s); - println("\r"); - return strlen(s) + 2; - default: - break; - } - return println(s); -} - -size_t ESP3DOutput::printMSGLine(const char *s) { - if (_client == ESP_ALL_CLIENTS) { - // process each client one by one - log_esp3d("PrintMSG to all clients"); - for (uint8_t c = 0; c < sizeof(activeClients); c++) { - if (activeClients[c]) { - log_esp3d("Sending PrintMSG to client %d", activeClients[c]); - _client = activeClients[c]; - printMSG(s); - } - } - _client = ESP_ALL_CLIENTS; - return strlen(s); - } - if (!isOutput(_client)) { - return 0; - } - String display; - log_esp3d("PrintMSG to client %d", _client); - if (_client == ESP_HTTP_CLIENT) { -#ifdef HTTP_FEATURE - if (_webserver) { - if (!_headerSent && !_footerSent) { - _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; - } - if (_headerSent && !_footerSent) { - _webserver->sendContent_P((const char *)s, strlen(s)); - _webserver->sendContent_P((const char *)"\n", 1); - return strlen(s + 1); - } - } - -#endif // HTTP_FEATURE - return 0; - } - // this is not supposed to be displayed on any screen - if (_client == ESP_SCREEN_CLIENT || _client == ESP_REMOTE_SCREEN_CLIENT || - _client == ESP_SCREEN_CLIENT) { - return print(s); - } - switch (Settings_ESP3D::GetFirmwareTarget()) { - case GRBL: - display = "[MSG:"; - display += s; - display += "]"; - break; - case MARLIN_EMBEDDED: - case MARLIN: - if (((_client == ESP_ECHO_SERIAL_CLIENT) || - (_client == ESP_STREAM_HOST_CLIENT)) && - (strcmp(s, "ok") == 0)) { - return 0; - } - - if (_client == ESP_ECHO_SERIAL_CLIENT) { - display = "echo:"; - } else { - display = ";echo:"; - } - - display += s; - break; - case SMOOTHIEWARE: - case REPETIER: - default: - - display = ";"; - - display += s; - } - - return printLN(display.c_str()); -} - -size_t ESP3DOutput::printMSG(const char *s, bool withNL) { - if (_client == ESP_ALL_CLIENTS) { - // process each client one by one - log_esp3d("PrintMSG to all clients"); - for (uint8_t c = 0; c < sizeof(activeClients); c++) { - if (activeClients[c]) { - log_esp3d("Sending PrintMSG to client %d", activeClients[c]); - _client = activeClients[c]; - printMSG(s, withNL); - } - } - _client = ESP_ALL_CLIENTS; - return strlen(s); - } - if (!isOutput(_client)) { - return 0; - } - String display; - log_esp3d("PrintMSG to client %d", _client); - if (_client == ESP_HTTP_CLIENT) { -#ifdef HTTP_FEATURE - 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 - _webserver->send(_code, "text/plain", s); - _headerSent = true; - _footerSent = true; - return strlen(s); - } - } -#endif // HTTP_FEATURE - return 0; - } - - if (_client == ESP_SCREEN_CLIENT) { - return print(s); - } - switch (Settings_ESP3D::GetFirmwareTarget()) { - case GRBL: - display = "[MSG:"; - display += s; - display += "]"; - break; - case MARLIN_EMBEDDED: - case MARLIN: - if (((_client == ESP_ECHO_SERIAL_CLIENT) || - (_client == ESP_STREAM_HOST_CLIENT)) && - (strcmp(s, "ok") == 0)) { - return 0; - } - if (_client == ESP_REMOTE_SCREEN_CLIENT) { -#if defined(HAS_SERIAL_DISPLAY) - display = HAS_SERIAL_DISPLAY; -#endif // HAS_REMOTE_SCREEN - display += "M117 "; - withNL = true; - log_esp3d("Screen should display %s%s", display.c_str(), s); - } else { - if (_client == ESP_ECHO_SERIAL_CLIENT) { - display = "echo:"; - } else { - display = ";echo:"; - } - } - display += s; - break; - case SMOOTHIEWARE: - case REPETIER: - default: - if (_client == ESP_REMOTE_SCREEN_CLIENT) { - display = "M117 "; - withNL = true; - } else { - display = ";"; - } - display += s; - } - if (withNL) { - return printLN(display.c_str()); - } else { - return print(display.c_str()); - } -} - -size_t ESP3DOutput::printERROR(const char *s, int code_error) { - String display = ""; - if (!isOutput(_client)) { - return 0; - } - if (_client == ESP_SCREEN_CLIENT) { - return print(s); - } - if (_client == ESP_HTTP_CLIENT) { -#ifdef HTTP_FEATURE - (void)code_error; - if (_webserver) { - if (!_headerSent && !_footerSent) { - _webserver->sendHeader("Cache-Control", "no-cache"); - HTTP_Server::set_http_headers(); - if (s[0] != '{') { - display = "error: "; - } else { - display = ""; - } - display += s; - _webserver->send(code_error, "text/plain", display.c_str()); - _headerSent = true; - _footerSent = true; - return display.length(); - } - } -#endif // HTTP_FEATURE - return 0; - } - switch (Settings_ESP3D::GetFirmwareTarget()) { - case GRBL: - if (s[0] != '{') { - display = "error: "; - } - display += s; - break; - case MARLIN_EMBEDDED: - case MARLIN: - if (s[0] != '{') { - display = "error: "; - } - display += s; - break; - case SMOOTHIEWARE: - case REPETIER: - default: - if (s[0] != '{') { - display = ";error: "; - } - display += s; - } - return printLN(display.c_str()); -} - -int ESP3DOutput::availableforwrite() { - switch (_client) { -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - case ESP_SERIAL_CLIENT: - return serial_service.availableForWrite(); -#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == - // MKS_SERIAL -#if defined(ESP_SERIAL_BRIDGE_OUTPUT) - case ESP_SERIAL_BRIDGE_CLIENT: - return serial_bridge_service.availableForWrite(); -#endif // ESP_SERIAL_BRIDGE_OUTPUT -#if defined(BLUETOOTH_FEATURE) - case ESP_BT_CLIENT: - return bt_service.availableForWrite(); - break; -#endif // BLUETOOTH_FEATURE -#if defined(TELNET_FEATURE) - case ESP_TELNET_CLIENT: - return telnet_server.availableForWrite(); - break; -#endif // TELNET_FEATURE -#if defined(WS_DATA_FEATURE) - case ESP_WEBSOCKET_CLIENT: - return websocket_data_server.availableForWrite(); - break; -#endif // WS_DATA_FEATURE - case ESP_ALL_CLIENTS: -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - return serial_service.availableForWrite(); -#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == - // MKS_SERIAL - default: - break; - } - return 0; -} -size_t ESP3DOutput::write(uint8_t c) { - if (!isOutput(_client)) { - return 0; - } - switch (_client) { -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - case ESP_SERIAL_CLIENT: - return serial_service.write(c); -#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == - // MKS_SERIAL -#if COMMUNICATION_PROTOCOL == SOCKET_SERIAL - case ESP_ECHO_SERIAL_CLIENT: - return MYSERIAL1.write(c); - case ESP_SOCKET_SERIAL_CLIENT: - return Serial2Socket.write(c); -#endif // COMMUNICATION_PROTOCOL == SOCKET_SERIAL -#if defined(BLUETOOTH_FEATURE) - case ESP_BT_CLIENT: - return bt_service.write(c); -#endif // BLUETOOTH_FEATURE -#if defined(ESP_SERIAL_BRIDGE_OUTPUT) - case ESP_SERIAL_BRIDGE_CLIENT: - return serial_bridge_service.write(c); - break; -#endif // ESP_SERIAL_BRIDGE_OUTPUT -#if defined(TELNET_FEATURE) - case ESP_TELNET_CLIENT: - return telnet_server.write(c); -#endif // TELNET_FEATURE -#if defined(WS_DATA_FEATURE) - case ESP_WEBSOCKET_CLIENT: - return websocket_data_server.write(c); -#endif // WS_DATA_FEATURE - case ESP_ALL_CLIENTS: -#if defined(BLUETOOTH_FEATURE) - bt_service.write(c); -#endif // BLUETOOTH_FEATURE -#if defined(ESP_SERIAL_BRIDGE_OUTPUT) - serial_bridge_service.write(c); -#endif // ESP_SERIAL_BRIDGE_OUTPUT -#if defined(TELNET_FEATURE) - telnet_server.write(c); -#endif // TELNET_FEATURE -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - serial_service.write(c); -#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == - // MKS_SERIAL -#if COMMUNICATION_PROTOCOL == SOCKET_SERIAL - MYSERIAL1.write(c); -#endif // COMMUNICATION_PROTOCOL == SOCKET_SERIAL - return 1; - default: - return 0; - } -} - -size_t ESP3DOutput::write(const uint8_t *buffer, size_t size) { - if (!isOutput(_client)) { - return 0; - } - switch (_client) { -#ifdef HTTP_FEATURE - case ESP_HTTP_CLIENT: - if (_webserver) { - if (!_headerSent && !_footerSent) { - _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; - } - if (_headerSent && !_footerSent) { - _webserver->sendContent_P((const char *)buffer, size); - } - } - break; -#endif // HTTP_FEATURE -#if defined(DISPLAY_DEVICE) - case ESP_SCREEN_CLIENT: - esp3d_display.setStatus((const char *)buffer); - return size; -#endif // DISPLAY_DEVICE -#if defined(BLUETOOTH_FEATURE) - case ESP_BT_CLIENT: - return bt_service.write(buffer, size); -#endif // BLUETOOTH_FEATURE -#if defined(ESP_SERIAL_BRIDGE_OUTPUT) - case ESP_SERIAL_BRIDGE_CLIENT: - return serial_bridge_service.write(buffer, size); -#endif // ESP_SERIAL_BRIDGE_OUTPUT -#if defined(TELNET_FEATURE) - case ESP_TELNET_CLIENT: - return telnet_server.write(buffer, size); -#endif // TELNET_FEATURE -#if defined(WS_DATA_FEATURE) - case ESP_WEBSOCKET_CLIENT: - return websocket_data_server.write(buffer, size); -#endif // WS_DATA_FEATURE -#if defined(GCODE_HOST_FEATURE) - case ESP_STREAM_HOST_CLIENT: { -#if COMMUNICATION_PROTOCOL == SOCKET_SERIAL - log_esp3d( - "ESP_STREAM_HOST_CLIENT do a dispatch to all clients but socket " - "serial"); - dispatch(buffer, size, ESP_SOCKET_SERIAL_CLIENT); -#endif // COMMUNICATION_PROTOCOL == SOCKET_SERIAL -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - log_esp3d( - "ESP_STREAM_HOST_CLIENT do a dispatch to all clients but serial"); - dispatch(buffer, size, ESP_SERIAL_CLIENT); -#endif // COMMUNICATION_PROTOCOL == SOCKET_SERIAL - } - return size; - break; -#endif // GCODE_HOST_FEATURE - -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - case ESP_REMOTE_SCREEN_CLIENT: - case ESP_SERIAL_CLIENT: - return serial_service.write(buffer, size); - break; -#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == - // MKS_SERIAL -#if COMMUNICATION_PROTOCOL == SOCKET_SERIAL - case ESP_REMOTE_SCREEN_CLIENT: - log_esp3d("Writing to remote screen: %s", buffer); - return Serial2Socket.push(buffer, size); - break; - case ESP_ECHO_SERIAL_CLIENT: - return MYSERIAL1.write(buffer, size); - break; - case ESP_SOCKET_SERIAL_CLIENT: - return Serial2Socket.push(buffer, size); - break; -#endif // COMMUNICATION_PROTOCOL == SOCKET_SERIAL - case ESP_ALL_CLIENTS: -#if defined(BLUETOOTH_FEATURE) - bt_service.write(buffer, size); -#endif // BLUETOOTH_FEATURE -#if defined(ESP_SERIAL_BRIDGE_OUTPUT) - serial_bridge_service.write(buffer, size); -#endif // ESP_SERIAL_BRIDGE_OUTPUT -#if defined(TELNET_FEATURE) - telnet_server.write(buffer, size); -#endif // TELNET_FEATURE -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - serial_service.write(buffer, size); -#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == - // MKS_SERIAL -#if COMMUNICATION_PROTOCOL == SOCKET_SERIAL - MYSERIAL1.write(buffer, size); -#endif // COMMUNICATION_PROTOCOL == SOCKET_SERIAL - return size; - default: - break; - } - return 0; -} diff --git a/esp3d/src/core/esp3doutput.h b/esp3d/src/core/esp3doutput.h deleted file mode 100644 index 5a8e3b4c..00000000 --- a/esp3d/src/core/esp3doutput.h +++ /dev/null @@ -1,142 +0,0 @@ -/* - esp3doutput.h - output 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 -*/ - -#define ESP_NO_CLIENT 0 -#define ESP_SERIAL_CLIENT 1 -#define ESP_TELNET_CLIENT 2 -#define ESP_HTTP_CLIENT 4 -#define ESP_WEBSOCKET_TERMINAL_CLIENT 8 -#define ESP_REMOTE_SCREEN_CLIENT 16 -#define ESP_STREAM_HOST_CLIENT 30 -#define ESP_BT_CLIENT 32 -#define ESP_SCREEN_CLIENT 64 -#define ESP_WEBSOCKET_CLIENT 128 -#define ESP_SOCKET_SERIAL_CLIENT 129 -#define ESP_ECHO_SERIAL_CLIENT 130 -#define ESP_SERIAL_BRIDGE_CLIENT 150 -#define ESP_ALL_CLIENTS 255 - -#define ESP_STREAM_HOST_OUTPUT ESP_SERIAL_CLIENT - -#define ESP_OUTPUT_IP_ADDRESS 0 -#define ESP_OUTPUT_STATUS 1 -#define ESP_OUTPUT_PROGRESS 2 -#define ESP_OUTPUT_STATE 3 - -#define ESP_STATE_DISCONNECTED 0 - -#ifndef _ESP3DOUTPUT_H -#define _ESP3DOUTPUT_H - -#include "Print.h" -#include "../include/esp3d_config.h" -#ifdef HTTP_FEATURE -#if defined (ARDUINO_ARCH_ESP32) -class WebServer; -#define WEBSERVER WebServer -#endif //ARDUINO_ARCH_ESP32 -#if defined (ARDUINO_ARCH_ESP8266) -#include -#define WEBSERVER ESP8266WebServer -#endif //ARDUINO_ARCH_ESP8266 -#endif //HTTP_FEATURE - - -class ESP3DOutput : public Print -{ -public: - ESP3DOutput(uint8_t client = 0); -#ifdef HTTP_FEATURE - ESP3DOutput(WEBSERVER * webserver); -#endif //HTTP_FEATURE - ~ESP3DOutput(); - size_t write(uint8_t c); - size_t write(const uint8_t *buffer, size_t size); - - inline size_t write(const char * s) - { - return write((uint8_t*) s, strlen(s)); - } - inline size_t write(unsigned long n) - { - return write((uint8_t) n); - } - inline size_t write(long n) - { - return write((uint8_t) n); - } - inline size_t write(unsigned int n) - { - return write((uint8_t) n); - } - inline size_t write(int n) - { - return write((uint8_t) n); - } - uint8_t client(uint8_t client = 0); - size_t dispatch (const uint8_t * sbuf, size_t len, uint8_t ignoreClient = 0); - size_t printMSG(const char * s, bool withNL = true); - size_t printMSGLine(const char * s); - size_t printERROR(const char * s, int code_error = 500); - size_t printLN(const char * s); - void flush(); - int availableforwrite(); - static bool isOutput(uint8_t flag, bool fromsettings = false); - static void toScreen(uint8_t output_type, const char * s); - static const char * encodeString(const char * s); -#ifdef HTTP_FEATURE - bool footerSent() - { - return _footerSent; - } -#endif //HTTP_FEATURE -private: - uint8_t _client; -#ifdef HTTP_FEATURE - int _code; - bool _headerSent; - bool _footerSent; - WEBSERVER * _webserver; -#endif //HTTP_FEATURE -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL || COMMUNICATION_PROTOCOL == SOCKET_SERIAL - static uint8_t _serialoutputflags; -#endif //COMMUNICATION_PROTOCOL -#if defined(HAS_DISPLAY) || defined(HAS_SERIAL_DISPLAY) - static uint8_t _remotescreenoutputflags; -#endif //HAS_DISPLAY || HAS_SERIAL_DISPLAY -#if defined (WS_DATA_FEATURE) - static uint8_t _websocketoutputflags; -#endif //WS_DATA_FEATURE -#if defined (TELNET_FEATURE) - static uint8_t _telnetoutputflags; -#endif //TELNET_FEATURE -#if defined (DISPLAY_DEVICE) - static uint8_t _screenoutputflags; -#endif //DISPLAY_DEVICE -#if defined (BLUETOOTH_FEATURE) - static uint8_t _BToutputflags; -#endif //BLUETOOTH_FEATURE -#if defined(ESP_SERIAL_BRIDGE_OUTPUT) - static uint8_t _serialBridgeoutputflags; -#endif //ESP_SERIAL_BRIDGE_OUTPUT -}; - -#endif //_ESP3DOUTPUT_H - diff --git a/esp3d/src/core/espcmd/ESP100.cpp b/esp3d/src/core/espcmd/ESP100.cpp deleted file mode 100644 index efe5ddfa..00000000 --- a/esp3d/src/core/espcmd/ESP100.cpp +++ /dev/null @@ -1,93 +0,0 @@ -/* - ESP100.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#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"); - 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 (!Settings_ESP3D::isValidStringSetting(parameter.c_str(), - ESP_STA_SSID)) { - 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 (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 diff --git a/esp3d/src/core/espcmd/ESP101.cpp b/esp3d/src/core/espcmd/ESP101.cpp deleted file mode 100644 index 10121887..00000000 --- a/esp3d/src/core/espcmd/ESP101.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/* - ESP101.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#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 (!Settings_ESP3D::isValidStringSetting(parameter.c_str(), - ESP_STA_PASSWORD)) { - 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 (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 diff --git a/esp3d/src/core/espcmd/ESP102.cpp b/esp3d/src/core/espcmd/ESP102.cpp deleted file mode 100644 index 366c89c9..00000000 --- a/esp3d/src/core/espcmd/ESP102.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/* - ESP102.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) -#include "../../modules/network/netconfig.h" -#include "../commands.h" -#include "../esp3doutput.h" -#include "../settings_esp3d.h" - -#if defined(WIFI_FEATURE) -#include "../../modules/wifi/wificonfig.h" -#endif // WIFI_FEATURE -#if defined(ETH_FEATURE) -#include "../../modules/ethernet/ethconfig.h" -#endif // ETH_FEATURE -#include "../../modules/authentication/authentication_service.h" -#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 -#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) { - 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 (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 diff --git a/esp3d/src/core/espcmd/ESP103.cpp b/esp3d/src/core/espcmd/ESP103.cpp deleted file mode 100644 index 7ebf6a88..00000000 --- a/esp3d/src/core/espcmd/ESP103.cpp +++ /dev/null @@ -1,154 +0,0 @@ -/* - ESP103.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) -#include "../../modules/network/netconfig.h" -#include "../commands.h" -#include "../esp3doutput.h" -#include "../settings_esp3d.h" - -#if defined(WIFI_FEATURE) -#include "../../modules/wifi/wificonfig.h" -#endif // WIFI_FEATURE -#if defined(ETH_FEATURE) -#include "../../modules/ethernet/ethconfig.h" -#endif // ETH_FEATURE -#include "../../modules/authentication/authentication_service.h" -#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"); - 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 (!Settings_ESP3D::isValidIPStringSetting(IP.c_str(), - ESP_STA_IP_VALUE)) { - response = format_response(COMMANDID, json, false, "Incorrect IP"); - noError = false; - } - if (!Settings_ESP3D::isValidIPStringSetting(GW.c_str(), - ESP_STA_GATEWAY_VALUE)) { - response = - format_response(COMMANDID, json, false, "Incorrect gateway"); - noError = false; - } - if (!Settings_ESP3D::isValidIPStringSetting(MSK.c_str(), - ESP_STA_MASK_VALUE)) { - response = format_response(COMMANDID, json, false, "Incorrect mask"); - noError = false; - } - if (!Settings_ESP3D::isValidIPStringSetting(DNS.c_str(), - ESP_STA_DNS_VALUE)) { - 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); - } - } - - return noError; -} - -#endif // WIFI_FEATURE || ETH_FEATURE diff --git a/esp3d/src/core/espcmd/ESP104.cpp b/esp3d/src/core/espcmd/ESP104.cpp deleted file mode 100644 index 689f969f..00000000 --- a/esp3d/src/core/espcmd/ESP104.cpp +++ /dev/null @@ -1,133 +0,0 @@ -/* - ESP104.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#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 -#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) { - 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"))) { - - String res = - "Only " -#ifdef 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; -#ifdef 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 (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 diff --git a/esp3d/src/core/espcmd/ESP105.cpp b/esp3d/src/core/espcmd/ESP105.cpp deleted file mode 100644 index a96d6c57..00000000 --- a/esp3d/src/core/espcmd/ESP105.cpp +++ /dev/null @@ -1,93 +0,0 @@ -/* - ESP105.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#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"); - 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 (!Settings_ESP3D::isValidStringSetting(parameter.c_str(), - ESP_AP_SSID)) { - 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 (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 diff --git a/esp3d/src/core/espcmd/ESP106.cpp b/esp3d/src/core/espcmd/ESP106.cpp deleted file mode 100644 index 0e1a6130..00000000 --- a/esp3d/src/core/espcmd/ESP106.cpp +++ /dev/null @@ -1,87 +0,0 @@ -/* - ESP106.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#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 - -#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 (!Settings_ESP3D::isValidStringSetting(parameter.c_str(), - ESP_AP_PASSWORD)) { - 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 (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 diff --git a/esp3d/src/core/espcmd/ESP107.cpp b/esp3d/src/core/espcmd/ESP107.cpp deleted file mode 100644 index f0d7b6c5..00000000 --- a/esp3d/src/core/espcmd/ESP107.cpp +++ /dev/null @@ -1,95 +0,0 @@ -/* - ESP107.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#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 - -#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, - 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 (!Settings_ESP3D::isValidIPStringSetting(parameter.c_str(), - ESP_AP_IP_VALUE)) { - 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"); - } - } - } - } - 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 diff --git a/esp3d/src/core/espcmd/ESP108.cpp b/esp3d/src/core/espcmd/ESP108.cpp deleted file mode 100644 index 288f8645..00000000 --- a/esp3d/src/core/espcmd/ESP108.cpp +++ /dev/null @@ -1,95 +0,0 @@ -/* - ESP108.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#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 - -#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_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 (!Settings_ESP3D::isValidByteSetting(bbuf, 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 (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 diff --git a/esp3d/src/core/espcmd/ESP110.cpp b/esp3d/src/core/espcmd/ESP110.cpp deleted file mode 100644 index 4ebc08d8..00000000 --- a/esp3d/src/core/espcmd/ESP110.cpp +++ /dev/null @@ -1,165 +0,0 @@ -/* - ESP110.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#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 - -#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) { - 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"))) { - - String res = - "Only " -#ifdef BLUETOOTH_FEATURE - "BT or " -#endif // BLUETOOTH_FEATURE -#ifdef 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; -#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 -#ifdef ETH_FEATURE - if (parameter == "ETH-STA") { - bbuf = ESP_ETH_STA; - } -// if(parameter == "ETH-SRV") { -// bbuf = ESP_ETH_SRV; -// } -#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 (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 diff --git a/esp3d/src/core/espcmd/ESP111.cpp b/esp3d/src/core/espcmd/ESP111.cpp deleted file mode 100644 index c97c947e..00000000 --- a/esp3d/src/core/espcmd/ESP111.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/* - ESP111.cpp - ESP3D command 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 -*/ -// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 -#include "../../include/esp3d_config.h" -#if defined(WIFI_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" - -#define COMMANDID 111 -// Get current IP -//[ESP111] [json=no] -bool Commands::ESP111(const char* cmd_params, level_authenticate_type auth_type, - ESP3DOutput* output) { - log_esp3d("Client is %d", output ? output->client() : 0); - (void)auth_type; - bool noError = true; - bool json = has_tag(cmd_params, "json"); - String response; - String parameter = clean_param(get_param(cmd_params, "")); - if (parameter.length() == 0) { - response = - format_response(COMMANDID, json, true, NetConfig::localIP().c_str()); - } else { - parameter = get_param(cmd_params, "OUTPUT="); - if (parameter != "PRINTER") { - response = format_response(COMMANDID, json, false, "Unknown parameter"); - } - } - - if (noError) { - parameter = get_param(cmd_params, "OUTPUT="); - if (json) { - output->printLN(response.c_str()); - } else { - output->printMSG(response.c_str()); - if (parameter == "PRINTER") { - ESP3DOutput printerOutput(ESP_REMOTE_SCREEN_CLIENT); - printerOutput.printMSG(NetConfig::localIP().c_str()); - } - } - } else { - if (json) { - output->printLN(response.c_str()); - } else { - output->printERROR(response.c_str(), 200); - } - } - return noError; -} - -#endif // WIFI_FEATURE diff --git a/esp3d/src/core/espcmd/ESP112.cpp b/esp3d/src/core/espcmd/ESP112.cpp deleted file mode 100644 index aa79868e..00000000 --- a/esp3d/src/core/espcmd/ESP112.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/* - ESP112.cpp - ESP3D command 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 -*/ -#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" - -// 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 - -#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 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 (!Settings_ESP3D::isValidStringSetting(parameter.c_str(), - ESP_HOSTNAME)) { - 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 (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 diff --git a/esp3d/src/core/espcmd/ESP114.cpp b/esp3d/src/core/espcmd/ESP114.cpp deleted file mode 100644 index afa55e73..00000000 --- a/esp3d/src/core/espcmd/ESP114.cpp +++ /dev/null @@ -1,97 +0,0 @@ -/* - ESP114.cpp - ESP3D command 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 -*/ -#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" - - -// 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 - -#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, - (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 (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 diff --git a/esp3d/src/core/espcmd/ESP115.cpp b/esp3d/src/core/espcmd/ESP115.cpp deleted file mode 100644 index 2d4129eb..00000000 --- a/esp3d/src/core/espcmd/ESP115.cpp +++ /dev/null @@ -1,100 +0,0 @@ -/* - ESP115.cpp - ESP3D command 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 -*/ -#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" - -#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 - -#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, - (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; - } - } 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 (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 diff --git a/esp3d/src/core/espcmd/ESP120.cpp b/esp3d/src/core/espcmd/ESP120.cpp deleted file mode 100644 index dd5072df..00000000 --- a/esp3d/src/core/espcmd/ESP120.cpp +++ /dev/null @@ -1,95 +0,0 @@ -/* - ESP120.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#if defined(HTTP_FEATURE) -#include "../../modules/authentication/authentication_service.h" -#include "../commands.h" -#include "../esp3doutput.h" -#include "../settings_esp3d.h" - -#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 -#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, - (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 (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 diff --git a/esp3d/src/core/espcmd/ESP121.cpp b/esp3d/src/core/espcmd/ESP121.cpp deleted file mode 100644 index 094a257a..00000000 --- a/esp3d/src/core/espcmd/ESP121.cpp +++ /dev/null @@ -1,93 +0,0 @@ -/* - ESP121.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#if defined(HTTP_FEATURE) -#include "../../modules/authentication/authentication_service.h" -#include "../commands.h" -#include "../esp3doutput.h" -#include "../settings_esp3d.h" - -#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 - -#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_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 (!Settings_ESP3D::isValidIntegerSetting(ibuf, 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 (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 diff --git a/esp3d/src/core/espcmd/ESP130.cpp b/esp3d/src/core/espcmd/ESP130.cpp deleted file mode 100644 index 1e620912..00000000 --- a/esp3d/src/core/espcmd/ESP130.cpp +++ /dev/null @@ -1,101 +0,0 @@ -/* - ESP130.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#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 -#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, - (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 (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 diff --git a/esp3d/src/core/espcmd/ESP131.cpp b/esp3d/src/core/espcmd/ESP131.cpp deleted file mode 100644 index 50182755..00000000 --- a/esp3d/src/core/espcmd/ESP131.cpp +++ /dev/null @@ -1,92 +0,0 @@ -/* - ESP131.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#if defined(TELNET_FEATURE) -#include "../../modules/authentication/authentication_service.h" -#include "../commands.h" -#include "../esp3doutput.h" -#include "../settings_esp3d.h" - -#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 -#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_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 (!Settings_ESP3D::isValidIntegerSetting(ibuf, 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 (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 diff --git a/esp3d/src/core/espcmd/ESP140.cpp b/esp3d/src/core/espcmd/ESP140.cpp deleted file mode 100644 index 38b77786..00000000 --- a/esp3d/src/core/espcmd/ESP140.cpp +++ /dev/null @@ -1,267 +0,0 @@ -/* - ESP140.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#if defined(TIMESTAMP_FEATURE) -#include "../../modules/authentication/authentication_service.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= -bool Commands::ESP140(const char* cmd_params, level_authenticate_type auth_type, - ESP3DOutput* output) { - bool noError = true; - bool json = has_tag(cmd_params, "json"); - String response = "ok"; - 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) { -#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 = get_param(cmd_params, "srv1="); - if (parameter.length() > 0) { - hasParam = true; - if (Settings_ESP3D::isValidIPStringSetting(parameter.c_str(), - ESP_TIME_SERVER1)) { - if (!Settings_ESP3D::write_string(ESP_TIME_SERVER1, - parameter.c_str())) { - response = format_response(COMMANDID, json, false, - "Set server 1 failed"); - noError = false; - } - } - } - } - if (noError) { - parameter = get_param(cmd_params, "srv2="); - if (parameter.length() > 0) { - hasParam = true; - if (!Settings_ESP3D::isValidIPStringSetting(parameter.c_str(), - ESP_TIME_SERVER2)) { - if (!Settings_ESP3D::write_string(ESP_TIME_SERVER2, - parameter.c_str())) { - response = format_response(COMMANDID, json, false, - "Set server 2 failed"); - noError = false; - } - } - } - } - if (noError) { - parameter = get_param(cmd_params, "srv3="); - if (parameter.length() > 0) { - hasParam = true; - if (!Settings_ESP3D::isValidIPStringSetting(parameter.c_str(), - ESP_TIME_SERVER3)) { - if (!Settings_ESP3D::write_string(ESP_TIME_SERVER3, - parameter.c_str())) { - response = format_response(COMMANDID, json, false, - "Set server 3 failed"); - noError = false; - } - } - } - } - if (noError) { - parameter = get_param(cmd_params, "tzone="); - if (parameter.length() > 0) { - hasParam = true; - 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) { - parameter = get_param(cmd_params, "dst="); - if (parameter.length() > 0) { - hasParam = true; - parameter.toUpperCase(); - if (parameter.length() > 0) { - if (!Settings_ESP3D::write_byte(ESP_TIME_IS_DST, - (parameter == "NO") ? 0 : 1)) { - response = - format_response(COMMANDID, json, false, "Set dayligh failed"); - noError = false; - } - } - } - }*/ - if (noError) { - parameter = get_param(cmd_params, "time="); - parameter.toUpperCase(); - if (parameter.length() > 0) { - hasParam = true; - if (!timeService.setTime(parameter.c_str())) { - response = - format_response(COMMANDID, json, false, "Set time failed"); - noError = false; - } - } - } - 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 (timeService.is_internet_time()) { - if (!timeService.begin()) { - response = - format_response(COMMANDID, json, false, "Init time failed"); - noError = false; - } - } else { - response = - format_response(COMMANDID, json, false, "Time is manual"); - noError = false; - } - if (noError) { - log_esp3d("Get time"); - response = format_response(COMMANDID, json, true, - 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, tmp.c_str()); - } - } - if (noError && !hasParam) { - response = format_response(COMMANDID, json, false, "No parameter"); - noError = false; - } - } else { - // get display settings - String tmp = ""; - if (json) { - tmp += "{\"srv1\":\""; - } else { - tmp += "srv1="; - } - tmp += Settings_ESP3D::read_string(ESP_TIME_SERVER1); - if (json) { - tmp += "\",\"srv2\":\""; - } else { - tmp += ", srv2="; - } - tmp += Settings_ESP3D::read_string(ESP_TIME_SERVER2); - if (json) { - tmp += "\",\"srv3\":\""; - } else { - tmp += ", srv3="; - } - tmp += Settings_ESP3D::read_string(ESP_TIME_ZONE); - if (json) { - tmp += "\",\"tzone\":\""; - } else { - tmp += ", tzone="; - } - tmp += Settings_ESP3D::read_byte(ESP_INTERNET_TIME); - if (json) { - tmp += "\",\"ntp\":\""; - } else { - tmp += ", ntp="; - } - tmp += Settings_ESP3D::read_byte(ESP_INTERNET_TIME) ? "YES" : "NO"; - if (json) { - tmp += "\"}"; - } - response = format_response(COMMANDID, json, true, tmp.c_str()); - } - } - 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 // TIMESTAMP_FEATURE diff --git a/esp3d/src/core/espcmd/ESP150.cpp b/esp3d/src/core/espcmd/ESP150.cpp deleted file mode 100644 index bc5be2af..00000000 --- a/esp3d/src/core/espcmd/ESP150.cpp +++ /dev/null @@ -1,136 +0,0 @@ -/* - ESP150.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#include "../../modules/authentication/authentication_service.h" -#include "../commands.h" -#include "../esp3doutput.h" -#include "../settings_esp3d.h" - -#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 - -#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 += "{\"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; - } -#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 (!Settings_ESP3D::isValidIntegerSetting(ibuf, 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"); - } - } - } - } - 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/ESP160.cpp b/esp3d/src/core/espcmd/ESP160.cpp deleted file mode 100644 index b7137cb7..00000000 --- a/esp3d/src/core/espcmd/ESP160.cpp +++ /dev/null @@ -1,101 +0,0 @@ -/* - ESP160.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#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 -#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, - (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 (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 diff --git a/esp3d/src/core/espcmd/ESP161.cpp b/esp3d/src/core/espcmd/ESP161.cpp deleted file mode 100644 index df909fad..00000000 --- a/esp3d/src/core/espcmd/ESP161.cpp +++ /dev/null @@ -1,92 +0,0 @@ -/* - ESP161.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#if defined(WS_DATA_FEATURE) -#include "../../modules/authentication/authentication_service.h" -#include "../commands.h" -#include "../esp3doutput.h" -#include "../settings_esp3d.h" - -#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 -#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_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 !(Settings_ESP3D::isValidIntegerSetting(ibuf, 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 (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 diff --git a/esp3d/src/core/espcmd/ESP170.cpp b/esp3d/src/core/espcmd/ESP170.cpp deleted file mode 100644 index afae498b..00000000 --- a/esp3d/src/core/espcmd/ESP170.cpp +++ /dev/null @@ -1,499 +0,0 @@ -/* - ESP122.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#if defined(CAMERA_DEVICE) -#include "../../modules/authentication/authentication_service.h" -#include "../../modules/camera/camera.h" -#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 - -#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) { - 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 (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 diff --git a/esp3d/src/core/espcmd/ESP171.cpp b/esp3d/src/core/espcmd/ESP171.cpp deleted file mode 100644 index 84b8dab5..00000000 --- a/esp3d/src/core/espcmd/ESP171.cpp +++ /dev/null @@ -1,122 +0,0 @@ -/* - ESP122.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#if defined(CAMERA_DEVICE) -#include - -#include "../../modules/authentication/authentication_service.h" -#include "../../modules/camera/camera.h" -#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; - } -#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 (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 diff --git a/esp3d/src/core/espcmd/ESP180.cpp b/esp3d/src/core/espcmd/ESP180.cpp deleted file mode 100644 index 0b769cf7..00000000 --- a/esp3d/src/core/espcmd/ESP180.cpp +++ /dev/null @@ -1,103 +0,0 @@ -/* - ESP130.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#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 - -#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, - (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 (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 diff --git a/esp3d/src/core/espcmd/ESP181.cpp b/esp3d/src/core/espcmd/ESP181.cpp deleted file mode 100644 index be4e7a85..00000000 --- a/esp3d/src/core/espcmd/ESP181.cpp +++ /dev/null @@ -1,168 +0,0 @@ -/* - ESP181.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#if defined(FTP_FEATURE) -#include "../../modules/authentication/authentication_service.h" -#include "../commands.h" -#include "../esp3doutput.h" -#include "../settings_esp3d.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 - -#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 += "{\"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; - } -#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 (!Settings_ESP3D::isValidIntegerSetting(ibuf, 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 (!Settings_ESP3D::isValidIntegerSetting(ibuf, - 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 (!Settings_ESP3D::isValidIntegerSetting( - ibuf, 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 (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 diff --git a/esp3d/src/core/espcmd/ESP190.cpp b/esp3d/src/core/espcmd/ESP190.cpp deleted file mode 100644 index f21d75a4..00000000 --- a/esp3d/src/core/espcmd/ESP190.cpp +++ /dev/null @@ -1,104 +0,0 @@ -/* - ESP190.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#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 -#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, - (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 (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 diff --git a/esp3d/src/core/espcmd/ESP191.cpp b/esp3d/src/core/espcmd/ESP191.cpp deleted file mode 100644 index 5656c7b3..00000000 --- a/esp3d/src/core/espcmd/ESP191.cpp +++ /dev/null @@ -1,92 +0,0 @@ -/* - ESP191.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#if defined(WEBDAV_FEATURE) -#include "../../modules/authentication/authentication_service.h" -#include "../commands.h" -#include "../esp3doutput.h" -#include "../settings_esp3d.h" - -#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 -#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_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 (!Settings_ESP3D::isValidIntegerSetting(ibuf, 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 (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 diff --git a/esp3d/src/core/espcmd/ESP200.cpp b/esp3d/src/core/espcmd/ESP200.cpp deleted file mode 100644 index 1b9646c2..00000000 --- a/esp3d/src/core/espcmd/ESP200.cpp +++ /dev/null @@ -1,109 +0,0 @@ -/* - ESP200.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#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 - -#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) { - if (releaseSD) { - ESP_SD::releaseFS(); - response = format_response(COMMANDID, json, true, " SD card released"); - } - - if (!ESP_SD::accessFS()) { - log_esp3d_d("No Access to SD card"); - if (ESP_SD::getState() == ESP_SDCARD_BUSY) { - response = format_response(COMMANDID, json, true, "Busy"); - log_esp3d_d("Busy"); - } else { - response = format_response(COMMANDID, json, true, "Not available"); - log_esp3d_d("Not available"); - } - } else { - log_esp3d_d("Accessing SD card ok"); - int8_t state = ESP_SD::getState(true); - if (state != ESP_SDCARD_NOT_PRESENT) { - response = format_response(COMMANDID, json, true, "SD card ok"); - log_esp3d_d("SD card ok"); - if (refreshSD) { - ESP_SD::refreshStats(true); - } - } else { - log_esp3d_d("SD card state %d", state); - } - 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"); - log_esp3d_e("Unknown parameter"); - noError = false; - } - } - } - if (noError) { - if (response.length() == 0) { - log_esp3d_d("No SD card"); - 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 diff --git a/esp3d/src/core/espcmd/ESP201.cpp b/esp3d/src/core/espcmd/ESP201.cpp deleted file mode 100644 index 32a0c780..00000000 --- a/esp3d/src/core/espcmd/ESP201.cpp +++ /dev/null @@ -1,143 +0,0 @@ -/* - ESP201.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#if defined(DIRECT_PIN_FEATURE) -#include "../../modules/authentication/authentication_service.h" -#include "../commands.h" -#include "../esp3doutput.h" -#include "../hal.h" -#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; - } -#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 (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 diff --git a/esp3d/src/core/espcmd/ESP202.cpp b/esp3d/src/core/espcmd/ESP202.cpp deleted file mode 100644 index d077475a..00000000 --- a/esp3d/src/core/espcmd/ESP202.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/* - ESP202.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#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 (Settings_ESP3D::isValidByteSetting(parameter.toInt(), - ESP_SD_SPEED_DIV)) { - 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 (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 diff --git a/esp3d/src/core/espcmd/ESP210.cpp b/esp3d/src/core/espcmd/ESP210.cpp deleted file mode 100644 index 745155b0..00000000 --- a/esp3d/src/core/espcmd/ESP210.cpp +++ /dev/null @@ -1,160 +0,0 @@ -/* - ESP210.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#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"); - 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; - } -#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; - } - } - } - } - 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 diff --git a/esp3d/src/core/espcmd/ESP215.cpp b/esp3d/src/core/espcmd/ESP215.cpp deleted file mode 100644 index e15a3520..00000000 --- a/esp3d/src/core/espcmd/ESP215.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/* - ESP215.cpp - ESP3D command 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 -*/ -#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" - -#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 -#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, - (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(); - } else { - 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) { - output->printMSG(response.c_str()); - } else { - output->printERROR(response.c_str(), errorCode); - } - } - return noError; -} - -#endif // DISPLAY_DEVICE && DISPLAY_TOUCH_DRIVER diff --git a/esp3d/src/core/espcmd/ESP220.cpp b/esp3d/src/core/espcmd/ESP220.cpp deleted file mode 100644 index 454589a6..00000000 --- a/esp3d/src/core/espcmd/ESP220.cpp +++ /dev/null @@ -1,324 +0,0 @@ -/* - ESP220.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#include "../../modules/authentication/authentication_service.h" -#include "../commands.h" -#include "../esp3doutput.h" -#include "../settings_esp3d.h" - -#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 -#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, "")); - 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 -#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 -#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 -#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 -#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 (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 deleted file mode 100644 index 2501a2be..00000000 --- a/esp3d/src/core/espcmd/ESP250.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/* - ESP250.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#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 -#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) { - 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 (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 diff --git a/esp3d/src/core/espcmd/ESP290.cpp b/esp3d/src/core/espcmd/ESP290.cpp deleted file mode 100644 index 4c6077d4..00000000 --- a/esp3d/src/core/espcmd/ESP290.cpp +++ /dev/null @@ -1,70 +0,0 @@ -/* - ESP290.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.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 (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 deleted file mode 100644 index 89775577..00000000 --- a/esp3d/src/core/espcmd/ESP400.cpp +++ /dev/null @@ -1,551 +0,0 @@ -/* - ESP400.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#include "../commands.h" -#include "../esp3doutput.h" -#include "../settings_esp3d.h" -#if COMMUNICATION_PROTOCOL != SOCKET_SERIAL -#include "../../modules/serial/serial_service.h" -#endif // COMMUNICATION_PROTOCOL != SOCKET_SERIAL -#include "../../modules/authentication/authentication_service.h" -#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 - -const char* YesNoLabels[] = {"no", "yes"}; -const char* YesNoValues[] = {"0", "1"}; -const char* RadioModeLabels[] = {"none" -#ifdef WIFI_FEATURE - , - "sta", - "ap", - "setup" -#endif // WIFI_FEATURE -#ifdef BLUETOOTH_FEATURE - , - "bt" -#endif // BLUETOOTH_FEATURE -#ifdef ETH_FEATURE - , - "eth-sta" -#endif // ETH_FEATURE -}; -const char* RadioModeValues[] = {"0" -#ifdef WIFI_FEATURE - , - "1", - "2", - "5" -#endif // WIFI_FEATURE - -#ifdef BLUETOOTH_FEATURE - , - "3" - -#endif // BLUETOOTH_FEATURE - -#ifdef ETH_FEATURE - , - "4" -#endif // ETH_FEATURE -}; - -const char* FallbackLabels[] = {"none" -#ifdef WIFI_FEATURE - , - "setup" -#endif // WIFI_FEATURE -#ifdef BLUETOOTH_FEATURE - , - "bt" -#endif // BLUETOOTH_FEATURE -}; -const char* FallbackValues[] = {"0" -#ifdef WIFI_FEATURE - , - "5" -#endif // WIFI_FEATURE -#ifdef BLUETOOTH_FEATURE - , - "3" -#endif // BLUETOOTH_FEATURE -}; - -const char* FirmwareLabels[] = {"Unknown", "Grbl", "Marlin", "Smoothieware", - "Repetier"}; - -const char* FirmwareValues[] = {"0", "10", "20", "40", "50"}; -#ifdef NOTIFICATION_FEATURE -const char* NotificationsLabels[] = {"none", "pushover", "email", - "line", "telegram", "ifttt"}; - -const char* NotificationsValues[] = {"0", "1", "2", "3", "4", "5"}; -#endif // NOTIFICATION_FEATURE - -const char* IpModeLabels[] = {"static", "dhcp"}; -const char* IpModeValues[] = {"0", "1"}; - -const char* SupportedApChannelsStr[] = {"1", "2", "3", "4", "5", "6", "7", - "8", "9", "10", "11", "12", "13", "14"}; - -const char* SupportedBaudListSizeStr[] = { - "9600", "19200", "38400", "57600", "74880", "115200", - "230400", "250000", "500000", "921600", "1958400"}; - -#ifdef SENSOR_DEVICE - -const char* SensorLabels[] = {"none" -#if SENSOR_DEVICE == DHT11_DEVICE || SENSOR_DEVICE == DHT22_DEVICE - , - "DHT11", - "DHT22" - -#endif // SENSOR_DEVICE == DHT11_DEVICE || SENSOR_DEVICE == DHT22_DEVICE -#if SENSOR_DEVICE == ANALOG_DEVICE - , - "Analog" -#endif // SENSOR_DEVICE == ANALOG_DEVICE -#if SENSOR_DEVICE == BMP280_DEVICE || SENSOR_DEVICE == BME280_DEVICE - , - "BMP280", - "BME280" -#endif // SENSOR_DEVICE == BMP280_DEVICE || SENSOR_DEVICE == BME280_DEVICE -}; -const char* SensorValues[] = {"0" -#if SENSOR_DEVICE == DHT11_DEVICE || SENSOR_DEVICE == DHT22_DEVICE - , - "1", - "2" -#endif // SENSOR_DEVICE == DHT11_DEVICE || SENSOR_DEVICE == DHT22_DEVICE - -#if SENSOR_DEVICE == ANALOG_DEVICE - , - "3" -#endif // SENSOR_DEVICE == ANALOG_DEVICE -#if SENSOR_DEVICE == BMP280_DEVICE || SENSOR_DEVICE == BME280_DEVICE - , - "4", - "5" -#endif // SENSOR_DEVICE == BMP280_DEVICE || SENSOR_DEVICE == BME280_DEVICE - -}; - -#endif // SENSOR_DEVICE - -#ifdef SD_DEVICE -#if SD_DEVICE != ESP_SDIO -const char* SupportedSPIDividerStr[] = {"1", "2", "4", "6", "8", "16", "32"}; -const uint8_t SupportedSPIDividerStrSize = - sizeof(SupportedSPIDividerStr) / sizeof(char*); -#endif // SD_DEVICE != ESP_SDIO -#endif // SD_DEVICE - -// Get full ESP3D settings -//[ESP400] -bool Commands::ESP400(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; - uint8_t count = 0; - const long* bl = NULL; - 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 (json) { - output->printLN(response.c_str()); - } else { - if (noError) { - output->printERROR(response.c_str(), errorCode); - } - } - return false; - } -#else - (void)auth_type; -#endif // AUTHENTICATION_FEATURE - if (json) { - output->print("{\"cmd\":\"400\",\"status\":\"ok\",\"data\":["); - } else { - output->println("Settings:"); - } -#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BT_FEATURE) - // Hostname network/network - _dispatchSetting(json, "network/network", ESP_HOSTNAME, "hostname", NULL, - NULL, 32, 1, 1, -1, NULL, true, output, true); -#endif // WIFI_FEATURE || ETH_FEATURE || BT_FEATURE - - // radio mode network/network - _dispatchSetting(json, "network/network", ESP_RADIO_MODE, "radio mode", - RadioModeValues, RadioModeLabels, - sizeof(RadioModeValues) / sizeof(char*), -1, -1, -1, NULL, - true, output); - - // Radio State at Boot - _dispatchSetting(json, "network/network", ESP_BOOT_RADIO_STATE, "radio_boot", - YesNoValues, YesNoLabels, - sizeof(YesNoValues) / sizeof(char*), -1, -1, -1, NULL, true, - output); -#ifdef WIFI_FEATURE - // STA SSID network/sta - _dispatchSetting(json, "network/sta", ESP_STA_SSID, "SSID", nullptr, nullptr, - 32, 1, 1, -1, nullptr, true, output); - - // STA Password network/sta - _dispatchSetting(json, "network/sta", ESP_STA_PASSWORD, "pwd", nullptr, - nullptr, 64, 8, 0, -1, nullptr, true, output); - -#endif // WIFI_FEATURE -#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) - // STA IP mode - _dispatchSetting(json, "network/sta", ESP_STA_IP_MODE, "ip mode", - IpModeValues, IpModeLabels, - sizeof(IpModeLabels) / sizeof(char*), -1, -1, -1, nullptr, - true, output); - // STA static IP - _dispatchSetting(json, "network/sta", ESP_STA_IP_VALUE, "ip", nullptr, - nullptr, -1, -1, -1, -1, nullptr, true, output); - - // STA static Gateway - _dispatchSetting(json, "network/sta", ESP_STA_GATEWAY_VALUE, "gw", nullptr, - nullptr, -1, -1, -1, -1, nullptr, true, output); - // STA static Mask - _dispatchSetting(json, "network/sta", ESP_STA_MASK_VALUE, "msk", nullptr, - nullptr, -1, -1, -1, -1, nullptr, true, output); - // STA static DNS - _dispatchSetting(json, "network/sta", ESP_STA_DNS_VALUE, "DNS", nullptr, - nullptr, -1, -1, -1, -1, nullptr, true, output); - -#endif // WIFI_FEATURE || ETH_FEATURE - -#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BT_FEATURE) - // Sta fallback mode - _dispatchSetting(json, "network/sta", ESP_STA_FALLBACK_MODE, - "sta fallback mode", FallbackValues, FallbackLabels, - sizeof(FallbackValues) / sizeof(char*), -1, -1, -1, nullptr, - true, output); -#endif // WIFI_FEATURE || ETH_FEATURE || BT_FEATURE -#if defined(WIFI_FEATURE) - // AP SSID network/ap - _dispatchSetting(json, "network/ap", ESP_AP_SSID, "SSID", nullptr, nullptr, - 32, 1, 1, -1, nullptr, true, output); - - // AP password - _dispatchSetting(json, "network/ap", ESP_AP_PASSWORD, "pwd", nullptr, nullptr, - 64, 8, 0, -1, nullptr, true, output); - // AP static IP - _dispatchSetting(json, "network/ap", ESP_AP_IP_VALUE, "ip", nullptr, nullptr, - -1, -1, -1, -1, nullptr, true, output); - - // AP Channel - _dispatchSetting(json, "network/ap", ESP_AP_CHANNEL, "channel", - SupportedApChannelsStr, SupportedApChannelsStr, - sizeof(SupportedApChannelsStr) / sizeof(char*), -1, -1, -1, - nullptr, true, output); -#endif // WIFI_FEATURE - -#ifdef AUTHENTICATION_FEATURE - // Admin password - _dispatchSetting(json, "security/security", ESP_ADMIN_PWD, "adm pwd", nullptr, - nullptr, 20, 0, -1, -1, nullptr, true, output); - // User password - _dispatchSetting(json, "security/security", ESP_USER_PWD, "user pwd", nullptr, - nullptr, 20, 0, -1, -1, nullptr, true, output); - - // session timeout - _dispatchSetting(json, "security/security", ESP_SESSION_TIMEOUT, - "session timeout", nullptr, nullptr, 255, 0, -1, -1, nullptr, - true, output); - -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - // Secure Serial - _dispatchSetting(json, "security/security", ESP_SECURE_SERIAL, "serial", - YesNoValues, YesNoLabels, - sizeof(YesNoValues) / sizeof(char*), -1, -1, -1, nullptr, - true, output); - -#endif // COMMUNICATION_PROTOCOL -#endif // AUTHENTICATION_FEATURE -#ifdef HTTP_FEATURE - // HTTP On service/http - _dispatchSetting(json, "service/http", ESP_HTTP_ON, "enable", YesNoValues, - YesNoLabels, sizeof(YesNoValues) / sizeof(char*), -1, -1, -1, - nullptr, true, output); - // HTTP port - _dispatchSetting(json, "service/http", ESP_HTTP_PORT, "port", nullptr, - nullptr, 65535, 1, -1, -1, nullptr, true, output); -#endif // HTTP_FEATURE - -#ifdef TELNET_FEATURE - // TELNET On service/telnet - _dispatchSetting(json, "service/telnetp", ESP_TELNET_ON, "enable", - YesNoValues, YesNoLabels, - sizeof(YesNoValues) / sizeof(char*), -1, -1, -1, nullptr, - true, output); - - // TELNET Port - _dispatchSetting(json, "service/telnetp", ESP_TELNET_PORT, "port", nullptr, - nullptr, 65535, 1, -1, -1, nullptr, true, output); -#endif // TELNET_FEATURE - -#ifdef WS_DATA_FEATURE - // Websocket On service - _dispatchSetting(json, "service/websocketp", ESP_WEBSOCKET_ON, "enable", - YesNoValues, YesNoLabels, - sizeof(YesNoValues) / sizeof(char*), -1, -1, -1, nullptr, - true, output); - - // Websocket Port - _dispatchSetting(json, "service/websocketp", ESP_WEBSOCKET_PORT, "port", - nullptr, nullptr, 65535, 1, -1, -1, nullptr, true, output); -#endif // WS_DATA_FEATURE - -#ifdef WEBDAV_FEATURE - // WebDav On service - _dispatchSetting(json, "service/webdavp", ESP_WEBDAV_ON, "enable", - YesNoValues, YesNoLabels, - sizeof(YesNoValues) / sizeof(char*), -1, -1, -1, nullptr, - true, output); - - // WebDav Port - _dispatchSetting(json, "service/webdavp", ESP_WEBDAV_PORT, "port", nullptr, - nullptr, 65535, 1, -1, -1, nullptr, true, output); -#endif // WEBDAV_FEATURE - -#ifdef FTP_FEATURE - // FTP On service/ftp - _dispatchSetting(json, "service/ftp", ESP_FTP_ON, "enable", YesNoValues, - YesNoLabels, sizeof(YesNoValues) / sizeof(char*), -1, -1, -1, - nullptr, true, output); - - // FTP Ports - // CTRL Port - _dispatchSetting(json, "service/ftp", ESP_FTP_CTRL_PORT, "control port", - nullptr, nullptr, 65535, 1, -1, -1, nullptr, true, output); - - // Active Port - _dispatchSetting(json, "service/ftp", ESP_FTP_DATA_ACTIVE_PORT, "active port", - nullptr, nullptr, 65535, 1, -1, -1, nullptr, true, output); - - // Passive Port - _dispatchSetting(json, "service/ftp", ESP_FTP_DATA_PASSIVE_PORT, - "passive port", nullptr, nullptr, 65535, 1, -1, -1, nullptr, - true, output); -#endif // FTP_FEATURE - -#if defined(ESP_SERIAL_BRIDGE_OUTPUT) - // Serial bridge On service - _dispatchSetting(json, "service/serial_bridge", ESP_SERIAL_BRIDGE_ON, - "enable", YesNoValues, YesNoLabels, - sizeof(YesNoValues) / sizeof(char*), -1, -1, -1, nullptr, - true, output); - - // Baud Rate - _dispatchSetting(json, "service/serial_bridge", ESP_SERIAL_BRIDGE_BAUD, - "baud", SupportedBaudListSizeStr, SupportedBaudListSizeStr, - sizeof(SupportedBaudListSizeStr) / sizeof(char*), -1, -1, -1, - nullptr, true, output); -#endif // ESP_SERIAL_BRIDGE_OUTPUT - -#ifdef TIMESTAMP_FEATURE - - // Internet Time - _dispatchSetting(json, "service/time", ESP_INTERNET_TIME, "i-time", - YesNoValues, YesNoLabels, - sizeof(YesNoValues) / sizeof(char*), -1, -1, -1, nullptr, - true, output); - - // Time zone - _dispatchSetting(json, "service/time", ESP_TIME_ZONE, "tzone", - SupportedTimeZones, SupportedTimeZones, - SupportedTimeZonesSize, -1, -1, -1, nullptr, true, output); - - // Time Server1 - _dispatchSetting(json, "service/time", ESP_TIME_SERVER1, "t-server", nullptr, - nullptr, 127, 0, -1, -1, nullptr, true, output); - - // Time Server2 - _dispatchSetting(json, "service/time", ESP_TIME_SERVER2, "t-server", nullptr, - nullptr, 127, 0, -1, -1, nullptr, true, output); - - // Time Server3 - _dispatchSetting(json, "service/time", ESP_TIME_SERVER3, "t-server", nullptr, - nullptr, 127, 0, -1, -1, nullptr, true, output); -#endif // TIMESTAMP_FEATURE - -#ifdef NOTIFICATION_FEATURE - // Auto notification - _dispatchSetting(json, "service/notification", ESP_AUTO_NOTIFICATION, - "auto notif", YesNoValues, YesNoLabels, - sizeof(YesNoValues) / sizeof(char*), -1, -1, -1, nullptr, - true, output); - - // Notification type - _dispatchSetting(json, "service/notification", ESP_NOTIFICATION_TYPE, - "notification", NotificationsValues, NotificationsLabels, - sizeof(NotificationsValues) / sizeof(char*), -1, -1, -1, - nullptr, true, output); - - // Token 1 - _dispatchSetting(json, "service/notification", ESP_NOTIFICATION_TOKEN1, "t1", - nullptr, nullptr, 63, 1, 1, -1, nullptr, true, output); - - // Token 2 - _dispatchSetting(json, "service/notification", ESP_NOTIFICATION_TOKEN2, "t2", - nullptr, nullptr, 63, 1, 1, -1, nullptr, true, output); - - // Notifications Settings - _dispatchSetting(json, "service/notification", ESP_NOTIFICATION_SETTINGS, - "ts", nullptr, nullptr, 128, 0, -1, -1, nullptr, true, - output); -#endif // NOTIFICATION_FEATURE - -#ifdef BUZZER_DEVICE - // Buzzer state - _dispatchSetting(json, "device/device", ESP_BUZZER, "buzzer", YesNoValues, - YesNoLabels, sizeof(YesNoValues) / sizeof(char*), -1, -1, -1, - nullptr, true, output); -#endif // BUZZER_DEVICE - -#ifdef SENSOR_DEVICE - // Sensor type - _dispatchSetting(json, "device/sensor", ESP_SENSOR_TYPE, "type", SensorValues, - SensorLabels, sizeof(SensorValues) / sizeof(char*), -1, -1, - -1, nullptr, true, output); - - // Sensor interval - _dispatchSetting(json, "device/sensor", ESP_SENSOR_INTERVAL, "intervalms", - nullptr, nullptr, 60000, 0, -1, -1, nullptr, true, output); - -#endif // SENSOR_DEVICE -#if defined(SD_DEVICE) -#if SD_DEVICE != ESP_SDIO - // SPI SD Divider - _dispatchSetting(json, "device/sd", ESP_SD_SPEED_DIV, "speedx", - SupportedSPIDividerStr, SupportedSPIDividerStr, - SupportedSPIDividerStrSize, -1, -1, -1, nullptr, true, - output); -#endif // SD_DEVICE != ESP_SDIO -#ifdef SD_UPDATE_FEATURE - // SD CHECK UPDATE AT BOOT feature - _dispatchSetting(json, "device/sd", ESP_SD_CHECK_UPDATE_AT_BOOT, "SD updater", - YesNoValues, YesNoLabels, - sizeof(YesNoValues) / sizeof(char*), -1, -1, -1, nullptr, - true, output); -#endif // SD_UPDATE_FEATURE -#endif // SD_DEVICE - -#if !defined(FIXED_FW_TARGET) - // Target FW - _dispatchSetting(json, "system/system", ESP_TARGET_FW, "targetfw", - FirmwareValues, FirmwareLabels, - sizeof(FirmwareValues) / sizeof(char*), -1, -1, -1, nullptr, - true, output); -#endif // FIXED_FW_TARGET -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - // Baud Rate - _dispatchSetting(json, "system/system", ESP_BAUD_RATE, "baud", - SupportedBaudListSizeStr, SupportedBaudListSizeStr, - sizeof(SupportedBaudListSizeStr) / sizeof(char*), -1, -1, -1, - nullptr, true, output); -#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == - // MKS_SERIAL - - // Start delay - _dispatchSetting(json, "system/boot", ESP_BOOT_DELAY, "bootdelay", nullptr, - nullptr, 40000, 0, -1, -1, nullptr, true, output); - - // Verbose boot - _dispatchSetting(json, "system/boot", ESP_VERBOSE_BOOT, "verbose", - YesNoValues, YesNoLabels, - sizeof(YesNoValues) / sizeof(char*), -1, -1, -1, nullptr, - true, output); - -// Output flag -// Serial -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || \ - COMMUNICATION_PROTOCOL == MKS_SERIAL || \ - COMMUNICATION_PROTOCOL == SOCKET_SERIAL - - _dispatchSetting(json, "system/outputmsg", ESP_SERIAL_FLAG, "serial", - YesNoValues, YesNoLabels, - sizeof(YesNoValues) / sizeof(char*), -1, -1, -1, nullptr, - true, output); -#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || - -#if defined(ESP_SERIAL_BRIDGE_OUTPUT) - _dispatchSetting(json, "system/outputmsg", ESP_SERIAL_BRIDGE_FLAG, - "serial_bridge", YesNoValues, YesNoLabels, - sizeof(YesNoValues) / sizeof(char*), -1, -1, -1, nullptr, - true, output); -#endif // ESP_SERIAL_BRIDGE_OUTPUT - -#if (defined(ESP3DLIB_ENV) && defined(HAS_DISPLAY)) || \ - defined(HAS_SERIAL_DISPLAY) - _dispatchSetting(json, "system/outputmsg", ESP_REMOTE_SCREEN_FLAG, "M117", - YesNoValues, YesNoLabels, - sizeof(YesNoValues) / sizeof(char*), -1, -1, -1, nullptr, - true, output); -#endif // ESP3DLIB_ENV - -#ifdef DISPLAY_DEVICE - _dispatchSetting(json, "system/outputmsg", ESP_SCREEN_FLAG, "M117", - YesNoValues, YesNoLabels, - sizeof(YesNoValues) / sizeof(char*), -1, -1, -1, nullptr, - true, output); -#endif // DISPLAY_DEVICE - -#ifdef WS_DATA_FEATURE - _dispatchSetting(json, "system/outputmsg", ESP_WEBSOCKET_FLAG, "ws", - YesNoValues, YesNoLabels, - sizeof(YesNoValues) / sizeof(char*), -1, -1, -1, nullptr, - true, output); -#endif // WS_DATA_FEATURE - -#ifdef BLUETOOTH_FEATURE - _dispatchSetting(json, "system/outputmsg", ESP_BT_FLAG, "BT", YesNoValues, - YesNoLabels, sizeof(YesNoValues) / sizeof(char*), -1, -1, -1, - nullptr, true, output); -#endif // BLUETOOTH_FEATURE - -#ifdef TELNET_FEATURE - _dispatchSetting(json, "system/outputmsg", ESP_TELNET_FLAG, "telnet", - YesNoValues, YesNoLabels, - sizeof(YesNoValues) / sizeof(char*), -1, -1, -1, nullptr, - true, output); -#endif // TELNET_FEATURE - - if (json) { - output->print("]}"); - } else { - output->println("ok"); - } - return true; -} diff --git a/esp3d/src/core/espcmd/ESP401.cpp b/esp3d/src/core/espcmd/ESP401.cpp deleted file mode 100644 index 6c85c305..00000000 --- a/esp3d/src/core/espcmd/ESP401.cpp +++ /dev/null @@ -1,284 +0,0 @@ -/* - ESP401.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#include "../../modules/authentication/authentication_service.h" -#include "../commands.h" -#include "../esp3doutput.h" -#include "../settings_esp3d.h" - -#define COMMANDID 401 -#if COMMUNICATION_PROTOCOL != SOCKET_SERIAL || defined(ESP_SERIAL_BRIDGE_OUTPUT) -#include "../../modules/serial/serial_service.h" -#endif // COMMUNICATION_PROTOCOL != SOCKET_SERIAL -#ifdef SENSOR_DEVICE -#include "../../modules/sensor/sensor.h" -#endif // SENSOR_DEVICE -#ifdef BUZZER_DEVICE -#include "../../modules/buzzer/buzzer.h" -#endif // BUZZER_DEVICE -#ifdef TIMESTAMP_FEATURE -#include "../../modules/time/time_service.h" -#endif // TIMESTAMP_FEATURE -#ifdef NOTIFICATION_FEATURE -#include "../../modules/notifications/notifications_service.h" -#endif // NOTIFICATION_FEATURE -#ifdef SD_DEVICE -#include "../../modules/filesystem/esp_sd.h" -#endif // SD_DEVICE -// Set EEPROM setting -//[ESP401]P= T= V= json= pwd= -bool Commands::ESP401(const char* cmd_params, level_authenticate_type auth_type, - ESP3DOutput* output) { - bool noError = true; - bool json = has_tag(cmd_params, "json"); - String spos = ""; - 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 = "Wrong authentication level"; - noError = false; - errorCode = 401; - } -#else - (void)auth_type; -#endif // AUTHENTICATION_FEATURE - if (noError) { - // check validity of parameters - spos = get_param(cmd_params, "P="); - String styp = get_param(cmd_params, "T="); - String sval = get_param(cmd_params, "V="); - if (spos.length() == 0) { - response = "Invalid parameter P"; - noError = false; - } else if (styp.length() == 0) { - response = "Invalid parameter T"; - noError = false; - } else if (sval.length() == 0 && !strstr(cmd_params, "V=")) { - response = "Invalid parameter V"; - noError = false; - } else { - if (!(styp == "B" || styp == "S" || styp == "A" || styp == "I")) { - response = "Invalid value for T"; - noError = false; - } - } - if (noError) { - if (response) { - // Byte value - if (styp == "B") { - if (Settings_ESP3D::isValidByteSetting((uint8_t)sval.toInt(), - spos.toInt())) { - if (!Settings_ESP3D::write_byte(spos.toInt(), - (uint8_t)sval.toInt())) { - response = false; - log_esp3d_e("Set failed"); - } else { - // dynamique refresh is better than restart the boards - switch (spos.toInt()) { -#if defined(ESP_SERIAL_BRIDGE_OUTPUT) - case ESP_SERIAL_BRIDGE_ON: - if (!serial_bridge_service.started()) { - serial_bridge_service.begin(ESP_SERIAL_BRIDGE_OUTPUT); - } - break; -#endif // ESP_SERIAL_BRIDGE_OUTPUT - case ESP_SERIAL_BRIDGE_FLAG: - case ESP_SERIAL_FLAG: - case ESP_REMOTE_SCREEN_FLAG: - case ESP_WEBSOCKET_FLAG: - case ESP_TELNET_FLAG: - case ESP_SCREEN_FLAG: - case ESP_BT_FLAG: - ESP3DOutput::isOutput(ESP_ALL_CLIENTS, true); - break; - case ESP_VERBOSE_BOOT: - Settings_ESP3D::isVerboseBoot(true); - break; - case ESP_TARGET_FW: - Settings_ESP3D::GetFirmwareTarget(true); - break; -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - case ESP_SECURE_SERIAL: - serial_service.setParameters(); - break; -#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == - // MKS_SERIAL -#ifdef AUTHENTICATION_FEATURE - case ESP_SESSION_TIMEOUT: - AuthenticationService::setSessionTimeout(1000 * 60 * - sval.toInt()); - break; -#endif // AUTHENTICATION_FEATURE -#ifdef SD_DEVICE - case ESP_SD_SPEED_DIV: - ESP_SD::setSPISpeedDivider(sval.toInt()); - break; -#endif // SD_DEVICE -#ifdef TIMESTAMP_FEATURE - case ESP_INTERNET_TIME: - timeService.begin(); - break; -#endif // TIMESTAMP_FEATURE -#ifdef NOTIFICATION_FEATURE - case ESP_AUTO_NOTIFICATION: - notificationsservice.setAutonotification( - (sval.toInt() == 0) ? false : true); - break; -#endif // NOTIFICATION_FEATURE -#ifdef SENSOR_DEVICE - case ESP_SENSOR_TYPE: - esp3d_sensor.begin(); - break; -#endif // SENSOR_DEVICE -#ifdef BUZZER_DEVICE - case ESP_BUZZER: - if (sval.toInt() == 1) { - esp3d_buzzer.begin(); - } else if (sval.toInt() == 0) { - esp3d_buzzer.end(); - } - break; -#endif // BUZZER_DEVICE - default: - break; - } - } - } else { - response = "Invalid value for V"; - noError = false; - } - } - // Integer value - if (styp == "I") { - if (Settings_ESP3D::isValidByteSetting(sval.toInt(), spos.toInt())) { - if (!Settings_ESP3D::write_uint32(spos.toInt(), sval.toInt())) { - response = "Set failed"; - noError = false; - log_esp3d_e("Set failed"); - } else { - // dynamique refresh is better than restart the board - switch (spos.toInt()) { -#ifdef SENSOR_DEVICE - case ESP_SENSOR_INTERVAL: - esp3d_sensor.setInterval(sval.toInt()); - break; -#endif // SENSOR_DEVICE -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - case ESP_BAUD_RATE: - serial_service.updateBaudRate(sval.toInt()); - break; -#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == - // MKS_SERIAL -#if defined(ESP_SERIAL_BRIDGE_OUTPUT) - case ESP_SERIAL_BRIDGE_BAUD: - serial_bridge_service.updateBaudRate(sval.toInt()); - break; -#endif // defined(ESP_SERIAL_BRIDGE_OUTPUT) - default: - break; - } - } - } else { - response = "Invalid value for V"; - noError = false; - } - } - // String value - if (styp == "S") { - if (Settings_ESP3D::isValidStringSetting(sval.c_str(), - spos.toInt())) { - if (!Settings_ESP3D::write_string(spos.toInt(), sval.c_str())) { - response = "Set failed"; - noError = false; - log_esp3d_e("Set failed"); - } else { - // dynamique refresh is better than restart the board - switch (spos.toInt()) { -#ifdef AUTHENTICATION_FEATURE - case ESP_ADMIN_PWD: - case ESP_USER_PWD: - AuthenticationService::update(); - break; -#endif // AUTHENTICATION_FEATURE - default: - break; - } - } - } else { - response = "Invalid value for V"; - noError = false; - } - } -#if defined(WIFI_FEATURE) - // IP address - if (styp == "A") { - if (Settings_ESP3D::isValidIPStringSetting(sval.c_str(), - spos.toInt())) { - if (!Settings_ESP3D::write_IP_String(spos.toInt(), sval.c_str())) { - response = "Set failed"; - noError = false; - } else { - // dynamique refresh is better than restart the board - // TBD - } - } else { - response = "Invalid value for V"; - noError = false; - } - } -#endif // WIFI_FEATURE - } - } - } - if (noError) { - if (json) { - response = format_response(COMMANDID, json, true, String(spos).c_str()); - output->printLN(response.c_str()); - } else { - response = format_response(COMMANDID, json, true, "ok"); - output->printMSG(response.c_str()); - } - } else { - if (json) { - String tmp = "{\"error\":\""; - tmp += response; - tmp += "\""; - if (spos.length() > 0) { - tmp += ",\"position\":\""; - tmp += spos; - tmp += "\""; - } - tmp += "}"; - response = tmp; - } else { - response += spos.length() > 0 ? " for P=" + spos : ""; - } - response = format_response(COMMANDID, json, false, response.c_str()); - 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 deleted file mode 100644 index 27715675..00000000 --- a/esp3d/src/core/espcmd/ESP402.cpp +++ /dev/null @@ -1,95 +0,0 @@ -/* - ESP402.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#if defined(SD_UPDATE_FEATURE) -#include "../../modules/authentication/authentication_service.h" -#include "../commands.h" -#include "../esp3doutput.h" -#include "../settings_esp3d.h" - -// 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 - -#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, "")); - 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 (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 diff --git a/esp3d/src/core/espcmd/ESP410.cpp b/esp3d/src/core/espcmd/ESP410.cpp deleted file mode 100644 index ef105f59..00000000 --- a/esp3d/src/core/espcmd/ESP410.cpp +++ /dev/null @@ -1,147 +0,0 @@ -/* - ESP410.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -// 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 - -#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, "")); - 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) { - 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(); - if (json) { - output->printLN("]}"); - } else { - output->printMSGLine("End Scan"); - } - 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 // WIFI_FEATURE diff --git a/esp3d/src/core/espcmd/ESP420.cpp b/esp3d/src/core/espcmd/ESP420.cpp deleted file mode 100644 index 88b59c34..00000000 --- a/esp3d/src/core/espcmd/ESP420.cpp +++ /dev/null @@ -1,1673 +0,0 @@ -/* - ESP420.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#include "../../modules/authentication/authentication_service.h" -#include "../commands.h" -#include "../esp3doutput.h" -#include "../settings_esp3d.h" - -#if COMMUNICATION_PROTOCOL != SOCKET_SERIAL || defined(ESP_SERIAL_BRIDGE_OUTPUT) -#include "../../modules/serial/serial_service.h" -#endif // COMMUNICATION_PROTOCOL != SOCKET_SERIAL -#ifdef FILESYSTEM_FEATURE -#include "../../modules/filesystem/esp_filesystem.h" -#endif // FILESYSTEM_FEATURE -#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BLUETOOTH_FEATURE) -#include "../../modules/network/netconfig.h" -#if defined(WIFI_FEATURE) -#include "../../modules/wifi/wificonfig.h" -#endif // WIFI_FEATURE -#if defined(ETH_FEATURE) -#include "../../modules/ethernet/ethconfig.h" -#endif // ETH_FEATURE -#if defined(BLUETOOTH_FEATURE) -#include "../../modules/bluetooth/BT_service.h" -#endif // BLUETOOTH_FEATURE -#endif // WIFI_FEATURE || ETH_FEATURE || BLUETOOTH_FEATURE -#ifdef HTTP_FEATURE -#include "../../modules/http/http_server.h" -#endif // HTTP_FEATURE -#ifdef TELNET_FEATURE -#include "../../modules/telnet/telnet_server.h" -#endif // TELNET_FEATURE -#ifdef FTP_FEATURE -#include "../../modules/ftp/FtpServer.h" -#endif // FTP_FEATURE -#ifdef WS_DATA_FEATURE -#include "../../modules/websocket/websocket_server.h" -#endif // WS_DATA_FEATURE -#ifdef WEBDAV_FEATURE -#include "../../modules/webdav/webdav_server.h" -#endif // WEBDAV_FEATURE -#if defined(TIMESTAMP_FEATURE) -#include "../../modules/time/time_service.h" -#endif // TIMESTAMP_FEATURE -#if defined(SENSOR_DEVICE) -#include "../../modules/sensor/sensor.h" -#endif // SENSOR_DEVICE -#ifdef NOTIFICATION_FEATURE -#include "../../modules/notifications/notifications_service.h" -#endif // NOTIFICATION_FEATURE -#ifdef BUZZER_DEVICE -#include "../../modules/buzzer/buzzer.h" -#endif // BUZZER_DEVICE -#ifdef CAMERA_DEVICE -#include "../../modules/camera/camera.h" -#endif // CAMERA_DEVICE -#ifdef SD_DEVICE -#include "../../modules/filesystem/esp_sd.h" -#endif // SD_DEVICE -#if defined(DISPLAY_DEVICE) -#include "../../modules/display/display.h" -#endif // DISPLAY_DEVICE -#define COMMANDID 420 - -// Get ESP current status -// output is JSON or plain text according parameter -//[ESP420]json= -bool Commands::ESP420(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, "")); - if (parameter.length() == 0) { - String line = ""; - if (json) { - line = "{\"cmd\":\"420\",\"status\":\"ok\",\"data\":["; - } - // Chip ID - if (json) { - line += "{\"id\":\""; - } - line += "chip id"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += Hal::getChipID(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // CPU freq - if (json) { - line += ",{\"id\":\""; - } - line += "CPU Freq"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += ESP.getCpuFreqMHz(); - line += "Mhz"; - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // CPU temp - if (Hal::has_temperature_sensor()) { - if (json) { - line += ",{\"id\":\""; - } - line += "CPU Temp"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += String(Hal::temperature(), 1); - line += "C"; - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - } - // Free Memory - if (json) { - line += ",{\"id\":\""; - } - line += "free mem"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } -#ifdef FILESYSTEM_FEATURE - line += ESP_FileSystem::formatBytes(ESP.getFreeHeap()).c_str(); -#else - line += ESP.getFreeHeap(); -#endif // FILESYSTEM_FEATURE - -#ifdef ARDUINO_ARCH_ESP32 -#ifdef BOARD_HAS_PSRAM - line += " - PSRAM:"; - line += ESP_FileSystem::formatBytes(ESP.getFreePsram()); - -#endif // BOARD_HAS_PSRAM -#endif // ARDUINO_ARCH_ESP32 - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // SDK version - if (json) { - line += ",{\"id\":\""; - } - line += "SDK"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += ESP.getSdkVersion(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // Flash size - if (json) { - line += ",{\"id\":\""; - } - line += "flash size"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } -#ifdef FILESYSTEM_FEATURE - line += ESP_FileSystem::formatBytes(ESP.getFlashChipSize()); -#else - line += ESP.getFlashChipSize(); -#endif // FILESYSTEM_FEATURE - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - -#if (defined(WIFI_FEATURE) || defined(ETH_FEATURE)) && \ - (defined(OTA_FEATURE) || defined(WEB_UPDATE_FEATURE)) - // update space - if (json) { - line += ",{\"id\":\""; - } - line += "size for update"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += ESP_FileSystem::formatBytes(ESP_FileSystem::max_update_size()); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; -#endif // WIFI_FEATURE || ETH_FEATURE -#if defined(FILESYSTEM_FEATURE) - // FileSystem type - if (json) { - line += ",{\"id\":\""; - } - line += "FS type"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += ESP_FileSystem::FilesystemName(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // FileSystem capacity - if (json) { - line += ",{\"id\":\""; - } - line += "FS usage"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += ESP_FileSystem::formatBytes(ESP_FileSystem::usedBytes()); - line += "/"; - line += ESP_FileSystem::formatBytes(ESP_FileSystem::totalBytes()); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; -#endif // FILESYSTEM_FEATURE -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - // baud rate - if (json) { - line += ",{\"id\":\""; - } - line += "baud"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += serial_service.baudRate(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; -#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == - // MKS_SERIAL -#if defined(WIFI_FEATURE) - if (WiFi.getMode() != WIFI_OFF) { - // sleep mode - if (json) { - line += ",{\"id\":\""; - } - line += "sleep mode"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += WiFiConfig::getSleepModeString(); - 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) - // Wifi enabled - if (json) { - line += ",{\"id\":\""; - } - line += "wifi"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += (WiFi.getMode() == WIFI_OFF) ? "OFF" : "ON"; - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; -#if defined(ETH_FEATURE) - // Ethernet enabled - if (json) { - line += ",{\"id\":\""; - } - line += "ethernet"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += (EthConfig::started()) ? "ON" : "OFF"; - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; -#endif // ETH_FEATURE -#if defined(BLUETOOTH_FEATURE) - // BT enabled - if (json) { - line += ",{\"id\":\""; - } - line += "bt"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += (bt_service.started()) ? "ON" : "OFF"; - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; -#endif // BLUETOOTH_FEATURE - // Hostname - if (json) { - line += ",{\"id\":\""; - } - line += "hostname"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - if (json) { - line += ESP3DOutput::encodeString(NetConfig::hostname()); - } else { - line += NetConfig::hostname(); - } - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; -#if defined(HTTP_FEATURE) - if (HTTP_Server::started()) { - // http port - if (json) { - line += ",{\"id\":\""; - } - line += "HTTP port"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += HTTP_Server::port(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - } -#endif // HTTP_FEATURE -#if defined(TELNET_FEATURE) - if (telnet_server.started()) { - // telnet port - if (json) { - line += ",{\"id\":\""; - } - line += "Telnet port"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += telnet_server.port(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - if (telnet_server.isConnected()) { - if (json) { - line += ",{\"id\":\""; - } - line += "Telnet Client"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += telnet_server.clientIPAddress(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - } - } -#endif // TELNET_FEATURE -#if defined(WEBDAV_FEATURE) - if (webdav_server.started()) { - // WebDav port - if (json) { - line += ",{\"id\":\""; - } - line += "WebDav port"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += webdav_server.port(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - if (webdav_server.isConnected()) { - if (json) { - line += ",{\"id\":\""; - } - line += "WebDav Client"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += webdav_server.clientIPAddress(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - } - } -#endif // WEBDAV_FEATURE -#if defined(FTP_FEATURE) - if (ftp_server.started()) { - // ftp ports - if (json) { - line += ",{\"id\":\""; - } - line += "Ftp ports"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += String(ftp_server.ctrlport()) + "," + - String(ftp_server.dataactiveport()) + "," + - String(ftp_server.datapassiveport()); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - - if (ftp_server.isConnected()) { - if (json) { - line += ",{\"id\":\""; - } - line += "Ftp Client"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += ftp_server.clientIPAddress(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - } - } -#endif // FTP_FEATURE -#if defined(WS_DATA_FEATURE) - if (websocket_data_server.started()) { - // websocket port - if (json) { - line += ",{\"id\":\""; - } - line += "Websocket port"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += websocket_data_server.port(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - } -#endif // WS_DATA_FEATURE -#if defined(CAMERA_DEVICE) - if (esp3d_camera.started()) { - // camera name - if (json) { - line += ",{\"id\":\""; - } - line += "camera name"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += esp3d_camera.GetModelString(); - line += "("; - line += esp3d_camera.GetModel(); - line += ")"; - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - } - -#endif // CAMERA_DEVICE -#if defined(DISPLAY_DEVICE) - if (json) { - line += ",{\"id\":\""; - } - line += "display"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += esp3d_display.getModelString(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; -#endif // DISPLAY_DEVICE -#if defined(BLUETOOTH_FEATURE) - if (bt_service.started()) { - // BT mode - if (json) { - line += ",{\"id\":\""; - } - line += "bt"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += BTService::macAddress(); - - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // BT status - if (json) { - line += ",{\"id\":\""; - } - line += "BT Status"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += (bt_service.isConnected()) ? "connected" : "disconnected"; - if (bt_service.isConnected()) { - line += " (client: "; - line += BTService::clientmacAddress(); - line += ")"; - } - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - } -#endif // BLUETOOTH_FEATURE -#if defined(ETH_FEATURE) - if (EthConfig::started()) { - // Ethernet mode - if (json) { - line += ",{\"id\":\""; - } - line += "ethernet"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += ETH.macAddress(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // Ethernet cable - if (json) { - line += ",{\"id\":\""; - } - line += "cable"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += (EthConfig::linkUp()) ? "connected" : "disconnected"; - - if (EthConfig::linkUp()) { - line += " ("; - line += ETH.linkSpeed(); - line += "Mbps)"; - } - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // IP mode - if (json) { - line += ",{\"id\":\""; - } - line += "ip mode"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += (NetConfig::isIPModeDHCP(ESP_ETH_STA)) ? "dhcp" : "static"; - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // IP value - if (json) { - line += ",{\"id\":\""; - } - line += "ip"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += ETH.localIP().toString(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // GW value - if (json) { - line += ",{\"id\":\""; - } - line += "gw"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += ETH.gatewayIP().toString(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // Mask value - if (json) { - line += ",{\"id\":\""; - } - line += "msk"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += ETH.subnetMask().toString(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // DNS value - if (json) { - line += ",{\"id\":\""; - } - line += "DNS"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += ETH.dnsIP().toString(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - } -#endif // ETH_FEATURE -#if defined(WIFI_FEATURE) - if (WiFi.getMode() != WIFI_OFF) { - // WiFi Mode - if (json) { - line += ",{\"id\":\""; - } - if (WiFi.getMode() == WIFI_STA) { - line += "sta"; - } else if (WiFi.getMode() == WIFI_AP) { - line += "ap"; - } else if (WiFi.getMode() == - WIFI_AP_STA) { // we should not be in this state but just in - // case .... - line += "mixed"; - } else { - line += "unknown"; - } - - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += "ON"; - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - - // WiFi mac - if (json) { - line += ",{\"id\":\""; - } - line += "mac"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - if (WiFi.getMode() == WIFI_STA) { - line += WiFi.macAddress(); - } else if (WiFi.getMode() == WIFI_AP) { - line += WiFi.softAPmacAddress(); - } else if (WiFi.getMode() == - WIFI_AP_STA) { // we should not be in this state but just in - // case .... - line += WiFi.macAddress(); - line += "/"; - line += WiFi.softAPmacAddress(); - } else { - line += "unknown"; - } - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - - // WiFi Station - if (WiFi.getMode() == WIFI_STA) { - // Connected to SSID - if (json) { - line += ",{\"id\":\""; - } - line += "SSID"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - if (WiFi.isConnected()) { - if (json) { - line += ESP3DOutput::encodeString(WiFi.SSID().c_str()); - } else { - line += WiFi.SSID(); - } - } - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - if (WiFi.isConnected()) { // in case query come from serial - // Signal strength - if (json) { - line += ",{\"id\":\""; - } - line += "signal"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += WiFiConfig::getSignal(WiFi.RSSI(), false); - line += "%"; - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // Phy Mode - if (json) { - line += ",{\"id\":\""; - } - line += "phy mode"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += WiFiConfig::getPHYModeString(WIFI_STA); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // Channel - if (json) { - line += ",{\"id\":\""; - } - line += "channel"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += WiFi.channel(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // IP Mode - if (json) { - line += ",{\"id\":\""; - } - line += "ip mode"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += (NetConfig::isIPModeDHCP(ESP_WIFI_STA)) ? "dhcp" : "static"; - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // IP value - if (json) { - line += ",{\"id\":\""; - } - line += "ip"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += WiFi.localIP().toString(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // Gateway value - if (json) { - line += ",{\"id\":\""; - } - line += "gw"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += WiFi.gatewayIP().toString(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // Mask value - if (json) { - line += ",{\"id\":\""; - } - line += "msk"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += WiFi.subnetMask().toString(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // DNS value - if (json) { - line += ",{\"id\":\""; - } - line += "DNS"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += WiFi.dnsIP().toString(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - } - // Disabled Mode - if (json) { - line += ",{\"id\":\""; - } - line += "ap"; - - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += "OFF"; - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // Disabled Mode - if (json) { - line += ",{\"id\":\""; - } - line += "mac"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += WiFi.softAPmacAddress(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - } else if (WiFi.getMode() == WIFI_AP) { - // AP SSID - if (json) { - line += ",{\"id\":\""; - } - line += "SSID"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - if (json) { - line += ESP3DOutput::encodeString(WiFiConfig::AP_SSID()); - } else { - line += WiFiConfig::AP_SSID(); - } - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // AP Visibility - if (json) { - line += ",{\"id\":\""; - } - line += "visible"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += (WiFiConfig::is_AP_visible()) ? "yes" : "no"; - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // AP Authentication - if (json) { - line += ",{\"id\":\""; - } - line += "authentication"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += WiFiConfig::AP_Auth_String(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // DHCP Server - if (json) { - line += ",{\"id\":\""; - } - line += "DHCP Server"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += (NetConfig::isDHCPServer(ESP_WIFI_AP)) ? "ON" : "OFF"; - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // IP Value - if (json) { - line += ",{\"id\":\""; - } - line += "ip"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += WiFi.softAPIP().toString(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // Gateway Value - if (json) { - line += ",{\"id\":\""; - } - line += "gw"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += WiFiConfig::AP_Gateway_String(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // Mask Value - if (json) { - line += ",{\"id\":\""; - } - line += "msk"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += WiFiConfig::AP_Mask_String(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // Connected clients - const char* entry = NULL; - uint8_t nb = 0; - entry = WiFiConfig::getConnectedSTA(&nb, true); - if (json) { - line += ",{\"id\":\""; - } - line += "clients"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += nb; - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - for (uint8_t i = 0; i < nb; i++) { - // Client - if (json) { - line += ",{\"id\":\""; - } - line += "# " + String(i); - - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += entry; - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // get next - entry = WiFiConfig::getConnectedSTA(); - } - // Disabled Mode - if (json) { - line += ",{\"id\":\""; - } - line += "sta"; - - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += "OFF"; - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // Disabled Mode - if (json) { - line += ",{\"id\":\""; - } - line += "mac"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += WiFi.macAddress(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - } - } -#endif // WIFI_FEATURE -#endif // WIFI_FEATURE || ETH FEATURE -#if defined(TIMESTAMP_FEATURE) - if (json) { - line += ",{\"id\":\""; - } - line += "i-time"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += timeService.started() ? "ON" : "OFF"; - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; -#endif // TIMESTAMP_FEATURE -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - if (json) { - line += ",{\"id\":\""; - } - line += "serial"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += serial_service.started() ? "ON" : "OFF"; - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; -#endif // COMMUNICATION_PROTOCOL -#if defined(AUTHENTICATION_FEATURE) - if (json) { - line += ",{\"id\":\""; - } - line += "authentication"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += "ON"; - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; -#endif // AUTHENTICATION_FEATURE -#if defined(ESP_SERIAL_BRIDGE_OUTPUT) - if (json) { - line += ",{\"id\":\""; - } - line += "serial_bridge"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - if (serial_bridge_service.started()) { - line += "ON"; - } else { - line += "OFF"; - } - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - if (json) { - line += ",{\"id\":\""; - } - line += "baud"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += serial_bridge_service.baudRate(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - -#endif // ESP_SERIAL_BRIDGE_OUTPUT -#if defined(HAS_SERIAL_DISPLAY) - if (json) { - line += ",{\"id\":\""; - } - line += "M117"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += "ON"; - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; -#endif // HAS_SERIAL_DISPLAY -#if defined(NOTIFICATION_FEATURE) - if (json) { - line += ",{\"id\":\""; - } - line += "notification"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += notificationsservice.started() ? "ON" : "OFF"; - if (notificationsservice.started()) { - line += " ("; - line += notificationsservice.getTypeString(); - line += ")"; - } - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; -#endif // NOTIFICATION_FEATURE -#ifdef SD_DEVICE - if (json) { - line += ",{\"id\":\""; - } - line += "sd"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += (Settings_ESP3D::GetSDDevice() == ESP_DIRECT_SD) ? "direct " - : (Settings_ESP3D::GetSDDevice() == ESP_SHARED_SD) ? "shared " - : "none "; - line += "("; - line += ESP_SD::FilesystemName(); - line += ")"; - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; -#ifdef SD_UPDATE_FEATURE - if (json) { - line += ",{\"id\":\""; - } - line += "SD updater"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += Settings_ESP3D::read_byte(ESP_SD_CHECK_UPDATE_AT_BOOT) != 0 - ? "ON" - : "OFF"; - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; -#endif // SD_UPDATE_FEATURE - -#endif // SD_DEVICE -#if defined(SENSOR_DEVICE) - if (json) { - line += ",{\"id\":\""; - } - line += "sensor"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += esp3d_sensor.started() ? "ON" : "OFF"; - if (esp3d_sensor.started()) { - line += " ("; - line += esp3d_sensor.GetCurrentModelString(); - line += ")"; - } - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; -#endif // SENSOR_DEVICE -#if defined(BUZZER_DEVICE) - if (json) { - line += ",{\"id\":\""; - } - line += "buzzer"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += esp3d_buzzer.started() ? "ON" : "OFF"; - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; -#endif // BUZZER_DEVICE -#if defined(ESP_LOG_FEATURE) - // debug - if (json) { - line += ",{\"id\":\""; - } - line += "log"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } -#if ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL0 - line += "Serial"; -#endif // LOG_OUTPUT_SERIAL0 -#if ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL1 - line += "Serial1"; -#endif // LOG_OUTPUT_SERIAL1 -#if ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL2 - line += "Serial2"; -#endif // LOG_OUTPUT_SERIAL2 -#if ESP_LOG_FEATURE == LOG_OUTPUT_TELNET - line += "Telnet(" + String(LOG_ESP3D_OUTPUT_PORT) + ")"; -#endif // LOG_OUTPUT_TELNET -#if ESP_LOG_FEATURE == LOG_OUTPUT_WEBSOCKET - line += "Websocket(" + String(LOG_ESP3D_OUTPUT_PORT) + ")"; -#endif // LOG_OUTPUT_WEBSOCKET - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; -#endif // ESP_LOG_FEATURE -#if COMMUNICATION_PROTOCOL == MKS_SERIAL - // Target Firmware - if (json) { - line += ",{\"id\":\"serial"; - } else { - line += "Serial"; - } - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += "MKS"; - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; -#endif // COMMUNICATION_PROTOCOL - // Target Firmware - if (json) { - line += ",{\"id\":\"targetfw"; - } else { - line += "Target Fw"; - } - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += Settings_ESP3D::GetFirmwareTargetShortName(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // FW version - if (json) { - line += ",{\"id\":\""; - } - line += "FW ver"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } -#if defined(SHORT_BUILD_VERSION) - line += SHORT_BUILD_VERSION "-"; -#endif // SHORT_BUILD_VERSION - line += FW_VERSION; - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line = ""; - // FW architecture - if (json) { - line += ",{\"id\":\""; - } - - line += "FW arch"; - if (json) { - line += "\",\"value\":\""; - } else { - line += ": "; - } - line += Settings_ESP3D::TargetBoard(); - if (json) { - line += "\"}"; - output->print(line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - if (json) { - output->printLN("]}"); - } - 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; -} diff --git a/esp3d/src/core/espcmd/ESP444.cpp b/esp3d/src/core/espcmd/ESP444.cpp deleted file mode 100644 index ad3564e0..00000000 --- a/esp3d/src/core/espcmd/ESP444.cpp +++ /dev/null @@ -1,84 +0,0 @@ -/* - ESP444.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#include "../../modules/authentication/authentication_service.h" -#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 -#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) { - 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) { - output->printMSG(response.c_str()); - } else { - output->printERROR(response.c_str(), errorCode); - } - } - return noError; -} diff --git a/esp3d/src/core/espcmd/ESP450.cpp b/esp3d/src/core/espcmd/ESP450.cpp deleted file mode 100644 index 87b65ee5..00000000 --- a/esp3d/src/core/espcmd/ESP450.cpp +++ /dev/null @@ -1,153 +0,0 @@ -/* - ESP410.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -// 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 - -#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, "")); - 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()); - } - } - } - - if (json) { - output->printLN("]}"); - } else { - output->printMSGLine("End Scan"); - } - 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 diff --git a/esp3d/src/core/espcmd/ESP550.cpp b/esp3d/src/core/espcmd/ESP550.cpp deleted file mode 100644 index 8c3e729f..00000000 --- a/esp3d/src/core/espcmd/ESP550.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/* - ESP550.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#if defined(AUTHENTICATION_FEATURE) -#include "../../modules/authentication/authentication_service.h" -#include "../commands.h" -#include "../esp3doutput.h" -#include "../settings_esp3d.h" - -#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::isValidStringSetting(parameter.c_str(), - ESP_ADMIN_PWD)) { - 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; - } - } else { - response = format_response(COMMANDID, json, false, "Missing parameter"); - noError = false; - } - } 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 diff --git a/esp3d/src/core/espcmd/ESP555.cpp b/esp3d/src/core/espcmd/ESP555.cpp deleted file mode 100644 index 2dc9b7cd..00000000 --- a/esp3d/src/core/espcmd/ESP555.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/* - ESP555.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#if defined(AUTHENTICATION_FEATURE) -#include "../../modules/authentication/authentication_service.h" -#include "../commands.h" -#include "../esp3doutput.h" -#include "../settings_esp3d.h" - -// 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::isValidStringSetting(parameter.c_str(), - ESP_USER_PWD)) { - 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; - } - } else { - response = format_response(COMMANDID, json, false, "Missing parameter"); - noError = false; - } - } 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 diff --git a/esp3d/src/core/espcmd/ESP600.cpp b/esp3d/src/core/espcmd/ESP600.cpp deleted file mode 100644 index 5fa49cb9..00000000 --- a/esp3d/src/core/espcmd/ESP600.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* - ESP600.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#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 -#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, 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 (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 diff --git a/esp3d/src/core/espcmd/ESP610.cpp b/esp3d/src/core/espcmd/ESP610.cpp deleted file mode 100644 index f2a31f5d..00000000 --- a/esp3d/src/core/espcmd/ESP610.cpp +++ /dev/null @@ -1,197 +0,0 @@ -/* - ESP610.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#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; - } -#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 (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 diff --git a/esp3d/src/core/espcmd/ESP620.cpp b/esp3d/src/core/espcmd/ESP620.cpp deleted file mode 100644 index 3afa4470..00000000 --- a/esp3d/src/core/espcmd/ESP620.cpp +++ /dev/null @@ -1,78 +0,0 @@ -/* - ESP620.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#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 -#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 - 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 (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 diff --git a/esp3d/src/core/espcmd/ESP700.cpp b/esp3d/src/core/espcmd/ESP700.cpp deleted file mode 100644 index a3561aa1..00000000 --- a/esp3d/src/core/espcmd/ESP700.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/* - ESP700.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#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 -#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) { - 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; - } - } else { - 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 // GCODE_HOST_FEATURE diff --git a/esp3d/src/core/espcmd/ESP701.cpp b/esp3d/src/core/espcmd/ESP701.cpp deleted file mode 100644 index 71f8114a..00000000 --- a/esp3d/src/core/espcmd/ESP701.cpp +++ /dev/null @@ -1,155 +0,0 @@ -/* - ESP701.cpp - ESP3D command 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 -*/ -// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 -#include "../../include/esp3d_config.h" -#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" - -#define COMMANDID 701 - -// Query and Control ESP700 stream -//[ESP701]action= -bool Commands::ESP701(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; - } -#else - (void)auth_type; -#endif // AUTHENTICATION_FEATURE - if (noError) { - parameter = (get_param(cmd_params, "action=")); - if (parameter.length() != 0) { - if (parameter.equalsIgnoreCase("PAUSE")) { - if (esp3d_gcode_host.pause()) { - response = format_response(COMMANDID, json, true, "Stream paused"); - } else { - response = - format_response(COMMANDID, json, false, "No stream to pause"); - noError = false; - } - } else if (parameter.equalsIgnoreCase("RESUME")) { - if (esp3d_gcode_host.resume()) { - response = format_response(COMMANDID, json, true, "Stream resumed"); - } else { - response = - format_response(COMMANDID, json, false, "No stream to resume"); - noError = false; - } - } else if (parameter.equalsIgnoreCase("ABORT")) { - if (esp3d_gcode_host.abort()) { - response = format_response(COMMANDID, json, true, "Stream aborted"); - } else { - response = - format_response(COMMANDID, json, false, "No stream to abort"); - noError = false; - } - } - if (parameter.equalsIgnoreCase("CLEAR_ERROR")) { - esp3d_gcode_host.setErrorNum(ERROR_NO_ERROR); - response = format_response(COMMANDID, json, true, "Error cleared"); - } else { - response = format_response(COMMANDID, json, false, "Unknown action"); - noError = false; - } - - } else { - String resp; - bool noError = true; - switch (esp3d_gcode_host.getStatus()) { - case HOST_START_STREAM: - case HOST_READ_LINE: - case HOST_PROCESS_LINE: - case HOST_WAIT4_ACK: - // TODO add % of progress and filename if any - // totalSize / processedSize / fileName - if (json) { - resp = "{\"status\":\"processing\",\"total\":\"" + - String(esp3d_gcode_host.totalSize()) + - "\",\"processed\":\"" + - String(esp3d_gcode_host.processedSize()) + "\",\"type\":\"" + - String(esp3d_gcode_host.getFSType()); - if (esp3d_gcode_host.getFSType() != TYPE_SCRIPT_STREAM) { - resp += "\",\"name\":\"" + String(esp3d_gcode_host.fileName()); - } - resp += "\"}"; - } else { - resp = "processing"; - } - response = format_response(COMMANDID, json, true, resp.c_str()); - break; - case HOST_PAUSE_STREAM: - response = format_response(COMMANDID, json, true, "pause"); - break; - case HOST_RESUME_STREAM: - response = format_response(COMMANDID, json, true, "resume stream"); - break; - case HOST_NO_STREAM: - log_esp3d("No stream %d", esp3d_gcode_host.getErrorNum()); - if (esp3d_gcode_host.getErrorNum() != ERROR_NO_ERROR) { - noError = false; - if (json) { - resp = "{\"status\":\"no stream\",\"code\":\"" + - String(esp3d_gcode_host.getErrorNum()) + "\"}"; - } else { - resp = "no stream, last error " + - String(esp3d_gcode_host.getErrorNum()); - } - } else { - resp = "no stream"; - } - response = format_response(COMMANDID, json, noError, resp.c_str()); - break; - default: - response = - format_response(COMMANDID, json, false, - String(esp3d_gcode_host.getStatus()).c_str()); - noError = false; - break; - } - } - } - 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 diff --git a/esp3d/src/core/espcmd/ESP710.cpp b/esp3d/src/core/espcmd/ESP710.cpp deleted file mode 100644 index d84cad90..00000000 --- a/esp3d/src/core/espcmd/ESP710.cpp +++ /dev/null @@ -1,73 +0,0 @@ -/* - ESP710.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#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 -#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) { - 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 (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 diff --git a/esp3d/src/core/espcmd/ESP715.cpp b/esp3d/src/core/espcmd/ESP715.cpp deleted file mode 100644 index 0bfd08bd..00000000 --- a/esp3d/src/core/espcmd/ESP715.cpp +++ /dev/null @@ -1,84 +0,0 @@ -/* - ESP715.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#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 -#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) { - 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; - } - } - 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 diff --git a/esp3d/src/core/espcmd/ESP720.cpp b/esp3d/src/core/espcmd/ESP720.cpp deleted file mode 100644 index 529466c7..00000000 --- a/esp3d/src/core/espcmd/ESP720.cpp +++ /dev/null @@ -1,204 +0,0 @@ -/* - ESP720.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#ifdef FILESYSTEM_TIMESTAMP_FEATURE -#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 -#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) { - 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 = 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 { - response = format_response(COMMANDID, json, false, "Invalid directory"); - 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 diff --git a/esp3d/src/core/espcmd/ESP730.cpp b/esp3d/src/core/espcmd/ESP730.cpp deleted file mode 100644 index b14e4fd5..00000000 --- a/esp3d/src/core/espcmd/ESP730.cpp +++ /dev/null @@ -1,124 +0,0 @@ -/* - ESP730.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#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; - } - } - 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 diff --git a/esp3d/src/core/espcmd/ESP740.cpp b/esp3d/src/core/espcmd/ESP740.cpp deleted file mode 100644 index 184d21c4..00000000 --- a/esp3d/src/core/espcmd/ESP740.cpp +++ /dev/null @@ -1,214 +0,0 @@ -/* - ESP740.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#ifdef SD_TIMESTAMP_FEATURE -#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 -#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) { - 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 { - 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 SD_TIMESTAMP_FEATURE - time = timeService.getDateTime((time_t)sub.getLastWrite()); -#endif // SD_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; - } - } else { - response = - format_response(COMMANDID, json, false, "Invalid directory"); - noError = false; - } - } - ESP_SD::releaseFS(); - } - } - 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 diff --git a/esp3d/src/core/espcmd/ESP750.cpp b/esp3d/src/core/espcmd/ESP750.cpp deleted file mode 100644 index ab510eee..00000000 --- a/esp3d/src/core/espcmd/ESP750.cpp +++ /dev/null @@ -1,140 +0,0 @@ -/* - ESP750.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#define COMMANDID 750 -// Action on SD Filesystem -// 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; -#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) { - 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 (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 diff --git a/esp3d/src/core/espcmd/ESP780.cpp b/esp3d/src/core/espcmd/ESP780.cpp deleted file mode 100644 index e3db51ba..00000000 --- a/esp3d/src/core/espcmd/ESP780.cpp +++ /dev/null @@ -1,210 +0,0 @@ -/* - ESP780.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#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 -#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) { - 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 = 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); - } - } - } - 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 diff --git a/esp3d/src/core/espcmd/ESP790.cpp b/esp3d/src/core/espcmd/ESP790.cpp deleted file mode 100644 index 51efcdd2..00000000 --- a/esp3d/src/core/espcmd/ESP790.cpp +++ /dev/null @@ -1,149 +0,0 @@ -/* - ESP790.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#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"); - 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 // GLOBAL_FILESYSTEM_FEATURE diff --git a/esp3d/src/core/espcmd/ESP800.cpp b/esp3d/src/core/espcmd/ESP800.cpp deleted file mode 100644 index 80c892bd..00000000 --- a/esp3d/src/core/espcmd/ESP800.cpp +++ /dev/null @@ -1,448 +0,0 @@ -/* - ESP800.cpp - ESP3D command 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 -*/ -#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" - -#ifdef FILESYSTEM_FEATURE -#include "../../modules/filesystem/esp_filesystem.h" -#endif // FILESYSTEM_FEATURE -#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BLUETOOTH_FEATURE) -#include "../../modules/network/netconfig.h" -#if defined(WIFI_FEATURE) -#include "../../modules/wifi/wificonfig.h" -#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 -#ifdef 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 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 -#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, "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; - } - } - } - 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 - String tparm = "none"; -#endif // TIMESTAMP_FEATURE - - 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:"; - } - -#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"; -#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 (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 deleted file mode 100644 index 3bc1979d..00000000 --- a/esp3d/src/core/espcmd/ESP900.cpp +++ /dev/null @@ -1,90 +0,0 @@ -/* - ESP900.cpp - ESP3D command 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 -*/ -#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" - -#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 -#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 - 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 (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 deleted file mode 100644 index 23f539e1..00000000 --- a/esp3d/src/core/espcmd/ESP901.cpp +++ /dev/null @@ -1,93 +0,0 @@ -/* - ESP901.cpp - ESP3D command 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 -*/ -#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" - -#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 -#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_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 (Settings_ESP3D::isValidIntegerSetting(ibuf, ESP_BAUD_RATE)) { - 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 (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 diff --git a/esp3d/src/core/espcmd/ESP910.cpp b/esp3d/src/core/espcmd/ESP910.cpp deleted file mode 100644 index 35dd45cc..00000000 --- a/esp3d/src/core/espcmd/ESP910.cpp +++ /dev/null @@ -1,95 +0,0 @@ -/* - ESP910.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#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 -#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) { - 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 (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 diff --git a/esp3d/src/core/espcmd/ESP920.cpp b/esp3d/src/core/espcmd/ESP920.cpp deleted file mode 100644 index 037c79c0..00000000 --- a/esp3d/src/core/espcmd/ESP920.cpp +++ /dev/null @@ -1,382 +0,0 @@ -/* - ESP910.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#include "../../modules/authentication/authentication_service.h" -#include "../commands.h" -#include "../esp3doutput.h" -#include "../settings_esp3d.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 (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 deleted file mode 100644 index ec80cb23..00000000 --- a/esp3d/src/core/espcmd/ESP930.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/* - ESP930.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#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 -#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 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 (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 diff --git a/esp3d/src/core/espcmd/ESP931.cpp b/esp3d/src/core/espcmd/ESP931.cpp deleted file mode 100644 index add1b0fc..00000000 --- a/esp3d/src/core/espcmd/ESP931.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/* - ESP931.cpp - ESP3D command 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 -*/ -#include "../../include/esp3d_config.h" -#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" - -#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 -#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_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 (Settings_ESP3D.isValidIntegerSetting(ibuf, ESP_SERIAL_BRIDGE_BAUD)) { - 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 (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 diff --git a/esp3d/src/core/log_esp3d.cpp b/esp3d/src/core/log_esp3d.cpp deleted file mode 100644 index 12a18b6a..00000000 --- a/esp3d/src/core/log_esp3d.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/* - log_esp3d.cpp - log esp3d 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 -*/ - -#include "../include/esp3d_config.h" -#if defined(ESP_LOG_FEATURE) - -#ifndef LOG_ESP3D_BAUDRATE -#define LOG_ESP3D_BAUDRATE 115200 -#endif //~LOG_ESP3D_BAUDRATE - -void initEsp3dLog() { -#if (ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL0) || \ - (ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL1) || \ - (ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL2) -#ifdef ARDUINO_ARCH_ESP8266 - LOG_OUTPUT_SERIAL.begin(LOG_ESP3D_BAUDRATE, SERIAL_8N1, SERIAL_FULL, - (ESP_LOG_TX_PIN == -1) ? 1 : ESP_LOG_TX_PIN); -#if ESP_LOG_RX_PIN != -1 - LOG_OUTPUT_SERIAL - .pins((ESP_LOG_TX_PIN == -1) ? 1 : ESP_LOG_TX_PIN, ESP_LOG_RX_PIN) -#endif // ESP_LOG_RX_PIN != -1 -#endif // ARDUINO_ARCH_ESP8266 -#if defined(ARDUINO_ARCH_ESP32) - LOG_OUTPUT_SERIAL.begin(LOG_ESP3D_BAUDRATE, SERIAL_8N1, - ESP_LOG_RX_PIN, ESP_LOG_TX_PIN); -#endif // ARDUINO_ARCH_ESP32 - -#endif // (ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL0) || (ESP_LOG_FEATURE == - // LOG_OUTPUT_SERIAL1)||(ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL2) -} - -// Telnet -#if ESP_LOG_FEATURE == LOG_OUTPUT_TELNET -Telnet_Server telnet_log; -#endif // ESP_LOG_FEATURE == LOG_OUTPUT_TELNET - -// Websocket -#if ESP_LOG_FEATURE == LOG_OUTPUT_WEBSOCKET -WebSocket_Server websocket_log("log"); -#endif // ESP_LOG_FEATURE == LOG_OUTPUT_WEBSOCKET -#endif // ESP_LOG_FEATURE diff --git a/esp3d/src/core/log_esp3d.h b/esp3d/src/core/log_esp3d.h deleted file mode 100644 index 1de3cfce..00000000 --- a/esp3d/src/core/log_esp3d.h +++ /dev/null @@ -1,183 +0,0 @@ -/* - log_esp3d.h - esp3d log functions - - 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 _LOG_ESP3D_H -#define _LOG_ESP3D_H -#include "../include/defines.h" -#include "../include/esp3d_config.h" - -#ifndef ESP3D_DEBUG_LEVEL -#define ESP3D_DEBUG_LEVEL LOG_LEVEL_NONE -#endif // ESP3D_DEBUG_LEVEL - -#define LOG_ESP3D_INIT -#define LOG_ESP3D_NETWORK_INIT -#define LOG_ESP3D_NETWORK_HANDLE -#define LOG_ESP3D_NETWORK_END - -#if defined(ESP_LOG_FEATURE) -#if defined(ARDUINO_ARCH_ESP8266) -// no need with latest esp8266 core -#define pathToFileName(p) p -#endif // ARDUINO_ARCH_ESP8266 - -#undef log_esp3d -#undef log_esp3ds -#undef log_esp3d_e -#undef log_esp3d_d -// Serial -#if (ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL0) || \ - (ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL1) || \ - (ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL2) - -extern void initEsp3dLog(); -#ifndef ESP3DLIB_ENV -#if ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL0 -#define LOG_OUTPUT_SERIAL Serial -#endif // LOG_OUTPUT_SERIAL0 -#if ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL1 -#define LOG_OUTPUT_SERIAL Serial1 -#endif // LOG_OUTPUT_SERIAL1 -#if ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL2 -#define LOG_OUTPUT_SERIAL Serial2 -#endif // LOG_OUTPUT_SERIAL2 -#undef LOG_ESP3D_INIT -#define LOG_ESP3D_INIT initEsp3dLog(); -#else -#define LOG_OUTPUT_SERIAL MYSERIAL1 - -#endif // ESP3DLIB_ENV - -#if ESP3D_DEBUG_LEVEL >= LOG_LEVEL_VERBOSE -#define log_esp3d(format, ...) \ - LOG_OUTPUT_SERIAL.printf("[ESP3D][%s:%u] %s(): " format "\r\n", \ - pathToFileName(__FILE__), __LINE__, __FUNCTION__, \ - ##__VA_ARGS__) -#define log_esp3ds(format, ...) LOG_OUTPUT_SERIAL.printf(format, ##__VA_ARGS__) -#else -#define log_esp3d(format, ...) -#define log_esp3ds(format, ...) -#endif // ESP3D_DEBUG_LEVEL>= LOG_LEVEL_VERBOSE - -#if ESP3D_DEBUG_LEVEL >= LOG_LEVEL_DEBUG -#define log_esp3d_d(format, ...) \ - LOG_OUTPUT_SERIAL.printf("[ESP3D-DEBUG][%s:%u] %s(): " format "\r\n", \ - pathToFileName(__FILE__), __LINE__, __FUNCTION__, \ - ##__VA_ARGS__) -#else -#define log_esp3d_d(format, ...) -#endif // ESP3D_DEBUG_LEVEL>= LOG_LEVEL_DEBUG -#if ESP3D_DEBUG_LEVEL >= LOG_LEVEL_ERROR -#define log_esp3d_e(format, ...) \ - LOG_OUTPUT_SERIAL.printf("[ESP3D-ERROR][%s:%u] %s(): " format "\r\n", \ - pathToFileName(__FILE__), __LINE__, __FUNCTION__, \ - ##__VA_ARGS__) -#else -#define log_esp3d_e(format, ...) -#endif // ESP3D_DEBUG_LEVEL >= LOG_LEVEL_ERROR -#endif // LOG_OUTPUT_SERIAL0 || LOG_OUTPUT_SERIAL1 || LOG_OUTPUT_SERIAL2 - -// Telnet -#if ESP_LOG_FEATURE == LOG_OUTPUT_TELNET -#include "../modules/telnet/telnet_server.h" -extern Telnet_Server telnet_log; -#undef LOG_ESP3D_NETWORK_INIT -#undef LOG_ESP3D_NETWORK_END -#undef LOG_ESP3D_NETWORK_HANDLE -#define LOG_ESP3D_NETWORK_INIT telnet_log.begin(LOG_ESP3D_OUTPUT_PORT, true); -#define LOG_ESP3D_NETWORK_HANDLE telnet_log.handle(); -#define LOG_ESP3D_NETWORK_END telnet_log.end(); -#if ESP3D_DEBUG_LEVEL >= LOG_LEVEL_VERBOSE -#define log_esp3d(format, ...) \ - if (telnet_log.isConnected()) \ - telnet_log.printf("[ESP3D][%s:%u] %s(): " format "\r\n", \ - pathToFileName(__FILE__), __LINE__, __FUNCTION__, \ - ##__VA_ARGS__) -#define log_esp3ds(format, ...) \ - if (telnet_log.isConnected()) telnet_log.printf(format, ##__VA_ARGS__) -#else -#define log_esp3d(format, ...) -#define log_esp3ds(format, ...) -#endif // ESP3D_DEBUG_LEVEL >= LOG_LEVEL_VERBOSE - -#if ESP3D_DEBUG_LEVEL >= LOG_LEVEL_DEBUG -#define log_esp3d_d(format, ...) \ - if (telnet_log.isConnected()) \ - telnet_log.printf("[ESP3D-DEBUG][%s:%u] %s(): " format "\r\n", \ - pathToFileName(__FILE__), __LINE__, __FUNCTION__, \ - ##__VA_ARGS__) -#else -#define log_esp3d_d(format, ...) -#endif // ESP3D_DEBUG_LEVEL >= LOG_LEVEL_DEBUG -#if ESP3D_DEBUG_LEVEL >= LOG_LEVEL_ERROR -#define log_esp3d_e(format, ...) \ - if (telnet_log.isConnected()) \ - telnet_log.printf("[ESP3D-ERROR][%s:%u] %s(): " format "\r\n", \ - pathToFileName(__FILE__), __LINE__, __FUNCTION__, \ - ##__VA_ARGS__) - -#endif // ESP3D_DEBUG_LEVEL >= LOG_LEVEL_ERROR -#endif // LOG_OUTPUT_TELNET - -// Telnet -#if ESP_LOG_FEATURE == LOG_OUTPUT_WEBSOCKET -#include "../modules/websocket/websocket_server.h" -extern WebSocket_Server websocket_log; -#undef LOG_ESP3D_NETWORK_INIT -#undef LOG_ESP3D_NETWORK_END -#undef LOG_ESP3D_NETWORK_HANDLE -#define LOG_ESP3D_NETWORK_INIT websocket_log.begin(LOG_ESP3D_OUTPUT_PORT, true); -#define LOG_ESP3D_NETWORK_HANDLE websocket_log.handle(); -#define LOG_ESP3D_NETWORK_END websocket_log.end(); -#if ESP3D_DEBUG_LEVEL >= LOG_LEVEL_VERBOSE -#define log_esp3d(format, ...) \ - websocket_log.printf("[ESP3D][%s:%u] %s(): " format "\r\n", \ - pathToFileName(__FILE__), __LINE__, __FUNCTION__, \ - ##__VA_ARGS__) -#define log_esp3ds(format, ...) websocket_log.printf(format, ##__VA_ARGS__) -#else -#define log_esp3d(format, ...) -#define log_esp3ds(format, ...) -#endif // ESP3D_DEBUG_LEVEL >= LOG_LEVEL_VERBOSE - -#if ESP3D_DEBUG_LEVEL >= LOG_LEVEL_DEBUG -#define log_esp3d_d(format, ...) \ - websocket_log.printf("[ESP3D-DEBUG][%s:%u] %s(): " format "\r\n", \ - pathToFileName(__FILE__), __LINE__, __FUNCTION__, \ - ##__VA_ARGS__) -#else -#define log_esp3d(format, ...) -#endif // ESP3D_DEBUG_LEVEL >= ESP_LOG_DEBUG - -#if ESP3D_DEBUG_LEVEL >= LOG_LEVEL_ERROR -#define log_esp3d(format, ...) \ - websocket_log.printf("[ESP3D-ERROR][%s:%u] %s(): " format "\r\n", \ - pathToFileName(__FILE__), __LINE__, __FUNCTION__, \ - ##__VA_ARGS__) -#endif // ESP3D_DEBUG_LEVEL >= LOG_LEVEL_ERROR -#endif // LOG_OUTPUT_WEBSOCKET -#else -#define log_esp3d(format, ...) -#define log_esp3ds(format, ...) -#define log_esp3d_e(format, ...) -#define log_esp3d_d(format, ...) -#endif // ESP_LOG_FEATURE - -#endif //_LOG_ESP3D_H diff --git a/esp3d/src/include/esp3d_config.h b/esp3d/src/include/esp3d_config.h index 7719f7e6..1e7aa770 100644 --- a/esp3d/src/include/esp3d_config.h +++ b/esp3d/src/include/esp3d_config.h @@ -22,7 +22,7 @@ #define _ESP3D_CONFIG_H #include -#include "../include/defines.h" +#include "../include/esp3d_defines.h" #if defined __has_include #if __has_include("../../configuration.h") @@ -40,12 +40,11 @@ #endif #endif -#include "../core/hal.h" -#include "../core/log_esp3d.h" -#include "../include/pins.h" -#include "../include/sanity_esp3d.h" -#include "../include/version.h" - +#include "../core/esp3d_hal.h" +#include "../core/esp3d_log.h" +#include "../include/esp3d_pins.h" +#include "../include/esp3d_sanity.h" +#include "../include/esp3d_version.h" #if defined(ARDUINO_ARCH_ESP8266) /************************************ diff --git a/esp3d/src/include/defines.h b/esp3d/src/include/esp3d_defines.h similarity index 52% rename from esp3d/src/include/defines.h rename to esp3d/src/include/esp3d_defines.h index e3f28706..f5920ade 100644 --- a/esp3d/src/include/defines.h +++ b/esp3d/src/include/esp3d_defines.h @@ -1,5 +1,5 @@ /* - defines.h - ESP3D defines file + esp3d_defines.h - ESP3D defines file Copyright (c) 2014 Luc Lebosse. All rights reserved. @@ -40,102 +40,76 @@ typedef uint ESP3DSettingIndex; // position in EEPROM / preferences will use `P_` + to make a string // : P_0 for 0 -#define ESP_RADIO_MODE 0 // 1 byte = flag -#define ESP_STA_SSID \ - 1 // 33 bytes 32+1 = string ; warning does not support multibyte char like - // chinese -#define ESP_STA_PASSWORD \ - 34 // 65 bytes 64 +1 = string ;warning does not support multibyte char like - // chinese -#define ESP_STA_IP_MODE 99 // 1 byte = flag -#define ESP_STA_IP_VALUE 100 // 4 bytes xxx.xxx.xxx.xxx -#define ESP_STA_MASK_VALUE 104 // 4 bytes xxx.xxx.xxx.xxx -#define ESP_STA_GATEWAY_VALUE 108 // 4 bytes xxx.xxx.xxx.xxx -#define ESP_BAUD_RATE 112 // 4 bytes = int -#define ESP_NOTIFICATION_TYPE 116 // 1 byte = flag -#define ESP_CALIBRATION 117 // 1 byte = flag -#define ESP_AP_CHANNEL 118 // 1 byte = flag -#define ESP_BUZZER 119 // 1 byte = flag -#define ESP_INTERNET_TIME 120 // 1 byte = flag -#define ESP_HTTP_PORT 121 // 4 bytes = int -#define ESP_TELNET_PORT 125 // 4 bytes = int -#define ESP_SERIAL_FLAG 129 // 1 bytes = flag -#define ESP_HOSTNAME \ - 130 // 33 bytes 32+1 = string ; warning does not support multibyte char like - // chinese -#define ESP_SENSOR_INTERVAL 164 // 4 bytes = int -#define ESP_SETTINGS_VERSION 168 // 8 bytes = 7+1 = string ESP3D + 2 digits -#define ESP_ADMIN_PWD \ - 176 // 21 bytes 20+1 = string ; warning does not support multibyte char - // like chinese -#define ESP_USER_PWD \ - 197 // 21 bytes 20+1 = string ; warning does not support multibyte char - // like chinese -#define ESP_AP_SSID \ - 218 // 33 bytes 32+1 = string ; warning does not support multibyte char like - // chinese -#define ESP_AP_PASSWORD \ - 251 // 65 bytes 64 +1 = string ;warning does not support multibyte char like - // chinese -#define ESP_AP_IP_VALUE 316 // 4 bytes xxx.xxx.xxx.xxx -#define ESP_BOOT_DELAY 320 // 4 bytes = int -#define ESP_WEBSOCKET_PORT 324 // 4 bytes= int -#define ESP_HTTP_ON 328 // 1 byte = flag -#define ESP_TELNET_ON 329 // 1 byte = flag -#define ESP_WEBSOCKET_ON 330 // 1 byte = flag -#define ESP_SD_SPEED_DIV 331 // 1 byte = flag -#define ESP_NOTIFICATION_TOKEN1 \ - 332 // 64 bytes 63+1 = string ; warning does not support multibyte char like - // chinese -#define ESP_NOTIFICATION_TOKEN2 \ - 396 // 64 bytes 63+1 = string ; warning does not support multibyte char like - // chinese -#define ESP_SENSOR_TYPE 460 // 1 bytes = flag -#define ESP_TARGET_FW 461 // 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 - // like chinese -#define ESP_TIME_SERVER2 \ - 593 // 129 bytes 128+1 = string ; warning does not support multibyte char - // like chinese -#define ESP_TIME_SERVER3 \ - 722 // 129 bytes 128+1 = string ; warning does not support multibyte char - // like chinese -#define ESP_REMOTE_SCREEN_FLAG 851 // 1 bytes = flag -#define ESP_SD_MOUNT 852 // 1 bytes = flag -#define ESP_SESSION_TIMEOUT 853 // 1 bytes = flag -#define ESP_WEBSOCKET_FLAG 854 // 1 bytes = flag -#define ESP_SD_CHECK_UPDATE_AT_BOOT 855 // 1 bytes = flag -#define ESP_NOTIFICATION_SETTINGS \ - 856 // 129 bytes 128+1 = string ; warning does not support multibyte char - // like chinese -#define ESP_CALIBRATION_1 985 // 4 bytes = int -#define ESP_CALIBRATION_2 989 // 4 bytes = int -#define ESP_CALIBRATION_3 993 // 4 bytes = int -#define ESP_CALIBRATION_4 997 // 4 bytes = int -#define ESP_CALIBRATION_5 1001 // 4 bytes = int -#define ESP_SETUP 1005 // 1 byte = flag -#define ESP_TELNET_FLAG 1006 // 1 byte = flag -#define ESP_BT_FLAG 1007 // 1 byte = flag -#define ESP_SCREEN_FLAG 1008 // 1 byte = flag -#define ESP_FTP_CTRL_PORT 1009 // 4 bytes = int -#define ESP_FTP_DATA_ACTIVE_PORT 1013 // 4 bytes = int -#define ESP_FTP_DATA_PASSIVE_PORT 1017 // 4 bytes = int -#define ESP_FTP_ON 1021 // 1 byte = flag -#define ESP_AUTO_NOTIFICATION 1022 // 1 byte = flag -#define ESP_VERBOSE_BOOT 1023 // 1 byte = flag -#define ESP_WEBDAV_ON 1024 // 1 byte = flag -#define ESP_WEBDAV_PORT 1025 // 4 bytes= int -#define ESP_STA_DNS_VALUE 1029 // 4 bytes= int -#define ESP_SECURE_SERIAL 1033 // 1 byte = flag -#define ESP_BOOT_RADIO_STATE 1034 // 1 byte = flag -#define ESP_STA_FALLBACK_MODE 1035 // 1 byte = flag -#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 +#define ESP_RADIO_MODE 0 // 1 byte = flag +#define ESP_STA_SSID 1 // 33 bytes 32+1 = string ; warning does not support multibyte char like chinese +#define ESP_STA_PASSWORD 34 // 65 bytes 64 +1 = string ;warning does not support multibyte char like chinese +#define ESP_STA_IP_MODE 99 // 1 byte = flag +#define ESP_STA_IP_VALUE 100 // 4 bytes xxx.xxx.xxx.xxx +#define ESP_STA_MASK_VALUE 104 // 4 bytes xxx.xxx.xxx.xxx +#define ESP_STA_GATEWAY_VALUE 108 // 4 bytes xxx.xxx.xxx.xxx +#define ESP_BAUD_RATE 112 // 4 bytes = int +#define ESP_NOTIFICATION_TYPE 116 // 1 byte = flag +#define ESP_CALIBRATION 117 // 1 byte = flag +#define ESP_AP_CHANNEL 118 // 1 byte = flag +#define ESP_BUZZER 119 // 1 byte = flag +#define ESP_INTERNET_TIME 120 // 1 byte = flag +#define ESP_HTTP_PORT 121 // 4 bytes = int +#define ESP_TELNET_PORT 125 // 4 bytes = int +// #define FREE 129 // 1 bytes = flag +#define ESP_HOSTNAME 130 // 33 bytes 32+1 = string ; warning does not support multibyte char like chinese +#define ESP_SENSOR_INTERVAL 164 // 4 bytes = int +#define ESP_SETTINGS_VERSION 168 // 8 bytes = 7+1 = string ESP3D + 2 digits +#define ESP_ADMIN_PWD 176 // 21 bytes 20+1 = string ; warning does not support multibyte char like chinese +#define ESP_USER_PWD 197 // 21 bytes 20+1 = string ; warning does not support multibyte char like chinese +#define ESP_AP_SSID 218 // 33 bytes 32+1 = string ; warning does not support multibyte char like chinese +#define ESP_AP_PASSWORD 251 // 65 bytes 64 +1 = string ;warning does not support multibyte char like chinese +#define ESP_AP_IP_VALUE 316 // 4 bytes xxx.xxx.xxx.xxx +#define ESP_BOOT_DELAY 320 // 4 bytes = int +#define ESP_WEBSOCKET_PORT 324 // 4 bytes= int +#define ESP_HTTP_ON 328 // 1 byte = flag +#define ESP_TELNET_ON 329 // 1 byte = flag +#define ESP_WEBSOCKET_ON 330 // 1 byte = flag +#define ESP_SD_SPEED_DIV 331 // 1 byte = flag +#define ESP_NOTIFICATION_TOKEN1 332 // 251 bytes 250+1 = string ; warning does not support multibyte char like chinese +#define ESP_NOTIFICATION_TOKEN2 583 // 64 bytes 63+1 = string ; warning does not support multibyte char like chinese +#define ESP_SENSOR_TYPE 647 // 1 bytes = flag +#define ESP_TARGET_FW 648 // 1 bytes = flag +#define ESP_FREE 649 // 1 bytes = flag +// #define FREE 650 // 1 bytes = flag +#define ESP_TIME_SERVER1 651 // 129 bytes 128+1 = string ; warning does not support multibyte char like chinese +#define ESP_TIME_SERVER2 780 // 129 bytes 128+1 = string ; warning does not support multibyte char like chinese +#define ESP_TIME_SERVER3 909 // 129 bytes 128+1 = string ; warning does not support multibyte char like chinese +// #define FREE 1038 // 1 bytes = flag +#define ESP_SD_MOUNT 1039 // 1 bytes = flag +#define ESP_SESSION_TIMEOUT 1040 // 1 bytes = flag +// #define FREE 1041 // 1 bytes = flag +#define ESP_SD_CHECK_UPDATE_AT_BOOT 1042 // 1 bytes = flag +#define ESP_NOTIFICATION_SETTINGS 1043 // 129 bytes 128+1 = string ; warning does not support multibyte char like chinese +#define ESP_CALIBRATION_1 1172 // 4 bytes = int +#define ESP_CALIBRATION_2 1176 // 4 bytes = int +#define ESP_CALIBRATION_3 1180 // 4 bytes = int +#define ESP_CALIBRATION_4 1184 // 4 bytes = int +#define ESP_CALIBRATION_5 1188 // 4 bytes = int +#define ESP_SETUP 1192 // 1 byte = flag +// #define FREE 1193 // 1 byte = flag +// #define FREE 1194 // 1 byte = flag +// #define FREE 1195 // 1 byte = flag +#define ESP_FTP_CTRL_PORT 1196 // 4 bytes = int +#define ESP_FTP_DATA_ACTIVE_PORT 1200 // 4 bytes = int +#define ESP_FTP_DATA_PASSIVE_PORT 1204 // 4 bytes = int +#define ESP_FTP_ON 1208 // 1 byte = flag +#define ESP_AUTO_NOTIFICATION 1209 // 1 byte = flag +#define ESP_VERBOSE_BOOT 1210 // 1 byte = flag +#define ESP_WEBDAV_ON 1211 // 1 byte = flag +#define ESP_WEBDAV_PORT 1212 // 4 bytes= int +#define ESP_STA_DNS_VALUE 1216 // 4 bytes= int +#define ESP_SECURE_SERIAL 1220 // 1 byte = flag +#define ESP_BOOT_RADIO_STATE 1221 // 1 byte = flag +#define ESP_STA_FALLBACK_MODE 1222 // 1 byte = flag +#define ESP_SERIAL_BRIDGE_ON 1223 // 1 byte = flag +// #define FREE 1224 // 1 byte = flag +#define ESP_SERIAL_BRIDGE_BAUD 1225 // 4 bytes= int +#define ESP_TIME_ZONE 1229 // 7 bytes 6+1 = string // Hidden password #define HIDDEN_PASSWORD "********" @@ -247,6 +221,7 @@ typedef uint ESP3DSettingIndex; #define ESP_LINE_NOTIFICATION 3 #define ESP_TELEGRAM_NOTIFICATION 4 #define ESP_IFTTT_NOTIFICATION 5 +#define ESP_HOMEASSISTANT_NOTIFICATION 6 // SENSOR #define NO_SENSOR_DEVICE 0 diff --git a/esp3d/src/include/pins.h b/esp3d/src/include/esp3d_pins.h similarity index 99% rename from esp3d/src/include/pins.h rename to esp3d/src/include/esp3d_pins.h index c8bb8ac9..53e593a2 100644 --- a/esp3d/src/include/pins.h +++ b/esp3d/src/include/esp3d_pins.h @@ -1,5 +1,5 @@ /* - pins.h - pins definition file + esp3d_pins.h - pins definition file Copyright (c) 2014 Luc Lebosse. All rights reserved. diff --git a/esp3d/src/include/sanity_esp3d.h b/esp3d/src/include/esp3d_sanity.h similarity index 93% rename from esp3d/src/include/sanity_esp3d.h rename to esp3d/src/include/esp3d_sanity.h index 7b12f530..bd935102 100644 --- a/esp3d/src/include/sanity_esp3d.h +++ b/esp3d/src/include/esp3d_sanity.h @@ -1,5 +1,5 @@ /* - sanity_esp3d.h - esp3d sanity check functions + esp3d_sanity.h - esp3d sanity check functions Copyright (c) 2014 Luc Lebosse. All rights reserved. @@ -64,6 +64,15 @@ #error Serial 2 is not available in ESP8266 #endif // ESP_SERIAL_OUTPUT == USE_SERIAL_2 ) && ARDUINO_ARCH_ESP8266 +#if COMMUNICATION_PROTOCOL == MKS_SERIAL +#if defined(PRINTER_HAS_DISPLAY) +#error MKS serial protocol is not compatible with display output +#endif // defined(PRINTER_HAS_DISPLAY) +#if defined(ESP_SERIAL_BRIDGE_OUTPUT) +#error MKS serial protocol is not compatible with serial bridge output +#endif // defined(ESP_SERIAL_BRIDGE_OUTPUT) +#endif // COMMUNICATION_PROTOCOL == MKS_SERIAL + /************************** * Bluetooth * ***********************/ diff --git a/esp3d/src/include/version.h b/esp3d/src/include/esp3d_version.h similarity index 93% rename from esp3d/src/include/version.h rename to esp3d/src/include/esp3d_version.h index cc35b532..b7e485fe 100644 --- a/esp3d/src/include/version.h +++ b/esp3d/src/include/esp3d_version.h @@ -1,5 +1,5 @@ /* - version.h - ESP3D version file + esp3d_version.h - ESP3D version file Copyright (c) 2014 Luc Lebosse. All rights reserved. @@ -22,7 +22,7 @@ #define _VERSION_ESP3D_H // version and sources location -#define FW_VERSION "3.0.0.a225" +#define FW_VERSION "3.0.0.a226" #define REPOSITORY "https://github.com/luc-github/ESP3D/tree/3.0" #endif //_VERSION_ESP3D_H diff --git a/esp3d/src/modules/authentication/authentication_level_types.h b/esp3d/src/modules/authentication/authentication_level_types.h new file mode 100644 index 00000000..4d3fc0d6 --- /dev/null +++ b/esp3d/src/modules/authentication/authentication_level_types.h @@ -0,0 +1,30 @@ +/* + authentication_level_types.h - authentication 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 _AUTHENTICATION_LEVEL_TYPE_H +#define _AUTHENTICATION_LEVEL_TYPE_H +enum class ESP3DAuthenticationLevel : uint8_t { + guest = 0, + user = 1, + admin = 2, + not_authenticated, +}; + +#endif //_AUTHENTICATION_LEVEL_TYPE_H diff --git a/esp3d/src/modules/authentication/authentication_service.cpp b/esp3d/src/modules/authentication/authentication_service.cpp index c0f44191..f7cb304e 100644 --- a/esp3d/src/modules/authentication/authentication_service.cpp +++ b/esp3d/src/modules/authentication/authentication_service.cpp @@ -19,20 +19,21 @@ */ #include "authentication_service.h" -#include "../../core/esp3doutput.h" -#include "../../core/settings_esp3d.h" + +#include "../../core/esp3d_message.h" +#include "../../core/esp3d_settings.h" #if defined(AUTHENTICATION_FEATURE) #if defined(HTTP_FEATURE) #if defined(ARDUINO_ARCH_ESP32) #include -#endif //ARDUINO_ARCH_ESP32 +#endif // ARDUINO_ARCH_ESP32 #if defined(ARDUINO_ARCH_ESP8266) #include -#endif //ARDUINO_ARCH_ESP8266 +#endif // ARDUINO_ARCH_ESP8266 Authwebserver *AuthenticationService::_webserver = nullptr; -#endif //HTTP_FEATURE -#endif //AUTHENTICATION_FEATURE +#endif // HTTP_FEATURE +#endif // AUTHENTICATION_FEATURE #if defined(AUTHENTICATION_FEATURE) String AuthenticationService::_adminpwd = ""; @@ -41,315 +42,308 @@ String AuthenticationService::_userpwd = ""; uint32_t AuthenticationService::_sessionTimeout = 360000; auth_ip *AuthenticationService::_head = nullptr; uint8_t AuthenticationService::_current_nb_ip = 0; -#endif //HTTP_FEATURE -#endif //AUTHENTICATION_FEATURE +#endif // HTTP_FEATURE +#endif // AUTHENTICATION_FEATURE #define MAX_AUTH_IP 10 -//#define ALLOW_MULTIPLE_SESSIONS +// #define ALLOW_MULTIPLE_SESSIONS -//check authentification -level_authenticate_type AuthenticationService::authenticated_level(const char *pwd, ESP3DOutput *output) -{ +// check authentification +ESP3DAuthenticationLevel AuthenticationService::getAuthenticatedLevel( + const char *pwd, ESP3DMessage *esp3dmsg) { #ifdef AUTHENTICATION_FEATURE - level_authenticate_type auth_type = LEVEL_GUEST; - if (pwd != nullptr) { - - if (isadmin(pwd)) { - auth_type = LEVEL_ADMIN; - } - if (isuser(pwd) && (auth_type != LEVEL_ADMIN)) { - auth_type = LEVEL_USER; - } - return auth_type; - } else { - if (output) { - if (output->client() != ESP_HTTP_CLIENT) { - return auth_type; - } - } -#if defined(HTTP_FEATURE) - if (_webserver) { - if (_webserver->hasHeader("Authorization")) { - //log_esp3d("Check authorization %",(_webserver->uri()).c_str()); - if (_webserver->authenticate(DEFAULT_ADMIN_LOGIN, _adminpwd.c_str())) { - auth_type = LEVEL_ADMIN; - } else { - if (_webserver->authenticate(DEFAULT_USER_LOGIN, _userpwd.c_str())) { - auth_type = LEVEL_USER; - } - } - } - if (_webserver->hasHeader("Cookie")) { - //log_esp3d("Check Cookie %s",(_webserver->uri()).c_str()); - String cookie = _webserver->header("Cookie"); - int pos = cookie.indexOf("ESPSESSIONID="); - if (pos != -1) { - int pos2 = cookie.indexOf(";", pos); - String sessionID = cookie.substring(pos + strlen("ESPSESSIONID="), pos2); - IPAddress ip = _webserver->client().remoteIP(); - //check if cookie can be reset and clean table in same time - auth_type = ResetAuthIP(ip, sessionID.c_str()); - //log_esp3d("Authentication = %d", auth_type); - } - } - } -#endif //HTTP_FEATURE + ESP3DAuthenticationLevel auth_type = ESP3DAuthenticationLevel::guest; + if (pwd != nullptr) { + if (isadmin(pwd)) { + auth_type = ESP3DAuthenticationLevel::admin; + } + if (isuser(pwd) && (auth_type != ESP3DAuthenticationLevel::admin)) { + auth_type = ESP3DAuthenticationLevel::user; } return auth_type; + } else { + if (esp3dmsg) { + if (esp3dmsg->origin != ESP3DClientType::http) { + return auth_type; + } + } +#if defined(HTTP_FEATURE) + if (_webserver) { + if (_webserver->hasHeader("Authorization")) { + // esp3d_log("Check authorization %",(_webserver->uri()).c_str()); + if (_webserver->authenticate(DEFAULT_ADMIN_LOGIN, _adminpwd.c_str())) { + auth_type = ESP3DAuthenticationLevel::admin; + } else { + if (_webserver->authenticate(DEFAULT_USER_LOGIN, _userpwd.c_str())) { + auth_type = ESP3DAuthenticationLevel::user; + } + } + } + if (_webserver->hasHeader("Cookie")) { + // esp3d_log("Check Cookie %s",(_webserver->uri()).c_str()); + String cookie = _webserver->header("Cookie"); + int pos = cookie.indexOf("ESPSESSIONID="); + if (pos != -1) { + int pos2 = cookie.indexOf(";", pos); + String sessionID = + cookie.substring(pos + strlen("ESPSESSIONID="), pos2); + IPAddress ip = _webserver->client().remoteIP(); + // check if cookie can be reset and clean table in same time + auth_type = ResetAuthIP(ip, sessionID.c_str()); + // esp3d_log("Authentication = %d", auth_type); + } + } + } +#endif // HTTP_FEATURE + } + return auth_type; #else - (void)pwd; - (void)output; - return LEVEL_ADMIN; -#endif //AUTHENTICATION_FEATURE + (void)pwd; + (void)esp3dmsg; + return ESP3DAuthenticationLevel::admin; +#endif // AUTHENTICATION_FEATURE } #ifdef AUTHENTICATION_FEATURE #if defined(HTTP_FEATURE) -uint32_t AuthenticationService::setSessionTimeout(uint32_t timeout) -{ - if (timeout >= 0) { - _sessionTimeout = timeout; - } - return _sessionTimeout; +uint32_t AuthenticationService::setSessionTimeout(uint32_t timeout) { + if (timeout >= 0) { + _sessionTimeout = timeout; + } + return _sessionTimeout; } -uint32_t AuthenticationService::getSessionTimeout() -{ - return _sessionTimeout; -} -#endif //HTTP_FEATURE +uint32_t AuthenticationService::getSessionTimeout() { return _sessionTimeout; } +#endif // HTTP_FEATURE -bool AuthenticationService::begin(Authwebserver *webserver) -{ - end(); - update(); +bool AuthenticationService::begin(Authwebserver *webserver) { + end(); + update(); #if defined(HTTP_FEATURE) - _webserver = webserver; -#endif //HTTP_FEATURE - //value is in ms but storage is in min - _sessionTimeout = 1000 * 60 * Settings_ESP3D::read_byte(ESP_SESSION_TIMEOUT); + _webserver = webserver; +#endif // HTTP_FEATURE + // value is in ms but storage is in min + _sessionTimeout = 1000 * 60 * ESP3DSettings::readByte(ESP_SESSION_TIMEOUT); + return true; +} +void AuthenticationService::end() { +#if defined(HTTP_FEATURE) + _webserver = nullptr; + ClearAllSessions(); +#endif // HTTP_FEATURE +} + +void AuthenticationService::update() { + _adminpwd = ESP3DSettings::readString(ESP_ADMIN_PWD); + _userpwd = ESP3DSettings::readString(ESP_USER_PWD); +} + +void AuthenticationService::handle() {} + +// check admin password +bool AuthenticationService::isadmin(const char *pwd) { + if (strcmp(_adminpwd.c_str(), pwd) != 0) { + return false; + } else { return true; -} -void AuthenticationService::end() -{ -#if defined(HTTP_FEATURE) - _webserver = nullptr; - ClearAllSessions(); -#endif //HTTP_FEATURE + } } -void AuthenticationService::update() -{ - _adminpwd = Settings_ESP3D::read_string(ESP_ADMIN_PWD); - _userpwd = Settings_ESP3D::read_string(ESP_USER_PWD); -} - -void AuthenticationService::handle() -{ -} - -//check admin password -bool AuthenticationService::isadmin(const char *pwd) -{ - if (strcmp(_adminpwd.c_str(), pwd) != 0) { - return false; - } else { - return true; - } -} - -//check user password - admin password is also valid -bool AuthenticationService::isuser(const char *pwd) -{ - //it is not user password - if (strcmp(_userpwd.c_str(), pwd) != 0) { - //check admin password - return isadmin(pwd); - } else { - return true; - } +// check user password - admin password is also valid +bool AuthenticationService::isuser(const char *pwd) { + // it is not user password + if (strcmp(_userpwd.c_str(), pwd) != 0) { + // check admin password + return isadmin(pwd); + } else { + return true; + } } #if defined(HTTP_FEATURE) -//add the information in the linked list if possible -bool AuthenticationService::AddAuthIP(auth_ip *item) -{ - if (_current_nb_ip > MAX_AUTH_IP) { - return false; - } - item->_next = _head; - _head = item; - _current_nb_ip++; - return true; +// add the information in the linked list if possible +bool AuthenticationService::AddAuthIP(auth_ip *item) { + if (_current_nb_ip > MAX_AUTH_IP) { + return false; + } + item->_next = _head; + _head = item; + _current_nb_ip++; + return true; } -//Session ID based on IP and time using 16 char -char *AuthenticationService::create_session_ID() -{ - static char sessionID[17]; - //reset SESSIONID - for (int i = 0; i < 17; i++) { - sessionID[i] = '\0'; - } - //get time - uint32_t now = millis(); - //get remote IP - IPAddress remoteIP = _webserver->client().remoteIP(); - //generate SESSIONID - if (0 > sprintf(sessionID, "%02X%02X%02X%02X%02X%02X%02X%02X", remoteIP[0], remoteIP[1], remoteIP[2], remoteIP[3], (uint8_t)((now >> 0) & 0xff), (uint8_t)((now >> 8) & 0xff), (uint8_t)((now >> 16) & 0xff), (uint8_t)((now >> 24) & 0xff))) { - strcpy(sessionID, "NONE"); - } - return sessionID; +// Session ID based on IP and time using 16 char +char *AuthenticationService::create_session_ID() { + static char sessionID[17]; + // reset SESSIONID + for (int i = 0; i < 17; i++) { + sessionID[i] = '\0'; + } + // get time + uint32_t now = millis(); + // get remote IP + IPAddress remoteIP = _webserver->client().remoteIP(); + // generate SESSIONID + if (0 > sprintf(sessionID, "%02X%02X%02X%02X%02X%02X%02X%02X", remoteIP[0], + remoteIP[1], remoteIP[2], remoteIP[3], + (uint8_t)((now >> 0) & 0xff), (uint8_t)((now >> 8) & 0xff), + (uint8_t)((now >> 16) & 0xff), + (uint8_t)((now >> 24) & 0xff))) { + strcpy(sessionID, "NONE"); + } + return sessionID; } -bool AuthenticationService::ClearAllSessions() -{ - while (_head) { - auth_ip *current = _head; - _head = _head->_next; - delete current; - } - _current_nb_ip = 0; - _head = nullptr; +bool AuthenticationService::ClearAllSessions() { + while (_head) { + auth_ip *current = _head; + _head = _head->_next; + free(current); + } + _current_nb_ip = 0; + _head = nullptr; - return true; + return true; } -bool AuthenticationService::ClearCurrentSession() -{ - String cookie = _webserver->header("Cookie"); - int pos = cookie.indexOf("ESPSESSIONID="); - String sessionID; - if (pos != -1) { - int pos2 = cookie.indexOf(";", pos); - sessionID = cookie.substring(pos + strlen("ESPSESSIONID="), pos2); - } - return ClearAuthIP(_webserver->client().remoteIP(), sessionID.c_str()); +bool AuthenticationService::ClearCurrentHttpSession() { + String cookie = _webserver->header("Cookie"); + int pos = cookie.indexOf("ESPSESSIONID="); + String sessionID; + if (pos != -1) { + int pos2 = cookie.indexOf(";", pos); + sessionID = cookie.substring(pos + strlen("ESPSESSIONID="), pos2); + } + return ClearAuthIP(_webserver->client().remoteIP(), sessionID.c_str()); } -bool AuthenticationService::CreateSession(level_authenticate_type auth_level, const char *username, const char *session_ID) -{ - auth_ip *current_auth = new auth_ip; - current_auth->level = auth_level; - current_auth->ip = _webserver->client().remoteIP(); - strcpy(current_auth->sessionID, session_ID); - strcpy(current_auth->userID, username); - current_auth->last_time = millis(); +bool AuthenticationService::CreateSession(ESP3DAuthenticationLevel auth_level, + ESP3DClientType client_type, + const char *session_ID) { + auth_ip *current_auth = (auth_ip *)malloc(sizeof(auth_ip)); + if (!current_auth) { + esp3d_log_e("Error allocating memory for session"); + return false; + } + current_auth->level = auth_level; + current_auth->ip = _webserver->client().remoteIP(); + current_auth->client_type = client_type; + strcpy(current_auth->sessionID, session_ID); + current_auth->last_time = millis(); #ifndef ALLOW_MULTIPLE_SESSIONS - //if not multiple session no need to keep all session, current one is enough - ClearAllSessions(); -#endif //ALLOW_MULTIPLE_SESSIONS - if (AddAuthIP(current_auth)) { - return true; + // if not multiple session no need to keep all session, current one is enough + ClearAllSessions(); +#endif // ALLOW_MULTIPLE_SESSIONS + if (AddAuthIP(current_auth)) { + return true; + } else { + free(current_auth); + return false; + } +} + +bool AuthenticationService::ClearAuthIP(IPAddress ip, const char *sessionID) { + auth_ip *current = _head; + auth_ip *previous = NULL; + bool done = false; + while (current) { + if ((ip == current->ip) && (strcmp(sessionID, current->sessionID) == 0)) { + // remove + done = true; + if (current == _head) { + _head = current->_next; + _current_nb_ip--; + free(current); + current = _head; + } else { + previous->_next = current->_next; + _current_nb_ip--; + free(current); + current = previous->_next; + } } else { - delete current_auth; - return false; + previous = current; + current = current->_next; } + } + return done; } -bool AuthenticationService::ClearAuthIP(IPAddress ip, const char *sessionID) -{ - auth_ip *current = _head; - auth_ip *previous = NULL; - bool done = false; - while (current) { - if ((ip == current->ip) && (strcmp(sessionID, current->sessionID) == 0)) { - //remove - done = true; - if (current == _head) { - _head = current->_next; - _current_nb_ip--; - delete current; - current = _head; - } else { - previous->_next = current->_next; - _current_nb_ip--; - delete current; - current = previous->_next; - } - } else { - previous = current; - current = current->_next; - } +// Get info +auth_ip *AuthenticationService::GetAuth(IPAddress ip, const char *sessionID) { + auth_ip *current = _head; + while (current) { + if (ip == current->ip) { + if (strcmp(sessionID, current->sessionID) == 0) { + // found + return current; + } } - return done; + // previous = current; + current = current->_next; + } + return NULL; } -//Get info -auth_ip *AuthenticationService::GetAuth(IPAddress ip, const char *sessionID) -{ - auth_ip *current = _head; - while (current) { - if (ip == current->ip) { - if (strcmp(sessionID, current->sessionID) == 0) { - //found - return current; - } - } - //previous = current; - current = current->_next; - } - return NULL; -} - -//Get time left for specific session -uint32_t AuthenticationService::getSessionRemaining(const char *sessionID) -{ - auth_ip *current = _head; - if ((sessionID == nullptr) || (strlen(sessionID) == 0)) { - return 0; - } - while (current) { - if (strcmp(sessionID, current->sessionID) == 0) { - //found - uint32_t now = millis(); - if ((now - current->last_time) > _sessionTimeout) { - return 0; - } - return _sessionTimeout - (now - current->last_time); - } - //previous = current; - current = current->_next; - } +// Get time left for specific session +uint32_t AuthenticationService::getSessionRemaining(const char *sessionID) { + auth_ip *current = _head; + if ((sessionID == nullptr) || (strlen(sessionID) == 0)) { return 0; -} - -//Review all IP to reset timers -level_authenticate_type AuthenticationService::ResetAuthIP(IPAddress ip, const char *sessionID) -{ - auth_ip *current = _head; - auth_ip *previous = NULL; - //get time - //uint32_t now = millis(); - while (current) { - //if time out is reached and time out is not disabled - //if IP is not current one and time out is disabled - if ((((millis() - current->last_time) > _sessionTimeout) && (_sessionTimeout != 0)) || ((ip != current->ip) && (_sessionTimeout == 0))) { - //remove - if (current == _head) { - _head = current->_next; - _current_nb_ip--; - delete current; - current = _head; - } else { - previous->_next = current->_next; - _current_nb_ip--; - delete current; - current = previous->_next; - } - } else { - if (ip == current->ip) { - if (strcmp(sessionID, current->sessionID) == 0) { - //reset time - current->last_time = millis(); - return (level_authenticate_type)current->level; - } - } - previous = current; - current = current->_next; - } + } + while (current) { + if (strcmp(sessionID, current->sessionID) == 0) { + // found + uint32_t now = millis(); + if ((now - current->last_time) > _sessionTimeout) { + return 0; + } + return _sessionTimeout - (now - current->last_time); } - return LEVEL_GUEST; + // previous = current; + current = current->_next; + } + return 0; } -#endif //HTTP_FEATURE -#endif //AUTHENTICATION_FEATURE +// Review all IP to reset timers +ESP3DAuthenticationLevel AuthenticationService::ResetAuthIP( + IPAddress ip, const char *sessionID) { + auth_ip *current = _head; + auth_ip *previous = NULL; + // get time + // uint32_t now = millis(); + while (current) { + // if time out is reached and time out is not disabled + // if IP is not current one and time out is disabled + if ((((millis() - current->last_time) > _sessionTimeout) && + (_sessionTimeout != 0)) || + ((ip != current->ip) && (_sessionTimeout == 0))) { + // remove + if (current == _head) { + _head = current->_next; + _current_nb_ip--; + free(current); + current = _head; + } else { + previous->_next = current->_next; + _current_nb_ip--; + free(current); + current = previous->_next; + } + } else { + if (ip == current->ip) { + if (strcmp(sessionID, current->sessionID) == 0) { + // reset time + current->last_time = millis(); + return (ESP3DAuthenticationLevel)current->level; + } + } + previous = current; + current = current->_next; + } + } + return ESP3DAuthenticationLevel::guest; +} +#endif // HTTP_FEATURE + +#endif // AUTHENTICATION_FEATURE diff --git a/esp3d/src/modules/authentication/authentication_service.h b/esp3d/src/modules/authentication/authentication_service.h index 9be9d676..58bae4d3 100644 --- a/esp3d/src/modules/authentication/authentication_service.h +++ b/esp3d/src/modules/authentication/authentication_service.h @@ -18,79 +18,75 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - #ifndef _AUTHENTICATION_SERVICE_H #define _AUTHENTICATION_SERVICE_H -typedef enum { - LEVEL_GUEST = 0, - LEVEL_USER = 1, - LEVEL_ADMIN = 2 -} level_authenticate_type; -const char DEFAULT_ADMIN_LOGIN [] = "admin"; -const char DEFAULT_USER_LOGIN [] = "user"; +const char DEFAULT_ADMIN_LOGIN[] = "admin"; +const char DEFAULT_USER_LOGIN[] = "user"; +#include "../../core/esp3d_message.h" #include "../../include/esp3d_config.h" -#include "../../core/esp3doutput.h" -#if defined (AUTHENTICATION_FEATURE) -#if defined (HTTP_FEATURE) +#include "authentication_level_types.h" + +#if defined(AUTHENTICATION_FEATURE) +#if defined(HTTP_FEATURE) #include struct auth_ip { - IPAddress ip; - level_authenticate_type level; - char userID[17]; - char sessionID[17]; - uint32_t last_time; - auth_ip * _next; + IPAddress ip; + ESP3DAuthenticationLevel level; + ESP3DClientType client_type; + char sessionID[17]; + uint32_t last_time; + auth_ip *_next; }; -#if defined (ARDUINO_ARCH_ESP32) +#if defined(ARDUINO_ARCH_ESP32) class WebServer; -typedef WebServer Authwebserver; -#endif //ARDUINO_ARCH_ESP32 -#if defined (ARDUINO_ARCH_ESP8266) +typedef WebServer Authwebserver; +#endif // ARDUINO_ARCH_ESP32 +#if defined(ARDUINO_ARCH_ESP8266) #include -typedef ESP8266WebServer Authwebserver; -#endif //ARDUINO_ARCH_ESP8266 +typedef ESP8266WebServer Authwebserver; +#endif // ARDUINO_ARCH_ESP8266 #else typedef void Authwebserver; -#endif // HTTP_FEATURE -#endif //AUTHENTICATION_FEATURE -class AuthenticationService -{ -public: - static level_authenticate_type authenticated_level(const char * pwd = nullptr, ESP3DOutput * output= nullptr); +#endif // HTTP_FEATURE +#endif // AUTHENTICATION_FEATURE +class AuthenticationService { + public: + static ESP3DAuthenticationLevel getAuthenticatedLevel( + const char *pwd = nullptr, ESP3DMessage *esp3dmsg = nullptr); #ifdef AUTHENTICATION_FEATURE - static bool begin(Authwebserver * webserver); - static void end(); - static void handle(); - static bool isadmin (const char *pwd); - static void update(); - static bool isuser (const char *pwd); -#if defined (HTTP_FEATURE) - static uint32_t setSessionTimeout(uint32_t timeout); - static uint32_t getSessionTimeout(); - static uint32_t getSessionRemaining(const char * sessionID); - static char * create_session_ID(); - static bool ClearCurrentSession (); - static bool ClearAllSessions (); - static bool CreateSession(level_authenticate_type auth_level, const char * username, const char* session_ID); -#endif //HTTP_FEATURE -private: - static String _adminpwd; - static String _userpwd; -#if defined (HTTP_FEATURE) - static bool AddAuthIP (auth_ip * item); - static bool ClearAuthIP (IPAddress ip, const char * sessionID); - static auth_ip * GetAuth (IPAddress ip, const char * sessionID); - static level_authenticate_type ResetAuthIP (IPAddress ip, const char * sessionID); - static Authwebserver * _webserver; - static uint32_t _sessionTimeout; - static auth_ip * _head; - static uint8_t _current_nb_ip; -#endif //HTTP_FEATURE -#endif //AUTHENTICATION_FEATURE + static bool begin(Authwebserver *webserver); + static void end(); + static void handle(); + static bool isadmin(const char *pwd); + static void update(); + static bool isuser(const char *pwd); +#if defined(HTTP_FEATURE) + static uint32_t setSessionTimeout(uint32_t timeout); + static uint32_t getSessionTimeout(); + static uint32_t getSessionRemaining(const char *sessionID); + static char *create_session_ID(); + static bool ClearCurrentHttpSession(); + static bool ClearAllSessions(); + static bool CreateSession(ESP3DAuthenticationLevel auth_level, + ESP3DClientType client_type, const char *session_ID); +#endif // HTTP_FEATURE + private: + static String _adminpwd; + static String _userpwd; +#if defined(HTTP_FEATURE) + static bool AddAuthIP(auth_ip *item); + static bool ClearAuthIP(IPAddress ip, const char *sessionID); + static auth_ip *GetAuth(IPAddress ip, const char *sessionID); + static ESP3DAuthenticationLevel ResetAuthIP(IPAddress ip, + const char *sessionID); + static Authwebserver *_webserver; + static uint32_t _sessionTimeout; + static auth_ip *_head; + static uint8_t _current_nb_ip; +#endif // HTTP_FEATURE +#endif // AUTHENTICATION_FEATURE }; -#endif //_ESP3DSECURITY_H - +#endif //_ESP3DSECURITY_H diff --git a/esp3d/src/modules/bluetooth/BT_service.cpp b/esp3d/src/modules/bluetooth/BT_service.cpp index 81efb522..171844b4 100644 --- a/esp3d/src/modules/bluetooth/BT_service.cpp +++ b/esp3d/src/modules/bluetooth/BT_service.cpp @@ -23,12 +23,12 @@ #include "../../include/esp3d_config.h" #ifdef BLUETOOTH_FEATURE -#include "BluetoothSerial.h" -#include "../../core/esp3doutput.h" -#include "../../core/settings_esp3d.h" -#include "../../core/commands.h" +#include "../../core/esp3d_commands.h" +#include "../../core/esp3d_settings.h" #include "../network/netconfig.h" #include "BT_service.h" +#include "BluetoothSerial.h" + BluetoothSerial SerialBT; #ifdef __cplusplus extern "C" { @@ -45,265 +45,255 @@ BTService bt_service; String BTService::_btname = ""; String BTService::_btclient = ""; -BTService::BTService() -{ - _buffer_size = 0; - _started=false; +BTService::BTService() { + _buffer_size = 0; + _started = false; } -BTService::~BTService() -{ - end(); +BTService::~BTService() { end(); } + +bool BTService::isConnected() { + return ((_btclient.length() > 0) ? true : false); } -bool BTService::isConnected() -{ - return ((_btclient.length() > 0)?true:false); -} +void BTService::setClientAddress(const char *saddress) { _btclient = saddress; } -void BTService::setClientAddress(const char * saddress) -{ - _btclient = saddress; -} - -static void my_spp_cb(esp_spp_cb_event_t event, esp_spp_cb_param_t *param) -{ - ESP3DOutput output(ESP_ALL_CLIENTS); - switch (event) { +static void my_spp_cb(esp_spp_cb_event_t event, esp_spp_cb_param_t *param) { + switch (event) { case ESP_SPP_SRV_OPEN_EVT: { - //Server connection open - char str[18]; - str[17]='\0'; - uint8_t * addr = param->srv_open.rem_bda; - sprintf(str, "%02X:%02X:%02X:%02X:%02X:%02X", addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]); - BTService::setClientAddress(str); - String stmp = "BT Connected with "; - stmp += str; - output.printMSG(stmp.c_str()); -#if defined (DISPLAY_DEVICE) - ESP3DOutput outputscr(ESP_SCREEN_CLIENT); - outputscr.printMSG(stmp.c_str()); -#endif //DISPLAY_DEVICE - } - break; + // Server connection open + char str[18]; + str[17] = '\0'; + uint8_t *addr = param->srv_open.rem_bda; + sprintf(str, "%02X:%02X:%02X:%02X:%02X:%02X", addr[0], addr[1], addr[2], + addr[3], addr[4], addr[5]); + BTService::setClientAddress(str); + String stmp = "BT Connected with "; + stmp += str; + esp3d_commands.dispatch(stmp.c_str(), ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); + } break; case ESP_SPP_CLOSE_EVT: { - //Client connection closed - output.printMSG("BT Disconnected"); -#if defined (DISPLAY_DEVICE) - ESP3DOutput outputscr(ESP_SCREEN_CLIENT); - outputscr.printMSG("BT Disconnected"); -#endif //DISPLAY_DEVICE - BTService::setClientAddress(""); - } - break; + // Client connection closed + esp3d_commands.dispatch("BT Disconnected", ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); + BTService::setClientAddress(""); + } break; default: - break; - } + break; + } } -const char* BTService::macAddress() -{ - const uint8_t* point = esp_bt_dev_get_address(); - static char str[18]; - str[17]='\0'; - sprintf(str, "%02X:%02X:%02X:%02X:%02X:%02X", (int)point[0], (int)point[1], (int)point[2], (int)point[3], (int)point[4], (int)point[5]); - return str; +const char *BTService::macAddress() { + const uint8_t *point = esp_bt_dev_get_address(); + static char str[18]; + str[17] = '\0'; + sprintf(str, "%02X:%02X:%02X:%02X:%02X:%02X", (int)point[0], (int)point[1], + (int)point[2], (int)point[3], (int)point[4], (int)point[5]); + return str; } -const char* BTService::clientmacAddress() -{ - return _btclient.c_str(); -} +const char *BTService::clientmacAddress() { return _btclient.c_str(); } /** * begin BT setup */ -bool BTService::begin() -{ - ESP3DOutput output(ESP_ALL_CLIENTS); - bool res = true; - _buffer_size = 0; - _lastflush = millis(); - //stop BT Serial if active - end(); - //Get hostname - //this allow to adjust if necessary - _btname = Settings_ESP3D::read_string(ESP_HOSTNAME); +bool BTService::begin() { + bool res = true; + _buffer_size = 0; + _lastflush = millis(); + // stop BT Serial if active + end(); + // Get hostname + // this allow to adjust if necessary + _btname = ESP3DSettings::readString(ESP_HOSTNAME); + String stmp; + if (!SerialBT.begin(_btname)) { + stmp = "BT failed start"; + res = false; + } else { + SerialBT.register_callback(&my_spp_cb); + stmp = "Bluetooth Started with: '" + _btname + "'"; + } + esp3d_commands.dispatch(stmp.c_str(), ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::bluetooth, + ESP3DAuthenticationLevel::admin); + initAuthentication(); - if (!SerialBT.begin(_btname)) { - output.printERROR("BT failed start"); - res = false; - } else { - SerialBT.register_callback(&my_spp_cb); - String stmp = "Bluetooth Started with: '" + _btname + "'"; - output.printMSG(stmp.c_str()); - } - - return res; + return res; } /** * End BT */ -void BTService::end() -{ - flush(); - SerialBT.end(); - _buffer_size = 0; - _started=false; +void BTService::end() { + flush(); + SerialBT.end(); + _buffer_size = 0; + _started = false; } /** * Reset BT */ -bool BTService::reset() -{ - //nothing to reset - return true; +bool BTService::reset() { + // nothing to reset + return true; } /** * Check if BT is on and working */ -bool BTService::started() -{ - _started =btStarted(); - return _started; +bool BTService::started() { + _started = btStarted(); + return _started; } /** * Handle not critical actions that must be done in sync environement */ -void BTService::handle() -{ - //Do we have some data waiting - size_t len = SerialBT.available(); - if (len > 0) { - //if yes read them - uint8_t * sbuf = (uint8_t *)malloc(len); - if(sbuf) { - size_t count = readBytes(sbuf, len); - //push to buffer - if (count > 0) { - push2buffer(sbuf, count); - } - //freen buffer - free(sbuf); - } - } - //we cannot left data in buffer too long - //in case some commands "forget" to add \n - if (((millis() - _lastflush) > TIMEOUT_BT_FLUSH) && (_buffer_size > 0)) { - flushbuffer(); +void BTService::handle() { + // Do we have some data waiting + size_t len = SerialBT.available(); + if (len > 0) { + // if yes read them + uint8_t *sbuf = (uint8_t *)malloc(len); + if (sbuf) { + size_t count = readBytes(sbuf, len); + // push to buffer + if (count > 0) { + push2buffer(sbuf, count); + } + // freen buffer + free(sbuf); } + } + // we cannot left data in buffer too long + // in case some commands "forget" to add \n + if (((millis() - _lastflush) > TIMEOUT_BT_FLUSH) && (_buffer_size > 0)) { + flushbuffer(); + } } -void BTService::flushbuffer() -{ - ESP3DOutput output(ESP_BT_CLIENT); - _buffer[_buffer_size] = 0x0; - //dispatch command - esp3d_commands.process(_buffer, _buffer_size, &output); +void BTService::initAuthentication() { +#if defined(AUTHENTICATION_FEATURE) + _auth = ESP3DAuthenticationLevel::guest; +#else + _auth = ESP3DAuthenticationLevel::admin; +#endif // AUTHENTICATION_FEATURE +} +ESP3DAuthenticationLevel BTService::getAuthentication() { return _auth; } + +void BTService::flushbuffer() { + _buffer[_buffer_size] = 0x0; + // dispatch command + ESP3DMessage *msg = ESP3DMessageManager::newMsg( + ESP3DClientType::bluetooth, esp3d_commands.getOutputClient(), _buffer, + _buffer_size, _auth); + if (msg) { + // process command + esp3d_commands.process(msg); + } else { + esp3d_log_e("Cannot create message"); + } + _lastflush = millis(); + _buffer_size = 0; +} + +// push collected data to buffer and proceed accordingly +void BTService::push2buffer(uint8_t *sbuf, size_t len) { + for (size_t i = 0; i < len; i++) { _lastflush = millis(); - _buffer_size = 0; -} - -//push collected data to buffer and proceed accordingly -void BTService::push2buffer(uint8_t * sbuf, size_t len) -{ - 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_BT_BUFFER_SIZE) { - _buffer[_buffer_size] = sbuf[i]; - _buffer_size++; - } - flushbuffer(); - } else if (isPrintable (char(sbuf[i]) )) { - if (_buffer_size < ESP3D_BT_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(); - } + // command is defined + if ((char(sbuf[i]) == '\n') || (char(sbuf[i]) == '\r')) { + if (_buffer_size < ESP3D_BT_BUFFER_SIZE) { + _buffer[_buffer_size] = sbuf[i]; + _buffer_size++; + } + flushbuffer(); + } else if (isPrintable(char(sbuf[i]))) { + if (_buffer_size < ESP3D_BT_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 BTService::write(uint8_t c) -{ - return SerialBT.write(c); -} - -size_t BTService::write(const uint8_t *buffer, size_t size) -{ - if (availableForWrite() >= size) { - return SerialBT.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 = SerialBT.write(&buffertmp[sizesent], (available >= sizetosend)?sizetosend:available); - sizetosend-=available; - sizesent+=available; - starttime=millis(); - } else { - Hal::wait(5); - } - } - return sizesent; +size_t BTService::writeBytes(const uint8_t *buffer, size_t size) { + if (availableForWrite() >= size) { + return SerialBT.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 = + SerialBT.write(&buffertmp[sizesent], + (available >= sizetosend) ? sizetosend : available); + sizetosend -= available; + sizesent += available; + starttime = millis(); + } else { + ESP3DHal::wait(5); + } } + return sizesent; + } } -int BTService::availableForWrite() -{ - return 128;//SerialBT.availableForWrite(); +int BTService::availableForWrite() { + return 128; // SerialBT.availableForWrite(); } -int BTService::available() -{ - return SerialBT.available(); +int BTService::available() { return SerialBT.available(); } + +size_t BTService::readBytes(uint8_t *sbuf, size_t len) { + return SerialBT.readBytes(sbuf, len); } -int BTService::read() -{ - return SerialBT.read(); +void BTService::flush() { SerialBT.flush(); } + +const char *BTService::hostname() { return _btname.c_str(); } + +bool BTService::dispatch(ESP3DMessage *message) { + if (!message || !_started) { + return false; + } + if (message->size > 0 && message->data) { + size_t sentcnt = writeBytes(message->data, message->size); + if (sentcnt != message->size) { + return false; + } + ESP3DMessageManager::deleteMsg(message); + return true; + } + + return false; } -size_t BTService::readBytes(uint8_t * sbuf, size_t len) -{ - return SerialBT.readBytes(sbuf, len); -} +#endif // BLUETOOTH_FEATURE -void BTService::flush() -{ - SerialBT.flush(); -} - -const char * BTService::hostname() -{ - return _btname.c_str(); -} - -#endif // BLUETOOTH_FEATURE - -#endif // ARDUINO_ARCH_ESP32 +#endif // ARDUINO_ARCH_ESP32 diff --git a/esp3d/src/modules/bluetooth/BT_service.h b/esp3d/src/modules/bluetooth/BT_service.h index a51da710..2421ca7e 100644 --- a/esp3d/src/modules/bluetooth/BT_service.h +++ b/esp3d/src/modules/bluetooth/BT_service.h @@ -20,64 +20,47 @@ #ifndef _BT_SERVICE_H #define _BT_SERVICE_H -#include "Print.h" +#include "../../core/esp3d_message.h" #define ESP3D_BT_BUFFER_SIZE 512 -class BTService : public Print -{ -public: - BTService(); - ~BTService(); - static void BTEvent(uint8_t event); - const char * hostname(); - static const char* macAddress(); - static const char* clientmacAddress(); - bool begin(); - void end(); - void handle(); - bool reset(); - bool started(); - static void setClientAddress(const char * saddress); - bool isConnected(); - void flush(); - int availableForWrite(); - int available(); - size_t write(uint8_t c); - size_t write(const uint8_t *buffer, size_t size); - inline size_t write(const char * s) - { - return write((uint8_t*) s, strlen(s)); - } - inline size_t write(unsigned long n) - { - return write((uint8_t) n); - } - inline size_t write(long n) - { - return write((uint8_t) n); - } - inline size_t write(unsigned int n) - { - return write((uint8_t) n); - } - inline size_t write(int n) - { - return write((uint8_t) n); - } - int read(); - size_t readBytes (uint8_t * sbuf, size_t len); -private : - static String _btname; - static String _btclient; - uint32_t _lastflush; - uint8_t _buffer[ESP3D_BT_BUFFER_SIZE + 1]; //keep space of 0x0 terminal - size_t _buffer_size; - void push2buffer(uint8_t * sbuf, size_t len); - void flushbuffer(); - bool _started; +class BTService { + public: + BTService(); + ~BTService(); + static void BTEvent(uint8_t event); + const char* hostname(); + static const char* macAddress(); + static const char* clientmacAddress(); + bool begin(); + void end(); + void handle(); + bool reset(); + bool started(); + static void setClientAddress(const char* saddress); + bool isConnected(); + void flush(); + int availableForWrite(); + int available(); + size_t writeBytes(const uint8_t* buffer, size_t size); + size_t readBytes(uint8_t* sbuf, size_t len); + bool dispatch(ESP3DMessage* message); + void initAuthentication(); + void setAuthentication(ESP3DAuthenticationLevel auth) { _auth = auth; } + ESP3DAuthenticationLevel getAuthentication(); + + private: + ESP3DAuthenticationLevel _auth; + static String _btname; + static String _btclient; + uint32_t _lastflush; + uint8_t _buffer[ESP3D_BT_BUFFER_SIZE + 1]; // keep space of 0x0 terminal + size_t _buffer_size; + void push2buffer(uint8_t* sbuf, size_t len); + void flushbuffer(); + bool _started; }; -extern BTService bt_service; +extern BTService bt_service; -#endif //_BT_SERVICE_H +#endif //_BT_SERVICE_H diff --git a/esp3d/src/modules/boot_delay/boot_delay.cpp b/esp3d/src/modules/boot_delay/boot_delay.cpp index 396f1cf6..0f07ed3a 100644 --- a/esp3d/src/modules/boot_delay/boot_delay.cpp +++ b/esp3d/src/modules/boot_delay/boot_delay.cpp @@ -20,8 +20,8 @@ #include "boot_delay.h" -#include "../../core/esp3doutput.h" -#include "../../core/settings_esp3d.h" +#include "../../core/esp3d_commands.h" +#include "../../core/esp3d_settings.h" #include "../../include/esp3d_config.h" #if defined(RECOVERY_FEATURE) @@ -38,20 +38,30 @@ BootDelay::~BootDelay() { end(); } bool BootDelay::started() { return _started; } bool BootDelay::begin() { - _totalduration = Settings_ESP3D::read_uint32(ESP_BOOT_DELAY); - log_esp3d("Boot delay %d", _totalduration); - if (!Settings_ESP3D::isValidIntegerSetting(_totalduration, ESP_BOOT_DELAY)) { - _totalduration = Settings_ESP3D::getDefaultIntegerSetting(ESP_BOOT_DELAY); - log_esp3d("Boot delay modified %d", _totalduration); + _totalduration = ESP3DSettings::readUint32(ESP_BOOT_DELAY); + esp3d_log("Boot delay %d", _totalduration); + if (!ESP3DSettings::isValidIntegerSetting(_totalduration, ESP_BOOT_DELAY)) { + _totalduration = ESP3DSettings::getDefaultIntegerSetting(ESP_BOOT_DELAY); + esp3d_log("Boot delay modified %d", _totalduration); } _started = true; - ESP3DOutput::toScreen(ESP_OUTPUT_PROGRESS, "0"); +#if defined(DISPLAY_DEVICE) + ESP3DRequest reqId = { + .id = ESP_OUTPUT_PROGRESS, + }; + esp3d_commands.dispatch("0", ESP3DClientType::rendering, reqId, + ESP3DMessageType::unique); +#endif // + if (_totalduration > 0) { _startdelay = millis(); handle(); } - ESP3DOutput::toScreen(ESP_OUTPUT_PROGRESS, "100"); - log_esp3d("Boot delay done"); +#if defined(DISPLAY_DEVICE) + esp3d_commands.dispatch("100", ESP3DClientType::rendering, reqId, + ESP3DMessageType::unique); +#endif // DISPLAY_DEVICE + esp3d_log("Boot delay done"); return _started; } void BootDelay::end() {} @@ -59,6 +69,11 @@ void BootDelay::end() {} void BootDelay::handle() { uint8_t lastpercent = 0; uint32_t lastSent = millis(); +#if defined(DISPLAY_DEVICE) + ESP3DRequest reqId = { + .id = ESP_OUTPUT_PROGRESS, + }; +#endif // DISPLAY_DEVICE while ((millis() - _startdelay) < _totalduration) { #if defined(RECOVERY_FEATURE) recovery_service.handle(); @@ -69,9 +84,12 @@ void BootDelay::handle() { uint8_t p = (100 * (millis() - _startdelay)) / _totalduration; if (p != lastpercent) { lastpercent = p; - ESP3DOutput::toScreen(ESP_OUTPUT_PROGRESS, String(p).c_str()); +#if defined(DISPLAY_DEVICE) + esp3d_commands.dispatch(String(p).c_str(), ESP3DClientType::rendering, + reqId, ESP3DMessageType::unique); +#endif // DISPLAY_DEVICE } } - Hal::wait(10); + ESP3DHal::wait(10); } } diff --git a/esp3d/src/modules/buzzer/buzzer.cpp b/esp3d/src/modules/buzzer/buzzer.cpp index a5408882..1ead8682 100644 --- a/esp3d/src/modules/buzzer/buzzer.cpp +++ b/esp3d/src/modules/buzzer/buzzer.cpp @@ -21,153 +21,139 @@ #include "../../include/esp3d_config.h" #ifdef BUZZER_DEVICE -#include -#include "buzzer.h" -#include "../../core/settings_esp3d.h" #include +#include + +#include "../../core/esp3d_settings.h" +#include "buzzer.h" +// #include "esp32-hal-ledc.h" + BuzzerDevice esp3d_buzzer; Ticker buzzer_tick; -#define BEEP_DURATION 200 +#define BEEP_DURATION 200 - -void process() -{ - if (esp3d_buzzer.started()) { - tone_data * current = esp3d_buzzer.getNextTone(); - if (current) { - tone(ESP3D_BUZZER_PIN,(unsigned int)current->frequency, (unsigned long) current->duration); - buzzer_tick.once_ms(current->duration, process); - } +void process() { + if (esp3d_buzzer.started()) { + tone_data* current = esp3d_buzzer.getNextTone(); + if (current) { + tone(ESP3D_BUZZER_PIN, (unsigned int)current->frequency, + (unsigned long)current->duration); + buzzer_tick.once_ms(current->duration, process); } + } } -BuzzerDevice::BuzzerDevice() -{ - _head = nullptr; - _tail = nullptr; - _started = false; +BuzzerDevice::BuzzerDevice() { + _head = nullptr; + _tail = nullptr; + _started = false; } -bool BuzzerDevice::begin() -{ - if(_started) { - end(); - } - if (Settings_ESP3D::read_byte(ESP_BUZZER) == 1) { - _started = true; - playsound(5000, 240); - playsound(3000, 120); - } - return _started; -} -void BuzzerDevice::end() -{ - if(!_started) { - return; - } - purgeData(); - _started = false; - no_tone(); -} - - -void BuzzerDevice::handle() -{ - //Nothing to do as handled by ticker -} - -void BuzzerDevice::beep(int count, int delay, int frequency) -{ - if (_started) { - while (count > 0) { - playsound(frequency,BEEP_DURATION); - if (delay > 0 ) { - playsound(0,delay); - } - waitWhilePlaying(); - count--; - } - } -} - -void BuzzerDevice::no_tone() -{ - noTone(ESP3D_BUZZER_PIN); -} - -bool BuzzerDevice::isPlaying() -{ - return !(_head == nullptr); -} -void BuzzerDevice::waitWhilePlaying() -{ - while (_head != nullptr) { - delay(10); - } -} - -bool BuzzerDevice::addToneToList(int frequency, int duration) -{ - tone_data * tmp = (tone_data*)malloc(sizeof(tone_data)); - bool startprocess = false; - if (tmp) { - tmp->_next = nullptr; - tmp->frequency = frequency; - tmp->duration = duration; - tmp->processing = false; - if (_tail) { - _tail->_next=tmp; - } else { //no tail means also no head - _head = tmp; - startprocess = true;//no ongoing list, so lets start it - } - _tail = tmp; - if(startprocess) { - process(); - } - return true; - } - return false; -} - -tone_data * BuzzerDevice::getNextTone() -{ - if (_head) { - if (_head->processing == false) { - _head->processing = true; - } else { - tone_data * tmp = _head->_next; - free(_head); - _head = tmp; - if (!_head) { - _tail=_head; - no_tone(); - } - } - } - return _head; -} - -void BuzzerDevice::purgeData() -{ - while (_head) { - tone_data * tmp = _head->_next; - free(_head); - _head = tmp; - } - _tail = nullptr; -} - -BuzzerDevice::~BuzzerDevice() -{ +bool BuzzerDevice::begin() { + if (_started) { end(); + } +#if defined(ARDUINO_ARCH_ESP32) + setToneChannel(0); + ledcSetup(0, 12000, 8); +#endif // defined(ARDUINO_ARCH_ESP32) + if (ESP3DSettings::readByte(ESP_BUZZER) == 1) { + _started = true; + playsound(5000, 240); + playsound(3000, 120); + } + return _started; +} +void BuzzerDevice::end() { + if (!_started) { + return; + } + purgeData(); + _started = false; + no_tone(); } -void BuzzerDevice::playsound(int frequency, int duration) -{ - if (_started) { - addToneToList(frequency, duration); +void BuzzerDevice::handle() { + // Nothing to do as handled by ticker +} + +void BuzzerDevice::beep(int count, int delay, int frequency) { + if (_started) { + while (count > 0) { + playsound(frequency, BEEP_DURATION); + if (delay > 0) { + playsound(0, delay); + } + waitWhilePlaying(); + count--; } + } } -#endif //BUZZER_DEVICE +void BuzzerDevice::no_tone() { noTone(ESP3D_BUZZER_PIN); } + +bool BuzzerDevice::isPlaying() { return !(_head == nullptr); } +void BuzzerDevice::waitWhilePlaying() { + while (_head != nullptr) { + delay(10); + } +} + +bool BuzzerDevice::addToneToList(int frequency, int duration) { + tone_data* tmp = (tone_data*)malloc(sizeof(tone_data)); + bool startprocess = false; + if (tmp) { + tmp->_next = nullptr; + tmp->frequency = frequency; + tmp->duration = duration; + tmp->processing = false; + if (_tail) { + _tail->_next = tmp; + } else { // no tail means also no head + _head = tmp; + startprocess = true; // no ongoing list, so lets start it + } + _tail = tmp; + if (startprocess) { + process(); + } + return true; + } + return false; +} + +tone_data* BuzzerDevice::getNextTone() { + if (_head) { + if (_head->processing == false) { + _head->processing = true; + } else { + tone_data* tmp = _head->_next; + free(_head); + _head = tmp; + if (!_head) { + _tail = _head; + no_tone(); + } + } + } + return _head; +} + +void BuzzerDevice::purgeData() { + while (_head) { + tone_data* tmp = _head->_next; + free(_head); + _head = tmp; + } + _tail = nullptr; +} + +BuzzerDevice::~BuzzerDevice() { end(); } + +void BuzzerDevice::playsound(int frequency, int duration) { + if (_started) { + addToneToList(frequency, duration); + } +} + +#endif // BUZZER_DEVICE diff --git a/esp3d/src/modules/camera/camera.cpp b/esp3d/src/modules/camera/camera.cpp index edc3b674..91c461c9 100644 --- a/esp3d/src/modules/camera/camera.cpp +++ b/esp3d/src/modules/camera/camera.cpp @@ -26,7 +26,7 @@ #include //not sure this one is needed #include "../../core/esp3d.h" -#include "../../core/esp3doutput.h" +#include "../../core/esp3d_message.h" #include "../http/http_server.h" #include "camera.h" @@ -41,9 +41,9 @@ Camera esp3d_camera; bool Camera::handle_snap(WebServer *webserver, const char *path, const char *filename) { - log_esp3d("Camera stream reached"); + esp3d_log("Camera stream reached"); if (!_initialised) { - log_esp3d_e("Camera not started"); + esp3d_log_e("Camera not started"); if (webserver) { webserver->send(500, "text/plain", "Camera not started"); } @@ -82,10 +82,10 @@ bool Camera::handle_snap(WebServer *webserver, const char *path, HTTP_Server::set_http_headers(); webserver->send(200); } - log_esp3d("Camera capture ongoing"); + esp3d_log("Camera capture ongoing"); fb = esp_camera_fb_get(); if (!fb) { - log_esp3d_e("Camera capture failed"); + esp3d_log_e("Camera capture failed"); if (webserver) { webserver->send(500, "text/plain", "Capture failed"); } @@ -97,7 +97,7 @@ bool Camera::handle_snap(WebServer *webserver, const char *path, esp_camera_fb_return(fb); fb = NULL; if (!jpeg_converted) { - log_esp3d_e("JPEG compression failed"); + esp3d_log_e("JPEG compression failed"); res_error = true; } } else { @@ -113,11 +113,11 @@ bool Camera::handle_snap(WebServer *webserver, const char *path, if (filename != nullptr && path != nullptr) { if (!ESP_SD::accessFS()) { res_error = true; - log_esp3d_e("SD not available"); + esp3d_log_e("SD not available"); } else { if (ESP_SD::getState(true) == ESP_SDCARD_NOT_PRESENT) { res_error = true; - log_esp3d_e("No SD"); + esp3d_log_e("No SD"); } else { ESP_SD::setState(ESP_SDCARD_BUSY); String wpath = path[0] == '/' ? path : String("/") + path; @@ -133,10 +133,10 @@ bool Camera::handle_snap(WebServer *webserver, const char *path, if (f) { f.write((const uint8_t *)_jpg_buf, _jpg_buf_len); f.close(); - log_esp3d("Camera capture done"); + esp3d_log("Camera capture done"); } else { res_error = true; - log_esp3d_e("Failed to open file for writing"); + esp3d_log_e("Failed to open file for writing"); } } } @@ -145,7 +145,7 @@ bool Camera::handle_snap(WebServer *webserver, const char *path, } #endif // SD_DEVICE if (!webserver && filename == nullptr && path == nullptr) { - log_esp3d_e("No output defined"); + esp3d_log_e("No output defined"); res_error = true; } } @@ -172,7 +172,7 @@ Camera::Camera() { Camera::~Camera() { end(); } int Camera::command(const char *param, const char *value) { - log_esp3d("Camera: %s=%s\n", param, value); + esp3d_log("Camera: %s=%s\n", param, value); int res = 0; int val = atoi(value); sensor_t *s = esp_camera_sensor_get(); @@ -242,7 +242,7 @@ int Camera::command(const char *param, const char *value) { bool Camera::initHardware() { _initialised = false; - log_esp3d("Disable brown out"); + esp3d_log("Disable brown out"); WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); // disable brownout detector stopHardware(); camera_config_t config; @@ -273,10 +273,10 @@ bool Camera::initHardware() { config.grab_mode = CAMERA_GRAB_LATEST; if (!psramFound()) { _initialised = false; - log_esp3d_e("psram is not enabled"); + esp3d_log_e("psram is not enabled"); return false; } - log_esp3d("Init camera"); + esp3d_log("Init camera"); #if CAM_PULLUP1 != -1 pinMode(CAM_PULLUP1, INPUT_PULLUP); #endif // CAM_PULLUP1 @@ -291,7 +291,7 @@ bool Camera::initHardware() { // https://github.com/espressif/esp32-camera/issues/66#issuecomment-526283681 #if CAMERA_DEVICE == CAMERA_MODEL_AI_THINKER - log_esp3d("Specific config for CAMERA_MODEL_AI_THINKER"); + esp3d_log("Specific config for CAMERA_MODEL_AI_THINKER"); gpio_config_t gpio_pwr_config; gpio_pwr_config.pin_bit_mask = (1ULL << 32); gpio_pwr_config.mode = GPIO_MODE_OUTPUT; @@ -302,10 +302,10 @@ bool Camera::initHardware() { gpio_set_level(GPIO_NUM_32, 0); #endif // CAMERA_DEVICE == CAMERA_MODEL_AI_THINKER delay(500); - log_esp3d("Init camera config"); + esp3d_log("Init camera config"); esp_err_t err = esp_camera_init(&config); if (err != ESP_OK) { - log_esp3d_e("Camera init failed with error 0x%x", err); + esp3d_log_e("Camera init failed with error 0x%x", err); } else { _initialised = true; } @@ -317,12 +317,12 @@ bool Camera::stopHardware() { return true; } // need to be call by device and by network bool Camera::begin() { end(); - log_esp3d("Begin camera"); + esp3d_log("Begin camera"); if (!_initialised) { - log_esp3d("Init hardware not done"); + esp3d_log("Init hardware not done"); return false; } - log_esp3d("Init camera sensor settings"); + esp3d_log("Init camera sensor settings"); sensor_t *s = esp_camera_sensor_get(); if (s != nullptr) { // initial sensors are flipped vertically and colors are a bit saturated @@ -340,7 +340,7 @@ bool Camera::begin() { s->set_vflip(s, 1); #endif // CAMERA_DEVICE_FLIP_VERTICALY } else { - log_esp3d("Cannot access camera sensor"); + esp3d_log("Cannot access camera sensor"); } _started = _initialised; return _started; diff --git a/esp3d/src/modules/devices/devices_services.cpp b/esp3d/src/modules/devices/devices_services.cpp index 09d1a2e9..5be90349 100644 --- a/esp3d/src/modules/devices/devices_services.cpp +++ b/esp3d/src/modules/devices/devices_services.cpp @@ -20,8 +20,8 @@ #include "../../include/esp3d_config.h" #ifdef CONNECTED_DEVICES_FEATURE -#include "../../core/esp3doutput.h" -#include "../../core/settings_esp3d.h" +#include "../../core/esp3d_message.h" +#include "../../core/esp3d_settings.h" #include "devices_services.h" #ifdef DISPLAY_DEVICE @@ -50,37 +50,37 @@ bool DevicesServices::begin() { _started = false; #ifdef SD_DEVICE if (!ESP_SD::begin()) { - log_esp3d_e("Error sd intialization failed"); + esp3d_log_e("Error sd intialization failed"); res = false; } #endif // SD_DEVICE #ifdef DISPLAY_DEVICE if (!esp3d_display.begin()) { - log_esp3d_e("Error starting display device"); + esp3d_log_e("Error starting display device"); res = false; } #endif // DISPLAY_DEVICE #ifdef SENSOR_DEVICE if (!esp3d_sensor.begin()) { - log_esp3d_e("Error starting sensor device"); + esp3d_log_e("Error starting sensor device"); res = false; } #endif // SENSOR_DEVICE #ifdef BUZZER_DEVICE if (!esp3d_buzzer.begin()) { - log_esp3d_e("Error starting buzzer device"); + esp3d_log_e("Error starting buzzer device"); res = false; } #endif // BUZZER_DEVICE #ifdef RECOVERY_FEATURE if (!recovery_service.begin()) { - log_esp3d_e("Error starting recovery service"); + esp3d_log_e("Error starting recovery service"); res = false; } #endif // RECOVERY_FEATURE #ifdef CAMERA_DEVICE if (!esp3d_camera.initHardware()) { - log_esp3d_e("Error camera intialization failed"); + esp3d_log_e("Error camera intialization failed"); res = false; } #endif // CAMERA_DEVICE diff --git a/esp3d/src/modules/display/OLED_I2C_SSD1306_128X64/display.cpp b/esp3d/src/modules/display/OLED_I2C_SSD1306_128X64/display.cpp index 00c024fa..3220138a 100644 --- a/esp3d/src/modules/display/OLED_I2C_SSD1306_128X64/display.cpp +++ b/esp3d/src/modules/display/OLED_I2C_SSD1306_128X64/display.cpp @@ -19,76 +19,72 @@ */ #include "../../../include/esp3d_config.h" -#if defined (DISPLAY_DEVICE) && DISPLAY_DEVICE == OLED_I2C_SSD1306_128X64 +#if defined(DISPLAY_DEVICE) && DISPLAY_DEVICE == OLED_I2C_SSD1306_128X64 +#include + +#include "../../../core/esp3d_message.h" +#include "../../../core/esp3d_settings.h" #include "../display.h" -#include "../../../core/settings_esp3d.h" -#include "../../../core/esp3doutput.h" #include "Wire.h" #include "esp3d_logo.h" -#include #include "settings.h" -#if defined (WIFI_FEATURE) +#if defined(WIFI_FEATURE) #include "../../wifi/wificonfig.h" -#endif // WIFI_FEATURE -#if defined (ETH_FEATURE) +#endif // WIFI_FEATURE +#if defined(ETH_FEATURE) #include "../../ethernet/ethconfig.h" -#endif //ETH_FEATURE -#if defined (BLUETOOTH_FEATURE) +#endif // ETH_FEATURE +#if defined(BLUETOOTH_FEATURE) #include "../../bluetooth/BT_service.h" -#endif //BLUETOOTH_FEATURE -#if defined (WIFI_FEATURE) || defined (ETH_FEATURE) || defined (BLUETOOTH_FEATURE) +#endif // BLUETOOTH_FEATURE +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BLUETOOTH_FEATURE) #include "../../network/netconfig.h" -#endif //WIFI_FEATURE || ETH_FEATURE) ||BLUETOOTH_FEATURE +#endif // WIFI_FEATURE || ETH_FEATURE) ||BLUETOOTH_FEATURE #define DISPLAY_REFRESH_TIME 1000 -SSD1306Wire esp3d_screen(DISPLAY_I2C_ADDR, ESP_SDA_PIN, ESP_SCL_PIN); +SSD1306Wire esp3d_screen(DISPLAY_I2C_ADDR, ESP_SDA_PIN, ESP_SCL_PIN); Display esp3d_display; #if defined(DISPLAY_TOUCH_DRIVER) -bool Display::startCalibration() -{ +bool Display::startCalibration() { #error "DISPLAY_TOUCH_DRIVER not supported with OLED_I2C_SSD1306_128X64" } -#endif //DISPLAY_TOUCH_DRIVER +#endif // DISPLAY_TOUCH_DRIVER /** * The constructor for the Display class. */ -Display::Display() -{ - _started = false; - _screenID = SPLASH_SCREEN; - _splashDone=false; - _screenWidth = SCREEN_WIDTH; - _screenHeight = SCREEN_HEIGHT; +Display::Display() { + _started = false; + _screenID = SPLASH_SCREEN; + _splashDone = false; + _screenWidth = SCREEN_WIDTH; + _screenHeight = SCREEN_HEIGHT; } /** * The destructor for the Display class. */ -Display::~Display() -{ - end(); -} +Display::~Display() { end(); } /** - * If the display is started, set the status to blank, set the started flag to false, set the screen ID - * to the splash screen, set the splash displayed flag to false, and clear the screen + * If the display is started, set the status to blank, set the started flag to + * false, set the screen ID to the splash screen, set the splash displayed flag + * to false, and clear the screen * */ -void Display::end() -{ - if(!_started) { - return; - } - _status =""; - _started = false; - _screenID = SPLASH_SCREEN; - _splashDone=false; - clearScreen(); +void Display::end() { + if (!_started) { + return; + } + _status = ""; + _started = false; + _screenID = SPLASH_SCREEN; + _splashDone = false; + clearScreen(); } /** @@ -96,125 +92,108 @@ void Display::end() * * @return true if success. */ -bool Display::begin() -{ - bool res = true; - _started = false; - log_esp3d("Init Display"); +bool Display::begin() { + bool res = true; + _started = false; + esp3d_log("Init Display"); #if defined(DISPLAY_I2C_PIN_RST) - pinMode(DISPLAY_I2C_PIN_RST,OUTPUT); - digitalWrite(DISPLAY_I2C_PIN_RST, LOW); // turn the LED on (HIGH is the voltage level) - delay(10); // wait for a second - digitalWrite(DISPLAY_I2C_PIN_RST, HIGH); // turn the LED off by making the voltage LOW -#endif //DISPLAY_I2C_PIN_RST - esp3d_screen.init(); - esp3d_screen.clear(); - setTextFont(2); + pinMode(DISPLAY_I2C_PIN_RST, OUTPUT); + digitalWrite(DISPLAY_I2C_PIN_RST, + LOW); // turn the LED on (HIGH is the voltage level) + delay(10); // wait for a second + digitalWrite(DISPLAY_I2C_PIN_RST, + HIGH); // turn the LED off by making the voltage LOW +#endif // DISPLAY_I2C_PIN_RST + esp3d_screen.init(); + esp3d_screen.clear(); + setTextFont(2); #if defined(DISPLAY_FLIP_VERTICALY) - esp3d_screen.flipScreenVertically(); + esp3d_screen.flipScreenVertically(); #endif - showScreenID(SPLASH_SCREEN); - updateScreen(true); + showScreenID(SPLASH_SCREEN); + updateScreen(true); #if defined(DISPLAY_TOUCH_DRIVER) - if(Settings_ESP3D::read_byte(ESP_CALIBRATION)==1) { - uint16_t calibrationData[5]; - for (uint8_t i = 0; i < 5; i++) { - calibrationData[i] = Settings_ESP3D::read_uint32 (ESP_CALIBRATION_1+(4*i)); - } - esp3d_screen.setTouch(calibrationData); + if (ESP3DSettings::readByte(ESP_CALIBRATION) == 1) { + uint16_t calibrationData[5]; + for (uint8_t i = 0; i < 5; i++) { + calibrationData[i] = + ESP3DSettings::readUint32(ESP_CALIBRATION_1 + (4 * i)); } -#endif //DISPLAY_TOUCH_DRIVER - res = true; - if (!res) { - end(); - } - _started = res; - return _started; + esp3d_screen.setTouch(calibrationData); + } +#endif // DISPLAY_TOUCH_DRIVER + res = true; + if (!res) { + end(); + } + _started = res; + return _started; } -void Display::handle() -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - if (_started) { - updateScreen(); - } +void Display::handle() { + if (_started) { + updateScreen(); + } } -const char * Display::getModelString() -{ - return "OLED_I2C_SSD1306_128X64"; -} +const char *Display::getModelString() { return "OLED_I2C_SSD1306_128X64"; } -uint8_t Display::getModelID() -{ - return DISPLAY_DEVICE; -} +uint8_t Display::getModelID() { return DISPLAY_DEVICE; } /** * Display the screen with the given screenID * * @param screenID The screen ID to show. */ -void Display::showScreenID(uint8_t screenID) -{ - clearScreen(); - /* Calling the function updateScreen. */ - _screenID = screenID; +void Display::showScreenID(uint8_t screenID) { + clearScreen(); + /* Calling the function updateScreen. */ + _screenID = screenID; } /** - * The function takes a string as an argument and sets the value of the private member variable _status - * to the value of the argument + * The function takes a string as an argument and sets the value of the private + * member variable _status to the value of the argument * * @param status The status to set. */ -void Display::setStatus(const char * status) -{ - _status= status; -} +void Display::setStatus(const char *status) { _status = status; } /** - * The function clears the screen by calling the clear() function of the esp3d_screen object + * The function clears the screen by calling the clear() function of the + * esp3d_screen object */ -void Display::clearScreen() -{ - log_esp3d("clear screen"); - esp3d_screen.clear(); +void Display::clearScreen() { + esp3d_log("clear screen"); + esp3d_screen.clear(); } -void Display::updateScreen(bool force) -{ - log_esp3d("update screen"); - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - static uint32_t last_update = millis(); - bool need_update = force; - if (((millis()- last_update) > DISPLAY_REFRESH_TIME) ) { - last_update = millis(); - switch(_screenID) { - case SPLASH_SCREEN: - if (force) { - _splashDone=false; - } - need_update = splash(); - break; - case MAIN_SCREEN: - need_update = mainScreenHandler(force); - break; - default: - break; - } - if (need_update || force) { - esp3d_screen.display(); - Hal::wait(0); +void Display::updateScreen(bool force) { + esp3d_log("update screen"); + static uint32_t last_update = millis(); + bool need_update = force; + if (((millis() - last_update) > DISPLAY_REFRESH_TIME)) { + last_update = millis(); + switch (_screenID) { + case SPLASH_SCREEN: + if (force) { + _splashDone = false; } + need_update = splash(); + break; + case MAIN_SCREEN: + need_update = mainScreenHandler(force); + break; + default: + break; } + if (need_update || force) { + esp3d_screen.display(); + ESP3DHal::wait(0); + } + } } - /** * It returns the width of the string in pixels. * @@ -222,55 +201,49 @@ void Display::updateScreen(bool force) * * @return The width of the string in pixels. */ -uint16_t Display::getStringWidth(const char* text) -{ - return esp3d_screen.getStringWidth(text, strlen(text)); +uint16_t Display::getStringWidth(const char *text) { + return esp3d_screen.getStringWidth(text, strlen(text)); } /** - * It takes a string and a maximum width, and returns the number of characters that will fit in that - * width + * It takes a string and a maximum width, and returns the number of characters + * that will fit in that width * * @param string The string to be measured * @param maxwidth The maximum width of the string in pixels. * * @return The length of the string. */ -uint16_t Display::sizetoFitSpace(const char * string, uint16_t maxwidth) -{ - String s = string; - while (getStringWidth(s.c_str()) > maxwidth) { - if (s.length() > 0) { - s.remove(s.length()-1); - } else { - return 0; - } +uint16_t Display::sizetoFitSpace(const char *string, uint16_t maxwidth) { + String s = string; + while (getStringWidth(s.c_str()) > maxwidth) { + if (s.length() > 0) { + s.remove(s.length() - 1); + } else { + return 0; } - return s.length(); + } + return s.length(); } -void Display::setTextFont(uint8_t font) -{ - log_esp3d("setTextFont size %d", font); - switch(font) { +void Display::setTextFont(uint8_t font) { + esp3d_log("setTextFont size %d", font); + switch (font) { case 3: - esp3d_screen.setFont(ArialMT_Plain_16); - break; + esp3d_screen.setFont(ArialMT_Plain_16); + break; case 2: default: - esp3d_screen.setFont(ArialMT_Plain_10); - } + esp3d_screen.setFont(ArialMT_Plain_10); + } } -void Display::drawString(const char *string, int32_t poX, int32_t poY, int16_t color) -{ - log_esp3d("drawString %s at %d,%d", string, poX, poY); - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - esp3d_screen.setTextAlignment(TEXT_ALIGN_LEFT); - esp3d_screen.setColor((OLEDDISPLAY_COLOR)color); - esp3d_screen.drawString(poX, poY, string); +void Display::drawString(const char *string, int32_t poX, int32_t poY, + int16_t color) { + esp3d_log("drawString %s at %d,%d", string, poX, poY); + esp3d_screen.setTextAlignment(TEXT_ALIGN_LEFT); + esp3d_screen.setColor((OLEDDISPLAY_COLOR)color); + esp3d_screen.drawString(poX, poY, string); } /** @@ -284,16 +257,12 @@ void Display::drawString(const char *string, int32_t poX, int32_t poY, int16_t c * * @return Nothing. */ -void Display::drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t color) -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - esp3d_screen.setColor((OLEDDISPLAY_COLOR)color); - esp3d_screen.drawLine(x0, y0, x1, y1); +void Display::drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, + int16_t color) { + esp3d_screen.setColor((OLEDDISPLAY_COLOR)color); + esp3d_screen.drawLine(x0, y0, x1, y1); } - /** * > Draw a rectangle on the screen * @@ -305,13 +274,10 @@ void Display::drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t c * * @return Nothing. */ -void Display::drawRect(int16_t x, int16_t y, int16_t width, int16_t height, int16_t color) -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - esp3d_screen.setColor((OLEDDISPLAY_COLOR)color); - esp3d_screen.drawRect(x, y, width, height); +void Display::drawRect(int16_t x, int16_t y, int16_t width, int16_t height, + int16_t color) { + esp3d_screen.setColor((OLEDDISPLAY_COLOR)color); + esp3d_screen.drawRect(x, y, width, height); } /** @@ -325,13 +291,10 @@ void Display::drawRect(int16_t x, int16_t y, int16_t width, int16_t height, int1 * * @return Nothing. */ -void Display::fillRect(int16_t x, int16_t y, int16_t width, int16_t height, int16_t color) -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - esp3d_screen.setColor((OLEDDISPLAY_COLOR)color); - esp3d_screen.fillRect(x, y, width, height); +void Display::fillRect(int16_t x, int16_t y, int16_t width, int16_t height, + int16_t color) { + esp3d_screen.setColor((OLEDDISPLAY_COLOR)color); + esp3d_screen.fillRect(x, y, width, height); } /** @@ -346,13 +309,10 @@ void Display::fillRect(int16_t x, int16_t y, int16_t width, int16_t height, int1 * * @return Nothing. */ -void Display::drawXbm(int16_t x, int16_t y, int16_t width, int16_t height, int16_t color, const uint8_t *xbm) -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - (void)color; - esp3d_screen.drawXbm(x, y, width, height, xbm); +void Display::drawXbm(int16_t x, int16_t y, int16_t width, int16_t height, + int16_t color, const uint8_t *xbm) { + (void)color; + esp3d_screen.drawXbm(x, y, width, height, xbm); } /** @@ -367,417 +327,416 @@ void Display::drawXbm(int16_t x, int16_t y, int16_t width, int16_t height, int16 * @param xbm the xbm image data * */ -void Display::drawXbm(int16_t x, int16_t y, int16_t width, int16_t height, uint16_t fgcolor, uint16_t bgcolor, const uint8_t *xbm) -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - (void)fgcolor; - (void)bgcolor; - esp3d_screen.drawXbm(x, y, width, height, xbm); +void Display::drawXbm(int16_t x, int16_t y, int16_t width, int16_t height, + uint16_t fgcolor, uint16_t bgcolor, const uint8_t *xbm) { + (void)fgcolor; + (void)bgcolor; + esp3d_screen.drawXbm(x, y, width, height, xbm); } /** - * The function is called with a value between 0 and 100. The function draws a rectangle on the screen - * with a width that is proportional to the value + * The function is called with a value between 0 and 100. The function draws a + * rectangle on the screen with a width that is proportional to the value * * @param v The percentage of the progress bar to fill. * * @return the value of the variable v. */ -void Display::progress(uint8_t v) -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - static uint8_t previous = 0; - if (previous > v) { - //clear - fillRect(10, _screenHeight-2, _screenWidth-20, 2, SCREEN_BG); - } - log_esp3d("%d", v); - previous = v>100?100:v; - //display bar - drawRect(10, _screenHeight-2, ((_screenWidth-20) * v)/100, 2, PROGRESS_FG); - //update screen - updateScreen(true); +void Display::progress(uint8_t v) { + static uint8_t previous = 0; + if (previous > v) { + // clear + fillRect(10, _screenHeight - 2, _screenWidth - 20, 2, SCREEN_BG); + } + esp3d_log("%d", v); + previous = v > 100 ? 100 : v; + // display bar + drawRect(10, _screenHeight - 2, ((_screenWidth - 20) * v) / 100, 2, + PROGRESS_FG); + // update screen + updateScreen(true); } /** - * If the display is not busy, then check if the signal strength has changed, if so, then display it. - * If the IP address has changed, then display it. If the status has changed, then display it + * If the display is not busy, then check if the signal strength has changed, if + * so, then display it. If the IP address has changed, then display it. If the + * status has changed, then display it * - * @param force boolean, if true, the screen will be updated regardless of whether or not it needs to - * be. + * @param force boolean, if true, the screen will be updated regardless of + * whether or not it needs to be. * * @return A boolean value. */ -bool Display::mainScreenHandler(bool force) -{ - bool res = false; - if (displaySignal(force)) { - res = true; - } - if (displayIP(force)) { - res = true; - } - if (showStatus(force)) { - res = true; - } - return res; +bool Display::mainScreenHandler(bool force) { + bool res = false; + if (displaySignal(force)) { + res = true; + } + if (displayIP(force)) { + res = true; + } + if (showStatus(force)) { + res = true; + } + return res; } /** - * If the screen is connected, and the splash screen has not been displayed, then display the splash - * screen + * If the screen is connected, and the splash screen has not been displayed, + * then display the splash screen * * @return a boolean value. */ -bool Display::splash() -{ - log_esp3d("Splash"); - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return false; - } - if (!_splashDone) { - drawXbm((_screenWidth-ESP3D_Logo_width)/2, (_screenHeight-ESP3D_Logo_height)/2, ESP3D_Logo_width, ESP3D_Logo_height, SPLASH_FG, SPLASH_BG,ESP3D_Logo); - log_esp3d("Display Splash"); - _splashDone = true; - return true; - } - return false; +bool Display::splash() { + esp3d_log("Splash"); + + if (!_splashDone) { + drawXbm((_screenWidth - ESP3D_Logo_width) / 2, + (_screenHeight - ESP3D_Logo_height) / 2, ESP3D_Logo_width, + ESP3D_Logo_height, SPLASH_FG, SPLASH_BG, ESP3D_Logo); + esp3d_log("Display Splash"); + _splashDone = true; + return true; + } + return false; } -void Display::updateIP() -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - updateScreen(true); -} +void Display::updateIP() { updateScreen(true); } /** - * It takes a string, and if it's too long to fit in the status area, it chops it up into pieces and - * displays them one at a time + * It takes a string, and if it's too long to fit in the status area, it chops + * it up into pieces and displays them one at a time * - * @param force if true, the status will be redrawn regardless of whether it's changed or not. + * @param force if true, the status will be redrawn regardless of whether it's + * changed or not. * * @return a boolean value. */ -bool Display::showStatus(bool force) -{ - //Display Status - bool refresh_status = force; - static String status; - if (status != _status) { - status = _status; - refresh_status = true; - } +bool Display::showStatus(bool force) { + // Display Status + bool refresh_status = force; + static String status; + if (status != _status) { + status = _status; + refresh_status = true; + } - setTextFont(FONTSTATUS); - uint16_t size = sizetoFitSpace(status.c_str(), STATUS_AREA_W); - //check the need for resize + setTextFont(FONTSTATUS); + uint16_t size = sizetoFitSpace(status.c_str(), STATUS_AREA_W); + // check the need for resize + if (size < status.length()) { + static int status_shift = -1; + refresh_status = true; + status += " "; + esp3d_log("current %s", status.c_str()); + if (status_shift != -1) { + if ((uint16_t)(status_shift) > status.length()) { + status_shift = -1; + } + } + esp3d_log("shift %d", status_shift); + if (status_shift > 0) { + status.remove(0, status_shift); + } + esp3d_log("shifted %s", status.c_str()); + size = sizetoFitSpace(status.c_str(), STATUS_AREA_W); + esp3d_log("size available %d existing %d", size, status.length()); if (size < status.length()) { - static int status_shift = -1; - refresh_status = true; - status+=" "; - log_esp3d("current %s", status.c_str()); - if (status_shift != -1) { - if( (uint16_t)(status_shift)> status.length()) { - status_shift = -1; - } - } - log_esp3d("shift %d", status_shift); - if (status_shift > 0) { - status.remove(0,status_shift); - } - log_esp3d("shifted %s", status.c_str()); - size = sizetoFitSpace(status.c_str(), STATUS_AREA_W); - log_esp3d("size available %d existing %d",size, status.length()); - if (size < status.length()) { - //cut - status = status.substring(0,size); - status_shift++; - } else { - status_shift = -1; - } - log_esp3d("sized %s", status.c_str()); + // cut + status = status.substring(0, size); + status_shift++; + } else { + status_shift = -1; } - if (refresh_status) { - //clear area - fillRect(STATUS_AREA_X, STATUS_AREA_Y, STATUS_AREA_W, STATUS_AREA_H, SCREEN_BG); - drawString(status.c_str(), STATUS_AREA_X, STATUS_AREA_Y, STATUS_FG); - } - return refresh_status; + esp3d_log("sized %s", status.c_str()); + } + if (refresh_status) { + // clear area + fillRect(STATUS_AREA_X, STATUS_AREA_Y, STATUS_AREA_W, STATUS_AREA_H, + SCREEN_BG); + drawString(status.c_str(), STATUS_AREA_X, STATUS_AREA_Y, STATUS_FG); + } + return refresh_status; } -bool Display::displaySignal(bool force) -{ - static int sig = -1; - bool refresh_signal = false; - bool refresh_label = false; - static String label; -#if defined (WIFI_FEATURE) - if (WiFiConfig::started()) { - - if (WiFi.getMode() == WIFI_AP) { - if (sig != 100) { - sig = 100; - refresh_signal = true; - } - if (label != WiFiConfig::AP_SSID()) { - label = WiFiConfig::AP_SSID(); - refresh_label = true; - } - } else { - if (WiFi.isConnected()) { - int sigtmp = WiFiConfig::getSignal (WiFi.RSSI (),false); - if (sig != sigtmp) { - sig =sigtmp; - refresh_signal = true; - } - if (label != WiFi.SSID()) { - label = WiFi.SSID(); - refresh_label = true; - } - } else { - if (sig != -1) { - sig = -1; - refresh_signal = true; - } - if (label != "") { - label = ""; - refresh_label = true; - } - } - } - //Display SSID - setTextFont(FONTSSID); - uint16_t size = sizetoFitSpace(label.c_str(), SSID_AREA_W); - //check the need for resize - if (size < label.length()) { - refresh_label = true; - static int label_shift = -1; - label+=" "; - //log_esp3d("current %s", label.c_str()); - if (label_shift != -1) { - if((uint16_t)(label_shift)> label.length()) { - label_shift = -1; - } - } - //log_esp3d("shift %d", label_shift); - if (label_shift > 0) { - label.remove(0,label_shift); - } - //log_esp3d("shifted %s", label.c_str()); - size = sizetoFitSpace(label.c_str(), SSID_AREA_W); - //log_esp3d("size available %d existing %d",size, label.length()); - if (size < label.length()) { - //cut - label = label.substring(0,size); - label_shift++; - } else { - label_shift = -1; - } - //log_esp3d("sized %s", label.c_str()); - } - if (refresh_label || force) { - //clear area - fillRect(SSID_AREA_X, SSID_AREA_Y, SSID_AREA_W, SSID_AREA_H, SCREEN_BG); - drawString(label.c_str(), SSID_AREA_X, SSID_AREA_Y, SSID_FG); - } - } -#endif // WIFI_FEATURE - -#if defined (ETH_FEATURE) - if (EthConfig::started()) { - if (sig != -2) { - sig = -2; - refresh_signal = true; - } - //display connection speed - if(EthConfig::linkUp()) { - String tmp = ETH.linkSpeed(); - tmp+= "Mbps"; - if (label != tmp) { - label = tmp; - refresh_label = true; - } - } else { - if (label !="") { - label =""; - refresh_label = true; - } - } - if (refresh_label || force) { - setTextFont(FONTSSID); - //clear area - fillRect(SSID_AREA_X, SSID_AREA_Y, SSID_AREA_W, SSID_AREA_H, SCREEN_BG); - drawString(label.c_str(), SSID_AREA_X, SSID_AREA_Y, SSID_FG); - } - } -#endif //ETH_FEATURE - -#if defined (BLUETOOTH_FEATURE) - if (bt_service.started()) { - if (sig!=-3) { - sig = -3; - refresh_signal = true; - } - - //Display hostname - if (label != bt_service.hostname()) { - refresh_label = true; - label = bt_service.hostname(); - } - setTextFont(FONTSSID); - uint16_t size = sizetoFitSpace(label.c_str(), SSID_AREA_W); - //check the need for resize - if (size < label.length()) { - refresh_label = true; - static int label_shift = -1; - label+=" "; - //log_esp3d("current %s", hostname.c_str()); - if (label_shift > label.length()) { - label_shift = -1; - } - //log_esp3d("shift %d", label_shift); - if (label_shift > 0) { - label.remove(0,label_shift); - } - //log_esp3d("shifted %s", hostname.c_str()); - size = sizetoFitSpace(label.c_str(), SSID_AREA_W); - //log_esp3d("size available %d existing %d",size, hostname.length()); - if (size < label.length()) { - //cut - label = label.substring(0,size); - label_shift++; - } else { - label_shift = -1; - } - //log_esp3d("sized %s", hostname.c_str()); - } - if( refresh_label || force) { - //clear area - fillRect(SSID_AREA_X, SSID_AREA_Y, SSID_AREA_W, SSID_AREA_H, SCREEN_BG); - if (label.length()>0) { - drawString(label.c_str(), SSID_AREA_X, SSID_AREA_Y, SSID_FG); - } - } - } -#endif //BLUETOOTH_FEATURE - String s; - if (refresh_signal || force) { - - //set current font size - setTextFont(FONTSIGNAL); - fillRect(SIGNAL_X, SIGNAL_Y, SIGNAL_W, SIGNAL_H,SCREEN_BG); - fillRect(SIGNAL_ICON_X, SIGNAL_ICON_Y, SIGNAL_ICON_W, SIGNAL_ICON_H,SCREEN_BG); - if (sig > 0) { - //Signal % - s = String(sig); - s+="%"; - //Signal Icon according % - if (sig > 0) { - fillRect(SIGNAL_ICON_X, SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.6), SIGNAL_ICON_W_BAR, SIGNAL_ICON_H * 0.4, SIGNAL_FG); - } else { - drawRect(SIGNAL_ICON_X, SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.6), SIGNAL_ICON_W_BAR, SIGNAL_ICON_H * 0.4, SIGNAL_FG); - } - - if (sig >= 25) { - fillRect(SIGNAL_ICON_X + SIGNAL_ICON_SPACER_X +SIGNAL_ICON_W_BAR, SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.4), SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H * 0.6), SIGNAL_FG); - } else { - drawRect(SIGNAL_ICON_X + SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR, SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.4), SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H * 0.6), SIGNAL_FG); - } - - if (sig >= 50) { - fillRect(SIGNAL_ICON_X + (2*(SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.2), SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H * 0.8), SIGNAL_FG); - } else { - drawRect(SIGNAL_ICON_X + (2*(SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.2), SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H * 0.8), SIGNAL_FG); - } - - if (sig >= 75) { - fillRect(SIGNAL_ICON_X + (3*(SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), SIGNAL_ICON_Y, SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H), SIGNAL_FG); - } else { - drawRect(SIGNAL_ICON_X + (3*(SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), SIGNAL_ICON_Y, SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H), SIGNAL_FG); - } - - } - //No signal / no connection - if (sig == -1) { - s = " X"; - } - //Ethernet is connected - if (sig == -2) { - s = "Eth"; - } - //BT is active - if (sig == -3) { - s = "BT"; - } - //Show Connection type - drawString(s.c_str(), SIGNAL_X, SIGNAL_Y, SIGNAL_FG); - } - if (refresh_signal || refresh_label || force) { - return true; +bool Display::displaySignal(bool force) { + static int sig = -1; + bool refresh_signal = false; + bool refresh_label = false; + static String label; +#if defined(WIFI_FEATURE) + if (WiFiConfig::started()) { + if (WiFi.getMode() == WIFI_AP) { + if (sig != 100) { + sig = 100; + refresh_signal = true; + } + if (label != WiFiConfig::AP_SSID()) { + label = WiFiConfig::AP_SSID(); + refresh_label = true; + } } else { - return false; - } -} - -bool Display::displayIP(bool force) -{ - bool refresh_label = force; - static String label; -#if defined (WIFI_FEATURE) || defined (ETH_FEATURE) || defined (BLUETOOTH_FEATURE) - if (NetConfig::started()) { - String s; - switch(NetConfig::getMode()) { -#if defined (WIFI_FEATURE) - case ESP_WIFI_STA: - s = WiFi.localIP().toString(); - break; - case ESP_AP_SETUP: - case ESP_WIFI_AP: - s = WiFi.softAPIP().toString(); - break; -#endif //WIFI_FEATURE -#if defined (ETH_FEATURE) - case ESP_ETH_STA: - s = ETH.localIP().toString(); - break; -#endif //ETH_FEATURE -#if defined (BLUETOOTH_FEATURE) - case ESP_BT: - s = bt_service.isConnected()?"Connected":""; - break; -#endif //BLUETOOTH_FEATURE - default: - s=""; - log_esp3d("Unknown mode %d", NetConfig::getMode()); - break; + if (WiFi.isConnected()) { + int sigtmp = WiFiConfig::getSignal(WiFi.RSSI(), false); + if (sig != sigtmp) { + sig = sigtmp; + refresh_signal = true; } - if (s!= label) { - label = s; - refresh_label = true; + if (label != WiFi.SSID()) { + label = WiFi.SSID(); + refresh_label = true; } - if (refresh_label) { - if (label.length()>0) { - setTextFont(FONTIP); - fillRect(IP_AREA_X, IP_AREA_Y, IP_AREA_W, IP_AREA_H, SCREEN_BG); - drawString(label.c_str(), IP_AREA_X, IP_AREA_Y, IP_FG); - } - + } else { + if (sig != -1) { + sig = -1; + refresh_signal = true; } - } else { if (label != "") { - label = ""; - refresh_label = true; - fillRect(IP_AREA_X, IP_AREA_Y, IP_AREA_W, IP_AREA_H, SCREEN_BG); + label = ""; + refresh_label = true; } + } } -#endif //WIFI_FEATURE || ETH_FEATURE || BLUETOOTH_FEATURE - return refresh_label; + // Display SSID + setTextFont(FONTSSID); + uint16_t size = sizetoFitSpace(label.c_str(), SSID_AREA_W); + // check the need for resize + if (size < label.length()) { + refresh_label = true; + static int label_shift = -1; + label += " "; + // esp3d_log("current %s", label.c_str()); + if (label_shift != -1) { + if ((uint16_t)(label_shift) > label.length()) { + label_shift = -1; + } + } + // esp3d_log("shift %d", label_shift); + if (label_shift > 0) { + label.remove(0, label_shift); + } + // esp3d_log("shifted %s", label.c_str()); + size = sizetoFitSpace(label.c_str(), SSID_AREA_W); + // esp3d_log("size available %d existing %d",size, label.length()); + if (size < label.length()) { + // cut + label = label.substring(0, size); + label_shift++; + } else { + label_shift = -1; + } + // esp3d_log("sized %s", label.c_str()); + } + if (refresh_label || force) { + // clear area + fillRect(SSID_AREA_X, SSID_AREA_Y, SSID_AREA_W, SSID_AREA_H, SCREEN_BG); + drawString(label.c_str(), SSID_AREA_X, SSID_AREA_Y, SSID_FG); + } + } +#endif // WIFI_FEATURE + +#if defined(ETH_FEATURE) + if (EthConfig::started()) { + if (sig != -2) { + sig = -2; + refresh_signal = true; + } + // display connection speed + if (EthConfig::linkUp()) { + String tmp = String(ETH.linkSpeed()); + tmp += "Mbps"; + if (label != tmp) { + label = tmp; + refresh_label = true; + } + } else { + if (label != "") { + label = ""; + refresh_label = true; + } + } + if (refresh_label || force) { + setTextFont(FONTSSID); + // clear area + fillRect(SSID_AREA_X, SSID_AREA_Y, SSID_AREA_W, SSID_AREA_H, SCREEN_BG); + drawString(label.c_str(), SSID_AREA_X, SSID_AREA_Y, SSID_FG); + } + } +#endif // ETH_FEATURE + +#if defined(BLUETOOTH_FEATURE) + if (bt_service.started()) { + if (sig != -3) { + sig = -3; + refresh_signal = true; + } + + // Display hostname + if (label != bt_service.hostname()) { + refresh_label = true; + label = bt_service.hostname(); + } + setTextFont(FONTSSID); + uint16_t size = sizetoFitSpace(label.c_str(), SSID_AREA_W); + // check the need for resize + if (size < label.length()) { + refresh_label = true; + static int label_shift = -1; + label += " "; + // esp3d_log("current %s", hostname.c_str()); + if (label_shift > label.length()) { + label_shift = -1; + } + // esp3d_log("shift %d", label_shift); + if (label_shift > 0) { + label.remove(0, label_shift); + } + // esp3d_log("shifted %s", hostname.c_str()); + size = sizetoFitSpace(label.c_str(), SSID_AREA_W); + // esp3d_log("size available %d existing %d",size, hostname.length()); + if (size < label.length()) { + // cut + label = label.substring(0, size); + label_shift++; + } else { + label_shift = -1; + } + // esp3d_log("sized %s", hostname.c_str()); + } + if (refresh_label || force) { + // clear area + fillRect(SSID_AREA_X, SSID_AREA_Y, SSID_AREA_W, SSID_AREA_H, SCREEN_BG); + if (label.length() > 0) { + drawString(label.c_str(), SSID_AREA_X, SSID_AREA_Y, SSID_FG); + } + } + } +#endif // BLUETOOTH_FEATURE + String s; + if (refresh_signal || force) { + // set current font size + setTextFont(FONTSIGNAL); + fillRect(SIGNAL_X, SIGNAL_Y, SIGNAL_W, SIGNAL_H, SCREEN_BG); + fillRect(SIGNAL_ICON_X, SIGNAL_ICON_Y, SIGNAL_ICON_W, SIGNAL_ICON_H, + SCREEN_BG); + if (sig > 0) { + // Signal % + s = String(sig); + s += "%"; + // Signal Icon according % + if (sig > 0) { + fillRect(SIGNAL_ICON_X, SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.6), + SIGNAL_ICON_W_BAR, SIGNAL_ICON_H * 0.4, SIGNAL_FG); + } else { + drawRect(SIGNAL_ICON_X, SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.6), + SIGNAL_ICON_W_BAR, SIGNAL_ICON_H * 0.4, SIGNAL_FG); + } + + if (sig >= 25) { + fillRect(SIGNAL_ICON_X + SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR, + SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.4), SIGNAL_ICON_W_BAR, + (SIGNAL_ICON_H * 0.6), SIGNAL_FG); + } else { + drawRect(SIGNAL_ICON_X + SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR, + SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.4), SIGNAL_ICON_W_BAR, + (SIGNAL_ICON_H * 0.6), SIGNAL_FG); + } + + if (sig >= 50) { + fillRect( + SIGNAL_ICON_X + (2 * (SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), + SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.2), SIGNAL_ICON_W_BAR, + (SIGNAL_ICON_H * 0.8), SIGNAL_FG); + } else { + drawRect( + SIGNAL_ICON_X + (2 * (SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), + SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.2), SIGNAL_ICON_W_BAR, + (SIGNAL_ICON_H * 0.8), SIGNAL_FG); + } + + if (sig >= 75) { + fillRect( + SIGNAL_ICON_X + (3 * (SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), + SIGNAL_ICON_Y, SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H), SIGNAL_FG); + } else { + drawRect( + SIGNAL_ICON_X + (3 * (SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), + SIGNAL_ICON_Y, SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H), SIGNAL_FG); + } + } + // No signal / no connection + if (sig == -1) { + s = " X"; + } + // Ethernet is connected + if (sig == -2) { + s = "Eth"; + } + // BT is active + if (sig == -3) { + s = "BT"; + } + // Show Connection type + drawString(s.c_str(), SIGNAL_X, SIGNAL_Y, SIGNAL_FG); + } + if (refresh_signal || refresh_label || force) { + return true; + } else { + return false; + } } -#endif //DISPLAY_DEVICE && DISPLAY_DEVICE == OLED_I2C_SSD1306_128X64 +bool Display::displayIP(bool force) { + bool refresh_label = force; + static String label; +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BLUETOOTH_FEATURE) + if (NetConfig::started()) { + String s; + switch (NetConfig::getMode()) { +#if defined(WIFI_FEATURE) + case ESP_WIFI_STA: + s = WiFi.localIP().toString(); + break; + case ESP_AP_SETUP: + case ESP_WIFI_AP: + s = WiFi.softAPIP().toString(); + break; +#endif // WIFI_FEATURE +#if defined(ETH_FEATURE) + case ESP_ETH_STA: + s = ETH.localIP().toString(); + break; +#endif // ETH_FEATURE +#if defined(BLUETOOTH_FEATURE) + case ESP_BT: + s = bt_service.isConnected() ? "Connected" : ""; + break; +#endif // BLUETOOTH_FEATURE + default: + s = ""; + esp3d_log("Unknown mode %d", NetConfig::getMode()); + break; + } + if (s != label) { + label = s; + refresh_label = true; + } + if (refresh_label) { + if (label.length() > 0) { + setTextFont(FONTIP); + fillRect(IP_AREA_X, IP_AREA_Y, IP_AREA_W, IP_AREA_H, SCREEN_BG); + drawString(label.c_str(), IP_AREA_X, IP_AREA_Y, IP_FG); + } + } + } else { + if (label != "") { + label = ""; + refresh_label = true; + fillRect(IP_AREA_X, IP_AREA_Y, IP_AREA_W, IP_AREA_H, SCREEN_BG); + } + } +#endif // WIFI_FEATURE || ETH_FEATURE || BLUETOOTH_FEATURE + return refresh_label; +} + +#endif // DISPLAY_DEVICE && DISPLAY_DEVICE == OLED_I2C_SSD1306_128X64 diff --git a/esp3d/src/modules/display/OLED_I2C_SSDSH1106_132X64/display.cpp b/esp3d/src/modules/display/OLED_I2C_SSDSH1106_132X64/display.cpp index 3c7243cd..d0d094a2 100644 --- a/esp3d/src/modules/display/OLED_I2C_SSDSH1106_132X64/display.cpp +++ b/esp3d/src/modules/display/OLED_I2C_SSDSH1106_132X64/display.cpp @@ -19,76 +19,72 @@ */ #include "../../../include/esp3d_config.h" -#if defined (DISPLAY_DEVICE) && DISPLAY_DEVICE == OLED_I2C_SSDSH1106_132X64 +#if defined(DISPLAY_DEVICE) && DISPLAY_DEVICE == OLED_I2C_SSDSH1106_132X64 +#include + +#include "../../../core/esp3d_message.h" +#include "../../../core/esp3d_settings.h" #include "../display.h" -#include "../../../core/settings_esp3d.h" -#include "../../../core/esp3doutput.h" #include "Wire.h" #include "esp3d_logo.h" -#include #include "settings.h" -#if defined (WIFI_FEATURE) +#if defined(WIFI_FEATURE) #include "../../wifi/wificonfig.h" -#endif // WIFI_FEATURE -#if defined (ETH_FEATURE) +#endif // WIFI_FEATURE +#if defined(ETH_FEATURE) #include "../../ethernet/ethconfig.h" -#endif //ETH_FEATURE -#if defined (BLUETOOTH_FEATURE) +#endif // ETH_FEATURE +#if defined(BLUETOOTH_FEATURE) #include "../../bluetooth/BT_service.h" -#endif //BLUETOOTH_FEATURE -#if defined (WIFI_FEATURE) || defined (ETH_FEATURE) || defined (BLUETOOTH_FEATURE) +#endif // BLUETOOTH_FEATURE +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BLUETOOTH_FEATURE) #include "../../network/netconfig.h" -#endif //WIFI_FEATURE || ETH_FEATURE) ||BLUETOOTH_FEATURE +#endif // WIFI_FEATURE || ETH_FEATURE) ||BLUETOOTH_FEATURE #define DISPLAY_REFRESH_TIME 1000 -SH1106Wire esp3d_screen(DISPLAY_I2C_ADDR, ESP_SDA_PIN, ESP_SCL_PIN); +SH1106Wire esp3d_screen(DISPLAY_I2C_ADDR, ESP_SDA_PIN, ESP_SCL_PIN); Display esp3d_display; #if defined(DISPLAY_TOUCH_DRIVER) -bool Display::startCalibration() -{ +bool Display::startCalibration() { #error "DISPLAY_TOUCH_DRIVER not supported with OLED_I2C_SSD1306_128X64" } -#endif //DISPLAY_TOUCH_DRIVER +#endif // DISPLAY_TOUCH_DRIVER /** * The constructor for the Display class. */ -Display::Display() -{ - _started = false; - _screenID = SPLASH_SCREEN; - _splashDone=false; - _screenWidth = SCREEN_WIDTH; - _screenHeight = SCREEN_HEIGHT; +Display::Display() { + _started = false; + _screenID = SPLASH_SCREEN; + _splashDone = false; + _screenWidth = SCREEN_WIDTH; + _screenHeight = SCREEN_HEIGHT; } /** * The destructor for the Display class. */ -Display::~Display() -{ - end(); -} +Display::~Display() { end(); } /** - * If the display is started, set the status to blank, set the started flag to false, set the screen ID - * to the splash screen, set the splash displayed flag to false, and clear the screen + * If the display is started, set the status to blank, set the started flag to + * false, set the screen ID to the splash screen, set the splash displayed flag + * to false, and clear the screen * */ -void Display::end() -{ - if(!_started) { - return; - } - _status =""; - _started = false; - _screenID = SPLASH_SCREEN; - _splashDone=false; - clearScreen(); +void Display::end() { + if (!_started) { + return; + } + _status = ""; + _started = false; + _screenID = SPLASH_SCREEN; + _splashDone = false; + clearScreen(); } /** @@ -96,124 +92,108 @@ void Display::end() * * @return true if success. */ -bool Display::begin() -{ - bool res = true; - _started = false; - log_esp3d("Init Display"); +bool Display::begin() { + bool res = true; + _started = false; + esp3d_log("Init Display"); #if defined(DISPLAY_I2C_PIN_RST) - pinMode(DISPLAY_I2C_PIN_RST,OUTPUT); - digitalWrite(DISPLAY_I2C_PIN_RST, LOW); // turn the LED on (HIGH is the voltage level) - delay(10); // wait for a second - digitalWrite(DISPLAY_I2C_PIN_RST, HIGH); // turn the LED off by making the voltage LOW -#endif //DISPLAY_I2C_PIN_RST - esp3d_screen.init(); - esp3d_screen.clear(); - setTextFont(2); + pinMode(DISPLAY_I2C_PIN_RST, OUTPUT); + digitalWrite(DISPLAY_I2C_PIN_RST, + LOW); // turn the LED on (HIGH is the voltage level) + delay(10); // wait for a second + digitalWrite(DISPLAY_I2C_PIN_RST, + HIGH); // turn the LED off by making the voltage LOW +#endif // DISPLAY_I2C_PIN_RST + esp3d_screen.init(); + esp3d_screen.clear(); + setTextFont(2); #if defined(DISPLAY_FLIP_VERTICALY) - esp3d_screen.flipScreenVertically(); + esp3d_screen.flipScreenVertically(); #endif - showScreenID(SPLASH_SCREEN); - updateScreen(true); + showScreenID(SPLASH_SCREEN); + updateScreen(true); #if defined(DISPLAY_TOUCH_DRIVER) - if(Settings_ESP3D::read_byte(ESP_CALIBRATION)==1) { - uint16_t calibrationData[5]; - for (uint8_t i = 0; i < 5; i++) { - calibrationData[i] = Settings_ESP3D::read_uint32 (ESP_CALIBRATION_1+(4*i)); - } - esp3d_screen.setTouch(calibrationData); + if (ESP3DSettings::readByte(ESP_CALIBRATION) == 1) { + uint16_t calibrationData[5]; + for (uint8_t i = 0; i < 5; i++) { + calibrationData[i] = + ESP3DSettings::readUint32(ESP_CALIBRATION_1 + (4 * i)); } -#endif //DISPLAY_TOUCH_DRIVER - res = true; - if (!res) { - end(); - } - _started = res; - return _started; + esp3d_screen.setTouch(calibrationData); + } +#endif // DISPLAY_TOUCH_DRIVER + res = true; + if (!res) { + end(); + } + _started = res; + return _started; } -void Display::handle() -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - if (_started) { - updateScreen(); - } +void Display::handle() { + if (_started) { + updateScreen(); + } } -const char * Display::getModelString() -{ - return "OLED_I2C_SSD1306_128X64"; -} +const char *Display::getModelString() { return "OLED_I2C_SSD1306_128X64"; } -uint8_t Display::getModelID() -{ - return DISPLAY_DEVICE; -} +uint8_t Display::getModelID() { return DISPLAY_DEVICE; } /** * Display the screen with the given screenID * * @param screenID The screen ID to show. */ -void Display::showScreenID(uint8_t screenID) -{ - clearScreen(); - /* Calling the function updateScreen. */ - _screenID = screenID; +void Display::showScreenID(uint8_t screenID) { + clearScreen(); + /* Calling the function updateScreen. */ + _screenID = screenID; } /** - * The function takes a string as an argument and sets the value of the private member variable _status - * to the value of the argument + * The function takes a string as an argument and sets the value of the private + * member variable _status to the value of the argument * * @param status The status to set. */ -void Display::setStatus(const char * status) -{ - _status= status; -} +void Display::setStatus(const char *status) { _status = status; } /** - * The function clears the screen by calling the clear() function of the esp3d_screen object + * The function clears the screen by calling the clear() function of the + * esp3d_screen object */ -void Display::clearScreen() -{ - log_esp3d("clear screen"); - esp3d_screen.clear(); +void Display::clearScreen() { + esp3d_log("clear screen"); + esp3d_screen.clear(); } -void Display::updateScreen(bool force) -{ - log_esp3d("update screen"); - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - static uint32_t last_update = millis(); - bool need_update = force; - if (((millis()- last_update) > DISPLAY_REFRESH_TIME) ) { - last_update = millis(); - switch(_screenID) { - case SPLASH_SCREEN: - if (force) { - _splashDone=false; - } - need_update = splash(); - break; - case MAIN_SCREEN: - need_update = mainScreenHandler(force); - break; - default: - break; - } - if (need_update || force) { - esp3d_screen.display(); - Hal::wait(0); - } - } -} +void Display::updateScreen(bool force) { + esp3d_log("update screen"); + static uint32_t last_update = millis(); + bool need_update = force; + if (((millis() - last_update) > DISPLAY_REFRESH_TIME)) { + last_update = millis(); + switch (_screenID) { + case SPLASH_SCREEN: + if (force) { + _splashDone = false; + } + need_update = splash(); + break; + case MAIN_SCREEN: + need_update = mainScreenHandler(force); + break; + default: + break; + } + if (need_update || force) { + esp3d_screen.display(); + ESP3DHal::wait(0); + } + } +} /** * It returns the width of the string in pixels. @@ -222,55 +202,50 @@ void Display::updateScreen(bool force) * * @return The width of the string in pixels. */ -uint16_t Display::getStringWidth(const char* text) -{ - return esp3d_screen.getStringWidth(text, strlen(text)); +uint16_t Display::getStringWidth(const char *text) { + return esp3d_screen.getStringWidth(text, strlen(text)); } /** - * It takes a string and a maximum width, and returns the number of characters that will fit in that - * width + * It takes a string and a maximum width, and returns the number of characters + * that will fit in that width * * @param string The string to be measured * @param maxwidth The maximum width of the string in pixels. * * @return The length of the string. */ -uint16_t Display::sizetoFitSpace(const char * string, uint16_t maxwidth) -{ - String s = string; - while (getStringWidth(s.c_str()) > maxwidth) { - if (s.length() > 0) { - s.remove(s.length()-1); - } else { - return 0; - } +uint16_t Display::sizetoFitSpace(const char *string, uint16_t maxwidth) { + String s = string; + while (getStringWidth(s.c_str()) > maxwidth) { + if (s.length() > 0) { + s.remove(s.length() - 1); + } else { + return 0; } - return s.length(); + } + return s.length(); } -void Display::setTextFont(uint8_t font) -{ - log_esp3d("setTextFont size %d", font); - switch(font) { +void Display::setTextFont(uint8_t font) { + esp3d_log("setTextFont size %d", font); + switch (font) { case 3: - esp3d_screen.setFont(ArialMT_Plain_16); - break; + esp3d_screen.setFont(ArialMT_Plain_16); + break; case 2: default: - esp3d_screen.setFont(ArialMT_Plain_10); - } + esp3d_screen.setFont(ArialMT_Plain_10); + } } -void Display::drawString(const char *string, int32_t poX, int32_t poY, int16_t color) -{ - log_esp3d("drawString %s at %d,%d", string, poX, poY); - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - esp3d_screen.setTextAlignment(TEXT_ALIGN_LEFT); - esp3d_screen.setColor((OLEDDISPLAY_COLOR)color); - esp3d_screen.drawString(poX, poY, string); +void Display::drawString(const char *string, int32_t poX, int32_t poY, + int16_t color) { + esp3d_log("drawString %s at %d,%d", string, poX, poY); + + esp3d_screen.setTextAlignment(TEXT_ALIGN_LEFT); + esp3d_screen.setColor((OLEDDISPLAY_COLOR)color); + esp3d_screen.drawString(poX, poY, string); } /** @@ -284,16 +259,12 @@ void Display::drawString(const char *string, int32_t poX, int32_t poY, int16_t c * * @return Nothing. */ -void Display::drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t color) -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - esp3d_screen.setColor((OLEDDISPLAY_COLOR)color); - esp3d_screen.drawLine(x0, y0, x1, y1); +void Display::drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, + int16_t color) { + esp3d_screen.setColor((OLEDDISPLAY_COLOR)color); + esp3d_screen.drawLine(x0, y0, x1, y1); } - /** * > Draw a rectangle on the screen * @@ -305,13 +276,10 @@ void Display::drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t c * * @return Nothing. */ -void Display::drawRect(int16_t x, int16_t y, int16_t width, int16_t height, int16_t color) -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - esp3d_screen.setColor((OLEDDISPLAY_COLOR)color); - esp3d_screen.drawRect(x, y, width, height); +void Display::drawRect(int16_t x, int16_t y, int16_t width, int16_t height, + int16_t color) { + esp3d_screen.setColor((OLEDDISPLAY_COLOR)color); + esp3d_screen.drawRect(x, y, width, height); } /** @@ -325,13 +293,10 @@ void Display::drawRect(int16_t x, int16_t y, int16_t width, int16_t height, int1 * * @return Nothing. */ -void Display::fillRect(int16_t x, int16_t y, int16_t width, int16_t height, int16_t color) -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - esp3d_screen.setColor((OLEDDISPLAY_COLOR)color); - esp3d_screen.fillRect(x, y, width, height); +void Display::fillRect(int16_t x, int16_t y, int16_t width, int16_t height, + int16_t color) { + esp3d_screen.setColor((OLEDDISPLAY_COLOR)color); + esp3d_screen.fillRect(x, y, width, height); } /** @@ -346,13 +311,10 @@ void Display::fillRect(int16_t x, int16_t y, int16_t width, int16_t height, int1 * * @return Nothing. */ -void Display::drawXbm(int16_t x, int16_t y, int16_t width, int16_t height, int16_t color, const uint8_t *xbm) -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - (void)color; - esp3d_screen.drawXbm(x, y, width, height, xbm); +void Display::drawXbm(int16_t x, int16_t y, int16_t width, int16_t height, + int16_t color, const uint8_t *xbm) { + (void)color; + esp3d_screen.drawXbm(x, y, width, height, xbm); } /** @@ -367,417 +329,416 @@ void Display::drawXbm(int16_t x, int16_t y, int16_t width, int16_t height, int16 * @param xbm the xbm image data * */ -void Display::drawXbm(int16_t x, int16_t y, int16_t width, int16_t height, uint16_t fgcolor, uint16_t bgcolor, const uint8_t *xbm) -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - (void)fgcolor; - (void)bgcolor; - esp3d_screen.drawXbm(x, y, width, height, xbm); +void Display::drawXbm(int16_t x, int16_t y, int16_t width, int16_t height, + uint16_t fgcolor, uint16_t bgcolor, const uint8_t *xbm) { + (void)fgcolor; + (void)bgcolor; + esp3d_screen.drawXbm(x, y, width, height, xbm); } /** - * The function is called with a value between 0 and 100. The function draws a rectangle on the screen - * with a width that is proportional to the value + * The function is called with a value between 0 and 100. The function draws a + * rectangle on the screen with a width that is proportional to the value * * @param v The percentage of the progress bar to fill. * * @return the value of the variable v. */ -void Display::progress(uint8_t v) -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - static uint8_t previous = 0; - if (previous > v) { - //clear - fillRect(10, _screenHeight-2, _screenWidth-20, 2, SCREEN_BG); - } - log_esp3d("%d", v); - previous = v>100?100:v; - //display bar - drawRect(10, _screenHeight-2, ((_screenWidth-20) * v)/100, 2, PROGRESS_FG); - //update screen - updateScreen(true); +void Display::progress(uint8_t v) { + static uint8_t previous = 0; + if (previous > v) { + // clear + fillRect(10, _screenHeight - 2, _screenWidth - 20, 2, SCREEN_BG); + } + esp3d_log("%d", v); + previous = v > 100 ? 100 : v; + // display bar + drawRect(10, _screenHeight - 2, ((_screenWidth - 20) * v) / 100, 2, + PROGRESS_FG); + // update screen + updateScreen(true); } /** - * If the display is not busy, then check if the signal strength has changed, if so, then display it. - * If the IP address has changed, then display it. If the status has changed, then display it + * If the display is not busy, then check if the signal strength has changed, if + * so, then display it. If the IP address has changed, then display it. If the + * status has changed, then display it * - * @param force boolean, if true, the screen will be updated regardless of whether or not it needs to - * be. + * @param force boolean, if true, the screen will be updated regardless of + * whether or not it needs to be. * * @return A boolean value. */ -bool Display::mainScreenHandler(bool force) -{ - bool res = false; - if (displaySignal(force)) { - res = true; - } - if (displayIP(force)) { - res = true; - } - if (showStatus(force)) { - res = true; - } - return res; +bool Display::mainScreenHandler(bool force) { + bool res = false; + if (displaySignal(force)) { + res = true; + } + if (displayIP(force)) { + res = true; + } + if (showStatus(force)) { + res = true; + } + return res; } /** - * If the screen is connected, and the splash screen has not been displayed, then display the splash - * screen + * If the screen is connected, and the splash screen has not been displayed, + * then display the splash screen * * @return a boolean value. */ -bool Display::splash() -{ - log_esp3d("Splash"); - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return false; - } - if (!_splashDone) { - drawXbm((_screenWidth-ESP3D_Logo_width)/2, (_screenHeight-ESP3D_Logo_height)/2, ESP3D_Logo_width, ESP3D_Logo_height, SPLASH_FG, SPLASH_BG,ESP3D_Logo); - log_esp3d("Display Splash"); - _splashDone = true; - return true; - } - return false; +bool Display::splash() { + esp3d_log("Splash"); + + if (!_splashDone) { + drawXbm((_screenWidth - ESP3D_Logo_width) / 2, + (_screenHeight - ESP3D_Logo_height) / 2, ESP3D_Logo_width, + ESP3D_Logo_height, SPLASH_FG, SPLASH_BG, ESP3D_Logo); + esp3d_log("Display Splash"); + _splashDone = true; + return true; + } + return false; } -void Display::updateIP() -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - updateScreen(true); -} +void Display::updateIP() { updateScreen(true); } /** - * It takes a string, and if it's too long to fit in the status area, it chops it up into pieces and - * displays them one at a time + * It takes a string, and if it's too long to fit in the status area, it chops + * it up into pieces and displays them one at a time * - * @param force if true, the status will be redrawn regardless of whether it's changed or not. + * @param force if true, the status will be redrawn regardless of whether it's + * changed or not. * * @return a boolean value. */ -bool Display::showStatus(bool force) -{ - //Display Status - bool refresh_status = force; - static String status; - if (status != _status) { - status = _status; - refresh_status = true; - } +bool Display::showStatus(bool force) { + // Display Status + bool refresh_status = force; + static String status; + if (status != _status) { + status = _status; + refresh_status = true; + } - setTextFont(FONTSTATUS); - uint16_t size = sizetoFitSpace(status.c_str(), STATUS_AREA_W); - //check the need for resize + setTextFont(FONTSTATUS); + uint16_t size = sizetoFitSpace(status.c_str(), STATUS_AREA_W); + // check the need for resize + if (size < status.length()) { + static int status_shift = -1; + refresh_status = true; + status += " "; + esp3d_log("current %s", status.c_str()); + if (status_shift != -1) { + if ((uint16_t)(status_shift) > status.length()) { + status_shift = -1; + } + } + esp3d_log("shift %d", status_shift); + if (status_shift > 0) { + status.remove(0, status_shift); + } + esp3d_log("shifted %s", status.c_str()); + size = sizetoFitSpace(status.c_str(), STATUS_AREA_W); + esp3d_log("size available %d existing %d", size, status.length()); if (size < status.length()) { - static int status_shift = -1; - refresh_status = true; - status+=" "; - log_esp3d("current %s", status.c_str()); - if (status_shift != -1) { - if( (uint16_t)(status_shift)> status.length()) { - status_shift = -1; - } - } - log_esp3d("shift %d", status_shift); - if (status_shift > 0) { - status.remove(0,status_shift); - } - log_esp3d("shifted %s", status.c_str()); - size = sizetoFitSpace(status.c_str(), STATUS_AREA_W); - log_esp3d("size available %d existing %d",size, status.length()); - if (size < status.length()) { - //cut - status = status.substring(0,size); - status_shift++; - } else { - status_shift = -1; - } - log_esp3d("sized %s", status.c_str()); + // cut + status = status.substring(0, size); + status_shift++; + } else { + status_shift = -1; } - if (refresh_status) { - //clear area - fillRect(STATUS_AREA_X, STATUS_AREA_Y, STATUS_AREA_W, STATUS_AREA_H, SCREEN_BG); - drawString(status.c_str(), STATUS_AREA_X, STATUS_AREA_Y, STATUS_FG); - } - return refresh_status; + esp3d_log("sized %s", status.c_str()); + } + if (refresh_status) { + // clear area + fillRect(STATUS_AREA_X, STATUS_AREA_Y, STATUS_AREA_W, STATUS_AREA_H, + SCREEN_BG); + drawString(status.c_str(), STATUS_AREA_X, STATUS_AREA_Y, STATUS_FG); + } + return refresh_status; } -bool Display::displaySignal(bool force) -{ - static int sig = -1; - bool refresh_signal = false; - bool refresh_label = false; - static String label; -#if defined (WIFI_FEATURE) - if (WiFiConfig::started()) { - - if (WiFi.getMode() == WIFI_AP) { - if (sig != 100) { - sig = 100; - refresh_signal = true; - } - if (label != WiFiConfig::AP_SSID()) { - label = WiFiConfig::AP_SSID(); - refresh_label = true; - } - } else { - if (WiFi.isConnected()) { - int sigtmp = WiFiConfig::getSignal (WiFi.RSSI (),false); - if (sig != sigtmp) { - sig =sigtmp; - refresh_signal = true; - } - if (label != WiFi.SSID()) { - label = WiFi.SSID(); - refresh_label = true; - } - } else { - if (sig != -1) { - sig = -1; - refresh_signal = true; - } - if (label != "") { - label = ""; - refresh_label = true; - } - } - } - //Display SSID - setTextFont(FONTSSID); - uint16_t size = sizetoFitSpace(label.c_str(), SSID_AREA_W); - //check the need for resize - if (size < label.length()) { - refresh_label = true; - static int label_shift = -1; - label+=" "; - //log_esp3d("current %s", label.c_str()); - if (label_shift != -1) { - if((uint16_t)(label_shift)> label.length()) { - label_shift = -1; - } - } - //log_esp3d("shift %d", label_shift); - if (label_shift > 0) { - label.remove(0,label_shift); - } - //log_esp3d("shifted %s", label.c_str()); - size = sizetoFitSpace(label.c_str(), SSID_AREA_W); - //log_esp3d("size available %d existing %d",size, label.length()); - if (size < label.length()) { - //cut - label = label.substring(0,size); - label_shift++; - } else { - label_shift = -1; - } - //log_esp3d("sized %s", label.c_str()); - } - if (refresh_label || force) { - //clear area - fillRect(SSID_AREA_X, SSID_AREA_Y, SSID_AREA_W, SSID_AREA_H, SCREEN_BG); - drawString(label.c_str(), SSID_AREA_X, SSID_AREA_Y, SSID_FG); - } - } -#endif // WIFI_FEATURE - -#if defined (ETH_FEATURE) - if (EthConfig::started()) { - if (sig != -2) { - sig = -2; - refresh_signal = true; - } - //display connection speed - if(EthConfig::linkUp()) { - String tmp = ETH.linkSpeed(); - tmp+= "Mbps"; - if (label != tmp) { - label = tmp; - refresh_label = true; - } - } else { - if (label !="") { - label =""; - refresh_label = true; - } - } - if (refresh_label || force) { - setTextFont(FONTSSID); - //clear area - fillRect(SSID_AREA_X, SSID_AREA_Y, SSID_AREA_W, SSID_AREA_H, SCREEN_BG); - drawString(label.c_str(), SSID_AREA_X, SSID_AREA_Y, SSID_FG); - } - } -#endif //ETH_FEATURE - -#if defined (BLUETOOTH_FEATURE) - if (bt_service.started()) { - if (sig!=-3) { - sig = -3; - refresh_signal = true; - } - - //Display hostname - if (label != bt_service.hostname()) { - refresh_label = true; - label = bt_service.hostname(); - } - setTextFont(FONTSSID); - uint16_t size = sizetoFitSpace(label.c_str(), SSID_AREA_W); - //check the need for resize - if (size < label.length()) { - refresh_label = true; - static int label_shift = -1; - label+=" "; - //log_esp3d("current %s", hostname.c_str()); - if (label_shift > label.length()) { - label_shift = -1; - } - //log_esp3d("shift %d", label_shift); - if (label_shift > 0) { - label.remove(0,label_shift); - } - //log_esp3d("shifted %s", hostname.c_str()); - size = sizetoFitSpace(label.c_str(), SSID_AREA_W); - //log_esp3d("size available %d existing %d",size, hostname.length()); - if (size < label.length()) { - //cut - label = label.substring(0,size); - label_shift++; - } else { - label_shift = -1; - } - //log_esp3d("sized %s", hostname.c_str()); - } - if( refresh_label || force) { - //clear area - fillRect(SSID_AREA_X, SSID_AREA_Y, SSID_AREA_W, SSID_AREA_H, SCREEN_BG); - if (label.length()>0) { - drawString(label.c_str(), SSID_AREA_X, SSID_AREA_Y, SSID_FG); - } - } - } -#endif //BLUETOOTH_FEATURE - String s; - if (refresh_signal || force) { - - //set current font size - setTextFont(FONTSIGNAL); - fillRect(SIGNAL_X, SIGNAL_Y, SIGNAL_W, SIGNAL_H,SCREEN_BG); - fillRect(SIGNAL_ICON_X, SIGNAL_ICON_Y, SIGNAL_ICON_W, SIGNAL_ICON_H,SCREEN_BG); - if (sig > 0) { - //Signal % - s = String(sig); - s+="%"; - //Signal Icon according % - if (sig > 0) { - fillRect(SIGNAL_ICON_X, SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.6), SIGNAL_ICON_W_BAR, SIGNAL_ICON_H * 0.4, SIGNAL_FG); - } else { - drawRect(SIGNAL_ICON_X, SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.6), SIGNAL_ICON_W_BAR, SIGNAL_ICON_H * 0.4, SIGNAL_FG); - } - - if (sig >= 25) { - fillRect(SIGNAL_ICON_X + SIGNAL_ICON_SPACER_X +SIGNAL_ICON_W_BAR, SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.4), SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H * 0.6), SIGNAL_FG); - } else { - drawRect(SIGNAL_ICON_X + SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR, SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.4), SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H * 0.6), SIGNAL_FG); - } - - if (sig >= 50) { - fillRect(SIGNAL_ICON_X + (2*(SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.2), SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H * 0.8), SIGNAL_FG); - } else { - drawRect(SIGNAL_ICON_X + (2*(SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.2), SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H * 0.8), SIGNAL_FG); - } - - if (sig >= 75) { - fillRect(SIGNAL_ICON_X + (3*(SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), SIGNAL_ICON_Y, SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H), SIGNAL_FG); - } else { - drawRect(SIGNAL_ICON_X + (3*(SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), SIGNAL_ICON_Y, SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H), SIGNAL_FG); - } - - } - //No signal / no connection - if (sig == -1) { - s = " X"; - } - //Ethernet is connected - if (sig == -2) { - s = "Eth"; - } - //BT is active - if (sig == -3) { - s = "BT"; - } - //Show Connection type - drawString(s.c_str(), SIGNAL_X, SIGNAL_Y, SIGNAL_FG); - } - if (refresh_signal || refresh_label || force) { - return true; +bool Display::displaySignal(bool force) { + static int sig = -1; + bool refresh_signal = false; + bool refresh_label = false; + static String label; +#if defined(WIFI_FEATURE) + if (WiFiConfig::started()) { + if (WiFi.getMode() == WIFI_AP) { + if (sig != 100) { + sig = 100; + refresh_signal = true; + } + if (label != WiFiConfig::AP_SSID()) { + label = WiFiConfig::AP_SSID(); + refresh_label = true; + } } else { - return false; - } -} - -bool Display::displayIP(bool force) -{ - bool refresh_label = force; - static String label; -#if defined (WIFI_FEATURE) || defined (ETH_FEATURE) || defined (BLUETOOTH_FEATURE) - if (NetConfig::started()) { - String s; - switch(NetConfig::getMode()) { -#if defined (WIFI_FEATURE) - case ESP_WIFI_STA: - s = WiFi.localIP().toString(); - break; - case ESP_AP_SETUP: - case ESP_WIFI_AP: - s = WiFi.softAPIP().toString(); - break; -#endif //WIFI_FEATURE -#if defined (ETH_FEATURE) - case ESP_ETH_STA: - s = ETH.localIP().toString(); - break; -#endif //ETH_FEATURE -#if defined (BLUETOOTH_FEATURE) - case ESP_BT: - s = bt_service.isConnected()?"Connected":""; - break; -#endif //BLUETOOTH_FEATURE - default: - s=""; - log_esp3d("Unknown mode %d", NetConfig::getMode()); - break; + if (WiFi.isConnected()) { + int sigtmp = WiFiConfig::getSignal(WiFi.RSSI(), false); + if (sig != sigtmp) { + sig = sigtmp; + refresh_signal = true; } - if (s!= label) { - label = s; - refresh_label = true; + if (label != WiFi.SSID()) { + label = WiFi.SSID(); + refresh_label = true; } - if (refresh_label) { - if (label.length()>0) { - setTextFont(FONTIP); - fillRect(IP_AREA_X, IP_AREA_Y, IP_AREA_W, IP_AREA_H, SCREEN_BG); - drawString(label.c_str(), IP_AREA_X, IP_AREA_Y, IP_FG); - } - + } else { + if (sig != -1) { + sig = -1; + refresh_signal = true; } - } else { if (label != "") { - label = ""; - refresh_label = true; - fillRect(IP_AREA_X, IP_AREA_Y, IP_AREA_W, IP_AREA_H, SCREEN_BG); + label = ""; + refresh_label = true; } + } } -#endif //WIFI_FEATURE || ETH_FEATURE || BLUETOOTH_FEATURE - return refresh_label; + // Display SSID + setTextFont(FONTSSID); + uint16_t size = sizetoFitSpace(label.c_str(), SSID_AREA_W); + // check the need for resize + if (size < label.length()) { + refresh_label = true; + static int label_shift = -1; + label += " "; + // esp3d_log("current %s", label.c_str()); + if (label_shift != -1) { + if ((uint16_t)(label_shift) > label.length()) { + label_shift = -1; + } + } + // esp3d_log("shift %d", label_shift); + if (label_shift > 0) { + label.remove(0, label_shift); + } + // esp3d_log("shifted %s", label.c_str()); + size = sizetoFitSpace(label.c_str(), SSID_AREA_W); + // esp3d_log("size available %d existing %d",size, label.length()); + if (size < label.length()) { + // cut + label = label.substring(0, size); + label_shift++; + } else { + label_shift = -1; + } + // esp3d_log("sized %s", label.c_str()); + } + if (refresh_label || force) { + // clear area + fillRect(SSID_AREA_X, SSID_AREA_Y, SSID_AREA_W, SSID_AREA_H, SCREEN_BG); + drawString(label.c_str(), SSID_AREA_X, SSID_AREA_Y, SSID_FG); + } + } +#endif // WIFI_FEATURE + +#if defined(ETH_FEATURE) + if (EthConfig::started()) { + if (sig != -2) { + sig = -2; + refresh_signal = true; + } + // display connection speed + if (EthConfig::linkUp()) { + String tmp = ETH.linkSpeed(); + tmp += "Mbps"; + if (label != tmp) { + label = tmp; + refresh_label = true; + } + } else { + if (label != "") { + label = ""; + refresh_label = true; + } + } + if (refresh_label || force) { + setTextFont(FONTSSID); + // clear area + fillRect(SSID_AREA_X, SSID_AREA_Y, SSID_AREA_W, SSID_AREA_H, SCREEN_BG); + drawString(label.c_str(), SSID_AREA_X, SSID_AREA_Y, SSID_FG); + } + } +#endif // ETH_FEATURE + +#if defined(BLUETOOTH_FEATURE) + if (bt_service.started()) { + if (sig != -3) { + sig = -3; + refresh_signal = true; + } + + // Display hostname + if (label != bt_service.hostname()) { + refresh_label = true; + label = bt_service.hostname(); + } + setTextFont(FONTSSID); + uint16_t size = sizetoFitSpace(label.c_str(), SSID_AREA_W); + // check the need for resize + if (size < label.length()) { + refresh_label = true; + static int label_shift = -1; + label += " "; + // esp3d_log("current %s", hostname.c_str()); + if (label_shift > label.length()) { + label_shift = -1; + } + // esp3d_log("shift %d", label_shift); + if (label_shift > 0) { + label.remove(0, label_shift); + } + // esp3d_log("shifted %s", hostname.c_str()); + size = sizetoFitSpace(label.c_str(), SSID_AREA_W); + // esp3d_log("size available %d existing %d",size, hostname.length()); + if (size < label.length()) { + // cut + label = label.substring(0, size); + label_shift++; + } else { + label_shift = -1; + } + // esp3d_log("sized %s", hostname.c_str()); + } + if (refresh_label || force) { + // clear area + fillRect(SSID_AREA_X, SSID_AREA_Y, SSID_AREA_W, SSID_AREA_H, SCREEN_BG); + if (label.length() > 0) { + drawString(label.c_str(), SSID_AREA_X, SSID_AREA_Y, SSID_FG); + } + } + } +#endif // BLUETOOTH_FEATURE + String s; + if (refresh_signal || force) { + // set current font size + setTextFont(FONTSIGNAL); + fillRect(SIGNAL_X, SIGNAL_Y, SIGNAL_W, SIGNAL_H, SCREEN_BG); + fillRect(SIGNAL_ICON_X, SIGNAL_ICON_Y, SIGNAL_ICON_W, SIGNAL_ICON_H, + SCREEN_BG); + if (sig > 0) { + // Signal % + s = String(sig); + s += "%"; + // Signal Icon according % + if (sig > 0) { + fillRect(SIGNAL_ICON_X, SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.6), + SIGNAL_ICON_W_BAR, SIGNAL_ICON_H * 0.4, SIGNAL_FG); + } else { + drawRect(SIGNAL_ICON_X, SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.6), + SIGNAL_ICON_W_BAR, SIGNAL_ICON_H * 0.4, SIGNAL_FG); + } + + if (sig >= 25) { + fillRect(SIGNAL_ICON_X + SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR, + SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.4), SIGNAL_ICON_W_BAR, + (SIGNAL_ICON_H * 0.6), SIGNAL_FG); + } else { + drawRect(SIGNAL_ICON_X + SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR, + SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.4), SIGNAL_ICON_W_BAR, + (SIGNAL_ICON_H * 0.6), SIGNAL_FG); + } + + if (sig >= 50) { + fillRect( + SIGNAL_ICON_X + (2 * (SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), + SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.2), SIGNAL_ICON_W_BAR, + (SIGNAL_ICON_H * 0.8), SIGNAL_FG); + } else { + drawRect( + SIGNAL_ICON_X + (2 * (SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), + SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.2), SIGNAL_ICON_W_BAR, + (SIGNAL_ICON_H * 0.8), SIGNAL_FG); + } + + if (sig >= 75) { + fillRect( + SIGNAL_ICON_X + (3 * (SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), + SIGNAL_ICON_Y, SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H), SIGNAL_FG); + } else { + drawRect( + SIGNAL_ICON_X + (3 * (SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), + SIGNAL_ICON_Y, SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H), SIGNAL_FG); + } + } + // No signal / no connection + if (sig == -1) { + s = " X"; + } + // Ethernet is connected + if (sig == -2) { + s = "Eth"; + } + // BT is active + if (sig == -3) { + s = "BT"; + } + // Show Connection type + drawString(s.c_str(), SIGNAL_X, SIGNAL_Y, SIGNAL_FG); + } + if (refresh_signal || refresh_label || force) { + return true; + } else { + return false; + } } -#endif //DISPLAY_DEVICE && DISPLAY_DEVICE == OLED_I2C_SSD1306_128X64 +bool Display::displayIP(bool force) { + bool refresh_label = force; + static String label; +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BLUETOOTH_FEATURE) + if (NetConfig::started()) { + String s; + switch (NetConfig::getMode()) { +#if defined(WIFI_FEATURE) + case ESP_WIFI_STA: + s = WiFi.localIP().toString(); + break; + case ESP_AP_SETUP: + case ESP_WIFI_AP: + s = WiFi.softAPIP().toString(); + break; +#endif // WIFI_FEATURE +#if defined(ETH_FEATURE) + case ESP_ETH_STA: + s = ETH.localIP().toString(); + break; +#endif // ETH_FEATURE +#if defined(BLUETOOTH_FEATURE) + case ESP_BT: + s = bt_service.isConnected() ? "Connected" : ""; + break; +#endif // BLUETOOTH_FEATURE + default: + s = ""; + esp3d_log("Unknown mode %d", NetConfig::getMode()); + break; + } + if (s != label) { + label = s; + refresh_label = true; + } + if (refresh_label) { + if (label.length() > 0) { + setTextFont(FONTIP); + fillRect(IP_AREA_X, IP_AREA_Y, IP_AREA_W, IP_AREA_H, SCREEN_BG); + drawString(label.c_str(), IP_AREA_X, IP_AREA_Y, IP_FG); + } + } + } else { + if (label != "") { + label = ""; + refresh_label = true; + fillRect(IP_AREA_X, IP_AREA_Y, IP_AREA_W, IP_AREA_H, SCREEN_BG); + } + } +#endif // WIFI_FEATURE || ETH_FEATURE || BLUETOOTH_FEATURE + return refresh_label; +} + +#endif // DISPLAY_DEVICE && DISPLAY_DEVICE == OLED_I2C_SSD1306_128X64 diff --git a/esp3d/src/modules/display/TFT_SPI_ST7789_135X240/display.cpp b/esp3d/src/modules/display/TFT_SPI_ST7789_135X240/display.cpp index a6dfbc30..467e3783 100644 --- a/esp3d/src/modules/display/TFT_SPI_ST7789_135X240/display.cpp +++ b/esp3d/src/modules/display/TFT_SPI_ST7789_135X240/display.cpp @@ -19,75 +19,71 @@ */ #include "../../../include/esp3d_config.h" -#if defined (DISPLAY_DEVICE) && DISPLAY_DEVICE == TFT_SPI_ST7789_135X240 +#if defined(DISPLAY_DEVICE) && DISPLAY_DEVICE == TFT_SPI_ST7789_135X240 +#include + +#include "../../../core/esp3d_message.h" +#include "../../../core/esp3d_settings.h" #include "../display.h" -#include "../../../core/settings_esp3d.h" -#include "../../../core/esp3doutput.h" #include "Wire.h" #include "esp3d_logo.h" -#include #include "settings.h" -#if defined (WIFI_FEATURE) +#if defined(WIFI_FEATURE) #include "../../wifi/wificonfig.h" -#endif // WIFI_FEATURE -#if defined (ETH_FEATURE) +#endif // WIFI_FEATURE +#if defined(ETH_FEATURE) #include "../../ethernet/ethconfig.h" -#endif //ETH_FEATURE -#if defined (BLUETOOTH_FEATURE) +#endif // ETH_FEATURE +#if defined(BLUETOOTH_FEATURE) #include "../../bluetooth/BT_service.h" -#endif //BLUETOOTH_FEATURE -#if defined (WIFI_FEATURE) || defined (ETH_FEATURE) || defined (BLUETOOTH_FEATURE) +#endif // BLUETOOTH_FEATURE +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BLUETOOTH_FEATURE) #include "../../network/netconfig.h" -#endif //WIFI_FEATURE || ETH_FEATURE) ||BLUETOOTH_FEATURE +#endif // WIFI_FEATURE || ETH_FEATURE) ||BLUETOOTH_FEATURE #define DISPLAY_REFRESH_TIME 1000 TFT_eSPI esp3d_screen = TFT_eSPI(); Display esp3d_display; #if defined(DISPLAY_TOUCH_DRIVER) -bool Display::startCalibration() -{ +bool Display::startCalibration() { #error "DISPLAY_TOUCH_DRIVER not supported with OLED_I2C_SSD1306_128X64" } -#endif //DISPLAY_TOUCH_DRIVER +#endif // DISPLAY_TOUCH_DRIVER /** * The constructor for the Display class. */ -Display::Display() -{ - _started = false; - _screenID = SPLASH_SCREEN; - _splashDone=false; - _screenWidth = SCREEN_WIDTH; - _screenHeight = SCREEN_HEIGHT; +Display::Display() { + _started = false; + _screenID = SPLASH_SCREEN; + _splashDone = false; + _screenWidth = SCREEN_WIDTH; + _screenHeight = SCREEN_HEIGHT; } /** * The destructor for the Display class. */ -Display::~Display() -{ - end(); -} +Display::~Display() { end(); } /** - * If the display is started, set the status to blank, set the started flag to false, set the screen ID - * to the splash screen, set the splash displayed flag to false, and clear the screen + * If the display is started, set the status to blank, set the started flag to + * false, set the screen ID to the splash screen, set the splash displayed flag + * to false, and clear the screen * */ -void Display::end() -{ - if(!_started) { - return; - } - _status =""; - _started = false; - _screenID = SPLASH_SCREEN; - _splashDone=false; - clearScreen(); +void Display::end() { + if (!_started) { + return; + } + _status = ""; + _started = false; + _screenID = SPLASH_SCREEN; + _splashDone = false; + clearScreen(); } /** @@ -95,124 +91,105 @@ void Display::end() * * @return true if success. */ -bool Display::begin() -{ - bool res = true; - _started = false; - log_esp3d("Init Display"); +bool Display::begin() { + bool res = true; + _started = false; + esp3d_log("Init Display"); - esp3d_screen.init(); - clearScreen(); - setTextFont(2); + esp3d_screen.init(); + clearScreen(); + setTextFont(2); #if defined(DISPLAY_FLIP_VERTICALY) - esp3d_screen.setRotation(3); + esp3d_screen.setRotation(3); #else - esp3d_screen.setRotation(1); + esp3d_screen.setRotation(1); #endif - showScreenID(SPLASH_SCREEN); - updateScreen(true); + showScreenID(SPLASH_SCREEN); + updateScreen(true); #if defined(DISPLAY_TOUCH_DRIVER) - if(Settings_ESP3D::read_byte(ESP_CALIBRATION)==1) { - uint16_t calibrationData[5]; - for (uint8_t i = 0; i < 5; i++) { - calibrationData[i] = Settings_ESP3D::read_uint32 (ESP_CALIBRATION_1+(4*i)); - } - esp3d_screen.setTouch(calibrationData); + if (ESP3DSettings::readByte(ESP_CALIBRATION) == 1) { + uint16_t calibrationData[5]; + for (uint8_t i = 0; i < 5; i++) { + calibrationData[i] = + ESP3DSettings::readUint32(ESP_CALIBRATION_1 + (4 * i)); } -#endif //DISPLAY_TOUCH_DRIVER - res = true; - if (!res) { - end(); - } - _started = res; - return _started; + esp3d_screen.setTouch(calibrationData); + } +#endif // DISPLAY_TOUCH_DRIVER + res = true; + if (!res) { + end(); + } + _started = res; + return _started; } -void Display::handle() -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - if (_started) { - updateScreen(); - } +void Display::handle() { + if (_started) { + updateScreen(); + } } -const char * Display::getModelString() -{ - return "TFT_SPI_ST7789_135X240"; -} +const char *Display::getModelString() { return "TFT_SPI_ST7789_135X240"; } -uint8_t Display::getModelID() -{ - return DISPLAY_DEVICE; -} +uint8_t Display::getModelID() { return DISPLAY_DEVICE; } /** * Display the screen with the given screenID * * @param screenID The screen ID to show. */ -void Display::showScreenID(uint8_t screenID) -{ - /* Calling the function updateScreen. */ - _screenID = screenID; +void Display::showScreenID(uint8_t screenID) { + /* Calling the function updateScreen. */ + _screenID = screenID; } /** - * The function takes a string as an argument and sets the value of the private member variable _status - * to the value of the argument + * The function takes a string as an argument and sets the value of the private + * member variable _status to the value of the argument * * @param status The status to set. */ -void Display::setStatus(const char * status) -{ - _status= status; -} +void Display::setStatus(const char *status) { _status = status; } /** - * The function clears the screen by calling the clear() function of the esp3d_screen object + * The function clears the screen by calling the clear() function of the + * esp3d_screen object */ -void Display::clearScreen() -{ - log_esp3d("clear screen"); - esp3d_screen.fillScreen(SCREEN_BG); +void Display::clearScreen() { + esp3d_log("clear screen"); + esp3d_screen.fillScreen(SCREEN_BG); } -void Display::updateScreen(bool force) -{ - static uint8_t lastScreenID = 255; - log_esp3d("update screen"); - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - static uint32_t last_update = millis(); - bool need_update = force; - if (((millis()- last_update) > DISPLAY_REFRESH_TIME) ) { - if (lastScreenID != _screenID) { - lastScreenID = _screenID; - need_update = true; - clearScreen(); - } - last_update = millis(); - switch(_screenID) { - case SPLASH_SCREEN: - if (force) { - _splashDone=false; - } - need_update = splash(); - break; - case MAIN_SCREEN: - need_update = mainScreenHandler(force); - break; - default: - break; - } +void Display::updateScreen(bool force) { + static uint8_t lastScreenID = 255; + esp3d_log("update screen"); + static uint32_t last_update = millis(); + bool need_update = force; + if (((millis() - last_update) > DISPLAY_REFRESH_TIME)) { + if (lastScreenID != _screenID) { + lastScreenID = _screenID; + need_update = true; + clearScreen(); } + last_update = millis(); + switch (_screenID) { + case SPLASH_SCREEN: + if (force) { + _splashDone = false; + } + need_update = splash(); + break; + case MAIN_SCREEN: + need_update = mainScreenHandler(force); + break; + default: + break; + } + } } - /** * It returns the width of the string in pixels. * @@ -220,47 +197,42 @@ void Display::updateScreen(bool force) * * @return The width of the string in pixels. */ -uint16_t Display::getStringWidth(const char* text) -{ - return esp3d_screen.textWidth(text, _font); +uint16_t Display::getStringWidth(const char *text) { + return esp3d_screen.textWidth(text, _font); } /** - * It takes a string and a maximum width, and returns the number of characters that will fit in that - * width + * It takes a string and a maximum width, and returns the number of characters + * that will fit in that width * * @param string The string to be measured * @param maxwidth The maximum width of the string in pixels. * * @return The length of the string. */ -uint16_t Display::sizetoFitSpace(const char * string, uint16_t maxwidth) -{ - String s = string; - while (getStringWidth(s.c_str()) > maxwidth) { - if (s.length() > 0) { - s.remove(s.length()-1); - } else { - return 0; - } +uint16_t Display::sizetoFitSpace(const char *string, uint16_t maxwidth) { + String s = string; + while (getStringWidth(s.c_str()) > maxwidth) { + if (s.length() > 0) { + s.remove(s.length() - 1); + } else { + return 0; } - return s.length(); + } + return s.length(); } -void Display::setTextFont(uint8_t font) -{ - log_esp3d("setTextFont size %d", font); - _font=font; +void Display::setTextFont(uint8_t font) { + esp3d_log("setTextFont size %d", font); + _font = font; } -void Display::drawString(const char *string, int32_t poX, int32_t poY, int16_t color) -{ - log_esp3d("drawString %s at %d,%d", string, poX, poY); - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - esp3d_screen.setTextColor(color); - esp3d_screen.drawString(string,poX, poY, _font); +void Display::drawString(const char *string, int32_t poX, int32_t poY, + int16_t color) { + esp3d_log("drawString %s at %d,%d", string, poX, poY); + + esp3d_screen.setTextColor(color); + esp3d_screen.drawString(string, poX, poY, _font); } /** @@ -274,15 +246,11 @@ void Display::drawString(const char *string, int32_t poX, int32_t poY, int16_t c * * @return Nothing. */ -void Display::drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t color) -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - esp3d_screen.drawLine(x0, y0, x1, y1,color); +void Display::drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, + int16_t color) { + esp3d_screen.drawLine(x0, y0, x1, y1, color); } - /** * > Draw a rectangle on the screen * @@ -294,12 +262,9 @@ void Display::drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t c * * @return Nothing. */ -void Display::drawRect(int16_t x, int16_t y, int16_t width, int16_t height, int16_t color) -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - esp3d_screen.drawRect(x, y, width, height, color); +void Display::drawRect(int16_t x, int16_t y, int16_t width, int16_t height, + int16_t color) { + esp3d_screen.drawRect(x, y, width, height, color); } /** @@ -313,12 +278,9 @@ void Display::drawRect(int16_t x, int16_t y, int16_t width, int16_t height, int1 * * @return Nothing. */ -void Display::fillRect(int16_t x, int16_t y, int16_t width, int16_t height, int16_t color) -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - esp3d_screen.fillRect(x, y, width, height, color); +void Display::fillRect(int16_t x, int16_t y, int16_t width, int16_t height, + int16_t color) { + esp3d_screen.fillRect(x, y, width, height, color); } /** @@ -333,12 +295,9 @@ void Display::fillRect(int16_t x, int16_t y, int16_t width, int16_t height, int1 * * @return Nothing. */ -void Display::drawXbm(int16_t x, int16_t y, int16_t width, int16_t height, int16_t color, const uint8_t *xbm) -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - esp3d_screen.drawXBitmap(x, y, xbm, width, height,color); +void Display::drawXbm(int16_t x, int16_t y, int16_t width, int16_t height, + int16_t color, const uint8_t *xbm) { + esp3d_screen.drawXBitmap(x, y, xbm, width, height, color); } /** @@ -353,417 +312,416 @@ void Display::drawXbm(int16_t x, int16_t y, int16_t width, int16_t height, int16 * @param xbm the xbm image data * */ -void Display::drawXbm(int16_t x, int16_t y, int16_t width, int16_t height, uint16_t fgcolor, uint16_t bgcolor, const uint8_t *xbm) -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - (void)fgcolor; - (void)bgcolor; - esp3d_screen.drawXBitmap(x, y, xbm, width, height,fgcolor,bgcolor); +void Display::drawXbm(int16_t x, int16_t y, int16_t width, int16_t height, + uint16_t fgcolor, uint16_t bgcolor, const uint8_t *xbm) { + (void)fgcolor; + (void)bgcolor; + esp3d_screen.drawXBitmap(x, y, xbm, width, height, fgcolor, bgcolor); } /** - * The function is called with a value between 0 and 100. The function draws a rectangle on the screen - * with a width that is proportional to the value + * The function is called with a value between 0 and 100. The function draws a + * rectangle on the screen with a width that is proportional to the value * * @param v The percentage of the progress bar to fill. * * @return the value of the variable v. */ -void Display::progress(uint8_t v) -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - static uint8_t previous = 0; - if (previous > v) { - //clear - fillRect(10, _screenHeight-4, _screenWidth-20, 4, SCREEN_BG); - } - log_esp3d("%d", v); - previous = v>100?100:v; - //display bar - fillRect(10, _screenHeight-4, ((_screenWidth-20) * v)/100, 4, PROGRESS_FG); - //update screen - updateScreen(true); +void Display::progress(uint8_t v) { + static uint8_t previous = 0; + if (previous > v) { + // clear + fillRect(10, _screenHeight - 4, _screenWidth - 20, 4, SCREEN_BG); + } + esp3d_log("%d", v); + previous = v > 100 ? 100 : v; + // display bar + fillRect(10, _screenHeight - 4, ((_screenWidth - 20) * v) / 100, 4, + PROGRESS_FG); + // update screen + updateScreen(true); } /** - * If the display is not busy, then check if the signal strength has changed, if so, then display it. - * If the IP address has changed, then display it. If the status has changed, then display it + * If the display is not busy, then check if the signal strength has changed, if + * so, then display it. If the IP address has changed, then display it. If the + * status has changed, then display it * - * @param force boolean, if true, the screen will be updated regardless of whether or not it needs to - * be. + * @param force boolean, if true, the screen will be updated regardless of + * whether or not it needs to be. * * @return A boolean value. */ -bool Display::mainScreenHandler(bool force) -{ - bool res = false; - if (displaySignal(force)) { - res = true; - } - if (displayIP(force)) { - res = true; - } - if (showStatus(force)) { - res = true; - } - return res; +bool Display::mainScreenHandler(bool force) { + bool res = false; + if (displaySignal(force)) { + res = true; + } + if (displayIP(force)) { + res = true; + } + if (showStatus(force)) { + res = true; + } + return res; } /** - * If the screen is connected, and the splash screen has not been displayed, then display the splash - * screen + * If the screen is connected, and the splash screen has not been displayed, + * then display the splash screen * * @return a boolean value. */ -bool Display::splash() -{ - log_esp3d("Splash"); - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return false; - } - if (!_splashDone) { - drawXbm((_screenWidth-ESP3D_Logo_width)/2, (_screenHeight-ESP3D_Logo_height)/2, ESP3D_Logo_width, ESP3D_Logo_height, SPLASH_FG, SPLASH_BG,ESP3D_Logo); - log_esp3d("Display Splash"); - _splashDone = true; - return true; - } - return false; +bool Display::splash() { + esp3d_log("Splash"); + + if (!_splashDone) { + drawXbm((_screenWidth - ESP3D_Logo_width) / 2, + (_screenHeight - ESP3D_Logo_height) / 2, ESP3D_Logo_width, + ESP3D_Logo_height, SPLASH_FG, SPLASH_BG, ESP3D_Logo); + esp3d_log("Display Splash"); + _splashDone = true; + return true; + } + return false; } -void Display::updateIP() -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - updateScreen(true); -} +void Display::updateIP() { updateScreen(true); } /** - * It takes a string, and if it's too long to fit in the status area, it chops it up into pieces and - * displays them one at a time + * It takes a string, and if it's too long to fit in the status area, it chops + * it up into pieces and displays them one at a time * - * @param force if true, the status will be redrawn regardless of whether it's changed or not. + * @param force if true, the status will be redrawn regardless of whether it's + * changed or not. * * @return a boolean value. */ -bool Display::showStatus(bool force) -{ - //Display Status - bool refresh_status = force; - static String status; - if (status != _status) { - status = _status; - refresh_status = true; - } +bool Display::showStatus(bool force) { + // Display Status + bool refresh_status = force; + static String status; + if (status != _status) { + status = _status; + refresh_status = true; + } - setTextFont(FONTSTATUS); - uint16_t size = sizetoFitSpace(status.c_str(), STATUS_AREA_W); - //check the need for resize + setTextFont(FONTSTATUS); + uint16_t size = sizetoFitSpace(status.c_str(), STATUS_AREA_W); + // check the need for resize + if (size < status.length()) { + static int status_shift = -1; + refresh_status = true; + status += " "; + esp3d_log("current %s", status.c_str()); + if (status_shift != -1) { + if ((uint16_t)(status_shift) > status.length()) { + status_shift = -1; + } + } + esp3d_log("shift %d", status_shift); + if (status_shift > 0) { + status.remove(0, status_shift); + } + esp3d_log("shifted %s", status.c_str()); + size = sizetoFitSpace(status.c_str(), STATUS_AREA_W); + esp3d_log("size available %d existing %d", size, status.length()); if (size < status.length()) { - static int status_shift = -1; - refresh_status = true; - status+=" "; - log_esp3d("current %s", status.c_str()); - if (status_shift != -1) { - if( (uint16_t)(status_shift)> status.length()) { - status_shift = -1; - } - } - log_esp3d("shift %d", status_shift); - if (status_shift > 0) { - status.remove(0,status_shift); - } - log_esp3d("shifted %s", status.c_str()); - size = sizetoFitSpace(status.c_str(), STATUS_AREA_W); - log_esp3d("size available %d existing %d",size, status.length()); - if (size < status.length()) { - //cut - status = status.substring(0,size); - status_shift++; - } else { - status_shift = -1; - } - log_esp3d("sized %s", status.c_str()); + // cut + status = status.substring(0, size); + status_shift++; + } else { + status_shift = -1; } - if (refresh_status) { - //clear area - fillRect(STATUS_AREA_X, STATUS_AREA_Y, STATUS_AREA_W, STATUS_AREA_H, SCREEN_BG); - drawString(status.c_str(), STATUS_AREA_X, STATUS_AREA_Y, STATUS_FG); - } - return refresh_status; + esp3d_log("sized %s", status.c_str()); + } + if (refresh_status) { + // clear area + fillRect(STATUS_AREA_X, STATUS_AREA_Y, STATUS_AREA_W, STATUS_AREA_H, + SCREEN_BG); + drawString(status.c_str(), STATUS_AREA_X, STATUS_AREA_Y, STATUS_FG); + } + return refresh_status; } -bool Display::displaySignal(bool force) -{ - static int sig = -1; - bool refresh_signal = false; - bool refresh_label = false; - static String label; -#if defined (WIFI_FEATURE) - if (WiFiConfig::started()) { - - if (WiFi.getMode() == WIFI_AP) { - if (sig != 100) { - sig = 100; - refresh_signal = true; - } - if (label != WiFiConfig::AP_SSID()) { - label = WiFiConfig::AP_SSID(); - refresh_label = true; - } - } else { - if (WiFi.isConnected()) { - int sigtmp = WiFiConfig::getSignal (WiFi.RSSI (),false); - if (sig != sigtmp) { - sig =sigtmp; - refresh_signal = true; - } - if (label != WiFi.SSID()) { - label = WiFi.SSID(); - refresh_label = true; - } - } else { - if (sig != -1) { - sig = -1; - refresh_signal = true; - } - if (label != "") { - label = ""; - refresh_label = true; - } - } - } - //Display SSID - setTextFont(FONTSSID); - uint16_t size = sizetoFitSpace(label.c_str(), SSID_AREA_W); - //check the need for resize - if (size < label.length()) { - refresh_label = true; - static int label_shift = -1; - label+=" "; - //log_esp3d("current %s", label.c_str()); - if (label_shift != -1) { - if((uint16_t)(label_shift)> label.length()) { - label_shift = -1; - } - } - //log_esp3d("shift %d", label_shift); - if (label_shift > 0) { - label.remove(0,label_shift); - } - //log_esp3d("shifted %s", label.c_str()); - size = sizetoFitSpace(label.c_str(), SSID_AREA_W); - //log_esp3d("size available %d existing %d",size, label.length()); - if (size < label.length()) { - //cut - label = label.substring(0,size); - label_shift++; - } else { - label_shift = -1; - } - //log_esp3d("sized %s", label.c_str()); - } - if (refresh_label || force) { - //clear area - fillRect(SSID_AREA_X, SSID_AREA_Y, SSID_AREA_W, SSID_AREA_H, SCREEN_BG); - drawString(label.c_str(), SSID_AREA_X, SSID_AREA_Y, SSID_FG); - } - } -#endif // WIFI_FEATURE - -#if defined (ETH_FEATURE) - if (EthConfig::started()) { - if (sig != -2) { - sig = -2; - refresh_signal = true; - } - //display connection speed - if(EthConfig::linkUp()) { - String tmp = ETH.linkSpeed(); - tmp+= "Mbps"; - if (label != tmp) { - label = tmp; - refresh_label = true; - } - } else { - if (label !="") { - label =""; - refresh_label = true; - } - } - if (refresh_label || force) { - setTextFont(FONTSSID); - //clear area - fillRect(SSID_AREA_X, SSID_AREA_Y, SSID_AREA_W, SSID_AREA_H, SCREEN_BG); - drawString(label.c_str(), SSID_AREA_X, SSID_AREA_Y, SSID_FG); - } - } -#endif //ETH_FEATURE - -#if defined (BLUETOOTH_FEATURE) - if (bt_service.started()) { - if (sig!=-3) { - sig = -3; - refresh_signal = true; - } - - //Display hostname - if (label != bt_service.hostname()) { - refresh_label = true; - label = bt_service.hostname(); - } - setTextFont(FONTSSID); - uint16_t size = sizetoFitSpace(label.c_str(), SSID_AREA_W); - //check the need for resize - if (size < label.length()) { - refresh_label = true; - static int label_shift = -1; - label+=" "; - //log_esp3d("current %s", hostname.c_str()); - if (label_shift > label.length()) { - label_shift = -1; - } - //log_esp3d("shift %d", label_shift); - if (label_shift > 0) { - label.remove(0,label_shift); - } - //log_esp3d("shifted %s", hostname.c_str()); - size = sizetoFitSpace(label.c_str(), SSID_AREA_W); - //log_esp3d("size available %d existing %d",size, hostname.length()); - if (size < label.length()) { - //cut - label = label.substring(0,size); - label_shift++; - } else { - label_shift = -1; - } - //log_esp3d("sized %s", hostname.c_str()); - } - if( refresh_label || force) { - //clear area - fillRect(SSID_AREA_X, SSID_AREA_Y, SSID_AREA_W, SSID_AREA_H, SCREEN_BG); - if (label.length()>0) { - drawString(label.c_str(), SSID_AREA_X, SSID_AREA_Y, SSID_FG); - } - } - } -#endif //BLUETOOTH_FEATURE - String s; - if (refresh_signal || force) { - - //set current font size - setTextFont(FONTSIGNAL); - fillRect(SIGNAL_X, SIGNAL_Y, SIGNAL_W, SIGNAL_H,SCREEN_BG); - fillRect(SIGNAL_ICON_X, SIGNAL_ICON_Y, SIGNAL_ICON_W, SIGNAL_ICON_H,SCREEN_BG); - if (sig > 0) { - //Signal % - s = String(sig); - s+="%"; - //Signal Icon according % - if (sig > 0) { - fillRect(SIGNAL_ICON_X, SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.6), SIGNAL_ICON_W_BAR, SIGNAL_ICON_H * 0.4, SIGNAL_FG); - } else { - drawRect(SIGNAL_ICON_X, SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.6), SIGNAL_ICON_W_BAR, SIGNAL_ICON_H * 0.4, SIGNAL_FG); - } - - if (sig >= 25) { - fillRect(SIGNAL_ICON_X + SIGNAL_ICON_SPACER_X +SIGNAL_ICON_W_BAR, SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.4), SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H * 0.6), SIGNAL_FG); - } else { - drawRect(SIGNAL_ICON_X + SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR, SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.4), SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H * 0.6), SIGNAL_FG); - } - - if (sig >= 50) { - fillRect(SIGNAL_ICON_X + (2*(SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.2), SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H * 0.8), SIGNAL_FG); - } else { - drawRect(SIGNAL_ICON_X + (2*(SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.2), SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H * 0.8), SIGNAL_FG); - } - - if (sig >= 75) { - fillRect(SIGNAL_ICON_X + (3*(SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), SIGNAL_ICON_Y, SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H), SIGNAL_FG); - } else { - drawRect(SIGNAL_ICON_X + (3*(SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), SIGNAL_ICON_Y, SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H), SIGNAL_FG); - } - - } - //No signal / no connection - if (sig == -1) { - s = " X"; - } - //Ethernet is connected - if (sig == -2) { - s = "Eth"; - } - //BT is active - if (sig == -3) { - s = "BT"; - } - //Show Connection type - drawString(s.c_str(), SIGNAL_X, SIGNAL_Y, SIGNAL_FG); - } - if (refresh_signal || refresh_label || force) { - return true; +bool Display::displaySignal(bool force) { + static int sig = -1; + bool refresh_signal = false; + bool refresh_label = false; + static String label; +#if defined(WIFI_FEATURE) + if (WiFiConfig::started()) { + if (WiFi.getMode() == WIFI_AP) { + if (sig != 100) { + sig = 100; + refresh_signal = true; + } + if (label != WiFiConfig::AP_SSID()) { + label = WiFiConfig::AP_SSID(); + refresh_label = true; + } } else { - return false; - } -} - -bool Display::displayIP(bool force) -{ - bool refresh_label = force; - static String label; -#if defined (WIFI_FEATURE) || defined (ETH_FEATURE) || defined (BLUETOOTH_FEATURE) - if (NetConfig::started()) { - String s; - switch(NetConfig::getMode()) { -#if defined (WIFI_FEATURE) - case ESP_WIFI_STA: - s = WiFi.localIP().toString(); - break; - case ESP_AP_SETUP: - case ESP_WIFI_AP: - s = WiFi.softAPIP().toString(); - break; -#endif //WIFI_FEATURE -#if defined (ETH_FEATURE) - case ESP_ETH_STA: - s = ETH.localIP().toString(); - break; -#endif //ETH_FEATURE -#if defined (BLUETOOTH_FEATURE) - case ESP_BT: - s = bt_service.isConnected()?"Connected":""; - break; -#endif //BLUETOOTH_FEATURE - default: - s=""; - log_esp3d("Unknown mode %d", NetConfig::getMode()); - break; + if (WiFi.isConnected()) { + int sigtmp = WiFiConfig::getSignal(WiFi.RSSI(), false); + if (sig != sigtmp) { + sig = sigtmp; + refresh_signal = true; } - if (s!= label) { - label = s; - refresh_label = true; + if (label != WiFi.SSID()) { + label = WiFi.SSID(); + refresh_label = true; } - if (refresh_label) { - if (label.length()>0) { - setTextFont(FONTIP); - fillRect(IP_AREA_X, IP_AREA_Y, IP_AREA_W, IP_AREA_H, SCREEN_BG); - drawString(label.c_str(), IP_AREA_X, IP_AREA_Y, IP_FG); - } - + } else { + if (sig != -1) { + sig = -1; + refresh_signal = true; } - } else { if (label != "") { - label = ""; - refresh_label = true; - fillRect(IP_AREA_X, IP_AREA_Y, IP_AREA_W, IP_AREA_H, SCREEN_BG); + label = ""; + refresh_label = true; } + } } -#endif //WIFI_FEATURE || ETH_FEATURE || BLUETOOTH_FEATURE - return refresh_label; + // Display SSID + setTextFont(FONTSSID); + uint16_t size = sizetoFitSpace(label.c_str(), SSID_AREA_W); + // check the need for resize + if (size < label.length()) { + refresh_label = true; + static int label_shift = -1; + label += " "; + // esp3d_log("current %s", label.c_str()); + if (label_shift != -1) { + if ((uint16_t)(label_shift) > label.length()) { + label_shift = -1; + } + } + // esp3d_log("shift %d", label_shift); + if (label_shift > 0) { + label.remove(0, label_shift); + } + // esp3d_log("shifted %s", label.c_str()); + size = sizetoFitSpace(label.c_str(), SSID_AREA_W); + // esp3d_log("size available %d existing %d",size, label.length()); + if (size < label.length()) { + // cut + label = label.substring(0, size); + label_shift++; + } else { + label_shift = -1; + } + // esp3d_log("sized %s", label.c_str()); + } + if (refresh_label || force) { + // clear area + fillRect(SSID_AREA_X, SSID_AREA_Y, SSID_AREA_W, SSID_AREA_H, SCREEN_BG); + drawString(label.c_str(), SSID_AREA_X, SSID_AREA_Y, SSID_FG); + } + } +#endif // WIFI_FEATURE + +#if defined(ETH_FEATURE) + if (EthConfig::started()) { + if (sig != -2) { + sig = -2; + refresh_signal = true; + } + // display connection speed + if (EthConfig::linkUp()) { + String tmp = ETH.linkSpeed(); + tmp += "Mbps"; + if (label != tmp) { + label = tmp; + refresh_label = true; + } + } else { + if (label != "") { + label = ""; + refresh_label = true; + } + } + if (refresh_label || force) { + setTextFont(FONTSSID); + // clear area + fillRect(SSID_AREA_X, SSID_AREA_Y, SSID_AREA_W, SSID_AREA_H, SCREEN_BG); + drawString(label.c_str(), SSID_AREA_X, SSID_AREA_Y, SSID_FG); + } + } +#endif // ETH_FEATURE + +#if defined(BLUETOOTH_FEATURE) + if (bt_service.started()) { + if (sig != -3) { + sig = -3; + refresh_signal = true; + } + + // Display hostname + if (label != bt_service.hostname()) { + refresh_label = true; + label = bt_service.hostname(); + } + setTextFont(FONTSSID); + uint16_t size = sizetoFitSpace(label.c_str(), SSID_AREA_W); + // check the need for resize + if (size < label.length()) { + refresh_label = true; + static int label_shift = -1; + label += " "; + // esp3d_log("current %s", hostname.c_str()); + if (label_shift > label.length()) { + label_shift = -1; + } + // esp3d_log("shift %d", label_shift); + if (label_shift > 0) { + label.remove(0, label_shift); + } + // esp3d_log("shifted %s", hostname.c_str()); + size = sizetoFitSpace(label.c_str(), SSID_AREA_W); + // esp3d_log("size available %d existing %d",size, hostname.length()); + if (size < label.length()) { + // cut + label = label.substring(0, size); + label_shift++; + } else { + label_shift = -1; + } + // esp3d_log("sized %s", hostname.c_str()); + } + if (refresh_label || force) { + // clear area + fillRect(SSID_AREA_X, SSID_AREA_Y, SSID_AREA_W, SSID_AREA_H, SCREEN_BG); + if (label.length() > 0) { + drawString(label.c_str(), SSID_AREA_X, SSID_AREA_Y, SSID_FG); + } + } + } +#endif // BLUETOOTH_FEATURE + String s; + if (refresh_signal || force) { + // set current font size + setTextFont(FONTSIGNAL); + fillRect(SIGNAL_X, SIGNAL_Y, SIGNAL_W, SIGNAL_H, SCREEN_BG); + fillRect(SIGNAL_ICON_X, SIGNAL_ICON_Y, SIGNAL_ICON_W, SIGNAL_ICON_H, + SCREEN_BG); + if (sig > 0) { + // Signal % + s = String(sig); + s += "%"; + // Signal Icon according % + if (sig > 0) { + fillRect(SIGNAL_ICON_X, SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.6), + SIGNAL_ICON_W_BAR, SIGNAL_ICON_H * 0.4, SIGNAL_FG); + } else { + drawRect(SIGNAL_ICON_X, SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.6), + SIGNAL_ICON_W_BAR, SIGNAL_ICON_H * 0.4, SIGNAL_FG); + } + + if (sig >= 25) { + fillRect(SIGNAL_ICON_X + SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR, + SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.4), SIGNAL_ICON_W_BAR, + (SIGNAL_ICON_H * 0.6), SIGNAL_FG); + } else { + drawRect(SIGNAL_ICON_X + SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR, + SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.4), SIGNAL_ICON_W_BAR, + (SIGNAL_ICON_H * 0.6), SIGNAL_FG); + } + + if (sig >= 50) { + fillRect( + SIGNAL_ICON_X + (2 * (SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), + SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.2), SIGNAL_ICON_W_BAR, + (SIGNAL_ICON_H * 0.8), SIGNAL_FG); + } else { + drawRect( + SIGNAL_ICON_X + (2 * (SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), + SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.2), SIGNAL_ICON_W_BAR, + (SIGNAL_ICON_H * 0.8), SIGNAL_FG); + } + + if (sig >= 75) { + fillRect( + SIGNAL_ICON_X + (3 * (SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), + SIGNAL_ICON_Y, SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H), SIGNAL_FG); + } else { + drawRect( + SIGNAL_ICON_X + (3 * (SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), + SIGNAL_ICON_Y, SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H), SIGNAL_FG); + } + } + // No signal / no connection + if (sig == -1) { + s = " X"; + } + // Ethernet is connected + if (sig == -2) { + s = "Eth"; + } + // BT is active + if (sig == -3) { + s = "BT"; + } + // Show Connection type + drawString(s.c_str(), SIGNAL_X, SIGNAL_Y, SIGNAL_FG); + } + if (refresh_signal || refresh_label || force) { + return true; + } else { + return false; + } } -#endif //DISPLAY_DEVICE && DISPLAY_DEVICE == OLED_I2C_SSD1306_128X64 +bool Display::displayIP(bool force) { + bool refresh_label = force; + static String label; +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BLUETOOTH_FEATURE) + if (NetConfig::started()) { + String s; + switch (NetConfig::getMode()) { +#if defined(WIFI_FEATURE) + case ESP_WIFI_STA: + s = WiFi.localIP().toString(); + break; + case ESP_AP_SETUP: + case ESP_WIFI_AP: + s = WiFi.softAPIP().toString(); + break; +#endif // WIFI_FEATURE +#if defined(ETH_FEATURE) + case ESP_ETH_STA: + s = ETH.localIP().toString(); + break; +#endif // ETH_FEATURE +#if defined(BLUETOOTH_FEATURE) + case ESP_BT: + s = bt_service.isConnected() ? "Connected" : ""; + break; +#endif // BLUETOOTH_FEATURE + default: + s = ""; + esp3d_log("Unknown mode %d", NetConfig::getMode()); + break; + } + if (s != label) { + label = s; + refresh_label = true; + } + if (refresh_label) { + if (label.length() > 0) { + setTextFont(FONTIP); + fillRect(IP_AREA_X, IP_AREA_Y, IP_AREA_W, IP_AREA_H, SCREEN_BG); + drawString(label.c_str(), IP_AREA_X, IP_AREA_Y, IP_FG); + } + } + } else { + if (label != "") { + label = ""; + refresh_label = true; + fillRect(IP_AREA_X, IP_AREA_Y, IP_AREA_W, IP_AREA_H, SCREEN_BG); + } + } +#endif // WIFI_FEATURE || ETH_FEATURE || BLUETOOTH_FEATURE + return refresh_label; +} + +#endif // DISPLAY_DEVICE && DISPLAY_DEVICE == OLED_I2C_SSD1306_128X64 diff --git a/esp3d/src/modules/display/TFT_SPI_ST7789_240X240/display.cpp b/esp3d/src/modules/display/TFT_SPI_ST7789_240X240/display.cpp index e2a35713..6d3a0102 100644 --- a/esp3d/src/modules/display/TFT_SPI_ST7789_240X240/display.cpp +++ b/esp3d/src/modules/display/TFT_SPI_ST7789_240X240/display.cpp @@ -19,75 +19,71 @@ */ #include "../../../include/esp3d_config.h" -#if defined (DISPLAY_DEVICE) && DISPLAY_DEVICE == TFT_SPI_ST7789_240X240 +#if defined(DISPLAY_DEVICE) && DISPLAY_DEVICE == TFT_SPI_ST7789_240X240 +#include + +#include "../../../core/esp3d_message.h" +#include "../../../core/esp3d_settings.h" #include "../display.h" -#include "../../../core/settings_esp3d.h" -#include "../../../core/esp3doutput.h" #include "Wire.h" #include "esp3d_logo.h" -#include #include "settings.h" -#if defined (WIFI_FEATURE) +#if defined(WIFI_FEATURE) #include "../../wifi/wificonfig.h" -#endif // WIFI_FEATURE -#if defined (ETH_FEATURE) +#endif // WIFI_FEATURE +#if defined(ETH_FEATURE) #include "../../ethernet/ethconfig.h" -#endif //ETH_FEATURE -#if defined (BLUETOOTH_FEATURE) +#endif // ETH_FEATURE +#if defined(BLUETOOTH_FEATURE) #include "../../bluetooth/BT_service.h" -#endif //BLUETOOTH_FEATURE -#if defined (WIFI_FEATURE) || defined (ETH_FEATURE) || defined (BLUETOOTH_FEATURE) +#endif // BLUETOOTH_FEATURE +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BLUETOOTH_FEATURE) #include "../../network/netconfig.h" -#endif //WIFI_FEATURE || ETH_FEATURE) ||BLUETOOTH_FEATURE +#endif // WIFI_FEATURE || ETH_FEATURE) ||BLUETOOTH_FEATURE #define DISPLAY_REFRESH_TIME 1000 TFT_eSPI esp3d_screen = TFT_eSPI(); Display esp3d_display; #if defined(DISPLAY_TOUCH_DRIVER) -bool Display::startCalibration() -{ +bool Display::startCalibration() { #error "DISPLAY_TOUCH_DRIVER not supported with OLED_I2C_SSD1306_128X64" } -#endif //DISPLAY_TOUCH_DRIVER +#endif // DISPLAY_TOUCH_DRIVER /** * The constructor for the Display class. */ -Display::Display() -{ - _started = false; - _screenID = SPLASH_SCREEN; - _splashDone=false; - _screenWidth = SCREEN_WIDTH; - _screenHeight = SCREEN_HEIGHT; +Display::Display() { + _started = false; + _screenID = SPLASH_SCREEN; + _splashDone = false; + _screenWidth = SCREEN_WIDTH; + _screenHeight = SCREEN_HEIGHT; } /** * The destructor for the Display class. */ -Display::~Display() -{ - end(); -} +Display::~Display() { end(); } /** - * If the display is started, set the status to blank, set the started flag to false, set the screen ID - * to the splash screen, set the splash displayed flag to false, and clear the screen + * If the display is started, set the status to blank, set the started flag to + * false, set the screen ID to the splash screen, set the splash displayed flag + * to false, and clear the screen * */ -void Display::end() -{ - if(!_started) { - return; - } - _status =""; - _started = false; - _screenID = SPLASH_SCREEN; - _splashDone=false; - clearScreen(); +void Display::end() { + if (!_started) { + return; + } + _status = ""; + _started = false; + _screenID = SPLASH_SCREEN; + _splashDone = false; + clearScreen(); } /** @@ -95,124 +91,105 @@ void Display::end() * * @return true if success. */ -bool Display::begin() -{ - bool res = true; - _started = false; - log_esp3d("Init Display"); +bool Display::begin() { + bool res = true; + _started = false; + esp3d_log("Init Display"); - esp3d_screen.init(); - clearScreen(); - setTextFont(2); + esp3d_screen.init(); + clearScreen(); + setTextFont(2); #if defined(DISPLAY_FLIP_VERTICALY) - esp3d_screen.setRotation(3); + esp3d_screen.setRotation(3); #else - esp3d_screen.setRotation(1); + esp3d_screen.setRotation(1); #endif - showScreenID(SPLASH_SCREEN); - updateScreen(true); + showScreenID(SPLASH_SCREEN); + updateScreen(true); #if defined(DISPLAY_TOUCH_DRIVER) - if(Settings_ESP3D::read_byte(ESP_CALIBRATION)==1) { - uint16_t calibrationData[5]; - for (uint8_t i = 0; i < 5; i++) { - calibrationData[i] = Settings_ESP3D::read_uint32 (ESP_CALIBRATION_1+(4*i)); - } - esp3d_screen.setTouch(calibrationData); + if (ESP3DSettings::readByte(ESP_CALIBRATION) == 1) { + uint16_t calibrationData[5]; + for (uint8_t i = 0; i < 5; i++) { + calibrationData[i] = + ESP3DSettings::readUint32(ESP_CALIBRATION_1 + (4 * i)); } -#endif //DISPLAY_TOUCH_DRIVER - res = true; - if (!res) { - end(); - } - _started = res; - return _started; + esp3d_screen.setTouch(calibrationData); + } +#endif // DISPLAY_TOUCH_DRIVER + res = true; + if (!res) { + end(); + } + _started = res; + return _started; } -void Display::handle() -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - if (_started) { - updateScreen(); - } +void Display::handle() { + if (_started) { + updateScreen(); + } } -const char * Display::getModelString() -{ - return "TFT_SPI_ST7789_240X240"; -} +const char *Display::getModelString() { return "TFT_SPI_ST7789_240X240"; } -uint8_t Display::getModelID() -{ - return DISPLAY_DEVICE; -} +uint8_t Display::getModelID() { return DISPLAY_DEVICE; } /** * Display the screen with the given screenID * * @param screenID The screen ID to show. */ -void Display::showScreenID(uint8_t screenID) -{ - /* Calling the function updateScreen. */ - _screenID = screenID; +void Display::showScreenID(uint8_t screenID) { + /* Calling the function updateScreen. */ + _screenID = screenID; } /** - * The function takes a string as an argument and sets the value of the private member variable _status - * to the value of the argument + * The function takes a string as an argument and sets the value of the private + * member variable _status to the value of the argument * * @param status The status to set. */ -void Display::setStatus(const char * status) -{ - _status= status; -} +void Display::setStatus(const char *status) { _status = status; } /** - * The function clears the screen by calling the clear() function of the esp3d_screen object + * The function clears the screen by calling the clear() function of the + * esp3d_screen object */ -void Display::clearScreen() -{ - log_esp3d("clear screen"); - esp3d_screen.fillScreen(SCREEN_BG); +void Display::clearScreen() { + esp3d_log("clear screen"); + esp3d_screen.fillScreen(SCREEN_BG); } -void Display::updateScreen(bool force) -{ - static uint8_t lastScreenID = 255; - log_esp3d("update screen"); - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - static uint32_t last_update = millis(); - bool need_update = force; - if (((millis()- last_update) > DISPLAY_REFRESH_TIME) ) { - if (lastScreenID != _screenID) { - lastScreenID = _screenID; - need_update = true; - clearScreen(); - } - last_update = millis(); - switch(_screenID) { - case SPLASH_SCREEN: - if (force) { - _splashDone=false; - } - need_update = splash(); - break; - case MAIN_SCREEN: - need_update = mainScreenHandler(force); - break; - default: - break; - } +void Display::updateScreen(bool force) { + static uint8_t lastScreenID = 255; + esp3d_log("update screen"); + static uint32_t last_update = millis(); + bool need_update = force; + if (((millis() - last_update) > DISPLAY_REFRESH_TIME)) { + if (lastScreenID != _screenID) { + lastScreenID = _screenID; + need_update = true; + clearScreen(); } + last_update = millis(); + switch (_screenID) { + case SPLASH_SCREEN: + if (force) { + _splashDone = false; + } + need_update = splash(); + break; + case MAIN_SCREEN: + need_update = mainScreenHandler(force); + break; + default: + break; + } + } } - /** * It returns the width of the string in pixels. * @@ -220,47 +197,42 @@ void Display::updateScreen(bool force) * * @return The width of the string in pixels. */ -uint16_t Display::getStringWidth(const char* text) -{ - return esp3d_screen.textWidth(text, _font); +uint16_t Display::getStringWidth(const char *text) { + return esp3d_screen.textWidth(text, _font); } /** - * It takes a string and a maximum width, and returns the number of characters that will fit in that - * width + * It takes a string and a maximum width, and returns the number of characters + * that will fit in that width * * @param string The string to be measured * @param maxwidth The maximum width of the string in pixels. * * @return The length of the string. */ -uint16_t Display::sizetoFitSpace(const char * string, uint16_t maxwidth) -{ - String s = string; - while (getStringWidth(s.c_str()) > maxwidth) { - if (s.length() > 0) { - s.remove(s.length()-1); - } else { - return 0; - } +uint16_t Display::sizetoFitSpace(const char *string, uint16_t maxwidth) { + String s = string; + while (getStringWidth(s.c_str()) > maxwidth) { + if (s.length() > 0) { + s.remove(s.length() - 1); + } else { + return 0; } - return s.length(); + } + return s.length(); } -void Display::setTextFont(uint8_t font) -{ - log_esp3d("setTextFont size %d", font); - _font=font; +void Display::setTextFont(uint8_t font) { + esp3d_log("setTextFont size %d", font); + _font = font; } -void Display::drawString(const char *string, int32_t poX, int32_t poY, int16_t color) -{ - log_esp3d("drawString %s at %d,%d", string, poX, poY); - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - esp3d_screen.setTextColor(color); - esp3d_screen.drawString(string,poX, poY, _font); +void Display::drawString(const char *string, int32_t poX, int32_t poY, + int16_t color) { + esp3d_log("drawString %s at %d,%d", string, poX, poY); + + esp3d_screen.setTextColor(color); + esp3d_screen.drawString(string, poX, poY, _font); } /** @@ -274,15 +246,11 @@ void Display::drawString(const char *string, int32_t poX, int32_t poY, int16_t c * * @return Nothing. */ -void Display::drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t color) -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - esp3d_screen.drawLine(x0, y0, x1, y1,color); +void Display::drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, + int16_t color) { + esp3d_screen.drawLine(x0, y0, x1, y1, color); } - /** * > Draw a rectangle on the screen * @@ -294,12 +262,9 @@ void Display::drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t c * * @return Nothing. */ -void Display::drawRect(int16_t x, int16_t y, int16_t width, int16_t height, int16_t color) -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - esp3d_screen.drawRect(x, y, width, height, color); +void Display::drawRect(int16_t x, int16_t y, int16_t width, int16_t height, + int16_t color) { + esp3d_screen.drawRect(x, y, width, height, color); } /** @@ -313,12 +278,9 @@ void Display::drawRect(int16_t x, int16_t y, int16_t width, int16_t height, int1 * * @return Nothing. */ -void Display::fillRect(int16_t x, int16_t y, int16_t width, int16_t height, int16_t color) -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - esp3d_screen.fillRect(x, y, width, height, color); +void Display::fillRect(int16_t x, int16_t y, int16_t width, int16_t height, + int16_t color) { + esp3d_screen.fillRect(x, y, width, height, color); } /** @@ -333,12 +295,9 @@ void Display::fillRect(int16_t x, int16_t y, int16_t width, int16_t height, int1 * * @return Nothing. */ -void Display::drawXbm(int16_t x, int16_t y, int16_t width, int16_t height, int16_t color, const uint8_t *xbm) -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - esp3d_screen.drawXBitmap(x, y, xbm, width, height,color); +void Display::drawXbm(int16_t x, int16_t y, int16_t width, int16_t height, + int16_t color, const uint8_t *xbm) { + esp3d_screen.drawXBitmap(x, y, xbm, width, height, color); } /** @@ -353,417 +312,416 @@ void Display::drawXbm(int16_t x, int16_t y, int16_t width, int16_t height, int16 * @param xbm the xbm image data * */ -void Display::drawXbm(int16_t x, int16_t y, int16_t width, int16_t height, uint16_t fgcolor, uint16_t bgcolor, const uint8_t *xbm) -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - (void)fgcolor; - (void)bgcolor; - esp3d_screen.drawXBitmap(x, y, xbm, width, height,fgcolor,bgcolor); +void Display::drawXbm(int16_t x, int16_t y, int16_t width, int16_t height, + uint16_t fgcolor, uint16_t bgcolor, const uint8_t *xbm) { + (void)fgcolor; + (void)bgcolor; + esp3d_screen.drawXBitmap(x, y, xbm, width, height, fgcolor, bgcolor); } /** - * The function is called with a value between 0 and 100. The function draws a rectangle on the screen - * with a width that is proportional to the value + * The function is called with a value between 0 and 100. The function draws a + * rectangle on the screen with a width that is proportional to the value * * @param v The percentage of the progress bar to fill. * * @return the value of the variable v. */ -void Display::progress(uint8_t v) -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - static uint8_t previous = 0; - if (previous > v) { - //clear - fillRect(10, _screenHeight-4, _screenWidth-20, 4, SCREEN_BG); - } - log_esp3d("%d", v); - previous = v>100?100:v; - //display bar - fillRect(10, _screenHeight-4, ((_screenWidth-20) * v)/100, 4, PROGRESS_FG); - //update screen - updateScreen(true); +void Display::progress(uint8_t v) { + static uint8_t previous = 0; + if (previous > v) { + // clear + fillRect(10, _screenHeight - 4, _screenWidth - 20, 4, SCREEN_BG); + } + esp3d_log("%d", v); + previous = v > 100 ? 100 : v; + // display bar + fillRect(10, _screenHeight - 4, ((_screenWidth - 20) * v) / 100, 4, + PROGRESS_FG); + // update screen + updateScreen(true); } /** - * If the display is not busy, then check if the signal strength has changed, if so, then display it. - * If the IP address has changed, then display it. If the status has changed, then display it + * If the display is not busy, then check if the signal strength has changed, if + * so, then display it. If the IP address has changed, then display it. If the + * status has changed, then display it * - * @param force boolean, if true, the screen will be updated regardless of whether or not it needs to - * be. + * @param force boolean, if true, the screen will be updated regardless of + * whether or not it needs to be. * * @return A boolean value. */ -bool Display::mainScreenHandler(bool force) -{ - bool res = false; - if (displaySignal(force)) { - res = true; - } - if (displayIP(force)) { - res = true; - } - if (showStatus(force)) { - res = true; - } - return res; +bool Display::mainScreenHandler(bool force) { + bool res = false; + if (displaySignal(force)) { + res = true; + } + if (displayIP(force)) { + res = true; + } + if (showStatus(force)) { + res = true; + } + return res; } /** - * If the screen is connected, and the splash screen has not been displayed, then display the splash - * screen + * If the screen is connected, and the splash screen has not been displayed, + * then display the splash screen * * @return a boolean value. */ -bool Display::splash() -{ - log_esp3d("Splash"); - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return false; - } - if (!_splashDone) { - drawXbm((_screenWidth-ESP3D_Logo_width)/2, (_screenHeight-ESP3D_Logo_height)/2, ESP3D_Logo_width, ESP3D_Logo_height, SPLASH_FG, SPLASH_BG,ESP3D_Logo); - log_esp3d("Display Splash"); - _splashDone = true; - return true; - } - return false; +bool Display::splash() { + esp3d_log("Splash"); + + if (!_splashDone) { + drawXbm((_screenWidth - ESP3D_Logo_width) / 2, + (_screenHeight - ESP3D_Logo_height) / 2, ESP3D_Logo_width, + ESP3D_Logo_height, SPLASH_FG, SPLASH_BG, ESP3D_Logo); + esp3d_log("Display Splash"); + _splashDone = true; + return true; + } + return false; } -void Display::updateIP() -{ - if ( !ESP3DOutput::isOutput(ESP_SCREEN_CLIENT)) { - return; - } - updateScreen(true); -} +void Display::updateIP() { updateScreen(true); } /** - * It takes a string, and if it's too long to fit in the status area, it chops it up into pieces and - * displays them one at a time + * It takes a string, and if it's too long to fit in the status area, it chops + * it up into pieces and displays them one at a time * - * @param force if true, the status will be redrawn regardless of whether it's changed or not. + * @param force if true, the status will be redrawn regardless of whether it's + * changed or not. * * @return a boolean value. */ -bool Display::showStatus(bool force) -{ - //Display Status - bool refresh_status = force; - static String status; - if (status != _status) { - status = _status; - refresh_status = true; - } +bool Display::showStatus(bool force) { + // Display Status + bool refresh_status = force; + static String status; + if (status != _status) { + status = _status; + refresh_status = true; + } - setTextFont(FONTSTATUS); - uint16_t size = sizetoFitSpace(status.c_str(), STATUS_AREA_W); - //check the need for resize + setTextFont(FONTSTATUS); + uint16_t size = sizetoFitSpace(status.c_str(), STATUS_AREA_W); + // check the need for resize + if (size < status.length()) { + static int status_shift = -1; + refresh_status = true; + status += " "; + esp3d_log("current %s", status.c_str()); + if (status_shift != -1) { + if ((uint16_t)(status_shift) > status.length()) { + status_shift = -1; + } + } + esp3d_log("shift %d", status_shift); + if (status_shift > 0) { + status.remove(0, status_shift); + } + esp3d_log("shifted %s", status.c_str()); + size = sizetoFitSpace(status.c_str(), STATUS_AREA_W); + esp3d_log("size available %d existing %d", size, status.length()); if (size < status.length()) { - static int status_shift = -1; - refresh_status = true; - status+=" "; - log_esp3d("current %s", status.c_str()); - if (status_shift != -1) { - if( (uint16_t)(status_shift)> status.length()) { - status_shift = -1; - } - } - log_esp3d("shift %d", status_shift); - if (status_shift > 0) { - status.remove(0,status_shift); - } - log_esp3d("shifted %s", status.c_str()); - size = sizetoFitSpace(status.c_str(), STATUS_AREA_W); - log_esp3d("size available %d existing %d",size, status.length()); - if (size < status.length()) { - //cut - status = status.substring(0,size); - status_shift++; - } else { - status_shift = -1; - } - log_esp3d("sized %s", status.c_str()); + // cut + status = status.substring(0, size); + status_shift++; + } else { + status_shift = -1; } - if (refresh_status) { - //clear area - fillRect(STATUS_AREA_X, STATUS_AREA_Y, STATUS_AREA_W, STATUS_AREA_H, SCREEN_BG); - drawString(status.c_str(), STATUS_AREA_X, STATUS_AREA_Y, STATUS_FG); - } - return refresh_status; + esp3d_log("sized %s", status.c_str()); + } + if (refresh_status) { + // clear area + fillRect(STATUS_AREA_X, STATUS_AREA_Y, STATUS_AREA_W, STATUS_AREA_H, + SCREEN_BG); + drawString(status.c_str(), STATUS_AREA_X, STATUS_AREA_Y, STATUS_FG); + } + return refresh_status; } -bool Display::displaySignal(bool force) -{ - static int sig = -1; - bool refresh_signal = false; - bool refresh_label = false; - static String label; -#if defined (WIFI_FEATURE) - if (WiFiConfig::started()) { - - if (WiFi.getMode() == WIFI_AP) { - if (sig != 100) { - sig = 100; - refresh_signal = true; - } - if (label != WiFiConfig::AP_SSID()) { - label = WiFiConfig::AP_SSID(); - refresh_label = true; - } - } else { - if (WiFi.isConnected()) { - int sigtmp = WiFiConfig::getSignal (WiFi.RSSI (),false); - if (sig != sigtmp) { - sig =sigtmp; - refresh_signal = true; - } - if (label != WiFi.SSID()) { - label = WiFi.SSID(); - refresh_label = true; - } - } else { - if (sig != -1) { - sig = -1; - refresh_signal = true; - } - if (label != "") { - label = ""; - refresh_label = true; - } - } - } - //Display SSID - setTextFont(FONTSSID); - uint16_t size = sizetoFitSpace(label.c_str(), SSID_AREA_W); - //check the need for resize - if (size < label.length()) { - refresh_label = true; - static int label_shift = -1; - label+=" "; - //log_esp3d("current %s", label.c_str()); - if (label_shift != -1) { - if((uint16_t)(label_shift)> label.length()) { - label_shift = -1; - } - } - //log_esp3d("shift %d", label_shift); - if (label_shift > 0) { - label.remove(0,label_shift); - } - //log_esp3d("shifted %s", label.c_str()); - size = sizetoFitSpace(label.c_str(), SSID_AREA_W); - //log_esp3d("size available %d existing %d",size, label.length()); - if (size < label.length()) { - //cut - label = label.substring(0,size); - label_shift++; - } else { - label_shift = -1; - } - //log_esp3d("sized %s", label.c_str()); - } - if (refresh_label || force) { - //clear area - fillRect(SSID_AREA_X, SSID_AREA_Y, SSID_AREA_W, SSID_AREA_H, SCREEN_BG); - drawString(label.c_str(), SSID_AREA_X, SSID_AREA_Y, SSID_FG); - } - } -#endif // WIFI_FEATURE - -#if defined (ETH_FEATURE) - if (EthConfig::started()) { - if (sig != -2) { - sig = -2; - refresh_signal = true; - } - //display connection speed - if(EthConfig::linkUp()) { - String tmp = ETH.linkSpeed(); - tmp+= "Mbps"; - if (label != tmp) { - label = tmp; - refresh_label = true; - } - } else { - if (label !="") { - label =""; - refresh_label = true; - } - } - if (refresh_label || force) { - setTextFont(FONTSSID); - //clear area - fillRect(SSID_AREA_X, SSID_AREA_Y, SSID_AREA_W, SSID_AREA_H, SCREEN_BG); - drawString(label.c_str(), SSID_AREA_X, SSID_AREA_Y, SSID_FG); - } - } -#endif //ETH_FEATURE - -#if defined (BLUETOOTH_FEATURE) - if (bt_service.started()) { - if (sig!=-3) { - sig = -3; - refresh_signal = true; - } - - //Display hostname - if (label != bt_service.hostname()) { - refresh_label = true; - label = bt_service.hostname(); - } - setTextFont(FONTSSID); - uint16_t size = sizetoFitSpace(label.c_str(), SSID_AREA_W); - //check the need for resize - if (size < label.length()) { - refresh_label = true; - static int label_shift = -1; - label+=" "; - //log_esp3d("current %s", hostname.c_str()); - if (label_shift > label.length()) { - label_shift = -1; - } - //log_esp3d("shift %d", label_shift); - if (label_shift > 0) { - label.remove(0,label_shift); - } - //log_esp3d("shifted %s", hostname.c_str()); - size = sizetoFitSpace(label.c_str(), SSID_AREA_W); - //log_esp3d("size available %d existing %d",size, hostname.length()); - if (size < label.length()) { - //cut - label = label.substring(0,size); - label_shift++; - } else { - label_shift = -1; - } - //log_esp3d("sized %s", hostname.c_str()); - } - if( refresh_label || force) { - //clear area - fillRect(SSID_AREA_X, SSID_AREA_Y, SSID_AREA_W, SSID_AREA_H, SCREEN_BG); - if (label.length()>0) { - drawString(label.c_str(), SSID_AREA_X, SSID_AREA_Y, SSID_FG); - } - } - } -#endif //BLUETOOTH_FEATURE - String s; - if (refresh_signal || force) { - - //set current font size - setTextFont(FONTSIGNAL); - fillRect(SIGNAL_X, SIGNAL_Y, SIGNAL_W, SIGNAL_H,SCREEN_BG); - fillRect(SIGNAL_ICON_X, SIGNAL_ICON_Y, SIGNAL_ICON_W, SIGNAL_ICON_H,SCREEN_BG); - if (sig > 0) { - //Signal % - s = String(sig); - s+="%"; - //Signal Icon according % - if (sig > 0) { - fillRect(SIGNAL_ICON_X, SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.6), SIGNAL_ICON_W_BAR, SIGNAL_ICON_H * 0.4, SIGNAL_FG); - } else { - drawRect(SIGNAL_ICON_X, SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.6), SIGNAL_ICON_W_BAR, SIGNAL_ICON_H * 0.4, SIGNAL_FG); - } - - if (sig >= 25) { - fillRect(SIGNAL_ICON_X + SIGNAL_ICON_SPACER_X +SIGNAL_ICON_W_BAR, SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.4), SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H * 0.6), SIGNAL_FG); - } else { - drawRect(SIGNAL_ICON_X + SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR, SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.4), SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H * 0.6), SIGNAL_FG); - } - - if (sig >= 50) { - fillRect(SIGNAL_ICON_X + (2*(SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.2), SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H * 0.8), SIGNAL_FG); - } else { - drawRect(SIGNAL_ICON_X + (2*(SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.2), SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H * 0.8), SIGNAL_FG); - } - - if (sig >= 75) { - fillRect(SIGNAL_ICON_X + (3*(SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), SIGNAL_ICON_Y, SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H), SIGNAL_FG); - } else { - drawRect(SIGNAL_ICON_X + (3*(SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), SIGNAL_ICON_Y, SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H), SIGNAL_FG); - } - - } - //No signal / no connection - if (sig == -1) { - s = " X"; - } - //Ethernet is connected - if (sig == -2) { - s = "Eth"; - } - //BT is active - if (sig == -3) { - s = "BT"; - } - //Show Connection type - drawString(s.c_str(), SIGNAL_X, SIGNAL_Y, SIGNAL_FG); - } - if (refresh_signal || refresh_label || force) { - return true; +bool Display::displaySignal(bool force) { + static int sig = -1; + bool refresh_signal = false; + bool refresh_label = false; + static String label; +#if defined(WIFI_FEATURE) + if (WiFiConfig::started()) { + if (WiFi.getMode() == WIFI_AP) { + if (sig != 100) { + sig = 100; + refresh_signal = true; + } + if (label != WiFiConfig::AP_SSID()) { + label = WiFiConfig::AP_SSID(); + refresh_label = true; + } } else { - return false; - } -} - -bool Display::displayIP(bool force) -{ - bool refresh_label = force; - static String label; -#if defined (WIFI_FEATURE) || defined (ETH_FEATURE) || defined (BLUETOOTH_FEATURE) - if (NetConfig::started()) { - String s; - switch(NetConfig::getMode()) { -#if defined (WIFI_FEATURE) - case ESP_WIFI_STA: - s = WiFi.localIP().toString(); - break; - case ESP_AP_SETUP: - case ESP_WIFI_AP: - s = WiFi.softAPIP().toString(); - break; -#endif //WIFI_FEATURE -#if defined (ETH_FEATURE) - case ESP_ETH_STA: - s = ETH.localIP().toString(); - break; -#endif //ETH_FEATURE -#if defined (BLUETOOTH_FEATURE) - case ESP_BT: - s = bt_service.isConnected()?"Connected":""; - break; -#endif //BLUETOOTH_FEATURE - default: - s=""; - log_esp3d("Unknown mode %d", NetConfig::getMode()); - break; + if (WiFi.isConnected()) { + int sigtmp = WiFiConfig::getSignal(WiFi.RSSI(), false); + if (sig != sigtmp) { + sig = sigtmp; + refresh_signal = true; } - if (s!= label) { - label = s; - refresh_label = true; + if (label != WiFi.SSID()) { + label = WiFi.SSID(); + refresh_label = true; } - if (refresh_label) { - if (label.length()>0) { - setTextFont(FONTIP); - fillRect(IP_AREA_X, IP_AREA_Y, IP_AREA_W, IP_AREA_H, SCREEN_BG); - drawString(label.c_str(), IP_AREA_X, IP_AREA_Y, IP_FG); - } - + } else { + if (sig != -1) { + sig = -1; + refresh_signal = true; } - } else { if (label != "") { - label = ""; - refresh_label = true; - fillRect(IP_AREA_X, IP_AREA_Y, IP_AREA_W, IP_AREA_H, SCREEN_BG); + label = ""; + refresh_label = true; } + } } -#endif //WIFI_FEATURE || ETH_FEATURE || BLUETOOTH_FEATURE - return refresh_label; + // Display SSID + setTextFont(FONTSSID); + uint16_t size = sizetoFitSpace(label.c_str(), SSID_AREA_W); + // check the need for resize + if (size < label.length()) { + refresh_label = true; + static int label_shift = -1; + label += " "; + // esp3d_log("current %s", label.c_str()); + if (label_shift != -1) { + if ((uint16_t)(label_shift) > label.length()) { + label_shift = -1; + } + } + // esp3d_log("shift %d", label_shift); + if (label_shift > 0) { + label.remove(0, label_shift); + } + // esp3d_log("shifted %s", label.c_str()); + size = sizetoFitSpace(label.c_str(), SSID_AREA_W); + // esp3d_log("size available %d existing %d",size, label.length()); + if (size < label.length()) { + // cut + label = label.substring(0, size); + label_shift++; + } else { + label_shift = -1; + } + // esp3d_log("sized %s", label.c_str()); + } + if (refresh_label || force) { + // clear area + fillRect(SSID_AREA_X, SSID_AREA_Y, SSID_AREA_W, SSID_AREA_H, SCREEN_BG); + drawString(label.c_str(), SSID_AREA_X, SSID_AREA_Y, SSID_FG); + } + } +#endif // WIFI_FEATURE + +#if defined(ETH_FEATURE) + if (EthConfig::started()) { + if (sig != -2) { + sig = -2; + refresh_signal = true; + } + // display connection speed + if (EthConfig::linkUp()) { + String tmp = ETH.linkSpeed(); + tmp += "Mbps"; + if (label != tmp) { + label = tmp; + refresh_label = true; + } + } else { + if (label != "") { + label = ""; + refresh_label = true; + } + } + if (refresh_label || force) { + setTextFont(FONTSSID); + // clear area + fillRect(SSID_AREA_X, SSID_AREA_Y, SSID_AREA_W, SSID_AREA_H, SCREEN_BG); + drawString(label.c_str(), SSID_AREA_X, SSID_AREA_Y, SSID_FG); + } + } +#endif // ETH_FEATURE + +#if defined(BLUETOOTH_FEATURE) + if (bt_service.started()) { + if (sig != -3) { + sig = -3; + refresh_signal = true; + } + + // Display hostname + if (label != bt_service.hostname()) { + refresh_label = true; + label = bt_service.hostname(); + } + setTextFont(FONTSSID); + uint16_t size = sizetoFitSpace(label.c_str(), SSID_AREA_W); + // check the need for resize + if (size < label.length()) { + refresh_label = true; + static int label_shift = -1; + label += " "; + // esp3d_log("current %s", hostname.c_str()); + if (label_shift > label.length()) { + label_shift = -1; + } + // esp3d_log("shift %d", label_shift); + if (label_shift > 0) { + label.remove(0, label_shift); + } + // esp3d_log("shifted %s", hostname.c_str()); + size = sizetoFitSpace(label.c_str(), SSID_AREA_W); + // esp3d_log("size available %d existing %d",size, hostname.length()); + if (size < label.length()) { + // cut + label = label.substring(0, size); + label_shift++; + } else { + label_shift = -1; + } + // esp3d_log("sized %s", hostname.c_str()); + } + if (refresh_label || force) { + // clear area + fillRect(SSID_AREA_X, SSID_AREA_Y, SSID_AREA_W, SSID_AREA_H, SCREEN_BG); + if (label.length() > 0) { + drawString(label.c_str(), SSID_AREA_X, SSID_AREA_Y, SSID_FG); + } + } + } +#endif // BLUETOOTH_FEATURE + String s; + if (refresh_signal || force) { + // set current font size + setTextFont(FONTSIGNAL); + fillRect(SIGNAL_X, SIGNAL_Y, SIGNAL_W, SIGNAL_H, SCREEN_BG); + fillRect(SIGNAL_ICON_X, SIGNAL_ICON_Y, SIGNAL_ICON_W, SIGNAL_ICON_H, + SCREEN_BG); + if (sig > 0) { + // Signal % + s = String(sig); + s += "%"; + // Signal Icon according % + if (sig > 0) { + fillRect(SIGNAL_ICON_X, SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.6), + SIGNAL_ICON_W_BAR, SIGNAL_ICON_H * 0.4, SIGNAL_FG); + } else { + drawRect(SIGNAL_ICON_X, SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.6), + SIGNAL_ICON_W_BAR, SIGNAL_ICON_H * 0.4, SIGNAL_FG); + } + + if (sig >= 25) { + fillRect(SIGNAL_ICON_X + SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR, + SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.4), SIGNAL_ICON_W_BAR, + (SIGNAL_ICON_H * 0.6), SIGNAL_FG); + } else { + drawRect(SIGNAL_ICON_X + SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR, + SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.4), SIGNAL_ICON_W_BAR, + (SIGNAL_ICON_H * 0.6), SIGNAL_FG); + } + + if (sig >= 50) { + fillRect( + SIGNAL_ICON_X + (2 * (SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), + SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.2), SIGNAL_ICON_W_BAR, + (SIGNAL_ICON_H * 0.8), SIGNAL_FG); + } else { + drawRect( + SIGNAL_ICON_X + (2 * (SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), + SIGNAL_ICON_Y + (SIGNAL_ICON_H * 0.2), SIGNAL_ICON_W_BAR, + (SIGNAL_ICON_H * 0.8), SIGNAL_FG); + } + + if (sig >= 75) { + fillRect( + SIGNAL_ICON_X + (3 * (SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), + SIGNAL_ICON_Y, SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H), SIGNAL_FG); + } else { + drawRect( + SIGNAL_ICON_X + (3 * (SIGNAL_ICON_SPACER_X + SIGNAL_ICON_W_BAR)), + SIGNAL_ICON_Y, SIGNAL_ICON_W_BAR, (SIGNAL_ICON_H), SIGNAL_FG); + } + } + // No signal / no connection + if (sig == -1) { + s = " X"; + } + // Ethernet is connected + if (sig == -2) { + s = "Eth"; + } + // BT is active + if (sig == -3) { + s = "BT"; + } + // Show Connection type + drawString(s.c_str(), SIGNAL_X, SIGNAL_Y, SIGNAL_FG); + } + if (refresh_signal || refresh_label || force) { + return true; + } else { + return false; + } } -#endif //DISPLAY_DEVICE && DISPLAY_DEVICE == OLED_I2C_SSD1306_128X64 +bool Display::displayIP(bool force) { + bool refresh_label = force; + static String label; +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BLUETOOTH_FEATURE) + if (NetConfig::started()) { + String s; + switch (NetConfig::getMode()) { +#if defined(WIFI_FEATURE) + case ESP_WIFI_STA: + s = WiFi.localIP().toString(); + break; + case ESP_AP_SETUP: + case ESP_WIFI_AP: + s = WiFi.softAPIP().toString(); + break; +#endif // WIFI_FEATURE +#if defined(ETH_FEATURE) + case ESP_ETH_STA: + s = ETH.localIP().toString(); + break; +#endif // ETH_FEATURE +#if defined(BLUETOOTH_FEATURE) + case ESP_BT: + s = bt_service.isConnected() ? "Connected" : ""; + break; +#endif // BLUETOOTH_FEATURE + default: + s = ""; + esp3d_log("Unknown mode %d", NetConfig::getMode()); + break; + } + if (s != label) { + label = s; + refresh_label = true; + } + if (refresh_label) { + if (label.length() > 0) { + setTextFont(FONTIP); + fillRect(IP_AREA_X, IP_AREA_Y, IP_AREA_W, IP_AREA_H, SCREEN_BG); + drawString(label.c_str(), IP_AREA_X, IP_AREA_Y, IP_FG); + } + } + } else { + if (label != "") { + label = ""; + refresh_label = true; + fillRect(IP_AREA_X, IP_AREA_Y, IP_AREA_W, IP_AREA_H, SCREEN_BG); + } + } +#endif // WIFI_FEATURE || ETH_FEATURE || BLUETOOTH_FEATURE + return refresh_label; +} + +#endif // DISPLAY_DEVICE && DISPLAY_DEVICE == OLED_I2C_SSD1306_128X64 diff --git a/esp3d/src/modules/display/display.cpp b/esp3d/src/modules/display/display.cpp index d020299d..e630015a 100644 --- a/esp3d/src/modules/display/display.cpp +++ b/esp3d/src/modules/display/display.cpp @@ -19,6 +19,42 @@ */ #include "../../include/esp3d_config.h" -#if defined (DISPLAY_DEVICE) -//TBD -#endif //DISPLAY_DEVICE \ No newline at end of file + +#if defined(DISPLAY_DEVICE) +#include "display.h" +bool Display::dispatch(ESP3DMessage* message) { + if (!message || !_started) { + return false; + } + if (message->size > 0 && message->data) { + switch (message->request_id.id) { + case ESP_OUTPUT_IP_ADDRESS: + updateIP(); + break; + case ESP_OUTPUT_STATUS: + setStatus((const char*)message->data); + break; + case ESP_OUTPUT_PROGRESS: + progress((uint8_t)atoi((const char*)message->data)); + break; + case ESP_OUTPUT_STATE: + switch (atoi((const char*)message->data)) { + case ESP_STATE_DISCONNECTED: + setStatus("Disconnected"); + break; + default: + return false; + break; + } + break; + default: + return false; + break; + } + + ESP3DMessageManager::deleteMsg(message); + return true; + } + return false; +} +#endif // DISPLAY_DEVICE \ No newline at end of file diff --git a/esp3d/src/modules/display/display.h b/esp3d/src/modules/display/display.h index 8d41ac99..d1209634 100644 --- a/esp3d/src/modules/display/display.h +++ b/esp3d/src/modules/display/display.h @@ -18,56 +18,61 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#define SPLASH_SCREEN 0 -#define MAIN_SCREEN 1 -#define CALIBRATION_SCREEN 2 +#define SPLASH_SCREEN 0 +#define MAIN_SCREEN 1 +#define CALIBRATION_SCREEN 2 #ifndef _DISPLAY_CLASS_H #define _DISPLAY_CLASS_H +#include "../../core/esp3d_message.h" -class Display -{ -public: - Display(); - ~Display(); - bool begin(); - void end(); - void handle(); - void showScreenID(uint8_t screenID); - void updateScreen(bool force=false); - void clearScreen(); - void progress(uint8_t v); - void setStatus(const char * status); - void updateIP(); - const char * getModelString(); - uint8_t getModelID(); +class Display { + public: + Display(); + ~Display(); + bool begin(); + void end(); + void handle(); + void showScreenID(uint8_t screenID); + void updateScreen(bool force = false); + void clearScreen(); + void progress(uint8_t v); + void setStatus(const char *status); + void updateIP(); + const char *getModelString(); + uint8_t getModelID(); + bool dispatch(ESP3DMessage *message); #if defined(DISPLAY_TOUCH_DRIVER) - bool startCalibration(); -#endif //DISPLAY_TOUCH_DRIVER -private: - bool mainScreenHandler(bool force = false); - bool displaySignal(bool force = false); - bool displayIP(bool force = false); - bool splash(); - bool showStatus(bool force = false); - bool _started; - uint8_t _screenID; - bool _splashDone; - uint _screenWidth; - uint _screenHeight; - uint16_t sizetoFitSpace(const char * string, uint16_t maxwidth); - void drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t color); - void drawRect(int16_t x, int16_t y, int16_t width, int16_t height, int16_t color); - void fillRect(int16_t x, int16_t y, int16_t width, int16_t height, int16_t color); - void setTextFont(uint8_t font); - void drawString(const char *string, int32_t poX, int32_t poY, int16_t color); - void drawXbm(int16_t x, int16_t y, int16_t width, int16_t height, int16_t color, const uint8_t *xbm); - void drawXbm(int16_t x, int16_t y, int16_t width, int16_t height, uint16_t fgcolor, uint16_t bgcolor, const uint8_t *xbm); - uint16_t getStringWidth(const char* text); - uint8_t _font; - String _status; + bool startCalibration(); +#endif // DISPLAY_TOUCH_DRIVER + private: + bool mainScreenHandler(bool force = false); + bool displaySignal(bool force = false); + bool displayIP(bool force = false); + bool splash(); + bool showStatus(bool force = false); + bool _started; + uint8_t _screenID; + bool _splashDone; + uint _screenWidth; + uint _screenHeight; + uint16_t sizetoFitSpace(const char *string, uint16_t maxwidth); + void drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t color); + void drawRect(int16_t x, int16_t y, int16_t width, int16_t height, + int16_t color); + void fillRect(int16_t x, int16_t y, int16_t width, int16_t height, + int16_t color); + void setTextFont(uint8_t font); + void drawString(const char *string, int32_t poX, int32_t poY, int16_t color); + void drawXbm(int16_t x, int16_t y, int16_t width, int16_t height, + int16_t color, const uint8_t *xbm); + void drawXbm(int16_t x, int16_t y, int16_t width, int16_t height, + uint16_t fgcolor, uint16_t bgcolor, const uint8_t *xbm); + uint16_t getStringWidth(const char *text); + uint8_t _font; + String _status; }; extern Display esp3d_display; -#endif //_DISPLAY_CLASS_H +#endif //_DISPLAY_CLASS_H diff --git a/esp3d/src/modules/ethernet/ethconfig.cpp b/esp3d/src/modules/ethernet/ethconfig.cpp index b9c981bd..413a6e57 100644 --- a/esp3d/src/modules/ethernet/ethconfig.cpp +++ b/esp3d/src/modules/ethernet/ethconfig.cpp @@ -27,8 +27,8 @@ #endif // ARDUINO_ARCH_ESP32 #ifdef ARDUINO_ARCH_ESP8266 #endif // ARDUINO_ARCH_ESP8266 -#include "../../core/esp3doutput.h" -#include "../../core/settings_esp3d.h" +#include "../../core/esp3d_commands.h" +#include "../../core/esp3d_settings.h" #include "../network/netconfig.h" #include "ethconfig.h" bool EthConfig::_started = false; @@ -37,11 +37,11 @@ const uint8_t DEFAULT_AP_MASK_VALUE[] = {255, 255, 255, 0}; bool EthConfig::StartSTA() { bool res = true; - if ((Settings_ESP3D::read_byte(ESP_STA_IP_MODE) != DHCP_MODE)) { - int32_t IP = Settings_ESP3D::read_IP(ESP_STA_IP_VALUE); - int32_t GW = Settings_ESP3D::read_IP(ESP_STA_GATEWAY_VALUE); - int32_t MK = Settings_ESP3D::read_IP(ESP_STA_MASK_VALUE); - int32_t DNS = Settings_ESP3D::read_IP(ESP_STA_DNS_VALUE); + if ((ESP3DSettings::readByte(ESP_STA_IP_MODE) != DHCP_MODE)) { + int32_t IP = ESP3DSettings::read_IP(ESP_STA_IP_VALUE); + int32_t GW = ESP3DSettings::read_IP(ESP_STA_GATEWAY_VALUE); + int32_t MK = ESP3DSettings::read_IP(ESP_STA_MASK_VALUE); + int32_t DNS = ESP3DSettings::read_IP(ESP_STA_DNS_VALUE); IPAddress ip(IP), mask(MK), gateway(GW), dns(DNS); res = ETH.config(ip, gateway, mask, dns); } @@ -51,11 +51,11 @@ bool EthConfig::StartSTA() { { bool res = true; //static IP - int32_t IP = Settings_ESP3D::read_IP(ESP_AP_IP_VALUE); + int32_t IP = ESP3DSettings::read_IP(ESP_AP_IP_VALUE); IPAddress ip(IP), mask(DEFAULT_AP_MASK_VALUE), gateway(IP); if (!ETH.config(ip, gateway,mask)) { res = false; - log_esp3d_e("Set static IP error"); + esp3d_log_e("Set static IP error"); } //start DHCP server if(res) { @@ -72,7 +72,7 @@ bool EthConfig::StartSTA() { if (tcpip_adapter_dhcps_start(TCPIP_ADAPTER_IF_ETH) != ESP_OK){ res = false; - log_esp3d_e("Start DHCP server failed"); + esp3d_log_e("Start DHCP server failed"); } } return res; @@ -92,47 +92,62 @@ bool EthConfig::linkUp() { */ bool EthConfig::begin(int8_t& espMode) { bool res = false; - ESP3DOutput output(ESP_ALL_CLIENTS); + end(); _started = ETH.begin(); if (_started) { - if (Settings_ESP3D::isVerboseBoot()) { - output.printMSG("Starting Ethernet"); + if (ESP3DSettings::isVerboseBoot()) { + esp3d_commands.dispatch("Starting ethernet", ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } res = true; } else { - output.printERROR("Failed Starting Ethernet"); + esp3d_commands.dispatch("Failed starting ethernet write failed", + ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } ETH.setHostname(NetConfig::hostname(true)); // DHCP is only for Client if (espMode == ESP_ETH_STA) { if (!StartSTA()) { - if (Settings_ESP3D::isVerboseBoot()) { - output.printMSG("Starting fallback mode"); + if (ESP3DSettings::isVerboseBoot()) { + esp3d_commands.dispatch( + "Starting fallback mode", ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } - espMode = Settings_ESP3D::read_byte(ESP_STA_FALLBACK_MODE); + espMode = ESP3DSettings::readByte(ESP_STA_FALLBACK_MODE); res = true; } else { - if (Settings_ESP3D::isVerboseBoot()) { - output.printMSG("Client started"); + if (ESP3DSettings::isVerboseBoot()) { + esp3d_commands.dispatch("Client started", ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } } } else { // if(!StartSRV()){ // res = false; - // output.printMSG ("Failed Starting Server"); + // // } else { - // output.printMSG ("Server started"); + // // } } - // if ((Settings_ESP3D::read_byte(ESP_STA_IP_MODE) != DHCP_MODE) || (espMode + // if ((ESP3DSettings::readByte(ESP_STA_IP_MODE) != DHCP_MODE) || (espMode // == ESP_ETH_SRV)){ - if ((Settings_ESP3D::read_byte(ESP_STA_IP_MODE) != DHCP_MODE)) { + if ((ESP3DSettings::readByte(ESP_STA_IP_MODE) != DHCP_MODE)) { // as no event to display static IP - output.printMSG(ETH.localIP().toString().c_str()); + esp3d_commands.dispatch(ETH.localIP().toString().c_str(), + ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } return res; diff --git a/esp3d/src/modules/filesystem/esp_filesystem.cpp b/esp3d/src/modules/filesystem/esp_filesystem.cpp index 05530b7d..027baa4c 100644 --- a/esp3d/src/modules/filesystem/esp_filesystem.cpp +++ b/esp3d/src/modules/filesystem/esp_filesystem.cpp @@ -19,205 +19,162 @@ */ #include "../../include/esp3d_config.h" #ifdef FILESYSTEM_FEATURE -#include "esp_filesystem.h" -#include #include +#include + +#include "esp_filesystem.h" + #ifdef ARDUINO_ARCH_ESP32 #include -#endif //ARDUINO_ARCH_ESP32 +#endif // ARDUINO_ARCH_ESP32 #define ESP_MAX_OPENHANDLE 4 File tFile_handle[ESP_MAX_OPENHANDLE]; bool ESP_FileSystem::_started = false; -uint8_t ESP_FileSystem::getFSType(const char * path) -{ - (void)path; - return FS_FLASH; +uint8_t ESP_FileSystem::getFSType(const char* path) { + (void)path; + return FS_FLASH; } -//helper to format size to readable string -String & ESP_FileSystem::formatBytes (uint64_t bytes) -{ - static String res; - if (bytes < 1024) { - res = String ((uint16_t)bytes) + " B"; - } else if (bytes < (1024 * 1024) ) { - res = String ((float)(bytes / 1024.0),2) + " KB"; - } else if (bytes < (1024 * 1024 * 1024) ) { - res = String ((float)(bytes / 1024.0 / 1024.0),2) + " MB"; - } else { - res = String ((float)(bytes / 1024.0 / 1024.0 / 1024.0),2) + " GB"; +bool ESP_FileSystem::accessFS(uint8_t FS) { + (void)FS; + if (!_started) { + _started = begin(); + } + return _started; +} +void ESP_FileSystem::releaseFS(uint8_t FS) { + // nothing to do + (void)FS; +} + +size_t ESP_FileSystem::max_update_size() { + size_t flashsize = 0; +#if defined(ARDUINO_ARCH_ESP8266) + flashsize = ESP.getFlashChipSize(); + // if higher than 1MB or not (no more support for 512KB flash) + if (flashsize <= 1024 * 1024) { + flashsize = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000; + } else { + flashsize = flashsize - ESP.getSketchSize() - totalBytes() - 1024; + // max OTA partition is 1019Kb + if (flashsize > 1024 * 1024) { + flashsize = (1024 * 1024) - 1024; } - return res; -} - -bool ESP_FileSystem::accessFS(uint8_t FS) -{ - (void)FS; - if (!_started) { - _started = begin(); + } +#endif // ARDUINO_ARCH_ESP8266 +#if defined(ARDUINO_ARCH_ESP32) + // Is OTA available ? + const esp_partition_t* mainpartition = esp_ota_get_running_partition(); + if (mainpartition) { + const esp_partition_t* partition = + esp_ota_get_next_update_partition(mainpartition); + if (partition) { + const esp_partition_t* partition2 = + esp_ota_get_next_update_partition(partition); + if (partition2 && (partition->address != partition2->address)) { + flashsize = partition2->size; + } } - return _started; -} -void ESP_FileSystem::releaseFS(uint8_t FS) -{ - //nothing to do - (void)FS; + } +#endif // ARDUINO_ARCH_ESP32 + return flashsize; } -size_t ESP_FileSystem::max_update_size() -{ - size_t flashsize = 0; -#if defined (ARDUINO_ARCH_ESP8266) - flashsize = ESP.getFlashChipSize(); - //if higher than 1MB or not (no more support for 512KB flash) - if (flashsize <= 1024 * 1024) { - flashsize = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000; - } else { - flashsize = flashsize - ESP.getSketchSize()-totalBytes()-1024; - //max OTA partition is 1019Kb - if (flashsize > 1024 * 1024) { - flashsize = (1024 * 1024) - 1024; - } - } -#endif //ARDUINO_ARCH_ESP8266 -#if defined (ARDUINO_ARCH_ESP32) - //Is OTA available ? - const esp_partition_t* mainpartition = esp_ota_get_running_partition(); - if (mainpartition) { - const esp_partition_t* partition = esp_ota_get_next_update_partition(mainpartition); - if (partition) { - const esp_partition_t* partition2 = esp_ota_get_next_update_partition(partition); - if (partition2 && (partition->address!=partition2->address)) { - flashsize = partition2->size; - } - } - } -#endif //ARDUINO_ARCH_ESP32 - return flashsize; +ESP_File::ESP_File(const char* name, const char* filename, bool isdir, + size_t size) { + _isdir = isdir; + _dirlist = ""; + _isfakedir = isdir; + _index = -1; + _filename = filename; + _name = name; + _lastwrite = 0; + _iswritemode = false; + _size = size; } -ESP_File::ESP_File(const char * name, const char * filename, bool isdir, size_t size) -{ - _isdir = isdir; - _dirlist = ""; - _isfakedir = isdir; - _index = -1; - _filename = filename; - _name = name; - _lastwrite = 0; - _iswritemode = false; - _size = size; +ESP_File::~ESP_File() { + // esp3d_log("Destructor %s index %d",(_isdir)?"Dir":"File", _index); } -ESP_File::~ESP_File() -{ - //log_esp3d("Destructor %s index %d",(_isdir)?"Dir":"File", _index); +ESP_File::operator bool() const { + if ((_index != -1) || (_filename.length() > 0)) { + // esp3d_log("Bool yes %d %d",_index, _filename.length()); + return true; + } else { + return false; + } } -ESP_File::operator bool() const -{ - if ((_index != -1) || (_filename.length() > 0)) { - //log_esp3d("Bool yes %d %d",_index, _filename.length()); - return true; - } else { - return false; - } +bool ESP_File::isOpen() { return !(_index == -1); } + +const char* ESP_File::name() const { return _name.c_str(); } + +const char* ESP_File::filename() const { return _filename.c_str(); } + +bool ESP_File::isDirectory() { return _isdir; } + +size_t ESP_File::size() { return _size; } + +time_t ESP_File::getLastWrite() { return _lastwrite; } + +int ESP_File::available() { + if (_index == -1 || _isdir) { + return 0; + } + return tFile_handle[_index].available(); } -bool ESP_File::isOpen() -{ - return !(_index == -1); +size_t ESP_File::write(uint8_t i) { + if ((_index == -1) || _isdir) { + return 0; + } + return tFile_handle[_index].write(i); } -const char* ESP_File::name() const -{ - return _name.c_str(); +size_t ESP_File::write(const uint8_t* buf, size_t size) { + if ((_index == -1) || _isdir) { + return 0; + } + return tFile_handle[_index].write(buf, size); } -const char* ESP_File::filename() const -{ - return _filename.c_str(); +int ESP_File::read() { + if ((_index == -1) || _isdir) { + return -1; + } + return tFile_handle[_index].read(); } -bool ESP_File::isDirectory() -{ - return _isdir; +size_t ESP_File::read(uint8_t* buf, size_t size) { + if ((_index == -1) || _isdir) { + return -1; + } + return tFile_handle[_index].read(buf, size); } -size_t ESP_File::size() -{ - return _size; +void ESP_File::flush() { + if ((_index == -1) || _isdir) { + return; + } + tFile_handle[_index].flush(); } -time_t ESP_File::getLastWrite() -{ - return _lastwrite; +ESP_File& ESP_File::operator=(const ESP_File& other) { + // esp3d_log("Copy %s", other._filename.c_str()); + _isdir = other._isdir; + _isfakedir = other._isfakedir; + _index = other._index; + _filename = other._filename; + _name = other._name; + _size = other._size; + _iswritemode = other._iswritemode; + _dirlist = other._dirlist; + _lastwrite = other._lastwrite; + return *this; } -int ESP_File::available() -{ - if (_index == -1 || _isdir) { - return 0; - } - return tFile_handle[_index].available(); -} - -size_t ESP_File::write(uint8_t i) -{ - if ((_index == -1) || _isdir) { - return 0; - } - return tFile_handle[_index].write (i); -} - -size_t ESP_File::write(const uint8_t *buf, size_t size) -{ - if ((_index == -1) || _isdir) { - return 0; - } - return tFile_handle[_index].write (buf, size); -} - -int ESP_File::read() -{ - if ((_index == -1) || _isdir) { - return -1; - } - return tFile_handle[_index].read(); -} - -size_t ESP_File::read(uint8_t* buf, size_t size) -{ - if ((_index == -1) || _isdir) { - return -1; - } - return tFile_handle[_index].read(buf, size); -} - -void ESP_File::flush() -{ - if ((_index == -1) || _isdir) { - return; - } - tFile_handle[_index].flush(); -} - -ESP_File& ESP_File::operator=(const ESP_File & other) -{ - //log_esp3d("Copy %s", other._filename.c_str()); - _isdir = other._isdir; - _isfakedir = other._isfakedir; - _index = other._index; - _filename = other._filename; - _name = other._name; - _size = other._size; - _iswritemode = other._iswritemode; - _dirlist = other._dirlist; - _lastwrite = other._lastwrite; - return *this; -} - -#endif //FILESYSTEM_FEATURE +#endif // FILESYSTEM_FEATURE diff --git a/esp3d/src/modules/filesystem/esp_filesystem.h b/esp3d/src/modules/filesystem/esp_filesystem.h index 5bdd69f4..1515c4eb 100644 --- a/esp3d/src/modules/filesystem/esp_filesystem.h +++ b/esp3d/src/modules/filesystem/esp_filesystem.h @@ -20,79 +20,78 @@ #ifndef _ESP_FILESYSTEM_H #define _ESP_FILESYSTEM_H -#include "../../include/esp3d_config.h" #include +#include "../../include/esp3d_config.h" + + #define ESP_FLASH_FS_HEADER "/FS" #define ESP_MAX_OPENHANDLE 4 -class ESP_File -{ -public: - ESP_File(void * handle = nullptr, bool isdir =false, bool iswritemode = false, const char * path = nullptr); - ESP_File(const char * name, const char * filename, bool isdir = true, size_t size =0); - ~ESP_File(); - operator bool() const; - bool isDirectory(); - bool seek(uint32_t pos, uint8_t mode = ESP_SEEK_SET); - const char* name() const; - const char* filename() const; - void close(); - bool isOpen(); - ESP_File & operator=(const ESP_File & other); - size_t size(); - time_t getLastWrite(); - int available(); - size_t write(uint8_t i); - size_t write(const uint8_t *buf, size_t size); - int read(); - size_t read(uint8_t* buf, size_t size); - void flush(); - ESP_File openNextFile(); -private: - String _dirlist; - bool _isdir; - bool _isfakedir; - bool _iswritemode; - int8_t _index; - String _filename; - String _name; - size_t _size; - time_t _lastwrite; - uint64_t _timeout; +class ESP_File { + public: + ESP_File(void *handle = nullptr, bool isdir = false, bool iswritemode = false, + const char *path = nullptr); + ESP_File(const char *name, const char *filename, bool isdir = true, + size_t size = 0); + ~ESP_File(); + operator bool() const; + bool isDirectory(); + bool seek(uint32_t pos, uint8_t mode = ESP_SEEK_SET); + const char *name() const; + const char *filename() const; + void close(); + bool isOpen(); + ESP_File &operator=(const ESP_File &other); + size_t size(); + time_t getLastWrite(); + int available(); + size_t write(uint8_t i); + size_t write(const uint8_t *buf, size_t size); + int read(); + size_t read(uint8_t *buf, size_t size); + void flush(); + ESP_File openNextFile(); + + private: + String _dirlist; + bool _isdir; + bool _isfakedir; + bool _iswritemode; + int8_t _index; + String _filename; + String _name; + size_t _size; + time_t _lastwrite; + uint64_t _timeout; }; -class ESP_FileSystem -{ -public: - static String & formatBytes (uint64_t bytes); - static bool begin(); - static bool accessFS(uint8_t FS = FS_FLASH); - static void releaseFS(uint8_t FS = FS_FLASH); - static void end(); - static size_t totalBytes(); - static size_t usedBytes(); - static size_t freeBytes(); - static uint maxPathLength(); - static size_t max_update_size(); - static const char * FilesystemName(); - static bool format(); - static ESP_File open(const char* path, uint8_t mode = ESP_FILE_READ); - static bool exists(const char* path); - static bool remove(const char *path); - static bool mkdir(const char *path); - static bool rmdir(const char *path); - static bool rename(const char *oldpath, const char *newpath); - static void closeAll(); - static bool started() - { - return _started; - } - static uint8_t getFSType(const char * path=nullptr); -private: - static bool _started; +class ESP_FileSystem { + public: + static bool begin(); + static bool accessFS(uint8_t FS = FS_FLASH); + static void releaseFS(uint8_t FS = FS_FLASH); + static void end(); + static size_t totalBytes(); + static size_t usedBytes(); + static size_t freeBytes(); + static uint maxPathLength(); + static size_t max_update_size(); + static const char *FilesystemName(); + static bool format(); + static ESP_File open(const char *path, uint8_t mode = ESP_FILE_READ); + static bool exists(const char *path); + static bool remove(const char *path); + static bool mkdir(const char *path); + static bool rmdir(const char *path); + static bool rename(const char *oldpath, const char *newpath); + static void closeAll(); + static bool started() { return _started; } + static uint8_t getFSType(const char *path = nullptr); + + private: + static bool _started; }; - -#endif //ESP_FILESYSTEM_H +#endif // ESP_FILESYSTEM_H diff --git a/esp3d/src/modules/filesystem/esp_globalFS.cpp b/esp3d/src/modules/filesystem/esp_globalFS.cpp index 2483e76b..f00ea2e5 100644 --- a/esp3d/src/modules/filesystem/esp_globalFS.cpp +++ b/esp3d/src/modules/filesystem/esp_globalFS.cpp @@ -40,21 +40,6 @@ bool ESP_GBFS::isavailable(uint8_t FS) { uint8_t ESP_GBFS::_nbFS = 0; String ESP_GBFS::_rootlist[MAX_FS]; -// helper to format size to readable string -String &ESP_GBFS::formatBytes(uint64_t bytes) { - static String res; - if (bytes < 1024) { - res = String((uint16_t)bytes) + " B"; - } else if (bytes < (1024 * 1024)) { - res = String((float)(bytes / 1024.0), 2) + " KB"; - } else if (bytes < (1024 * 1024 * 1024)) { - res = String((float)(bytes / 1024.0 / 1024.0), 2) + " MB"; - } else { - res = String((float)(bytes / 1024.0 / 1024.0 / 1024.0), 2) + " GB"; - } - return res; -} - // depending FS uint64_t ESP_GBFS::totalBytes(uint8_t FS) { #ifdef FILESYSTEM_FEATURE @@ -153,7 +138,7 @@ uint64_t ESP_GBFS::freeBytes(uint8_t FS) { } // Format is not always available for all FS -bool format(uint8_t FS, ESP3DOutput *output = nullptr) { +bool format(uint8_t FS) { #ifdef FILESYSTEM_FEATURE if (FS == FS_FLASH) { return ESP_FileSystem::format(); @@ -161,10 +146,10 @@ bool format(uint8_t FS, ESP3DOutput *output = nullptr) { #endif // FILESYSTEM_FEATURE #ifdef SD_DEVICE if (FS == FS_SD) { - return ESP_SD::format(output); + return ESP_SD::format(); } #endif // SD_DEVICE - output->printERROR("Not available"); + esp3d_log_e("Not available"); return false; } @@ -259,29 +244,29 @@ bool ESP_GBFS::remove(const char *path) { } bool ESP_GBFS::rename(const char *oldpath, const char *newpath) { - log_esp3d("rename global %s to %s", oldpath, newpath); + esp3d_log("rename global %s to %s", oldpath, newpath); #if defined(FILESYSTEM_FEATURE) || defined(SD_DEVICE) uint8_t t = getFSType(oldpath); if (t == FS_ROOT) { - log_esp3d_e("rename on root not allowed"); + esp3d_log_e("rename on root not allowed"); return false; } String o = getRealPath(oldpath); String n = getRealPath(newpath); #if defined(FILESYSTEM_FEATURE) if (t == FS_FLASH) { - log_esp3d("rename FS %s to %s", n.c_str(), o.c_str()); + esp3d_log("rename FS %s to %s", n.c_str(), o.c_str()); return ESP_FileSystem::rename(o.c_str(), n.c_str()); } #endif // FILESYSTEM_FEATURE #if defined(SD_DEVICE) if (t == FS_SD) { - log_esp3d("rename FS %s to %s", o.c_str(), n.c_str()); + esp3d_log("rename FS %s to %s", o.c_str(), n.c_str()); return ESP_SD::rename(o.c_str(), n.c_str()); } #endif // SD_DEVICE #endif // FILESYSTEM_FEATURE || SD_DEVICE - log_esp3d_e("Unknow FS, rename not allowed"); + esp3d_log_e("Unknow FS, rename not allowed"); return false; } @@ -339,24 +324,24 @@ void ESP_GBFS::closeAll() { ESP_GBFile ESP_GBFS::open(const char *path, uint8_t mode) { ESP_GBFile f; - log_esp3d("open %s", path); + esp3d_log("open %s", path); #if defined(FILESYSTEM_FEATURE) || defined(SD_DEVICE) uint8_t t = getFSType(path); - log_esp3d("type %d", t); + esp3d_log("type %d", t); if ((t == FS_ROOT) && (mode == ESP_FILE_READ)) { f = ESP_GBFile(FS_ROOT, "/"); - log_esp3d("root"); + esp3d_log("root"); getNextFS(true); } #if defined(FILESYSTEM_FEATURE) if (t == FS_FLASH) { - log_esp3d("open flash : %s", getRealPath(path)); + esp3d_log("open flash : %s", getRealPath(path)); f = ESP_FileSystem::open(getRealPath(path), mode); } #endif // FILESYSTEM_FEATURE #if defined(SD_DEVICE) if (t == FS_SD) { - log_esp3d("open SD : %s", getRealPath(path)); + esp3d_log("open SD : %s", getRealPath(path)); f = ESP_SD::open(getRealPath(path), mode); } #endif // SD_DEVICE diff --git a/esp3d/src/modules/filesystem/esp_globalFS.h b/esp3d/src/modules/filesystem/esp_globalFS.h index 911857ac..de440033 100644 --- a/esp3d/src/modules/filesystem/esp_globalFS.h +++ b/esp3d/src/modules/filesystem/esp_globalFS.h @@ -20,91 +20,89 @@ #ifndef _ESP_GLOBAL_FS_H #define _ESP_GLOBAL_FS_H -#include "../../include/esp3d_config.h" -#include "../../core/esp3doutput.h" #include + +#include "../../core/esp3d_message.h" +#include "../../include/esp3d_config.h" + #ifdef FILESYSTEM_FEATURE #include "esp_filesystem.h" -#endif //FILESYSTEM_FEATURE +#endif // FILESYSTEM_FEATURE #ifdef SD_DEVICE #include "esp_sd.h" -#endif //SD_DEVICE +#endif // SD_DEVICE +class ESP_GBFile { + public: + ESP_GBFile(); + ESP_GBFile(uint8_t FS, const char *name = nullptr); +#ifdef FILESYSTEM_FEATURE + ESP_GBFile(ESP_File &flashFile); +#endif // FILESYSTEM_FEATURE +#ifdef SD_DEVICE + ESP_GBFile(ESP_SDFile &sdFile); +#endif // SD_DEVICE + ~ESP_GBFile(); + operator bool() const; + bool isDirectory(); + bool seek(uint32_t pos, uint8_t mode = ESP_SEEK_SET); + const char *name() const; + const char *shortname() const; + const char *filename() const; + void close(); + bool isOpen(); + ESP_GBFile &operator=(const ESP_GBFile &other); +#ifdef FILESYSTEM_FEATURE + ESP_GBFile &operator=(const ESP_File &other); +#endif // FILESYSTEM_FEATURE +#ifdef SD_DEVICE + ESP_GBFile &operator=(const ESP_SDFile &other); +#endif // SD_DEVICE + size_t size(); + time_t getLastWrite(); + int available(); + size_t write(uint8_t i); + size_t write(const uint8_t *buf, size_t size); + int read(); + size_t read(uint8_t *buf, size_t size); + void flush(); + ESP_GBFile openNextFile(); -class ESP_GBFile -{ -public: - ESP_GBFile(); - ESP_GBFile(uint8_t FS, const char *name=nullptr); + private: #ifdef FILESYSTEM_FEATURE - ESP_GBFile(ESP_File & flashFile); -#endif //FILESYSTEM_FEATURE + ESP_File _flashFile; +#endif // FILESYSTEM_FEATURE #ifdef SD_DEVICE - ESP_GBFile(ESP_SDFile & sdFile); -#endif //SD_DEVICE - ~ESP_GBFile(); - operator bool() const; - bool isDirectory(); - bool seek(uint32_t pos, uint8_t mode = ESP_SEEK_SET); - const char* name() const; - const char* shortname() const; - const char* filename() const; - void close(); - bool isOpen(); - ESP_GBFile & operator=(const ESP_GBFile & other); -#ifdef FILESYSTEM_FEATURE - ESP_GBFile & operator=(const ESP_File & other); -#endif //FILESYSTEM_FEATURE -#ifdef SD_DEVICE - ESP_GBFile & operator=(const ESP_SDFile & other); -#endif //SD_DEVICE - size_t size(); - time_t getLastWrite(); - int available(); - size_t write(uint8_t i); - size_t write(const uint8_t *buf, size_t size); - int read(); - size_t read(uint8_t* buf, size_t size); - void flush(); - ESP_GBFile openNextFile(); -private: - -#ifdef FILESYSTEM_FEATURE - ESP_File _flashFile; -#endif //FILESYSTEM_FEATURE -#ifdef SD_DEVICE - ESP_SDFile _sdFile; -#endif //SD_DEVICE - uint8_t _type; - String _name; + ESP_SDFile _sdFile; +#endif // SD_DEVICE + uint8_t _type; + String _name; }; -class ESP_GBFS -{ -public: - static bool accessFS(uint8_t FS); - static void releaseFS(uint8_t FS); - static bool isavailable(uint8_t FS=FS_UNKNOWN); - static uint64_t totalBytes(uint8_t FS=FS_UNKNOWN); - static uint64_t usedBytes(uint8_t FS=FS_UNKNOWN); - static uint64_t freeBytes(uint8_t FS=FS_UNKNOWN); - static uint maxPathLength(); - static bool format(uint8_t FS, ESP3DOutput * output = nullptr); - static ESP_GBFile open(const char* path, uint8_t mode = ESP_FILE_READ); - static bool exists(const char* path); - static bool remove(const char *path); - static bool mkdir(const char *path); - static bool rmdir(const char *path); - static bool rename(const char *oldpath, const char *newpath); - static void closeAll(); - static String & formatBytes (uint64_t bytes); - static const char * getNextFS(bool reset = false); - static uint8_t getFSType(const char * path); -private: - static const char * getRealPath(const char * path); - static uint8_t _nbFS; - static String _rootlist[MAX_FS]; +class ESP_GBFS { + public: + static bool accessFS(uint8_t FS); + static void releaseFS(uint8_t FS); + static bool isavailable(uint8_t FS = FS_UNKNOWN); + static uint64_t totalBytes(uint8_t FS = FS_UNKNOWN); + static uint64_t usedBytes(uint8_t FS = FS_UNKNOWN); + static uint64_t freeBytes(uint8_t FS = FS_UNKNOWN); + static uint maxPathLength(); + static bool format(uint8_t FS = FS_UNKNOWN); + static ESP_GBFile open(const char *path, uint8_t mode = ESP_FILE_READ); + static bool exists(const char *path); + static bool remove(const char *path); + static bool mkdir(const char *path); + static bool rmdir(const char *path); + static bool rename(const char *oldpath, const char *newpath); + static void closeAll(); + static const char *getNextFS(bool reset = false); + static uint8_t getFSType(const char *path); + + private: + static const char *getRealPath(const char *path); + static uint8_t _nbFS; + static String _rootlist[MAX_FS]; }; - -#endif //_ESP_GLOBAL_FS_H +#endif //_ESP_GLOBAL_FS_H diff --git a/esp3d/src/modules/filesystem/esp_sd.cpp b/esp3d/src/modules/filesystem/esp_sd.cpp index fc304d41..c192a413 100644 --- a/esp3d/src/modules/filesystem/esp_sd.cpp +++ b/esp3d/src/modules/filesystem/esp_sd.cpp @@ -65,15 +65,15 @@ bool ESP_SD::_enabled = false; #include #endif // SD_CARD_TYPE == ESP_FYSETC_WIFI_PRO_SDCARD bool ESP_SD::enableSharedSD() { - log_esp3d("Enable Shared SD if possible"); + esp3d_log("Enable Shared SD if possible"); if (_enabled) { - log_esp3d("Already enabled, skip"); + esp3d_log("Already enabled, skip"); return false; } #if defined(ESP_SD_CS_SENSE) && ESP_SD_CS_SENSE != -1 bool active_cs = !digitalRead(ESP_SD_CS_SENSE); if (active_cs) { - log_esp3d("SD CS is active, skip"); + esp3d_log("SD CS is active, skip"); return false; } #endif // ESP_SD_CS_SENSE @@ -84,14 +84,14 @@ bool ESP_SD::enableSharedSD() { // Method : TBD // 1 - check sd cs state ? what about SDIO then ? // 2 - check M27 status ? - log_esp3d("SD shared enabled PIN %d with %d", ESP_FLAG_SHARED_SD_PIN, + esp3d_log("SD shared enabled PIN %d with %d", ESP_FLAG_SHARED_SD_PIN, ESP_FLAG_SHARED_SD_VALUE); digitalWrite(ESP_FLAG_SHARED_SD_PIN, ESP_FLAG_SHARED_SD_VALUE); - Hal::wait(100); + ESP3DHal::wait(100); #endif // ESP_FLAG_SHARED_SD_PIN #if SD_CARD_TYPE == ESP_FYSETC_WIFI_PRO_SDCARD - log_esp3d("Custom spi : CS: %d, Miso: %d, Mosi: %d, SCK: %d", ESP_SD_CS_PIN, + esp3d_log("Custom spi : CS: %d, Miso: %d, Mosi: %d, SCK: %d", ESP_SD_CS_PIN, ESP_SD_MISO_PIN, ESP_SD_MOSI_PIN, ESP_SD_SCK_PIN); SPI.begin(ESP_SD_SCK_PIN, ESP_SD_MISO_PIN, ESP_SD_MOSI_PIN, ESP_SD_CS_PIN); #endif // SD_CARD_TYPE == ESP_FYSETC_WIFI_PRO_SDCARD @@ -121,7 +121,7 @@ bool ESP_SD::disableSharedSD() { #endif // SD_CARD_TYPE == ESP_FYSETC_WIFI_PRO_SDCARD // do the switch digitalWrite(ESP_FLAG_SHARED_SD_PIN, !ESP_FLAG_SHARED_SD_VALUE); - Hal::wait(100); + ESP3DHal::wait(100); return true; } #endif // SD_DEVICE_CONNECTION == ESP_SHARED_SD @@ -145,32 +145,32 @@ bool ESP_SD::accessFS(uint8_t 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"); + esp3d_log("SD Busy"); return false; } #if SD_DEVICE_CONNECTION == ESP_SHARED_SD if (ESP_SD::enableSharedSD()) { - log_esp3d("Access shared SD ok"); + esp3d_log("Access shared SD ok"); res = true; } else { - log_esp3d_e("Enable shared SD failed"); + esp3d_log_e("Enable shared SD failed"); res = false; } #else - log_esp3d("Accessing Direct SD"); + esp3d_log("Accessing Direct SD"); res = true; #endif // SD_DEVICE_CONNECTION == ESP_SHARED_SD if (res) { - log_esp3d("Checking SD state"); + esp3d_log("Checking SD state"); if (ESP_SD::getState(true) == ESP_SDCARD_NOT_PRESENT) { - log_esp3d_e("SD not present"); + esp3d_log_e("SD not present"); res = false; // Sd is not available so release it ESP_SD::releaseFS(FS); } else { - log_esp3d("SD present"); + esp3d_log("SD present"); res = true; - log_esp3d("Accessing SD is ok"); + esp3d_log("Accessing SD is ok"); ESP_SD::setState(ESP_SDCARD_BUSY); } } @@ -178,17 +178,17 @@ bool ESP_SD::accessFS(uint8_t FS) { } void ESP_SD::releaseFS(uint8_t FS) { (void)FS; - log_esp3d("Release SD"); + esp3d_log("Release SD"); setState(ESP_SDCARD_IDLE); #if SD_DEVICE_CONNECTION == ESP_SHARED_SD _enabled = false; #if defined(ESP_FLAG_SHARED_SD_PIN) && ESP_FLAG_SHARED_SD_PIN != -1 if (ESP_SD::disableSharedSD()) { - log_esp3d("Shared SD disabled"); + esp3d_log("Shared SD disabled"); } #endif // ESP_FLAG_SHARED_SD_PIN #if defined(ESP3DLIB_ENV) - log_esp3d("Mount SD in Marlin"); + esp3d_log("Mount SD in Marlin"); card.mount(); #endif // ESP3DLIB_ENV #endif // SD_DEVICE_CONNECTION == ESP_SHARED_SD @@ -196,21 +196,6 @@ void ESP_SD::releaseFS(uint8_t FS) { void ESP_SD::handle() {} -// helper to format size to readable string -String& ESP_SD::formatBytes(uint64_t bytes) { - static String res; - if (bytes < 1024) { - res = String((uint16_t)bytes) + " B"; - } else if (bytes < (1024 * 1024)) { - res = String((float)(bytes / 1024.0), 2) + " KB"; - } else if (bytes < (1024 * 1024 * 1024)) { - res = String((float)(bytes / 1024.0 / 1024.0), 2) + " MB"; - } else { - res = String((float)(bytes / 1024.0 / 1024.0 / 1024.0), 2) + " GB"; - } - return res; -} - ESP_SDFile::ESP_SDFile(const char* name, const char* filename, bool isdir, size_t size) { _isdir = isdir; @@ -224,12 +209,12 @@ ESP_SDFile::ESP_SDFile(const char* name, const char* filename, bool isdir, } ESP_SDFile::~ESP_SDFile() { - // log_esp3d("Destructor %s index %d",(_isdir)?"Dir":"File", _index); + // esp3d_log("Destructor %s index %d",(_isdir)?"Dir":"File", _index); } ESP_SDFile::operator bool() const { if ((_index != -1) || (_filename.length() > 0)) { - // log_esp3d("Bool yes %d %d",_index, _filename.length()); + // esp3d_log("Bool yes %d %d",_index, _filename.length()); return true; } else { return false; @@ -291,7 +276,7 @@ void ESP_SDFile::flush() { } ESP_SDFile& ESP_SDFile::operator=(const ESP_SDFile& other) { - // log_esp3d("Copy %s", other._filename.c_str()); + // esp3d_log("Copy %s", other._filename.c_str()); _isdir = other._isdir; _index = other._index; _filename = other._filename; diff --git a/esp3d/src/modules/filesystem/esp_sd.h b/esp3d/src/modules/filesystem/esp_sd.h index c927ce1f..32bc3b6b 100644 --- a/esp3d/src/modules/filesystem/esp_sd.h +++ b/esp3d/src/modules/filesystem/esp_sd.h @@ -22,10 +22,9 @@ #define _ESP_SD_H #include -#include "../../core/esp3doutput.h" +#include "../../core/esp3d_message.h" #include "../../include/esp3d_config.h" - #define ESP_SD_FS_HEADER "/SD" #define ESP_MAX_SD_OPENHANDLE 4 @@ -69,7 +68,6 @@ class ESP_SDFile { class ESP_SD { public: - static String& formatBytes(uint64_t bytes); static bool begin(); static bool accessFS(uint8_t FS = FS_SD); static void releaseFS(uint8_t FS = FS_SD); @@ -84,7 +82,7 @@ class ESP_SD { static uint64_t freeBytes(bool refresh = false); static uint maxPathLength(); static const char* FilesystemName(); - static bool format(ESP3DOutput* output = nullptr); + static bool format(); static ESP_SDFile open(const char* path, uint8_t mode = ESP_FILE_READ); static bool exists(const char* path); static bool remove(const char* path); diff --git a/esp3d/src/modules/filesystem/flash/fat_esp32_filesystem.cpp b/esp3d/src/modules/filesystem/flash/fat_esp32_filesystem.cpp index 8284bcc2..1e95843b 100644 --- a/esp3d/src/modules/filesystem/flash/fat_esp32_filesystem.cpp +++ b/esp3d/src/modules/filesystem/flash/fat_esp32_filesystem.cpp @@ -64,17 +64,17 @@ bool ESP_FileSystem::format() { } ESP_File ESP_FileSystem::open(const char *path, uint8_t mode) { - log_esp3d("open %s as %s", path, (mode == ESP_FILE_WRITE ? "write" : "read")); + esp3d_log("open %s as %s", path, (mode == ESP_FILE_WRITE ? "write" : "read")); // do some check if (((strcmp(path, "/") == 0) && ((mode == ESP_FILE_WRITE) || (mode == ESP_FILE_APPEND))) || (strlen(path) == 0)) { - log_esp3d_e("reject %s", path); + esp3d_log_e("reject %s", path); return ESP_File(); } // path must start by '/' if (path[0] != '/') { - log_esp3d_e("%s is invalid path", path); + esp3d_log_e("%s is invalid path", path); return ESP_File(); } File tmp = FFat.open(path, (mode == ESP_FILE_READ) ? FILE_READ @@ -83,11 +83,11 @@ ESP_File ESP_FileSystem::open(const char *path, uint8_t mode) { if (tmp) { ESP_File esptmp(&tmp, tmp.isDirectory(), (mode == ESP_FILE_READ) ? false : true, path); - log_esp3d("%s is a %s", path, tmp.isDirectory() ? "Dir" : "File"); - log_esp3d("path is %s and filename path is %s", path, tmp.path()); + esp3d_log("%s is a %s", path, tmp.isDirectory() ? "Dir" : "File"); + esp3d_log("path is %s and filename path is %s", path, tmp.path()); return esptmp; } else { - log_esp3d_e("open %s failed", path); + esp3d_log_e("open %s failed", path); return ESP_File(); } } @@ -171,7 +171,7 @@ bool ESP_FileSystem::rmdir(const char *path) { dir.close(); } p = String(); - log_esp3d("count %d", pathlist.size()); + esp3d_log("count %d", pathlist.size()); return res; } @@ -194,7 +194,7 @@ ESP_File::ESP_File(void *handle, bool isdir, bool iswritemode, _iswritemode = iswritemode; _size = 0; if (!handle) { - log_esp3d("No handle"); + esp3d_log("No handle"); return; } bool set = false; @@ -221,15 +221,15 @@ ESP_File::ESP_File(void *handle, bool isdir, bool iswritemode, // time _lastwrite = tFile_handle[i].getLastWrite(); _index = i; - log_esp3d("Opening File at index %d", _index); - log_esp3d("name: %s", _name.c_str()); - log_esp3d("filename: %s", _filename.c_str()); - log_esp3d("path: %s", tFile_handle[i].path()); + esp3d_log("Opening File at index %d", _index); + esp3d_log("name: %s", _name.c_str()); + esp3d_log("filename: %s", _filename.c_str()); + esp3d_log("path: %s", tFile_handle[i].path()); set = true; } } if (!set) { - log_esp3d("No handle available"); + esp3d_log("No handle available"); } } @@ -239,17 +239,17 @@ bool ESP_File::seek(uint32_t pos, uint8_t mode) { void ESP_File::close() { if (_index != -1) { - log_esp3d("Closing File %s at index %d", _filename.c_str(), _index); - log_esp3d("name: %s", _name.c_str()); + esp3d_log("Closing File %s at index %d", _filename.c_str(), _index); + esp3d_log("name: %s", _name.c_str()); tFile_handle[_index].close(); // reopen if mode = write // udate size + date if (_iswritemode && !_isdir) { - log_esp3d("Updating %s size", _filename.c_str()); + esp3d_log("Updating %s size", _filename.c_str()); File ftmp = FFat.open(_filename.c_str()); if (ftmp) { _size = ftmp.size(); - log_esp3d("Size is %d", _size); + esp3d_log("Size is %d", _size); _lastwrite = ftmp.getLastWrite(); ftmp.close(); } @@ -261,12 +261,12 @@ void ESP_File::close() { ESP_File ESP_File::openNextFile() { if ((_index == -1) || !_isdir) { - log_esp3d("openNextFile %d failed", _index); + esp3d_log("openNextFile %d failed", _index); return ESP_File(); } File tmp = tFile_handle[_index].openNextFile(); while (tmp) { - log_esp3d("tmp name :%s %s", tmp.name(), + esp3d_log("tmp name :%s %s", tmp.name(), (tmp.isDirectory()) ? "isDir" : "isFile"); ESP_File esptmp(&tmp, tmp.isDirectory()); esptmp.close(); diff --git a/esp3d/src/modules/filesystem/flash/littlefs_esp32_filesystem.cpp b/esp3d/src/modules/filesystem/flash/littlefs_esp32_filesystem.cpp index 7e849b67..b937695c 100644 --- a/esp3d/src/modules/filesystem/flash/littlefs_esp32_filesystem.cpp +++ b/esp3d/src/modules/filesystem/flash/littlefs_esp32_filesystem.cpp @@ -51,7 +51,7 @@ size_t ESP_FileSystem::usedBytes() { return LittleFS.usedBytes(); } uint ESP_FileSystem::maxPathLength() { return 32; } bool ESP_FileSystem::rename(const char *oldpath, const char *newpath) { - log_esp3d("rename %s to %s", oldpath, newpath); + esp3d_log("rename %s to %s", oldpath, newpath); return LittleFS.rename(oldpath, newpath); } @@ -66,17 +66,17 @@ bool ESP_FileSystem::format() { } ESP_File ESP_FileSystem::open(const char *path, uint8_t mode) { - log_esp3d("open %s", path); + esp3d_log("open %s", path); // do some check if (((strcmp(path, "/") == 0) && ((mode == ESP_FILE_WRITE) || (mode == ESP_FILE_APPEND))) || (strlen(path) == 0)) { - log_esp3d("reject %s", path); + esp3d_log("reject %s", path); return ESP_File(); } // path must start by '/' if (path[0] != '/') { - log_esp3d("%s is invalid path", path); + esp3d_log("%s is invalid path", path); return ESP_File(); } File tmp = LittleFS.open(path, (mode == ESP_FILE_READ) ? FILE_READ @@ -85,10 +85,10 @@ ESP_File ESP_FileSystem::open(const char *path, uint8_t mode) { if (tmp) { ESP_File esptmp(&tmp, tmp.isDirectory(), (mode == ESP_FILE_READ) ? false : true, path); - log_esp3d("%s is a %s", path, tmp.isDirectory() ? "Dir" : "File"); + esp3d_log("%s is a %s", path, tmp.isDirectory() ? "Dir" : "File"); return esptmp; } else { - log_esp3d("open %s failed", path); + esp3d_log("open %s failed", path); return ESP_File(); } } @@ -182,7 +182,7 @@ bool ESP_FileSystem::rmdir(const char *path) { dir.close(); } p = String(); - log_esp3d("count %d", pathlist.size()); + esp3d_log("count %d", pathlist.size()); return res; } @@ -205,7 +205,7 @@ ESP_File::ESP_File(void *handle, bool isdir, bool iswritemode, _iswritemode = iswritemode; _size = 0; if (!handle) { - log_esp3d("No handle"); + esp3d_log("No handle"); return; } bool set = false; @@ -232,21 +232,21 @@ ESP_File::ESP_File(void *handle, bool isdir, bool iswritemode, // time _lastwrite = tFile_handle[i].getLastWrite(); _index = i; - log_esp3d("Opening File at index %d", _index); - log_esp3d("name: %s", _name.c_str()); - log_esp3d("filename: %s", _filename.c_str()); - log_esp3d("path: %s", tFile_handle[i].path()); + esp3d_log("Opening File at index %d", _index); + esp3d_log("name: %s", _name.c_str()); + esp3d_log("filename: %s", _filename.c_str()); + esp3d_log("path: %s", tFile_handle[i].path()); set = true; } else { - log_esp3d("File %d busy", i); - log_esp3d("%s", tFile_handle[i].name()); + esp3d_log("File %d busy", i); + esp3d_log("%s", tFile_handle[i].name()); } } if (!set) { - log_esp3d("No handle available"); + esp3d_log("No handle available"); #if defined(ESP_LOG_FEATURE) for (uint8_t i = 0; (i < ESP_MAX_OPENHANDLE); i++) { - log_esp3d("%s", tFile_handle[i].name()); + esp3d_log("%s", tFile_handle[i].name()); } #endif } @@ -254,7 +254,7 @@ ESP_File::ESP_File(void *handle, bool isdir, bool iswritemode, void ESP_File::close() { if (_index != -1) { - log_esp3d("Closing File at index %d", _index); + esp3d_log("Closing File at index %d", _index); tFile_handle[_index].close(); // reopen if mode = write // udate size + date @@ -265,7 +265,7 @@ void ESP_File::close() { _lastwrite = ftmp.getLastWrite(); ftmp.close(); } else { - log_esp3d("Error opening %s", _filename.c_str()); + esp3d_log("Error opening %s", _filename.c_str()); } } tFile_handle[_index] = File(); @@ -278,12 +278,12 @@ bool ESP_File::seek(uint32_t pos, uint8_t mode) { ESP_File ESP_File::openNextFile() { if ((_index == -1) || !_isdir) { - log_esp3d("openNextFile %d failed", _index); + esp3d_log("openNextFile %d failed", _index); return ESP_File(); } File tmp = tFile_handle[_index].openNextFile(); while (tmp) { - log_esp3d("tmp name :%s %s", tmp.name(), + esp3d_log("tmp name :%s %s", tmp.name(), (tmp.isDirectory()) ? "isDir" : "isFile"); ESP_File esptmp(&tmp, tmp.isDirectory()); esptmp.close(); diff --git a/esp3d/src/modules/filesystem/flash/littlefs_esp8266_filesystem.cpp b/esp3d/src/modules/filesystem/flash/littlefs_esp8266_filesystem.cpp index cfc76fa8..22e7d565 100644 --- a/esp3d/src/modules/filesystem/flash/littlefs_esp8266_filesystem.cpp +++ b/esp3d/src/modules/filesystem/flash/littlefs_esp8266_filesystem.cpp @@ -18,314 +18,300 @@ littlefs_esp8266_filesystem.cpp - ESP3D littlefs filesystem configuration class Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../../include/esp3d_config.h" -#if (FILESYSTEM_FEATURE == ESP_LITTLEFS_FILESYSTEM) && defined(ARDUINO_ARCH_ESP8266) -#include "../esp_filesystem.h" -#include +#if (FILESYSTEM_FEATURE == ESP_LITTLEFS_FILESYSTEM) && \ + defined(ARDUINO_ARCH_ESP8266) #include #include +#include + +#include "../esp_filesystem.h" + + Dir tDir_handle[ESP_MAX_OPENHANDLE]; extern File tFile_handle[ESP_MAX_OPENHANDLE]; -bool ESP_FileSystem::begin() -{ - _started = LittleFS.begin(); +bool ESP_FileSystem::begin() { + _started = LittleFS.begin(); + return _started; +} +void ESP_FileSystem::end() { + _started = false; + LittleFS.end(); +} + +size_t ESP_FileSystem::freeBytes() { return totalBytes() - usedBytes(); } + +size_t ESP_FileSystem::totalBytes() { + fs::FSInfo info; + LittleFS.info(info); + return info.totalBytes; +} + +size_t ESP_FileSystem::usedBytes() { + fs::FSInfo info; + LittleFS.info(info); + return info.usedBytes; +} + +uint ESP_FileSystem::maxPathLength() { return 32; } + +bool ESP_FileSystem::rename(const char *oldpath, const char *newpath) { + return LittleFS.rename(oldpath, newpath); +} + +const char *ESP_FileSystem::FilesystemName() { return "LittleFS"; } + +bool ESP_FileSystem::format() { + bool res = LittleFS.format(); + if (res) { + res = begin(); + } + return res; +} + +ESP_File ESP_FileSystem::open(const char *path, uint8_t mode) { + // do some check + if (((strcmp(path, "/") == 0) && + ((mode == ESP_FILE_WRITE) || (mode == ESP_FILE_APPEND))) || + (strlen(path) == 0)) { + return ESP_File(); + } + // path must start by '/' + if (path[0] != '/') { + return ESP_File(); + } + File ftmp = LittleFS.open(path, (mode == ESP_FILE_READ) ? "r" + : (mode == ESP_FILE_WRITE) ? "w" + : "a"); + if (ftmp) { + esp3d_log("Success openening: %s", path); + if (ftmp.isFile()) { + esp3d_log("It is a file"); + ESP_File esptmp(&ftmp, false, (mode == ESP_FILE_READ) ? false : true, + path); + return esptmp; + } + if (ftmp.isDirectory()) { + esp3d_log("It is a Directory"); + } + ftmp.close(); + } + esp3d_log("Opening as Directory"); + Dir dtmp = LittleFS.openDir(path); + ESP_File esptmp(&dtmp, true, false, path); + return esptmp; +} + +bool ESP_FileSystem::exists(const char *path) { + // root should always be there if started + if (strcmp(path, "/") == 0) { return _started; -} -void ESP_FileSystem::end() -{ - _started = false; - LittleFS.end(); -} - -size_t ESP_FileSystem::freeBytes() -{ - return totalBytes() - usedBytes(); -} - -size_t ESP_FileSystem::totalBytes() -{ - fs::FSInfo info; - LittleFS.info (info); - return info.totalBytes; -} - -size_t ESP_FileSystem::usedBytes() -{ - fs::FSInfo info; - LittleFS.info (info); - return info.usedBytes; -} - -uint ESP_FileSystem::maxPathLength() -{ - return 32; -} - -bool ESP_FileSystem::rename(const char *oldpath, const char *newpath) -{ - return LittleFS.rename(oldpath,newpath); -} - -const char * ESP_FileSystem::FilesystemName() -{ - return "LittleFS"; -} - -bool ESP_FileSystem::format() -{ - bool res = LittleFS.format(); - if (res) { - res = begin(); + } + String spath = path; + spath.trim(); + if (spath[spath.length() - 1] == '/') { + if (spath != "/") { + spath.remove(spath.length() - 1); } - return res; + } + return LittleFS.exists(spath.c_str()); } -ESP_File ESP_FileSystem::open(const char* path, uint8_t mode) -{ - //do some check - if(((strcmp(path,"/") == 0) && ((mode == ESP_FILE_WRITE) || (mode == ESP_FILE_APPEND))) || (strlen(path) == 0)) { - return ESP_File(); +bool ESP_FileSystem::remove(const char *path) { + String p = path; + if (p[0] != '/') { + p = "/" + p; + } + esp3d_log("delete %s", p.c_str()); + return LittleFS.remove(p); +} + +bool ESP_FileSystem::mkdir(const char *path) { + String spath = path; + spath.trim(); + if (spath[spath.length() - 1] == '/') { + if (spath != "/") { + spath.remove(spath.length() - 1); } - // path must start by '/' - if (path[0] != '/') { - return ESP_File(); + } + if (spath[0] != '/') { + spath = "/" + spath; + } + return LittleFS.mkdir(spath.c_str()); +} + +bool ESP_FileSystem::rmdir(const char *path) { + String p = path; + if (!p.endsWith("/")) { + p += '/'; + } + if (!p.startsWith("/")) { + p = '/' + p; + } + if (!exists(p.c_str())) { + return false; + } + bool res = true; + std::stack pathlist; + pathlist.push(p); + while (pathlist.size() > 0) { + bool candelete = true; + Dir dir = LittleFS.openDir(pathlist.top().c_str()); + while (dir.next()) { + if (dir.isDirectory()) { + candelete = false; + String newdir = pathlist.top() + dir.fileName() + "/"; + pathlist.push(newdir); + } else { + String filepath = pathlist.top() + '/'; + filepath += dir.fileName(); + esp3d_log("remove %s", filepath.c_str()); + LittleFS.remove(filepath.c_str()); + } } - File ftmp = LittleFS.open(path, (mode == ESP_FILE_READ)?"r":(mode == ESP_FILE_WRITE)?"w":"a"); - if(ftmp) { - log_esp3d("Success openening: %s", path); - if (ftmp.isFile()) { - log_esp3d("It is a file"); - ESP_File esptmp(&ftmp, false,(mode == ESP_FILE_READ)?false:true, path); - return esptmp; + if (candelete) { + if (pathlist.top() != "/") { + if (LittleFS.exists(pathlist.top().c_str())) { + res = LittleFS.rmdir(pathlist.top().c_str()); } - if (ftmp.isDirectory()) { - log_esp3d("It is a Directory"); + } + pathlist.pop(); + } + } + return res; +} + +void ESP_FileSystem::closeAll() { + for (uint8_t i = 0; i < ESP_MAX_OPENHANDLE; i++) { + tDir_handle[i] = Dir(); + tFile_handle[i].close(); + tFile_handle[i] = File(); + } +} + +ESP_File::ESP_File(void *handle, bool isdir, bool iswritemode, + const char *path) { + _isdir = isdir; + _dirlist = ""; + _isfakedir = false; + _index = -1; + _filename = ""; + _name = ""; + _lastwrite = 0; + _iswritemode = iswritemode; + _size = 0; + if (!handle) { + esp3d_log("No handle"); + return; + } + bool set = false; + if (_isdir) { + for (uint8_t i = 0; (i < ESP_MAX_OPENHANDLE) && !set; i++) { + if (tDir_handle[i].fileName().length() == 0) { + tDir_handle[i] = *((Dir *)handle); + _index = i; + // Path = filename + if (path) { + _filename = path; + _filename.trim(); + if (!((_filename[_filename.length() - 1] == '/') || + (_filename == "/"))) { + _filename += "/"; + } + // Name + if (_filename == "/") { + _name = "/"; + } else { + _name.remove(0, _name.lastIndexOf('/') + 1); + } } - ftmp.close(); + esp3d_log("Dir: %s index: %d", _name.c_str(), _index); + esp3d_log("name: %s", _name.c_str()); + esp3d_log("filename: %s", _filename.c_str()); + set = true; + } } - log_esp3d("Opening as Directory"); - Dir dtmp = LittleFS.openDir(path); - ESP_File esptmp(&dtmp, true, false, path); - return esptmp; + return; + } + + for (uint8_t i = 0; (i < ESP_MAX_OPENHANDLE) && !set; i++) { + if (!tFile_handle[i]) { + tFile_handle[i] = *((File *)handle); + // filename + _filename = tFile_handle[i].fullName(); + // name + _name = tFile_handle[i].name(); + // size + _size = tFile_handle[i].size(); + // time + _lastwrite = tFile_handle[i].getLastWrite(); + _index = i; + esp3d_log("Opening File at index %d", _index); + esp3d_log("name: %s", _name.c_str()); + esp3d_log("filename: %s", _filename.c_str()); + set = true; + } + } } -bool ESP_FileSystem::exists(const char* path) -{ - //root should always be there if started - if (strcmp(path, "/") == 0) { - return _started; - } - String spath = path; - spath.trim(); - if (spath[spath.length()-1] == '/') { - if (spath!="/") { - spath.remove(spath.length()-1); - } - } - return LittleFS.exists(spath.c_str()); +bool ESP_File::seek(uint32_t pos, uint8_t mode) { + return tFile_handle[_index].seek(pos, (SeekMode)mode); } -bool ESP_FileSystem::remove(const char *path) -{ - String p = path; - if(p[0]!='/') { - p="/"+p; - } - log_esp3d("delete %s", p.c_str()); - return LittleFS.remove(p); -} - -bool ESP_FileSystem::mkdir(const char *path) -{ - String spath = path; - spath.trim(); - if (spath[spath.length()-1] == '/') { - if (spath!="/") { - spath.remove(spath.length()-1); - } - } - if (spath[0]!='/') { - spath = "/"+spath; - } - return LittleFS.mkdir(spath.c_str()); -} - -bool ESP_FileSystem::rmdir(const char *path) -{ - String p = path; - if (!p.endsWith("/")) { - p+= '/'; - } - if (!p.startsWith("/")) { - p = '/'+p; - } - if (!exists(p.c_str())) { - return false; - } - bool res = true; - std::stack pathlist; - pathlist.push(p); - while (pathlist.size() > 0) { - - bool candelete = true; - Dir dir = LittleFS.openDir(pathlist.top().c_str()); - while (dir.next()) { - if (dir.isDirectory()) { - candelete = false; - String newdir = pathlist.top() + dir.fileName() + "/"; - pathlist.push(newdir); - } else { - String filepath = pathlist.top()+ '/'; - filepath+= dir.fileName(); - log_esp3d("remove %s", filepath.c_str()); - LittleFS.remove(filepath.c_str()); - } - } - if (candelete) { - if (pathlist.top() !="/") { - if (LittleFS.exists(pathlist.top().c_str())) { - res = LittleFS.rmdir(pathlist.top().c_str()); - } - } - pathlist.pop(); - } - } - return res; -} - -void ESP_FileSystem::closeAll() -{ - for (uint8_t i = 0; i < ESP_MAX_OPENHANDLE; i++) { - tDir_handle[i] = Dir(); - tFile_handle[i].close(); - tFile_handle[i] = File(); - } -} - -ESP_File::ESP_File(void* handle, bool isdir, bool iswritemode, const char * path) -{ - _isdir = isdir; - _dirlist = ""; - _isfakedir = false; - _index = -1; - _filename = ""; - _name = ""; - _lastwrite = 0; - _iswritemode = iswritemode; - _size = 0; - if (!handle) { - log_esp3d("No handle"); - return ; - } - bool set =false; +void ESP_File::close() { + if (_index != -1) { if (_isdir) { - for (uint8_t i=0; (i < ESP_MAX_OPENHANDLE) && !set; i++) { - if (tDir_handle[i].fileName().length() == 0) { - tDir_handle[i] = *((Dir *)handle); - _index = i; - //Path = filename - if (path) { - _filename = path; - _filename.trim(); - if (!((_filename[_filename.length()-1] == '/') || (_filename == "/"))) { - _filename+="/"; - } - //Name - if (_filename == "/") { - _name = "/"; - } else { - _name.remove( 0, _name.lastIndexOf('/')+1); - } - } - log_esp3d("Dir: %s index: %d", _name.c_str(), _index); - log_esp3d("name: %s", _name.c_str()); - log_esp3d("filename: %s", _filename.c_str()); - set = true; - } - } - return; + esp3d_log("Closing Dir at index %d", _index); + tDir_handle[_index] = Dir(); + _index = -1; + return; } - - for (uint8_t i=0; (i < ESP_MAX_OPENHANDLE) && !set; i++) { - if (!tFile_handle[i]) { - tFile_handle[i] = *((File*)handle); - //filename - _filename = tFile_handle[i].fullName(); - //name - _name = tFile_handle[i].name(); - //size - _size = tFile_handle[i].size(); - //time - _lastwrite = tFile_handle[i].getLastWrite(); - _index = i; - log_esp3d("Opening File at index %d",_index); - log_esp3d("name: %s", _name.c_str()); - log_esp3d("filename: %s", _filename.c_str()); - set = true; - } + esp3d_log("Closing File at index %d", _index); + esp3d_log("Size is %d", tFile_handle[_index].size()); + tFile_handle[_index].close(); + // reopen if mode = write + // udate size + date + if (_iswritemode && !_isdir) { + esp3d_log("Updating Size of %s", _filename.c_str()); + File ftmp = LittleFS.open(_filename.c_str(), "r"); + if (ftmp) { + _size = ftmp.size(); + esp3d_log("Updating Size to %d", ftmp.size()); + _lastwrite = ftmp.getLastWrite(); + ftmp.close(); + } } + _index = -1; + } } -bool ESP_File::seek(uint32_t pos, uint8_t mode) -{ - return tFile_handle[_index].seek(pos, (SeekMode)mode); +ESP_File ESP_File::openNextFile() { + if ((_index == -1) || !_isdir) { + esp3d_log("openNextFile failed"); + return ESP_File(); + } + if (tDir_handle[_index].next()) { + String name = tDir_handle[_index].fileName(); + esp3d_log("Getting next file from %s", _filename.c_str()); + esp3d_log("name :%s %s", name.c_str(), + (tDir_handle[_index].isDirectory()) ? "isDir" : "isFile"); + String s = _filename; + if (s[s.length() - 1] != '/') { + s += "/"; + } + s += name.c_str(); + if (tDir_handle[_index].isFile()) { + ESP_File esptmp(name.c_str(), s.c_str(), false, + tDir_handle[_index].fileSize()); + return esptmp; + } else { + esp3d_log("Found dir name: %s filename:%s", name.c_str(), s.c_str()); + ESP_File esptmp = ESP_File(name.c_str(), s.c_str()); + return esptmp; + } + } + return ESP_File(); } -void ESP_File::close() -{ - if (_index != -1) { - if (_isdir) { - log_esp3d("Closing Dir at index %d", _index); - tDir_handle[_index] = Dir(); - _index = -1; - return; - } - log_esp3d("Closing File at index %d", _index); - log_esp3d("Size is %d", tFile_handle[_index].size()); - tFile_handle[_index].close(); - //reopen if mode = write - //udate size + date - if (_iswritemode && !_isdir) { - log_esp3d("Updating Size of %s",_filename.c_str()); - File ftmp = LittleFS.open(_filename.c_str(), "r"); - if (ftmp) { - _size = ftmp.size(); - log_esp3d("Updating Size to %d", ftmp.size()); - _lastwrite = ftmp.getLastWrite(); - ftmp.close(); - } - } - _index = -1; - } -} - -ESP_File ESP_File::openNextFile() -{ - if ((_index == -1) || !_isdir) { - log_esp3d("openNextFile failed"); - return ESP_File(); - } - if(tDir_handle[_index].next()) { - String name = tDir_handle[_index].fileName(); - log_esp3d("Getting next file from %s", _filename.c_str()); - log_esp3d("name :%s %s", name.c_str(), (tDir_handle[_index].isDirectory())?"isDir":"isFile"); - String s = _filename; - if(s[s.length()-1]!='/') { - s+="/"; - } - s+=name.c_str(); - if (tDir_handle[_index].isFile()) { - ESP_File esptmp(name.c_str(), s.c_str(), false, tDir_handle[_index].fileSize()) ; - return esptmp; - } else { - log_esp3d("Found dir name: %s filename:%s",name.c_str(), s.c_str()); - ESP_File esptmp = ESP_File(name.c_str(), s.c_str()); - return esptmp; - } - - } - return ESP_File(); -} - -#endif //ESP_LITTLEFS_FILESYSTEM +#endif // ESP_LITTLEFS_FILESYSTEM diff --git a/esp3d/src/modules/filesystem/flash/spiffs_esp32_filesystem.cpp b/esp3d/src/modules/filesystem/flash/spiffs_esp32_filesystem.cpp index d9859cb0..430882f1 100644 --- a/esp3d/src/modules/filesystem/flash/spiffs_esp32_filesystem.cpp +++ b/esp3d/src/modules/filesystem/flash/spiffs_esp32_filesystem.cpp @@ -78,10 +78,10 @@ ESP_File ESP_FileSystem::open(const char *path, uint8_t mode) { if (tmp) { ESP_File esptmp(&tmp, tmp.isDirectory(), (mode == ESP_FILE_READ) ? false : true, path); - log_esp3d("%s is a %s", path, tmp.isDirectory() ? "Dir" : "File"); + esp3d_log("%s is a %s", path, tmp.isDirectory() ? "Dir" : "File"); return esptmp; } else { - log_esp3d("open %s failed", path); + esp3d_log("open %s failed", path); return ESP_File(); } } @@ -106,7 +106,7 @@ bool ESP_FileSystem::exists(const char *path) { newpath += "/"; } newpath += "."; - log_esp3d("Check %s", newpath.c_str()); + esp3d_log("Check %s", newpath.c_str()); res = SPIFFS.exists(newpath); if (!res) { ESP_File f = ESP_FileSystem::open(path, ESP_FILE_READ); @@ -139,7 +139,7 @@ bool ESP_FileSystem::mkdir(const char *path) { p += "/"; } p += "."; - log_esp3d("Dir create : %s", p.c_str()); + esp3d_log("Dir create : %s", p.c_str()); ESP_File f = open(p.c_str(), ESP_FILE_WRITE); if (f) { f.close(); @@ -160,12 +160,12 @@ bool ESP_FileSystem::rmdir(const char *path) { spath.remove(spath.length() - 1); } } - log_esp3d("Deleting : %s", spath.c_str()); + esp3d_log("Deleting : %s", spath.c_str()); File ftmp = SPIFFS.open(spath.c_str()); if (ftmp) { File pfile = ftmp.openNextFile(); while (pfile) { - log_esp3d("File: %s", pfile.path()); + esp3d_log("File: %s", pfile.path()); if (!SPIFFS.remove(pfile.path())) { pfile.close(); return false; @@ -199,7 +199,7 @@ ESP_File::ESP_File(void *handle, bool isdir, bool iswritemode, _iswritemode = iswritemode; _size = 0; if (!handle) { - log_esp3d("No handle"); + esp3d_log("No handle"); return; } bool set = false; @@ -244,9 +244,9 @@ ESP_File::ESP_File(void *handle, bool isdir, bool iswritemode, // time _lastwrite = tFile_handle[i].getLastWrite(); _index = i; - log_esp3d("Opening File at index %d", _index); - log_esp3d("name: %s", _name.c_str()); - log_esp3d("filename: %s", _filename.c_str()); + esp3d_log("Opening File at index %d", _index); + esp3d_log("name: %s", _name.c_str()); + esp3d_log("filename: %s", _filename.c_str()); set = true; } } @@ -258,7 +258,7 @@ bool ESP_File::seek(uint32_t pos, uint8_t mode) { void ESP_File::close() { if (_index != -1) { - log_esp3d("Closing File at index %d", _index); + esp3d_log("Closing File at index %d", _index); tFile_handle[_index].close(); // reopen if mode = write // udate size + date @@ -277,12 +277,12 @@ void ESP_File::close() { ESP_File ESP_File::openNextFile() { if ((_index == -1) || !_isdir) { - log_esp3d("openNextFile failed"); + esp3d_log("openNextFile failed"); return ESP_File(); } File tmp = tFile_handle[_index].openNextFile(); while (tmp) { - log_esp3d("tmp name :%s %s", tmp.name(), + esp3d_log("tmp name :%s %s", tmp.name(), (tmp.isDirectory()) ? "isDir" : "isFile"); ESP_File esptmp(&tmp, tmp.isDirectory()); esptmp.close(); @@ -292,7 +292,7 @@ ESP_File ESP_File::openNextFile() { if (pos != -1) { // is subdir sub = sub.substring(0, pos); - log_esp3d("file name:%s name: %s %s sub:%s root:%s", esptmp.filename(), + esp3d_log("file name:%s name: %s %s sub:%s root:%s", esptmp.filename(), esptmp.name(), (esptmp.isDirectory()) ? "isDir" : "isFile", sub.c_str(), _filename.c_str()); String tag = "*" + sub + "*"; @@ -302,28 +302,28 @@ ESP_File ESP_File::openNextFile() { _dirlist += tag; String fname = _filename.substring(0, _filename.length() - 1) + sub + "/."; - log_esp3d("Found dir # name: %s filename:%s", sub.c_str(), + esp3d_log("Found dir # name: %s filename:%s", sub.c_str(), fname.c_str()); if (sub == ".") { - log_esp3d("Dir tag, ignore it"); + esp3d_log("Dir tag, ignore it"); tmp = tFile_handle[_index].openNextFile(); } else { esptmp = ESP_File(sub.c_str(), fname.c_str()); return esptmp; } } else { // already in list so ignore it - log_esp3d("Dir name: %s already in list", sub.c_str()); + esp3d_log("Dir name: %s already in list", sub.c_str()); tmp = tFile_handle[_index].openNextFile(); } } else { // is file - log_esp3d("file name:%s name: %s %s sub:%s root:%s", esptmp.filename(), + esp3d_log("file name:%s name: %s %s sub:%s root:%s", esptmp.filename(), esptmp.name(), (esptmp.isDirectory()) ? "isDir" : "isFile", sub.c_str(), _filename.c_str()); if (sub == ".") { - log_esp3d("Dir tag, ignore it"); + esp3d_log("Dir tag, ignore it"); tmp = tFile_handle[_index].openNextFile(); } else { - log_esp3d("Found file # name: %s filename:%s", esptmp.filename(), + esp3d_log("Found file # name: %s filename:%s", esptmp.filename(), esptmp.name()); return esptmp; } diff --git a/esp3d/src/modules/filesystem/sd/sd_native_esp32.cpp b/esp3d/src/modules/filesystem/sd/sd_native_esp32.cpp index 80a18edb..c5871a5a 100644 --- a/esp3d/src/modules/filesystem/sd/sd_native_esp32.cpp +++ b/esp3d/src/modules/filesystem/sd/sd_native_esp32.cpp @@ -22,7 +22,7 @@ sd_native_esp32.cpp - ESP3D sd support class #if (SD_DEVICE == ESP_SD_NATIVE) #include -#include "../../../core/settings_esp3d.h" +#include "../../../core/esp3d_settings.h" #include "../esp_sd.h" #include "FS.h" #include "SD.h" @@ -57,7 +57,7 @@ uint8_t ESP_SD::getState(bool refresh) { _state = ESP_SDCARD_NOT_PRESENT; // using default value for speed ? should be parameter // refresh content if card was removed - log_esp3d("Spi : CS: %d, Miso: %d, Mosi: %d, SCK: %d", + esp3d_log("Spi : CS: %d, Miso: %d, Mosi: %d, SCK: %d", ESP_SD_CS_PIN != -1 ? ESP_SD_CS_PIN : SS, ESP_SD_MISO_PIN != -1 ? ESP_SD_MISO_PIN : MISO, ESP_SD_MOSI_PIN != -1 ? ESP_SD_MOSI_PIN : MOSI, @@ -74,7 +74,7 @@ uint8_t ESP_SD::getState(bool refresh) { bool ESP_SD::begin() { _started = true; _state = ESP_SDCARD_NOT_PRESENT; - _spi_speed_divider = Settings_ESP3D::read_byte(ESP_SD_SPEED_DIV); + _spi_speed_divider = ESP3DSettings::readByte(ESP_SD_SPEED_DIV); // sanity check if (_spi_speed_divider <= 0) { _spi_speed_divider = 1; @@ -90,11 +90,11 @@ bool ESP_SD::begin() { #endif // ESP_FLAG_SHARED_SD_PIN #if SD_CARD_TYPE == ESP_FYSETC_WIFI_PRO_SDCARD #if defined(ESP_SD_CS_SENSE) - log_esp3d("Setup SD sense pin %d", ESP_SD_CS_SENSE); + esp3d_log("Setup SD sense pin %d", ESP_SD_CS_SENSE); pinMode(ESP_SD_CS_SENSE, INPUT_PULLUP); #endif // defined(ESP_SD_CS_SENSE) #if defined(ESP_SD_POWER_PIN) && ESP_SD_POWER_PIN != -1 - log_esp3d("Setup SD power pin %d", ESP_SD_POWER_PIN); + esp3d_log("Setup SD power pin %d", ESP_SD_POWER_PIN); pinMode(ESP_SD_POWER_PIN, OUTPUT); digitalWrite(ESP_SD_POWER_PIN, ESP_POWER_SD_VALUE); #endif // defined(ESP3D_POWER_SD_PIN) @@ -102,7 +102,7 @@ bool ESP_SD::begin() { #endif // SD_DEVICE_CONNECTION == ESP_SHARED_SD #if (ESP_SD_CS_PIN != -1) || (ESP_SD_MISO_PIN != -1) || \ (ESP_SD_MOSI_PIN != -1) || (ESP_SD_SCK_PIN != -1) - log_esp3d("Custom spi : CS: %d, Miso: %d, Mosi: %d, SCK: %d", ESP_SD_CS_PIN, + esp3d_log("Custom spi : CS: %d, Miso: %d, Mosi: %d, SCK: %d", ESP_SD_CS_PIN, ESP_SD_MISO_PIN, ESP_SD_MOSI_PIN, ESP_SD_SCK_PIN); SPI.begin(ESP_SD_SCK_PIN, ESP_SD_MISO_PIN, ESP_SD_MOSI_PIN, ESP_SD_CS_PIN); #endif @@ -150,15 +150,13 @@ uint64_t ESP_SD::freeBytes(bool refresh) { uint ESP_SD::maxPathLength() { return 255; } bool ESP_SD::rename(const char *oldpath, const char *newpath) { - log_esp3d("rename %s to %s", oldpath, newpath); + esp3d_log("rename %s to %s", oldpath, newpath); return SD.rename(oldpath, newpath); } -bool ESP_SD::format(ESP3DOutput *output) { +bool ESP_SD::format() { // not available yet - if (output) { - output->printERROR("Not implemented!"); - } + esp3d_log_e("Not implemented!"); return false; } @@ -178,7 +176,7 @@ ESP_SDFile ESP_SD::open(const char *path, uint8_t mode) { String p = path; p.remove(p.lastIndexOf('/') + 1); if (!exists(p.c_str())) { - log_esp3d_e("Error opening: %s", path); + esp3d_log_e("Error opening: %s", path); return ESP_SDFile(); } } @@ -266,7 +264,7 @@ bool ESP_SD::rmdir(const char *path) { dir.close(); } p = String(); - log_esp3d("count %d", pathlist.size()); + esp3d_log("count %d", pathlist.size()); return res; } @@ -316,7 +314,7 @@ ESP_SDFile::ESP_SDFile(void *handle, bool isdir, bool iswritemode, // time _lastwrite = tSDFile_handle[i].getLastWrite(); _index = i; - // log_esp3d("Opening File at index %d",_index); + // esp3d_log("Opening File at index %d",_index); set = true; } } @@ -328,7 +326,7 @@ bool ESP_SDFile::seek(uint32_t pos, uint8_t mode) { void ESP_SDFile::close() { if (_index != -1) { - // log_esp3d("Closing File at index %d", _index); + // esp3d_log("Closing File at index %d", _index); tSDFile_handle[_index].close(); // reopen if mode = write // udate size + date @@ -341,19 +339,19 @@ void ESP_SDFile::close() { } } tSDFile_handle[_index] = File(); - // log_esp3d("Closing File at index %d",_index); + // esp3d_log("Closing File at index %d",_index); _index = -1; } } ESP_SDFile ESP_SDFile::openNextFile() { if ((_index == -1) || !_isdir) { - log_esp3d("openNextFile failed"); + esp3d_log("openNextFile failed"); return ESP_SDFile(); } File tmp = tSDFile_handle[_index].openNextFile(); if (tmp) { - log_esp3d("tmp name :%s %s %s", tmp.name(), + esp3d_log("tmp name :%s %s %s", tmp.name(), (tmp.isDirectory()) ? "isDir" : "isFile", _filename.c_str()); String s = tmp.name(); // if (s!="/")s+="/"; diff --git a/esp3d/src/modules/filesystem/sd/sd_native_esp8266.cpp b/esp3d/src/modules/filesystem/sd/sd_native_esp8266.cpp index 07dfb91a..c194e714 100644 --- a/esp3d/src/modules/filesystem/sd/sd_native_esp8266.cpp +++ b/esp3d/src/modules/filesystem/sd/sd_native_esp8266.cpp @@ -26,7 +26,7 @@ sd_native_esp8266.cpp - ESP3D sd support class #include -#include "../../../core/settings_esp3d.h" +#include "../../../core/esp3d_settings.h" #include "../esp_sd.h" extern File tSDFile_handle[ESP_MAX_SD_OPENHANDLE]; @@ -57,13 +57,13 @@ time_t getDateTimeFile(File& filehandle) { timefile.tm_isdst = -1; dt = mktime(&timefile); if (dt == -1) { - log_esp3d_e("mktime failed"); + esp3d_log_e("mktime failed"); } } else { - log_esp3d_e("stat file failed"); + esp3d_log_e("stat file failed"); } } else { - log_esp3d("check file for stat failed"); + esp3d_log("check file for stat failed"); } #endif // SD_TIMESTAMP_FEATURE return dt; @@ -74,21 +74,21 @@ uint8_t ESP_SD::getState(bool refresh) { // no need to go further if SD detect is not correct if (!((digitalRead(ESP_SD_DETECT_PIN) == ESP_SD_DETECT_VALUE) ? true : false)) { - log_esp3d("No SD State %d vs %d", digitalRead(ESP_SD_DETECT_PIN), + esp3d_log("No SD State %d vs %d", digitalRead(ESP_SD_DETECT_PIN), ESP_SD_DETECT_VALUE); _state = ESP_SDCARD_NOT_PRESENT; return _state; } else { - log_esp3d("SD Detect Pin ok"); + esp3d_log("SD Detect Pin ok"); } #endif // ESP_SD_DETECT_PIN // if busy doing something return state if (!((_state == ESP_SDCARD_NOT_PRESENT) || _state == ESP_SDCARD_IDLE)) { - log_esp3d("Busy SD State"); + esp3d_log("Busy SD State"); return _state; } if (!refresh) { - log_esp3d("SD State cache is %d", _state); + esp3d_log("SD State cache is %d", _state); return _state; // to avoid refresh=true + busy to reset SD and waste time } else { _sizechanged = true; @@ -98,24 +98,24 @@ uint8_t ESP_SD::getState(bool refresh) { // refresh content if card was removed if (SD.begin((ESP_SD_CS_PIN == -1) ? SS : ESP_SD_CS_PIN, SD_SCK_HZ(F_CPU / _spi_speed_divider))) { - log_esp3d("Init SD State ok"); + esp3d_log("Init SD State ok"); if (SD.size64() > 0) { - log_esp3d("SD available"); + esp3d_log("SD available"); _state = ESP_SDCARD_IDLE; } else { - log_esp3d_e("Cannot get card size"); + esp3d_log_e("Cannot get card size"); } } else { - log_esp3d_e("Init SD State failed"); + esp3d_log_e("Init SD State failed"); } - log_esp3d("SD State is %d", _state); + esp3d_log("SD State is %d", _state); return _state; } bool ESP_SD::begin() { _started = true; _state = ESP_SDCARD_NOT_PRESENT; - _spi_speed_divider = Settings_ESP3D::read_byte(ESP_SD_SPEED_DIV); + _spi_speed_divider = ESP3DSettings::readByte(ESP_SD_SPEED_DIV); // sanity check if (_spi_speed_divider <= 0) { _spi_speed_divider = 1; @@ -180,10 +180,9 @@ bool ESP_SD::rename(const char* oldpath, const char* newpath) { return (bool)SDFS.rename(oldpath, newpath); } -bool ESP_SD::format(ESP3DOutput* output) { - if (output) { - output->printERROR("Not implemented!"); - } +bool ESP_SD::format() { + esp3d_log_e("Not implemented!"); + return false; } @@ -204,7 +203,7 @@ ESP_SDFile ESP_SD::open(const char* path, uint8_t mode) { String p = path; p.remove(p.lastIndexOf('/') + 1); if (!exists(p.c_str())) { - log_esp3d("Error opening: %s", path); + esp3d_log("Error opening: %s", path); return ESP_SDFile(); } } @@ -222,16 +221,16 @@ bool ESP_SD::exists(const char* path) { if (strcmp(path, "/") == 0) { return _started; } - log_esp3d("%s exists ?", path); + esp3d_log("%s exists ?", path); res = SD.exists(path); if (!res) { - log_esp3d("Seems not - trying open it"); + esp3d_log("Seems not - trying open it"); ESP_SDFile root = ESP_SD::open(path, ESP_FILE_READ); if (root) { res = root.isDirectory(); } } - log_esp3d("Seems %s", res ? "yes" : "no"); + esp3d_log("Seems %s", res ? "yes" : "no"); return res; } @@ -288,7 +287,7 @@ bool ESP_SD::rmdir(const char* path) { dir.close(); } p = String(); - log_esp3d("count %d", pathlist.size()); + esp3d_log("count %d", pathlist.size()); return res; } @@ -349,7 +348,7 @@ ESP_SDFile::ESP_SDFile(void* handle, bool isdir, bool iswritemode, _lastwrite = 0; } _index = i; - // log_esp3d("Opening File at index %d",_index); + // esp3d_log("Opening File at index %d",_index); set = true; } } @@ -362,7 +361,7 @@ const char* ESP_SDFile::shortname() const { void ESP_SDFile::close() { if (_index != -1) { - // log_esp3d("Closing File at index %d", _index); + // esp3d_log("Closing File at index %d", _index); tSDFile_handle[_index].close(); // reopen if mode = write // udate size + date @@ -375,20 +374,20 @@ void ESP_SDFile::close() { } } tSDFile_handle[_index] = File(); - // log_esp3d("Closing File at index %d",_index); + // esp3d_log("Closing File at index %d",_index); _index = -1; } } ESP_SDFile ESP_SDFile::openNextFile() { if ((_index == -1) || !_isdir) { - log_esp3d_e("openNextFile failed"); + esp3d_log_e("openNextFile failed"); return ESP_SDFile(); } File tmp = tSDFile_handle[_index].openNextFile(); if (tmp) { String name = tmp.name(); - log_esp3d("tmp name :%s %s", name.c_str(), + esp3d_log("tmp name :%s %s", name.c_str(), (tmp.isDirectory()) ? "isDir" : "isFile"); String s = _filename; if (s != "/") { diff --git a/esp3d/src/modules/filesystem/sd/sd_sdfat2_esp32.cpp b/esp3d/src/modules/filesystem/sd/sd_sdfat2_esp32.cpp index 83d7c3c0..613c5733 100644 --- a/esp3d/src/modules/filesystem/sd/sd_sdfat2_esp32.cpp +++ b/esp3d/src/modules/filesystem/sd/sd_sdfat2_esp32.cpp @@ -26,7 +26,7 @@ sd_sdfat2_esp32.cpp - ESP3D sd support class #include -#include "../../../core/settings_esp3d.h" +#include "../../../core/esp3d_settings.h" #include "../esp_sd.h" #if SDFAT_FILE_TYPE == 1 @@ -89,13 +89,13 @@ time_t getDateTimeFile(File& filehandle) { timefile.tm_isdst = -1; dt = mktime(&timefile); if (dt == -1) { - log_esp3d_e("mktime failed"); + esp3d_log_e("mktime failed"); } } else { - log_esp3d_e("stat file failed"); + esp3d_log_e("stat file failed"); } } else { - log_esp3d_e("check file for stat failed"); + esp3d_log_e("check file for stat failed"); } #endif // SD_TIMESTAMP_FEATURE return dt; @@ -121,7 +121,7 @@ uint8_t ESP_SD::getState(bool refresh) { } // SD is idle or not detected, let see if still the case _state = ESP_SDCARD_NOT_PRESENT; - log_esp3d("Spi : CS: %d, Miso: %d, Mosi: %d, SCK: %d", + esp3d_log("Spi : CS: %d, Miso: %d, Mosi: %d, SCK: %d", ESP_SD_CS_PIN != -1 ? ESP_SD_CS_PIN : SS, ESP_SD_MISO_PIN != -1 ? ESP_SD_MISO_PIN : MISO, ESP_SD_MOSI_PIN != -1 ? ESP_SD_MOSI_PIN : MOSI, @@ -155,7 +155,7 @@ bool ESP_SD::begin() { pinMode(ESP_SD_CS_PIN, OUTPUT); _started = true; _state = ESP_SDCARD_NOT_PRESENT; - _spi_speed_divider = Settings_ESP3D::read_byte(ESP_SD_SPEED_DIV); + _spi_speed_divider = ESP3DSettings::readByte(ESP_SD_SPEED_DIV); // sanity check if (_spi_speed_divider <= 0) { _spi_speed_divider = 1; @@ -230,123 +230,108 @@ bool ESP_SD::rename(const char* oldpath, const char* newpath) { return SD.rename(oldpath, newpath); } -bool ESP_SD::format(ESP3DOutput* output) { +bool ESP_SD::format() { + uint32_t const ERASE_SIZE = 262144L; + uint32_t cardSectorCount = 0; + uint8_t sectorBuffer[512]; + // SdCardFactory constructs and initializes the appropriate card. + SdCardFactory cardFactory; + // Pointer to generic SD card. + SdCard* m_card = nullptr; if (ESP_SD::getState(true) == ESP_SDCARD_IDLE) { - uint32_t const ERASE_SIZE = 262144L; - uint32_t cardSectorCount = 0; - uint8_t sectorBuffer[512]; - // SdCardFactory constructs and initializes the appropriate card. - SdCardFactory cardFactory; - // Pointer to generic SD card. - SdCard* m_card = nullptr; // prepare m_card = cardFactory.newCard(SD_CONFIG); if (!m_card || m_card->errorCode()) { - if (output) { - output->printMSG("card init failed."); - } + esp3d_log_e("card init failed."); return false; } cardSectorCount = m_card->sectorCount(); if (!cardSectorCount) { - if (output) { - output->printMSG("Get sector count failed."); - } + esp3d_log_e("Get sector count failed."); return false; } - if (output) { - String s = - "Capacity detected :" + String(cardSectorCount * 5.12e-7) + "GB"; - output->printMSG(s.c_str()); + esp3d_log("Capacity detected :%d GB", cardSectorCount * 5.12e-7); + } else { + esp3d_log_e("SD not ready"); + return false; + } + + uint32_t firstBlock = 0; + uint32_t lastBlock; + uint16_t n = 0; + do { + lastBlock = firstBlock + ERASE_SIZE - 1; + if (lastBlock >= cardSectorCount) { + lastBlock = cardSectorCount - 1; } - - uint32_t firstBlock = 0; - uint32_t lastBlock; - uint16_t n = 0; - do { - lastBlock = firstBlock + ERASE_SIZE - 1; - if (lastBlock >= cardSectorCount) { - lastBlock = cardSectorCount - 1; - } - if (!m_card->erase(firstBlock, lastBlock)) { - if (output) { - output->printMSG("erase failed"); - } - return false; - } - - firstBlock += ERASE_SIZE; - if ((n++) % 64 == 63) { - Hal::wait(0); - } - } while (firstBlock < cardSectorCount); - - if (!m_card->readSector(0, sectorBuffer)) { - if (output) { - output->printMSG("readBlock"); - } - } - - ExFatFormatter exFatFormatter; - FatFormatter fatFormatter; - - // Format exFAT if larger than 32GB. - bool rtn = cardSectorCount > 67108864 - ? exFatFormatter.format(m_card, sectorBuffer, nullptr) - : fatFormatter.format(m_card, sectorBuffer, nullptr); - - if (!rtn) { - if (output) { - output->printMSG("erase failed"); - } + if (!m_card->erase(firstBlock, lastBlock)) { + esp3d_log_e("erase failed"); return false; } - return true; + firstBlock += ERASE_SIZE; + if ((n++) % 64 == 63) { + ESP3DHal::wait(0); + } + } while (firstBlock < cardSectorCount); + + if (!m_card->readSector(0, sectorBuffer)) { + esp3d_log("readBlock"); } - if (output) { - output->printMSG("cannot erase"); + + ExFatFormatter exFatFormatter; + FatFormatter fatFormatter; + + // Format exFAT if larger than 32GB. + bool rtn = cardSectorCount > 67108864 + ? exFatFormatter.format(m_card, sectorBuffer, nullptr) + : fatFormatter.format(m_card, sectorBuffer, nullptr); + + if (!rtn) { + esp3d_log_e("erase failed"); + return false; } - return false; + + return true; } ESP_SDFile ESP_SD::open(const char* path, uint8_t mode) { - log_esp3d("open %s, %d", path, mode); + esp3d_log("open %s, %d", path, mode); // do some check if (((strcmp(path, "/") == 0) && ((mode == ESP_FILE_WRITE) || (mode == ESP_FILE_APPEND))) || (strlen(path) == 0)) { - _sizechanged = true; - log_esp3d_e("reject %s", path); - return ESP_SDFile(); + _sizechanged = true; + esp3d_log_e("reject %s", path); + return ESP_SDFile(); } // path must start by '/' if (path[0] != '/') { - log_esp3d_e("%s is invalid path", path); - return ESP_SDFile(); + esp3d_log_e("%s is invalid path", path); + return ESP_SDFile(); } if (mode != ESP_FILE_READ) { - // check container exists - String p = path; - p.remove(p.lastIndexOf('/') + 1); - if (!exists(p.c_str())) { - log_esp3d_e("Error opening: %s", path); - return ESP_SDFile(); - } + // check container exists + String p = path; + p.remove(p.lastIndexOf('/') + 1); + if (!exists(p.c_str())) { + esp3d_log_e("Error opening: %s", path); + return ESP_SDFile(); + } } File tmp = SD.open(path, (mode == ESP_FILE_READ) ? FILE_READ : (mode == ESP_FILE_WRITE) ? FILE_WRITE : FILE_WRITE); if (tmp) { - ESP_SDFile esptmp(&tmp, strcmp(path, "/") == 0 ? true : tmp.isDir(), - (mode == ESP_FILE_READ) ? false : true, path); - log_esp3d("%s is a %s", path, tmp.isDir() ? "Dir" : "File"); - return esptmp; + ESP_SDFile esptmp(&tmp, strcmp(path, "/") == 0 ? true : tmp.isDir(), + (mode == ESP_FILE_READ) ? false : true, path); + esp3d_log("%s is a %s", path, tmp.isDir() ? "Dir" : "File"); + return esptmp; } else { - log_esp3d_e("open %s failed", path); - return ESP_SDFile(); + esp3d_log_e("open %s failed", path); + return ESP_SDFile(); } } @@ -354,14 +339,14 @@ bool ESP_SD::exists(const char* path) { bool res = false; // root should always be there if started if (strcmp(path, "/") == 0) { - return _started; + return _started; } res = SD.exists(path); if (!res) { - ESP_SDFile root = ESP_SD::open(path, ESP_FILE_READ); - if (root) { - res = root.isDirectory(); - } + ESP_SDFile root = ESP_SD::open(path, ESP_FILE_READ); + if (root) { + res = root.isDirectory(); + } } return res; } @@ -376,68 +361,68 @@ bool ESP_SD::mkdir(const char* path) { return SD.mkdir(path); } bool ESP_SD::rmdir(const char* path) { String p = path; if (!p.endsWith("/")) { - p += '/'; + p += '/'; } if (!p.startsWith("/")) { - p = '/' + p; + p = '/' + p; } if (!exists(p.c_str())) { - return false; + return false; } bool res = true; std::stack pathlist; pathlist.push(p); while (pathlist.size() > 0 && res) { - File dir = SD.open(pathlist.top().c_str()); - dir.rewindDirectory(); - File f = dir.openNextFile(); - bool candelete = true; - while (f && res) { - if (f.isDir()) { - candelete = false; - String newdir; - char tmp[255]; - f.getName(tmp, 254); - newdir = pathlist.top() + tmp; - newdir += "/"; - pathlist.push(newdir); - f.close(); - f = File(); - } else { - char tmp[255]; - f.getName(tmp, 254); - _sizechanged = true; - String filepath = pathlist.top() + tmp; - f.close(); - if (!SD.remove(filepath.c_str())) { - res = false; - } - f = dir.openNextFile(); - } - } - if (candelete) { - if (pathlist.top() != "/") { - res = SD.rmdir(pathlist.top().c_str()); - } - pathlist.pop(); - } - dir.close(); + File dir = SD.open(pathlist.top().c_str()); + dir.rewindDirectory(); + File f = dir.openNextFile(); + bool candelete = true; + while (f && res) { + if (f.isDir()) { + candelete = false; + String newdir; + char tmp[255]; + f.getName(tmp, 254); + newdir = pathlist.top() + tmp; + newdir += "/"; + pathlist.push(newdir); + f.close(); + f = File(); + } else { + char tmp[255]; + f.getName(tmp, 254); + _sizechanged = true; + String filepath = pathlist.top() + tmp; + f.close(); + if (!SD.remove(filepath.c_str())) { + res = false; + } + f = dir.openNextFile(); + } + } + if (candelete) { + if (pathlist.top() != "/") { + res = SD.rmdir(pathlist.top().c_str()); + } + pathlist.pop(); + } + dir.close(); } p = String(); - log_esp3d("count %d has error %d\n", pathlist.size(), res); + esp3d_log("count %d has error %d\n", pathlist.size(), res); return res; } void ESP_SD::closeAll() { for (uint8_t i = 0; i < ESP_MAX_SD_OPENHANDLE; i++) { - tSDFile_handle[i].close(); - tSDFile_handle[i] = File(); + tSDFile_handle[i].close(); + tSDFile_handle[i] = File(); } } bool ESP_SDFile::seek(uint32_t pos, uint8_t mode) { if (mode == ESP_SEEK_END) { - return tSDFile_handle[_index].seek(-pos); // based on SDFS comment + return tSDFile_handle[_index].seek(-pos); // based on SDFS comment } return tSDFile_handle[_index].seek(pos); } @@ -453,46 +438,46 @@ ESP_SDFile::ESP_SDFile(void* handle, bool isdir, bool iswritemode, _iswritemode = iswritemode; _size = 0; if (!handle) { - return; + return; } bool set = false; for (uint8_t i = 0; (i < ESP_MAX_SD_OPENHANDLE) && !set; i++) { - if (!tSDFile_handle[i]) { - tSDFile_handle[i] = *((File*)handle); - // filename - char tmp[255]; - tSDFile_handle[i].getName(tmp, 254); - _filename = path; - // name - _name = tmp; - if (_name.endsWith("/")) { - _name.remove(_name.length() - 1, 1); - _isdir = true; - } - if (_name[0] == '/') { - _name.remove(0, 1); - } - int pos = _name.lastIndexOf('/'); - if (pos != -1) { - _name.remove(0, pos + 1); - } - if (_name.length() == 0) { - _name = "/"; - } - // size - _size = tSDFile_handle[i].size(); - // time - if (!_isdir && !iswritemode) { - _lastwrite = getDateTimeFile(tSDFile_handle[i]); + if (!tSDFile_handle[i]) { + tSDFile_handle[i] = *((File*)handle); + // filename + char tmp[255]; + tSDFile_handle[i].getName(tmp, 254); + _filename = path; + // name + _name = tmp; + if (_name.endsWith("/")) { + _name.remove(_name.length() - 1, 1); + _isdir = true; + } + if (_name[0] == '/') { + _name.remove(0, 1); + } + int pos = _name.lastIndexOf('/'); + if (pos != -1) { + _name.remove(0, pos + 1); + } + if (_name.length() == 0) { + _name = "/"; + } + // size + _size = tSDFile_handle[i].size(); + // time + if (!_isdir && !iswritemode) { + _lastwrite = getDateTimeFile(tSDFile_handle[i]); - } else { - // no need date time for directory - _lastwrite = 0; - } - _index = i; - // log_esp3d("Opening File at index %d",_index); - set = true; - } + } else { + // no need date time for directory + _lastwrite = 0; + } + _index = i; + // esp3d_log("Opening File at index %d",_index); + set = true; + } } } // todo need also to add short filename @@ -503,56 +488,56 @@ const char* ESP_SDFile::shortname() const { static char sname[13]; File ftmp = SD.open(_filename.c_str()); if (ftmp) { - ftmp.getSFN(sname, 12); - ftmp.close(); - if (strlen(sname) == 0) { - return _name.c_str(); - } - return sname; + ftmp.getSFN(sname, 12); + ftmp.close(); + if (strlen(sname) == 0) { + return _name.c_str(); + } + return sname; } else { - return _name.c_str(); + return _name.c_str(); } #endif } void ESP_SDFile::close() { if (_index != -1) { - // log_esp3d("Closing File at index %d", _index); - tSDFile_handle[_index].close(); - // reopen if mode = write - // udate size + date - if (_iswritemode && !_isdir) { - File ftmp = SD.open(_filename.c_str()); - if (ftmp) { - _size = ftmp.size(); - _lastwrite = getDateTimeFile(ftmp); - ftmp.close(); - } - } - tSDFile_handle[_index] = File(); - // log_esp3d("Closing File at index %d",_index); - _index = -1; + // esp3d_log("Closing File at index %d", _index); + tSDFile_handle[_index].close(); + // reopen if mode = write + // udate size + date + if (_iswritemode && !_isdir) { + File ftmp = SD.open(_filename.c_str()); + if (ftmp) { + _size = ftmp.size(); + _lastwrite = getDateTimeFile(ftmp); + ftmp.close(); + } + } + tSDFile_handle[_index] = File(); + // esp3d_log("Closing File at index %d",_index); + _index = -1; } } ESP_SDFile ESP_SDFile::openNextFile() { if ((_index == -1) || !_isdir) { - log_esp3d("openNextFile failed"); - return ESP_SDFile(); + esp3d_log("openNextFile failed"); + return ESP_SDFile(); } File tmp = tSDFile_handle[_index].openNextFile(); if (tmp) { - char tmps[255]; - tmp.getName(tmps, 254); - log_esp3d("tmp name :%s %s", tmps, (tmp.isDir()) ? "isDir" : "isFile"); - String s = _filename; - if (s != "/") { - s += "/"; - } - s += tmps; - ESP_SDFile esptmp(&tmp, tmp.isDir(), false, s.c_str()); - esptmp.close(); - return esptmp; + char tmps[255]; + tmp.getName(tmps, 254); + esp3d_log("tmp name :%s %s", tmps, (tmp.isDir()) ? "isDir" : "isFile"); + String s = _filename; + if (s != "/") { + s += "/"; + } + s += tmps; + ESP_SDFile esptmp(&tmp, tmp.isDir(), false, s.c_str()); + esptmp.close(); + return esptmp; } return ESP_SDFile(); } diff --git a/esp3d/src/modules/filesystem/sd/sd_sdfat2_esp8266.cpp b/esp3d/src/modules/filesystem/sd/sd_sdfat2_esp8266.cpp index c74422b1..71293339 100644 --- a/esp3d/src/modules/filesystem/sd/sd_sdfat2_esp8266.cpp +++ b/esp3d/src/modules/filesystem/sd/sd_sdfat2_esp8266.cpp @@ -24,7 +24,7 @@ sd_sdfat2_esp8266.cpp - ESP3D sd support class #define FS_NO_GLOBALS #include -#include "../../../core/settings_esp3d.h" +#include "../../../core/esp3d_settings.h" #include "../esp_sd.h" #define NO_GLOBAL_SD @@ -73,13 +73,13 @@ time_t getDateTimeFile(sdfat::File& filehandle) { timefile.tm_isdst = -1; dt = mktime(&timefile); if (dt == -1) { - log_esp3d_e("mktime failed"); + esp3d_log_e("mktime failed"); } } else { - log_esp3d_e("stat file failed"); + esp3d_log_e("stat file failed"); } } else { - log_esp3d_e("check file for stat failed"); + esp3d_log_e("check file for stat failed"); } #endif // SD_TIMESTAMP_FEATURE return dt; @@ -90,21 +90,21 @@ uint8_t ESP_SD::getState(bool refresh) { // no need to go further if SD detect is not correct if (!((digitalRead(ESP_SD_DETECT_PIN) == ESP_SD_DETECT_VALUE) ? true : false)) { - log_esp3d("No SD State %d vs %d", digitalRead(ESP_SD_DETECT_PIN), + esp3d_log("No SD State %d vs %d", digitalRead(ESP_SD_DETECT_PIN), ESP_SD_DETECT_VALUE); _state = ESP_SDCARD_NOT_PRESENT; return _state; } else { - log_esp3d("SD Detect Pin ok"); + esp3d_log("SD Detect Pin ok"); } #endif // ESP_SD_DETECT_PIN // if busy doing something return state if (!((_state == ESP_SDCARD_NOT_PRESENT) || _state == ESP_SDCARD_IDLE)) { - log_esp3d("Busy SD State"); + esp3d_log("Busy SD State"); return _state; } if (!refresh) { - log_esp3d("SD State cache is %d", _state); + esp3d_log("SD State cache is %d", _state); return _state; // to avoid refresh=true + busy to reset SD and waste time } else { _sizechanged = true; @@ -114,24 +114,24 @@ uint8_t ESP_SD::getState(bool refresh) { // refresh content if card was removed if (SD.begin((ESP_SD_CS_PIN == -1) ? SS : ESP_SD_CS_PIN, SD_SCK_HZ(F_CPU / _spi_speed_divider))) { - log_esp3d("Init SD State ok"); + esp3d_log("Init SD State ok"); csd_t m_csd; if (SD.card()->readCSD(&m_csd) && sdCardCapacity(&m_csd) > 0) { _state = ESP_SDCARD_IDLE; } else { - log_esp3d_e("Cannot get card size"); + esp3d_log_e("Cannot get card size"); } } else { - log_esp3d_e("Init SD State failed"); + esp3d_log_e("Init SD State failed"); } - log_esp3d("SD State is %d", _state); + esp3d_log("SD State is %d", _state); return _state; } bool ESP_SD::begin() { _started = true; _state = ESP_SDCARD_NOT_PRESENT; - _spi_speed_divider = Settings_ESP3D::read_byte(ESP_SD_SPEED_DIV); + _spi_speed_divider = ESP3DSettings::readByte(ESP_SD_SPEED_DIV); // sanity check if (_spi_speed_divider <= 0) { _spi_speed_divider = 1; @@ -201,7 +201,7 @@ bool ESP_SD::rename(const char* oldpath, const char* newpath) { return SD.rename(oldpath, newpath); } -bool ESP_SD::format(ESP3DOutput* output) { +bool ESP_SD::format() { if (ESP_SD::getState(true) == ESP_SDCARD_IDLE) { uint32_t const ERASE_SIZE = 262144L; uint32_t cardSectorCount = 0; @@ -213,25 +213,19 @@ bool ESP_SD::format(ESP3DOutput* output) { // prepare m_card = cardFactory.newCard(SD_CONFIG); if (!m_card || m_card->errorCode()) { - if (output) { - output->printMSG("card init failed."); - } + esp3d_log_e("card init failed."); + return false; } cardSectorCount = m_card->sectorCount(); if (!cardSectorCount) { - if (output) { - output->printMSG("Get sector count failed."); - } + esp3d_log_e("Get sector count failed."); + return false; } - if (output) { - String s = - "Capacity detected :" + String(cardSectorCount * 5.12e-7) + "GB"; - output->printMSG(s.c_str()); - } + esp3d_log_("Capacity detected : %d GB", cardSectorCount * 5.12e-7); uint32_t firstBlock = 0; uint32_t lastBlock; @@ -242,22 +236,19 @@ bool ESP_SD::format(ESP3DOutput* output) { lastBlock = cardSectorCount - 1; } if (!m_card->erase(firstBlock, lastBlock)) { - if (output) { - output->printMSG("erase failed"); - } + esp3d_log_e("erase failed"); + return false; } firstBlock += ERASE_SIZE; if ((n++) % 64 == 63) { - Hal::wait(0); + ESP3DHal::wait(0); } } while (firstBlock < cardSectorCount); if (!m_card->readSector(0, sectorBuffer)) { - if (output) { - output->printMSG("readBlock"); - } + esp3d_log_e(("readBlock"); } ExFatFormatter exFatFormatter; @@ -269,95 +260,93 @@ bool ESP_SD::format(ESP3DOutput* output) { : fatFormatter.format(m_card, sectorBuffer, nullptr); if (!rtn) { - if (output) { - output->printMSG("erase failed"); - } + esp3d_log_e(("erase failed"); + return false; } return true; } - if (output) { - output->printMSG("cannot erase"); - } + esp3d_log_e(G("cannot erase"); + return false; } ESP_SDFile ESP_SD::open(const char* path, uint8_t mode) { - // do some check - if (((strcmp(path, "/") == 0) && - ((mode == ESP_FILE_WRITE) || (mode == ESP_FILE_APPEND))) || - (strlen(path) == 0)) { - _sizechanged = true; - return ESP_SDFile(); - } - // path must start by '/' - if (path[0] != '/') { - return ESP_SDFile(); - } - if (mode != ESP_FILE_READ) { - // check container exists - String p = path; - p.remove(p.lastIndexOf('/') + 1); - if (!exists(p.c_str())) { - log_esp3d("Error opening: %s", path); + // do some check + if (((strcmp(path, "/") == 0) && + ((mode == ESP_FILE_WRITE) || (mode == ESP_FILE_APPEND))) || + (strlen(path) == 0)) { + _sizechanged = true; + return ESP_SDFile(); + } + // path must start by '/' + if (path[0] != '/') { + return ESP_SDFile(); + } + if (mode != ESP_FILE_READ) { + // check container exists + String p = path; + p.remove(p.lastIndexOf('/') + 1); + if (!exists(p.c_str())) { + esp3d_log("Error opening: %s", path); return ESP_SDFile(); - } - } - sdfat::File tmp = SD.open(path, (mode == ESP_FILE_READ) ? FILE_READ - : (mode == ESP_FILE_WRITE) ? FILE_WRITE - : FILE_WRITE); - ESP_SDFile esptmp(&tmp, tmp.isDir(), (mode == ESP_FILE_READ) ? false : true, - path); - return esptmp; + } + } + sdfat::File tmp = SD.open(path, (mode == ESP_FILE_READ) ? FILE_READ + : (mode == ESP_FILE_WRITE) ? FILE_WRITE + : FILE_WRITE); + ESP_SDFile esptmp(&tmp, tmp.isDir(), (mode == ESP_FILE_READ) ? false : true, + path); + return esptmp; } bool ESP_SD::exists(const char* path) { - bool res = false; - // root should always be there if started - if (strcmp(path, "/") == 0) { - return _started; - } - log_esp3d("%s exists ?", path); - res = SD.exists(path); - if (!res) { - log_esp3d("Seems not - trying open it"); - ESP_SDFile root = ESP_SD::open(path, ESP_FILE_READ); - if (root) { + bool res = false; + // root should always be there if started + if (strcmp(path, "/") == 0) { + return _started; + } + esp3d_log("%s exists ?", path); + res = SD.exists(path); + if (!res) { + esp3d_log("Seems not - trying open it"); + ESP_SDFile root = ESP_SD::open(path, ESP_FILE_READ); + if (root) { res = root.isDirectory(); - } - } - log_esp3d("Seems %s", res ? "yes" : "no"); - return res; + } + } + esp3d_log("Seems %s", res ? "yes" : "no"); + return res; } bool ESP_SD::remove(const char* path) { - _sizechanged = true; - return SD.remove(path); + _sizechanged = true; + return SD.remove(path); } bool ESP_SD::mkdir(const char* path) { return SD.mkdir(path); } bool ESP_SD::rmdir(const char* path) { - String p = path; - if (!p.endsWith("/")) { - p += '/'; - } - if (!p.startsWith("/")) { - p = '/' + p; - } - if (!exists(p.c_str())) { - return false; - } - bool res = true; - std::stack pathlist; - pathlist.push(p); - while (pathlist.size() > 0 && res) { - sdfat::File dir = SD.open(pathlist.top().c_str()); - dir.rewindDirectory(); - sdfat::File f = dir.openNextFile(); - bool candelete = true; - while (f && res) { + String p = path; + if (!p.endsWith("/")) { + p += '/'; + } + if (!p.startsWith("/")) { + p = '/' + p; + } + if (!exists(p.c_str())) { + return false; + } + bool res = true; + std::stack pathlist; + pathlist.push(p); + while (pathlist.size() > 0 && res) { + sdfat::File dir = SD.open(pathlist.top().c_str()); + dir.rewindDirectory(); + sdfat::File f = dir.openNextFile(); + bool candelete = true; + while (f && res) { if (f.isDir()) { candelete = false; String newdir; @@ -379,54 +368,54 @@ bool ESP_SD::rmdir(const char* path) { } f = dir.openNextFile(); } - } - if (candelete) { + } + if (candelete) { if (pathlist.top() != "/") { res = SD.rmdir(pathlist.top().c_str()); } pathlist.pop(); - } - dir.close(); - } - p = String(); - log_esp3d("count %d", pathlist.size()); - return res; + } + dir.close(); + } + p = String(); + esp3d_log("count %d", pathlist.size()); + return res; } bool ESP_SDFile::seek(uint32_t pos, uint8_t mode) { - if (mode == SeekCur) { - return tSDFile_handle[_index].seekCur(pos); - } - if (mode == SeekEnd) { - return tSDFile_handle[_index].seekEnd(pos); - } - // if (mode == SeekSet) - return tSDFile_handle[_index].seekSet(pos); + if (mode == SeekCur) { + return tSDFile_handle[_index].seekCur(pos); + } + if (mode == SeekEnd) { + return tSDFile_handle[_index].seekEnd(pos); + } + // if (mode == SeekSet) + return tSDFile_handle[_index].seekSet(pos); } void ESP_SD::closeAll() { - for (uint8_t i = 0; i < ESP_MAX_SD_OPENHANDLE; i++) { - tSDFile_handle[i].close(); - tSDFile_handle[i] = sdfat::File(); - } + for (uint8_t i = 0; i < ESP_MAX_SD_OPENHANDLE; i++) { + tSDFile_handle[i].close(); + tSDFile_handle[i] = sdfat::File(); + } } ESP_SDFile::ESP_SDFile(void* handle, bool isdir, bool iswritemode, const char* path) { - _isdir = isdir; - _dirlist = ""; - _index = -1; - _filename = ""; - _name = ""; - _lastwrite = 0; - _iswritemode = iswritemode; - _size = 0; - if (!handle) { - return; - } - bool set = false; - for (uint8_t i = 0; (i < ESP_MAX_SD_OPENHANDLE) && !set; i++) { - if (!tSDFile_handle[i]) { + _isdir = isdir; + _dirlist = ""; + _index = -1; + _filename = ""; + _name = ""; + _lastwrite = 0; + _iswritemode = iswritemode; + _size = 0; + if (!handle) { + return; + } + bool set = false; + for (uint8_t i = 0; (i < ESP_MAX_SD_OPENHANDLE) && !set; i++) { + if (!tSDFile_handle[i]) { tSDFile_handle[i] = *((sdfat::File*)handle); // filename char tmp[255]; @@ -459,64 +448,64 @@ ESP_SDFile::ESP_SDFile(void* handle, bool isdir, bool iswritemode, _lastwrite = 0; } _index = i; - // log_esp3d("Opening File at index %d",_index); + // esp3d_log("Opening File at index %d",_index); set = true; - } - } + } + } } // todo need also to add short filename const char* ESP_SDFile::shortname() const { - static char sname[13]; - sdfat::File ftmp = SD.open(_filename.c_str()); - if (ftmp) { - ftmp.getSFN(sname); - ftmp.close(); - return sname; - } else { - return _name.c_str(); - } + static char sname[13]; + sdfat::File ftmp = SD.open(_filename.c_str()); + if (ftmp) { + ftmp.getSFN(sname); + ftmp.close(); + return sname; + } else { + return _name.c_str(); + } } void ESP_SDFile::close() { - if (_index != -1) { - // log_esp3d("Closing File at index %d", _index); - tSDFile_handle[_index].close(); - // reopen if mode = write - // udate size + date - if (_iswritemode && !_isdir) { + if (_index != -1) { + // esp3d_log("Closing File at index %d", _index); + tSDFile_handle[_index].close(); + // reopen if mode = write + // udate size + date + if (_iswritemode && !_isdir) { sdfat::File ftmp = SD.open(_filename.c_str()); if (ftmp) { _size = ftmp.size(); _lastwrite = getDateTimeFile(ftmp); ftmp.close(); } - } - tSDFile_handle[_index] = sdfat::File(); - // log_esp3d("Closing File at index %d",_index); - _index = -1; - } + } + tSDFile_handle[_index] = sdfat::File(); + // esp3d_log("Closing File at index %d",_index); + _index = -1; + } } ESP_SDFile ESP_SDFile::openNextFile() { - if ((_index == -1) || !_isdir) { - log_esp3d("openNextFile failed"); - return ESP_SDFile(); - } - sdfat::File tmp = tSDFile_handle[_index].openNextFile(); - if (tmp) { - char tmps[255]; - tmp.getName(tmps, 254); - log_esp3d("tmp name :%s %s", tmps, (tmp.isDir()) ? "isDir" : "isFile"); - String s = _filename; - if (s != "/") { + if ((_index == -1) || !_isdir) { + esp3d_log("openNextFile failed"); + return ESP_SDFile(); + } + sdfat::File tmp = tSDFile_handle[_index].openNextFile(); + if (tmp) { + char tmps[255]; + tmp.getName(tmps, 254); + esp3d_log("tmp name :%s %s", tmps, (tmp.isDir()) ? "isDir" : "isFile"); + String s = _filename; + if (s != "/") { s += "/"; - } - s += tmps; - ESP_SDFile esptmp(&tmp, tmp.isDir(), false, s.c_str()); - esptmp.close(); - return esptmp; - } - return ESP_SDFile(); + } + s += tmps; + ESP_SDFile esptmp(&tmp, tmp.isDir(), false, s.c_str()); + esptmp.close(); + return esptmp; + } + return ESP_SDFile(); } const char* ESP_SD::FilesystemName() { return "SDFat - " SD_FAT_VERSION_STR; } diff --git a/esp3d/src/modules/filesystem/sd/sdio_esp32.cpp b/esp3d/src/modules/filesystem/sd/sdio_esp32.cpp index 79a29f66..3b36e9b8 100644 --- a/esp3d/src/modules/filesystem/sd/sdio_esp32.cpp +++ b/esp3d/src/modules/filesystem/sd/sdio_esp32.cpp @@ -22,7 +22,7 @@ sdio_esp32.cpp - ESP3D sd support class #if (SD_DEVICE == ESP_SDIO) #include -#include "../../../core/settings_esp3d.h" +#include "../../../core/esp3d_settings.h" #include "../esp_sd.h" #include "FS.h" #include "SD_MMC.h" @@ -59,40 +59,40 @@ uint8_t ESP_SD::getState(bool refresh) { _state = ESP_SDCARD_NOT_PRESENT; // refresh content if card was removed if (!lastinitok) { - log_esp3d("last init was failed try sd_mmc begin"); + esp3d_log("last init was failed try sd_mmc begin"); SD_MMC.end(); if (SD_MMC.begin("/sdcard", SDIO_BIT_MODE)) { - log_esp3d("sd_mmc begin succeed"); + esp3d_log("sd_mmc begin succeed"); if (SD_MMC.cardType() != CARD_NONE) { _state = ESP_SDCARD_IDLE; lastinitok = true; - log_esp3d("sd_mmc card type succeed"); + esp3d_log("sd_mmc card type succeed"); } else { - log_esp3d_e("sd_mmc card type failed"); + esp3d_log_e("sd_mmc card type failed"); } } else { - log_esp3d_e("sd_mmc begin failed"); + esp3d_log_e("sd_mmc begin failed"); } } else { - log_esp3d("last init was ok try card type"); + esp3d_log("last init was ok try card type"); if (SD_MMC.cardType() != CARD_NONE) { - log_esp3d("checking sd_mmc card type succeed"); + esp3d_log("checking sd_mmc card type succeed"); _state = ESP_SDCARD_IDLE; } else { lastinitok = false; - log_esp3d_e("Soft sd check failed"); + esp3d_log_e("Soft sd check failed"); SD_MMC.end(); if (SD_MMC.begin("/sdcard", SDIO_BIT_MODE)) { - log_esp3d("new sd_mmc begin succeed"); + esp3d_log("new sd_mmc begin succeed"); if (SD_MMC.cardType() != CARD_NONE) { _state = ESP_SDCARD_IDLE; lastinitok = true; - log_esp3d("new sd_mmc card type succeed"); + esp3d_log("new sd_mmc card type succeed"); } else { - log_esp3d_e("new sd_mmc card type failed"); + esp3d_log_e("new sd_mmc card type failed"); } } else { - log_esp3d("new sd_mmc begin failed"); + esp3d_log("new sd_mmc begin failed"); } } } @@ -106,7 +106,7 @@ bool ESP_SD::begin() { SD_MMC.setPins(ESP_SDIO_CLK_PIN, ESP_SDIO_CMD_PIN, ESP_SDIO_D0_PIN, ESP_SDIO_D1_PIN, ESP_SDIO_D2_PIN, ESP_SDIO_D3_PIN) #endif //(ESP_SDIO_CLK_PIN != -1) - log_esp3d("Begin SDIO"); + esp3d_log("Begin SDIO"); _started = true; #ifdef SDMMC_FORCE_BEGIN _state = ESP_SDCARD_NOT_PRESENT; @@ -157,11 +157,10 @@ bool ESP_SD::rename(const char *oldpath, const char *newpath) { return SD_MMC.rename(oldpath, newpath); } -bool ESP_SD::format(ESP3DOutput *output) { +bool ESP_SD::format() { // not available yet - if (output) { - output->printERROR("Not implemented!"); - } + esp3d_log_e("Not implemented!"); + return false; } @@ -170,12 +169,12 @@ ESP_SDFile ESP_SD::open(const char *path, uint8_t mode) { if (((strcmp(path, "/") == 0) && ((mode == ESP_FILE_WRITE) || (mode == ESP_FILE_APPEND))) || (strlen(path) == 0)) { - log_esp3d_e("File open check : failed"); + esp3d_log_e("File open check : failed"); return ESP_SDFile(); } // path must start by '/' if (path[0] != '/') { - log_esp3d_e("File open path is invalid"); + esp3d_log_e("File open path is invalid"); return ESP_SDFile(); } if (mode != ESP_FILE_READ) { @@ -183,7 +182,7 @@ ESP_SDFile ESP_SD::open(const char *path, uint8_t mode) { String p = path; p.remove(p.lastIndexOf('/') + 1); if (!exists(p.c_str())) { - log_esp3d_e("Error opening: %s, %s does not exists", path, p.c_str()); + esp3d_log_e("Error opening: %s, %s does not exists", path, p.c_str()); return ESP_SDFile(); } } @@ -268,7 +267,7 @@ bool ESP_SD::rmdir(const char *path) { dir.close(); } p = String(); - log_esp3d("count %d", pathlist.size()); + esp3d_log("count %d", pathlist.size()); return res; } @@ -318,7 +317,7 @@ ESP_SDFile::ESP_SDFile(void *handle, bool isdir, bool iswritemode, // time _lastwrite = tSDFile_handle[i].getLastWrite(); _index = i; - // log_esp3d("Opening File at index %d",_index); + // esp3d_log("Opening File at index %d",_index); set = true; } } @@ -330,7 +329,7 @@ bool ESP_SDFile::seek(uint32_t pos, uint8_t mode) { void ESP_SDFile::close() { if (_index != -1) { - // log_esp3d("Closing File at index %d", _index); + // esp3d_log("Closing File at index %d", _index); tSDFile_handle[_index].close(); // reopen if mode = write // udate size + date @@ -343,19 +342,19 @@ void ESP_SDFile::close() { } } tSDFile_handle[_index] = File(); - // log_esp3d("Closing File at index %d",_index); + // esp3d_log("Closing File at index %d",_index); _index = -1; } } ESP_SDFile ESP_SDFile::openNextFile() { if ((_index == -1) || !_isdir) { - log_esp3d("openNextFile failed"); + esp3d_log("openNextFile failed"); return ESP_SDFile(); } File tmp = tSDFile_handle[_index].openNextFile(); if (tmp) { - log_esp3d("tmp name :%s %s %s", tmp.name(), + esp3d_log("tmp name :%s %s %s", tmp.name(), (tmp.isDirectory()) ? "isDir" : "isFile", _filename.c_str()); String s = tmp.name(); // if (s!="/")s+="/"; diff --git a/esp3d/src/modules/ftp/FtpServer.cpp b/esp3d/src/modules/ftp/FtpServer.cpp index 7313b5f1..bdddfb62 100644 --- a/esp3d/src/modules/ftp/FtpServer.cpp +++ b/esp3d/src/modules/ftp/FtpServer.cpp @@ -71,8 +71,9 @@ #include #include -#include "../../core/esp3doutput.h" -#include "../../core/settings_esp3d.h" +#include "../../core/esp3d_message.h" +#include "../../core/esp3d_settings.h" +#include "../../core/esp3d_string.h" #include "../authentication/authentication_service.h" #include "../network/netconfig.h" #include "ExtStreaming.h" @@ -159,12 +160,12 @@ bool FtpServer::started() { return _started; } bool FtpServer::begin() { end(); - if (Settings_ESP3D::read_byte(ESP_FTP_ON) != 1) { + if (ESP3DSettings::readByte(ESP_FTP_ON) != 1) { return true; } - ctrlPort = Settings_ESP3D::read_uint32(ESP_FTP_CTRL_PORT); - activePort = Settings_ESP3D::read_uint32(ESP_FTP_DATA_ACTIVE_PORT); - passivePort = Settings_ESP3D::read_uint32(ESP_FTP_DATA_PASSIVE_PORT); + ctrlPort = ESP3DSettings::readUint32(ESP_FTP_CTRL_PORT); + activePort = ESP3DSettings::readUint32(ESP_FTP_DATA_ACTIVE_PORT); + passivePort = ESP3DSettings::readUint32(ESP_FTP_DATA_PASSIVE_PORT); ftpServer = new WiFiServer(ctrlPort); if (!ftpServer) { return false; @@ -187,31 +188,31 @@ bool FtpServer::begin() { bool FtpServer::accessFS(const char* path) { if (_fsType != FS_UNKNOWN) { - log_esp3d_e("FTP: accessFS: already accessed"); + esp3d_log_e("FTP: accessFS: already accessed"); return false; } _fsType = FTPFS::getFSType(path); if (FTPFS::accessFS(_fsType)) { #if FTP_FEATURE == FS_SD if (FTPFS::getState(true) == ESP_SDCARD_NOT_PRESENT) { - log_esp3d_e("FTP: accessFS:No SD card"); + esp3d_log_e("FTP: accessFS:No SD card"); _fsType = FS_UNKNOWN; FTPFS::releaseFS(); return false; } else { FTPFS::setState(ESP_SDCARD_BUSY); - log_esp3d("FTP: accessFS: Accessed granted"); + esp3d_log("FTP: accessFS: Accessed granted"); } #endif // FTP_FEATURE == FS_SD return true; } - log_esp3d_e("FTP: accessFS: Access denied"); + esp3d_log_e("FTP: accessFS: Access denied"); return false; } void FtpServer::releaseFS() { if (_fsType != FS_UNKNOWN) { FTPFS::releaseFS(_fsType); - log_esp3d("FTP: accessFS: Access revoked"); + esp3d_log("FTP: accessFS: Access revoked"); _fsType = FS_UNKNOWN; } } @@ -245,7 +246,7 @@ void FtpServer::handle() { } if (cmdStage == FTP_Stop) { - log_esp3d("FTP_STOP"); + esp3d_log("FTP_STOP"); releaseFS(); if (client.connected()) { disconnectClient(); @@ -254,7 +255,7 @@ void FtpServer::handle() { } else if (cmdStage == FTP_Init) { // Ftp server waiting for connection abortTransfer(); iniVariables(); - log_esp3d(" Ftp server waiting for connection on port %d", ctrlPort); + esp3d_log(" Ftp server waiting for connection on port %d", ctrlPort); cmdStage = FTP_Client; } else if (cmdStage == FTP_Client) { // Ftp server idle if (ftpServer->hasClient()) { @@ -285,26 +286,26 @@ void FtpServer::handle() { if (transferStage == FTP_Retrieve) { // Retrieve data if (!doRetrieve()) { transferStage = FTP_Close; - log_esp3d("Release FS"); + esp3d_log("Release FS"); releaseFS(); } } else if (transferStage == FTP_Store) { // Store data if (!doStore()) { transferStage = FTP_Close; - log_esp3d("Release FS"); + esp3d_log("Release FS"); releaseFS(); } } else if (transferStage == FTP_List || transferStage == FTP_Nlst) { // LIST or NLST if (!doList()) { transferStage = FTP_Close; - log_esp3d("Release FS"); + esp3d_log("Release FS"); releaseFS(); } } else if (transferStage == FTP_Mlsd) { // MLSD listing if (!doMlsd()) { transferStage = FTP_Close; - log_esp3d("Release FS"); + esp3d_log("Release FS"); releaseFS(); } } else if (cmdStage > FTP_Client && @@ -319,21 +320,21 @@ void FtpServer::handle() { uint8_t dstat = data.status(); if (cmdStage != cmdStage0 || transferStage != transferStage0 || dstat != data0) { - log_esp3d(" Command: %d Transfer: %d Data: %d", cmdStage, transferStage, + esp3d_log(" Command: %d Transfer: %d Data: %d", cmdStage, transferStage, _HEX(dstat)); } #endif } void FtpServer::clientConnected() { - log_esp3d(" Client connected!"); + esp3d_log(" Client connected!"); client << F("220--- Welcome to FTP for ESP3D ---") << eol; client << F("220 -- Version ") << FW_VERSION << F(" --") << eol; iCL = 0; } bool FtpServer::isUser(const char* user) { - log_esp3d("Check User"); + esp3d_log("Check User"); _currentUser = ""; #ifdef AUTHENTICATION_FEATURE if ((user != nullptr) && ((strcmp(user, DEFAULT_ADMIN_LOGIN) == 0) || @@ -345,28 +346,28 @@ bool FtpServer::isUser(const char* user) { #endif // AUTHENTICATION_FEATURE (void)user; _currentUser = DEFAULT_ADMIN_LOGIN; - log_esp3d("User is %s", _currentUser.c_str()); + esp3d_log("User is %s", _currentUser.c_str()); return true; } bool FtpServer::isPassword(const char* password) { - log_esp3d("Check Password"); + esp3d_log("Check Password"); #ifdef AUTHENTICATION_FEATURE if (((_currentUser == DEFAULT_ADMIN_LOGIN) && AuthenticationService::isadmin(password)) || ((_currentUser == DEFAULT_USER_LOGIN) && AuthenticationService::isuser(password))) { - log_esp3d("Password ok"); + esp3d_log("Password ok"); return true; } return false; #endif // AUTHENTICATION_FEATURE (void)password; - log_esp3d("Password ok"); + esp3d_log("Password ok"); return true; } void FtpServer::disconnectClient() { - log_esp3d(" Disconnecting client"); + esp3d_log(" Disconnecting client"); abortTransfer(); client << F("221 Goodbye") << eol; client.stop(); @@ -374,7 +375,7 @@ void FtpServer::disconnectClient() { } bool FtpServer::processCommand() { - log_esp3d("Process Command"); + esp3d_log("Process Command"); /////////////////////////////////////// // // // AUTHENTICATION COMMANDS // @@ -385,14 +386,14 @@ bool FtpServer::processCommand() { // USER - User Identity // if (CommandIs("USER")) { - log_esp3d("USER : Command: %s Param: %s", command, + esp3d_log("USER : Command: %s Param: %s", command, (parameter == nullptr) ? "" : parameter); if (isUser(parameter)) { client << F("331 Ok. Password required") << eol; strcpy(cwdName, "/"); cmdStage = FTP_Pass; } else { - log_esp3d_e("Error USER"); + esp3d_log_e("Error USER"); client << F("530 ") << eol; cmdStage = FTP_Stop; } @@ -401,19 +402,19 @@ bool FtpServer::processCommand() { // PASS - Password // else if (CommandIs("PASS")) { - log_esp3d("PASS : Command: %s Param: %s", command, + esp3d_log("PASS : Command: %s Param: %s", command, (parameter == nullptr) ? "" : parameter); if (cmdStage != FTP_Pass) { - log_esp3d_e("Error PASS"); + esp3d_log_e("Error PASS"); client << F("503 ") << eol; cmdStage = FTP_Stop; } if (isPassword(parameter)) { - log_esp3d(" Authentication Ok. Waiting for commands."); + esp3d_log(" Authentication Ok. Waiting for commands."); client << F("230 Ok") << eol; cmdStage = FTP_Cmd; } else { - log_esp3d_e("Wrong PASS"); + esp3d_log_e("Wrong PASS"); client << F("530 ") << eol; cmdStage = FTP_Stop; } @@ -442,7 +443,7 @@ bool FtpServer::processCommand() { // else if ((cmdStage < FTP_Cmd) && (CommandIs("OPTS") || CommandIs("SYST") || CommandIs("TYPE"))) { - log_esp3d_e("Unsupported Command: %s Param: %s stage %d", command, + esp3d_log_e("Unsupported Command: %s Param: %s stage %d", command, (parameter == nullptr) ? "" : parameter, cmdStage); client << F("500 ") << eol; cmdStage = FTP_User; @@ -451,7 +452,7 @@ bool FtpServer::processCommand() { // Unrecognized commands at stage of authentication // else if (cmdStage < FTP_Cmd) { - log_esp3d_e("Unknow Command: %s Param: %s stage %d", command, + esp3d_log_e("Unknow Command: %s Param: %s stage %d", command, (parameter == nullptr) ? "" : parameter, cmdStage); client << F("200 ") << eol; cmdStage = FTP_Stop; @@ -487,14 +488,14 @@ bool FtpServer::processCommand() { // if found, ends the string on its position if (ok) { *pSep = 0; - log_esp3d("FTP: check accessFS"); + esp3d_log("FTP: check accessFS"); if (accessFS(cwdName)) { ok = FTPFS::exists(cwdName); - log_esp3d("FTP: releaseFS"); + esp3d_log("FTP: releaseFS"); releaseFS(); } else { ok = false; - log_esp3d_e("FTP: access is denied"); + esp3d_log_e("FTP: access is denied"); } } } @@ -518,9 +519,9 @@ bool FtpServer::processCommand() { // QUIT // else if (CommandIs("QUIT")) { - log_esp3d("QUIT"); + esp3d_log("QUIT"); client << F("221 Goodbye") << eol; - log_esp3d("FTP: releaseFS"); + esp3d_log("FTP: releaseFS"); releaseFS(); disconnectClient(); cmdStage = FTP_Stop; @@ -550,8 +551,8 @@ bool FtpServer::processCommand() { dataServer->begin(); dataIp.fromString(NetConfig::localIP()); dataPort = passivePort; - log_esp3d(" Connection management set to passive"); - log_esp3d(" Data port set to %d", dataPort); + esp3d_log(" Connection management set to passive"); + esp3d_log(" Data port set to %d", dataPort); client << F("227 Entering Passive Mode") << F(" (") << dataIp[0] << F(",") << dataIp[1] << F(",") << dataIp[2] << F(",") << dataIp[3] << F(",") << (dataPort >> 8) << F(",") << (dataPort & 255) << F(")") << eol; @@ -576,8 +577,8 @@ bool FtpServer::processCommand() { if (p == NULL) { client << F("501 Can't interpret parameters") << eol; } else { - log_esp3d(" Data IP set to %s", dataIp.toString().c_str()); - log_esp3d(" Data port set to %d", dataPort); + esp3d_log(" Data IP set to %s", dataIp.toString().c_str()); + esp3d_log(" Data port set to %d", dataPort); client << F("200 PORT command successful") << eol; dataConn = FTP_Active; } @@ -592,7 +593,7 @@ bool FtpServer::processCommand() { // else if( ParameterIs( "R" )) // client << F("200 B Ok") << eol; else { - log_esp3d_e("504 Only F(ile) is suported"); + esp3d_log_e("504 Only F(ile) is suported"); client << F("504 Only F(ile) is suported") << eol; } } @@ -628,23 +629,23 @@ bool FtpServer::processCommand() { else if (CommandIs("DELE")) { char path[FTP_CWD_SIZE]; if (haveParameter() && makeExistsPath(path)) { - log_esp3d("FTP: check accessFS"); + esp3d_log("FTP: check accessFS"); if (accessFS(path)) { if (FTPFS::remove(path)) { client << F("250 Deleted ") << parameter << eol; } else { client << F("450 Can't delete ") << parameter << eol; - log_esp3d_e("FTP: Can't delete %s", parameter); + esp3d_log_e("FTP: Can't delete %s", parameter); } - log_esp3d("FTP: releaseFS"); + esp3d_log("FTP: releaseFS"); releaseFS(); } else { client << F("550 Can't access ") << parameter << eol; - log_esp3d_e("FTP: Can't access %s", parameter); + esp3d_log_e("FTP: Can't access %s", parameter); } } else { client << F("550 Can't access ") << parameter << eol; - log_esp3d_e("FTP: Can't access %s", parameter); + esp3d_log_e("FTP: Can't access %s", parameter); } } // @@ -655,35 +656,35 @@ bool FtpServer::processCommand() { else if (CommandIs("LIST") || CommandIs("NLST") || CommandIs("MLSD")) { bool access = false; if (dataConnect()) { - log_esp3d("FTP: check accessFS"); + esp3d_log("FTP: check accessFS"); access = accessFS(cwdName); if (access) { dir = FTPFS::open(cwdName); - log_esp3d("Open %s", cwdName); + esp3d_log("Open %s", cwdName); } } if (dir) { - log_esp3d("Dir open"); + esp3d_log("Dir open"); nbMatch = 0; if (CommandIs("LIST")) { - log_esp3d("FTP: LIST"); + esp3d_log("FTP: LIST"); transferStage = FTP_List; } else if (CommandIs("NLST")) { - log_esp3d("FTP: NLST"); + esp3d_log("FTP: NLST"); transferStage = FTP_Nlst; } else { - log_esp3d("FTP: MLSD"); + esp3d_log("FTP: MLSD"); transferStage = FTP_Mlsd; } } else { - log_esp3d("FTP: Can't open directory %s", cwdName); + esp3d_log("FTP: Can't open directory %s", cwdName); // we got access but file opening failed, so let's release the FS if (access) { - log_esp3d("FTP: releaseFS"); + esp3d_log("FTP: releaseFS"); releaseFS(); } client << F("550 Can't open directory ") << cwdName << eol; - log_esp3d_e("FTP: Can't open directory %s", cwdName); + esp3d_log_e("FTP: Can't open directory %s", cwdName); data.stop(); } } @@ -696,11 +697,11 @@ bool FtpServer::processCommand() { char dtStr[15]; bool isdir = false; if (haveParameter() && makeExistsPath(path)) { - log_esp3d("FTP: check accessFS"); + esp3d_log("FTP: check accessFS"); if (accessFS(path)) { if (!getFileModTime(path, t)) { client << F("550 Unable to retrieve time for ") << parameter << eol; - log_esp3d_e("FTP: Unable to retrieve time for %s", parameter); + esp3d_log_e("FTP: Unable to retrieve time for %s", parameter); } else { if (file = FTPFS::open(path)) { isdir = file.isDirectory(); @@ -715,11 +716,11 @@ bool FtpServer::processCommand() { } client << F("; ") << path << eol << F("250 End.") << eol; } - log_esp3d("FTP: releaseFS"); + esp3d_log("FTP: releaseFS"); releaseFS(); } else { client << F("550 Can't access ") << parameter << eol; - log_esp3d_e("FTP: Can't access %s", parameter); + esp3d_log_e("FTP: Can't access %s", parameter); } } } @@ -735,16 +736,16 @@ bool FtpServer::processCommand() { else if (CommandIs("RETR")) { char path[FTP_CWD_SIZE]; if (haveParameter() && makeExistsPath(path)) { - log_esp3d("FTP: check accessFS"); + esp3d_log("FTP: check accessFS"); if (accessFS(path)) { file = FTPFS::open(path); if (!file.isOpen()) { client << F("450 Can't open ") << parameter << eol; - log_esp3d_e("FTP: Can't open %s", parameter); - log_esp3d("FTP: releaseFS"); + esp3d_log_e("FTP: Can't open %s", parameter); + esp3d_log("FTP: releaseFS"); releaseFS(); } else if (dataConnect(false)) { - log_esp3d(" Sending %s", parameter); + esp3d_log(" Sending %s", parameter); client << F("150-Connected to port ") << dataPort << eol; client << F("150 ") << file.size() << F(" bytes to download") << eol; millisBeginTrans = millis(); @@ -753,7 +754,7 @@ bool FtpServer::processCommand() { } } else { client << F("550 Can't access ") << parameter << eol; - log_esp3d_e("FTP: Can't access %s", parameter); + esp3d_log_e("FTP: Can't access %s", parameter); } } } @@ -764,7 +765,7 @@ bool FtpServer::processCommand() { else if (CommandIs("STOR") || CommandIs("APPE")) { char path[FTP_CWD_SIZE]; if (haveParameter() && makePath(path)) { - log_esp3d("FTP: check accessFS"); + esp3d_log("FTP: check accessFS"); if (accessFS(path)) { if (FTPFS::exists(path)) { file = FTPFS::open( @@ -775,22 +776,22 @@ bool FtpServer::processCommand() { } if (!file.isOpen()) { client << F("451 Can't open/create ") << parameter << eol; - log_esp3d_e("FTP: Can't open/create %s", parameter); - log_esp3d("FTP: releaseFS"); + esp3d_log_e("FTP: Can't open/create %s", parameter); + esp3d_log("FTP: releaseFS"); releaseFS(); } else if (!dataConnect()) { file.close(); - log_esp3d("FTP: releaseFS"); + esp3d_log("FTP: releaseFS"); releaseFS(); } else { - log_esp3d(" Receiving %s", parameter); + esp3d_log(" Receiving %s", parameter); millisBeginTrans = millis(); bytesTransfered = 0; transferStage = FTP_Store; } } else { client << F("550 Can't access ") << parameter << eol; - log_esp3d_e("FTP: Can't access %s", parameter); + esp3d_log_e("FTP: Can't access %s", parameter); } } } @@ -800,26 +801,26 @@ bool FtpServer::processCommand() { else if (CommandIs("MKD") || CommandIs("XMKD")) { char path[FTP_CWD_SIZE]; if (haveParameter() && makePath(path)) { - log_esp3d("FTP: check accessFS"); + esp3d_log("FTP: check accessFS"); if (accessFS(path)) { if (FTPFS::exists(path)) { client << F("521 \"") << parameter << F("\" directory already exists") << eol; } else { - log_esp3d(" Creating directory %s", parameter); + esp3d_log(" Creating directory %s", parameter); if (FTPFS::mkdir(path)) { client << F("257 \"") << parameter << F("\"") << F(" created") << eol; } else { client << F("550 Can't create \"") << parameter << F("\"") << eol; - log_esp3d_e("FTP: Can't create %s", parameter); + esp3d_log_e("FTP: Can't create %s", parameter); } } - log_esp3d("FTP: releaseFS"); + esp3d_log("FTP: releaseFS"); releaseFS(); } else { client << F("550 Can't access ") << parameter << eol; - log_esp3d_e("FTP: Can't access %s", parameter); + esp3d_log_e("FTP: Can't access %s", parameter); } } } @@ -829,21 +830,21 @@ bool FtpServer::processCommand() { else if (CommandIs("RMD") || CommandIs("XRMD")) { char path[FTP_CWD_SIZE]; if (haveParameter() && makeExistsPath(path)) { - log_esp3d("FTP: check accessFS"); + esp3d_log("FTP: check accessFS"); if (accessFS(path)) { if (FTPFS::rmdir(path)) { - log_esp3d(" Deleting %s", path); + esp3d_log(" Deleting %s", path); client << F("250 \"") << parameter << F("\" deleted") << eol; } else { client << F("550 Can't remove \"") << parameter << F("\". Directory not empty?") << eol; - log_esp3d_e("FTP: Can't remove %s", parameter); + esp3d_log_e("FTP: Can't remove %s", parameter); } - log_esp3d("FTP: releaseFS"); + esp3d_log("FTP: releaseFS"); releaseFS(); } else { client << F("550 Can't access ") << parameter << eol; - log_esp3d_e("FTP: Can't access %s", parameter); + esp3d_log_e("FTP: Can't access %s", parameter); } } } @@ -853,7 +854,7 @@ bool FtpServer::processCommand() { else if (CommandIs("RNFR")) { rnfrName[0] = 0; if (haveParameter() && makeExistsPath(rnfrName)) { - log_esp3d(" Ready for renaming %s", rnfrName); + esp3d_log(" Ready for renaming %s", rnfrName); client << F("350 RNFR accepted - file exists, ready for destination") << eol; rnfrCmd = true; @@ -868,7 +869,7 @@ bool FtpServer::processCommand() { if (strlen(rnfrName) == 0 || !rnfrCmd) { client << F("503 Need RNFR before RNTO") << eol; } else if (haveParameter() && makePath(path)) { - log_esp3d("FTP: check accessFS"); + esp3d_log("FTP: check accessFS"); if (accessFS(path)) { if (FTPFS::exists(path)) { client << F("553 ") << parameter << F(" already exists") << eol; @@ -887,7 +888,7 @@ bool FtpServer::processCommand() { if (fail) { client << F("550 \"") << dirp << F("\" is not directory") << eol; } else { - log_esp3d(" Renaming %s to %s", rnfrName, path); + esp3d_log(" Renaming %s to %s", rnfrName, path); if (FTPFS::rename(rnfrName, path)) { client << F("250 File successfully renamed or moved") << eol; } else { @@ -897,14 +898,14 @@ bool FtpServer::processCommand() { } if (fail) { client << F("451 Rename/move failure") << eol; - log_esp3d_e("FTP: Rename/move failure"); + esp3d_log_e("FTP: Rename/move failure"); } } - log_esp3d("FTP: releaseFS"); + esp3d_log("FTP: releaseFS"); releaseFS(); } else { client << F("550 Can't access ") << parameter << eol; - log_esp3d_e("FTP: Can't access %s", parameter); + esp3d_log_e("FTP: Can't access %s", parameter); } } rnfrCmd = false; @@ -946,24 +947,24 @@ bool FtpServer::processCommand() { client << "213 " << dt << eol; } else { client << "550 Unable to modify time" << eol; - log_esp3d_e("FTP: Unable to modify time"); + esp3d_log_e("FTP: Unable to modify time"); } } else if (mdtm) { // get file modification time time_t t = 0; char dtStr[15]; - log_esp3d("FTP: check accessFS"); + esp3d_log("FTP: check accessFS"); if (accessFS(path)) { if (getFileModTime(path, t)) { client << "213 " << makeDateTimeStr(dtStr, t) << eol; } else { client << "550 Unable to retrieve time" << eol; - log_esp3d_e("FTP: Unable to retrieve time"); + esp3d_log_e("FTP: Unable to retrieve time"); } - log_esp3d("FTP: releaseFS"); + esp3d_log("FTP: releaseFS"); releaseFS(); } else { client << "550 Unable to retrieve time" << eol; - log_esp3d_e("FTP: Unable to retrieve time for %s", path); + esp3d_log_e("FTP: Unable to retrieve time for %s", path); } } } @@ -975,25 +976,25 @@ bool FtpServer::processCommand() { else if (CommandIs("SIZE")) { char path[FTP_CWD_SIZE]; if (haveParameter() && makeExistsPath(path)) { - log_esp3d("FTP: check accessFS"); + esp3d_log("FTP: check accessFS"); if (accessFS(path)) { file = FTPFS::open(path); if (!file.isOpen()) { client << F("450 Can't open ") << parameter << eol; - log_esp3d_e("FTP: Can't open %s", parameter); + esp3d_log_e("FTP: Can't open %s", parameter); } else { client << F("213 ") << file.size() << eol; file.close(); } - log_esp3d("FTP: releaseFS"); + esp3d_log("FTP: releaseFS"); releaseFS(); } else { client << F("550 Can't access ") << parameter << eol; - log_esp3d_e("FTP: Can't access %s", parameter); + esp3d_log_e("FTP: Can't access %s", parameter); } } else { - log_esp3d_e("FTP:no parameter"); + esp3d_log_e("FTP:no parameter"); } } // @@ -1001,7 +1002,7 @@ bool FtpServer::processCommand() { // else if (CommandIs("SITE")) { if (ParameterIs("FREE")) { - log_esp3d("FTP: check accessFS"); + esp3d_log("FTP: check accessFS"); if (accessFS(cwdName)) { #if FTP_FEATURE == FS_ROOT uint8_t fs = FTPFS::getFSType(cwdName); @@ -1020,17 +1021,17 @@ bool FtpServer::processCommand() { capacity = FTPFS::totalBytes(); free = FTPFS::freeBytes(); #endif - client << F("200 ") << FTPFS::formatBytes(free) << F(" free of ") - << FTPFS::formatBytes(capacity) << F(" capacity") << eol; - log_esp3d("FTP: releaseFS"); + client << F("200 ") << esp3d_string::formatBytes(free) << F(" free of ") + << esp3d_string::formatBytes(capacity) << F(" capacity") << eol; + esp3d_log("FTP: releaseFS"); releaseFS(); } else { client << F("550 Can't access ") << cwdName << eol; - log_esp3d_e("FTP: Can't access %s", cwdName); + esp3d_log_e("FTP: Can't access %s", cwdName); } } else { client << F("500 Unknow SITE command ") << parameter << eol; - log_esp3d_e("FTP: Unknow SITE command %s", parameter); + esp3d_log_e("FTP: Unknow SITE command %s", parameter); } } // @@ -1038,7 +1039,7 @@ bool FtpServer::processCommand() { // else { client << F("500 Unknow command") << eol; - log_esp3d_e("FTP: Unknow command %s", command); + esp3d_log_e("FTP: Unknow command %s", command); } return true; } @@ -1115,7 +1116,7 @@ bool FtpServer::doStore() { return true; } client << F("552 Probably insufficient storage space") << eol; - log_esp3d_e("FTP: Probably insufficient storage space"); + esp3d_log_e("FTP: Probably insufficient storage space"); file.close(); data.stop(); return false; @@ -1123,7 +1124,7 @@ bool FtpServer::doStore() { bool FtpServer::doList() { if (!dataConnected()) { - log_esp3d_e("FTP: data not connected"); + esp3d_log_e("FTP: data not connected"); dir.close(); return false; } @@ -1147,10 +1148,10 @@ bool FtpServer::doList() { file.close(); return true; } else { - log_esp3d("FTP: no more file"); + esp3d_log("FTP: no more file"); } } else { - log_esp3d_e("FTP: dir not open"); + esp3d_log_e("FTP: dir not open"); } client << F("226 ") << nbMatch << F(" matches total") << eol; dir.close(); @@ -1160,12 +1161,12 @@ bool FtpServer::doList() { bool FtpServer::doMlsd() { if (!dataConnected()) { - log_esp3d_e("FTP: data not connected"); + esp3d_log_e("FTP: data not connected"); dir.close(); return false; } if (dir) { - log_esp3d("FTP: dir open"); + esp3d_log("FTP: dir open"); if (file) { file.close(); } @@ -1176,16 +1177,16 @@ bool FtpServer::doMlsd() { data << "Type=" << (file.isDirectory() ? F("dir") : F("file")) << ";Size=" << file.size() << ";Modify=" << makeDateTimeStr(dtStr, t) << "; " << file.name() << eol; - log_esp3d("%s %u %s %s", file.isDirectory() ? "dir" : "file", file.size(), + esp3d_log("%s %u %s %s", file.isDirectory() ? "dir" : "file", file.size(), makeDateTimeStr(dtStr, t), file.name()); file.close(); nbMatch++; return true; } else { - log_esp3d("FTP: no more file"); + esp3d_log("FTP: no more file"); } } else { - log_esp3d_e("FTP: dir not open"); + esp3d_log_e("FTP: dir not open"); } client << F("226-options: -a -l") << eol; client << F("226 ") << nbMatch << F(" matches total") << eol; @@ -1197,7 +1198,7 @@ bool FtpServer::doMlsd() { void FtpServer::closeTransfer() { uint32_t deltaT = (int32_t)(millis() - millisBeginTrans); if (deltaT > 0 && bytesTransfered > 0) { - log_esp3d(" Transfer completed in %d ms, %f kbytes/s", deltaT, + esp3d_log(" Transfer completed in %d ms, %f kbytes/s", deltaT, 1.0 * bytesTransfered / deltaT); client << F("226-File successfully transferred") << eol; client << F("226 ") << deltaT << F(" ms, ") << bytesTransfered / deltaT @@ -1215,7 +1216,7 @@ void FtpServer::abortTransfer() { file.close(); dir.close(); client << F("426 Transfer aborted") << eol; - log_esp3d_e(" Transfer aborted!"); + esp3d_log_e(" Transfer aborted!"); transferStage = FTP_Close; } // if( data.connected()) @@ -1237,7 +1238,7 @@ int8_t FtpServer::readChar() { if (client.available()) { char c = client.read(); - log_esp3d("read %c", c); + esp3d_log("read %c", c); if (c == '\\') { c = '/'; } @@ -1284,7 +1285,7 @@ int8_t FtpServer::readChar() { if (rc == -2) { iCL = 0; client << F("500 Syntax error") << eol; - log_esp3d_e("FTP: Syntax error"); + esp3d_log_e("FTP: Syntax error"); } } return rc; @@ -1295,7 +1296,7 @@ bool FtpServer::haveParameter() { return true; } client << "501 No file name" << eol; - log_esp3d_e("FTP: No file name"); + esp3d_log_e("FTP: No file name"); return false; } @@ -1337,13 +1338,13 @@ bool FtpServer::makePath(char* fullName, char* param) { } if (strlen(fullName) >= FTP_CWD_SIZE) { client << F("500 Command line too long") << eol; - log_esp3d_e("FTP: Command line too long"); + esp3d_log_e("FTP: Command line too long"); return false; } for (uint8_t i = 0; i < strlen(fullName); i++) if (!legalChar(fullName[i])) { client << F("553 File name not allowed") << eol; - log_esp3d_e("FTP: File name not allowed"); + esp3d_log_e("FTP: File name not allowed"); return false; } return true; @@ -1354,20 +1355,20 @@ bool FtpServer::makeExistsPath(char* path, char* param) { return false; } bool pathExists = false; - log_esp3d("FTP: check accessFS"); + esp3d_log("FTP: check accessFS"); if (accessFS(path)) { pathExists = FTPFS::exists(path); - log_esp3d("FTP: releaseFS"); + esp3d_log("FTP: releaseFS"); releaseFS(); } else { pathExists = false; - log_esp3d_e("FTP: access is denied"); + esp3d_log_e("FTP: access is denied"); } if (pathExists) { return true; } client << F("550 ") << path << F(" not found.") << eol; - log_esp3d_e("FTP: %s not found.", path); + esp3d_log_e("FTP: %s not found.", path); return false; } @@ -1425,7 +1426,7 @@ uint8_t FtpServer::getDateTime(char* dt, uint16_t* pyear, uint8_t* pmonth, dt[4] = 0; *pyear = atoi(dt); strncpy(dt, parameter, 14); - log_esp3d(" Modification time: %d/%d/%d %d:%d:%d of file: %s", *pyear, + esp3d_log(" Modification time: %d/%d/%d %d:%d:%d of file: %s", *pyear, *pmonth, *pday, *phour, *pminute, *psecond, (char*)(parameter + i)); return i; } @@ -1477,7 +1478,7 @@ bool FtpServer::getFileModTime(const char* path, time_t& t) { f.close(); return true; } - log_esp3d_e("Cannot get getLastWrite"); + esp3d_log_e("Cannot get getLastWrite"); t = 0; return false; } diff --git a/esp3d/src/modules/gcode_host/gcode_host.cpp b/esp3d/src/modules/gcode_host/gcode_host.cpp index 2e1c7846..a06b6025 100644 --- a/esp3d/src/modules/gcode_host/gcode_host.cpp +++ b/esp3d/src/modules/gcode_host/gcode_host.cpp @@ -20,9 +20,8 @@ // #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 #include "../../include/esp3d_config.h" #if defined(GCODE_HOST_FEATURE) -#include "../../core/commands.h" -#include "../../core/esp3doutput.h" -#include "../../core/settings_esp3d.h" +#include "../../core/esp3d_commands.h" +#include "../../core/esp3d_settings.h" #include "gcode_host.h" #if defined(FILESYSTEM_FEATURE) @@ -54,16 +53,20 @@ void GcodeHost::end() { _step = HOST_NO_STREAM; _currentPosition = 0; _bufferSize = 0; - _outputStream.client(ESP_STREAM_HOST_CLIENT); _totalSize = 0; _processedSize = 0; +#if defined(AUTHENTICATION_FEATURE) + _auth = ESP3DAuthenticationLevel::guest; +#else + _auth = ESP3DAuthenticationLevel::admin; +#endif // AUTHENTICATION_FEATURE } bool GcodeHost::push(const uint8_t *sbuf, size_t len) { if (_step == HOST_NO_STREAM) { return false; } - log_esp3d("Push got %d bytes", len); + esp3d_log("Push got %d bytes", len); for (size_t i = 0; i < len; i++) { // it is a line process it if (sbuf[i] == '\n' || sbuf[i] == '\r') { @@ -87,12 +90,12 @@ bool GcodeHost::push(const uint8_t *sbuf, size_t len) { bool GcodeHost::isAck(String &line) { if (line.indexOf("ok") != -1) { - log_esp3d("got ok"); + esp3d_log("got ok"); return true; } - if (Settings_ESP3D::GetFirmwareTarget() == SMOOTHIEWARE) { + if (ESP3DSettings::GetFirmwareTarget() == SMOOTHIEWARE) { if (line.indexOf("smoothie out") != -1) { - log_esp3d("got smoothie out"); + esp3d_log("got smoothie out"); return true; } } @@ -107,7 +110,7 @@ void GcodeHost::flush() { return; } _response = (const char *)_buffer; - log_esp3d("Stream got the response: %s", _response.c_str()); + esp3d_log("Stream got the response: %s", _response.c_str()); _response.toLowerCase(); if (isAck(_response)) { // check if we have proper ok response @@ -115,11 +118,11 @@ void GcodeHost::flush() { if (_step == HOST_WAIT4_ACK) { _step = HOST_READ_LINE; } else { - log_esp3d("Got ok but out of the query"); + esp3d_log("Got ok but out of the query"); } } else { if (_response.indexOf("error") != -1) { - log_esp3d_e("Got error"); + esp3d_log_e("Got error"); _step = HOST_ERROR_STREAM; } } @@ -131,7 +134,7 @@ void GcodeHost::flush() { void GcodeHost::startStream() { if (_fsType == TYPE_SCRIPT_STREAM) { _totalSize = _script.length(); - log_esp3d("Script line %s opened, size is %d", _script.c_str(), _totalSize); + esp3d_log("Script line %s opened, size is %d", _script.c_str(), _totalSize); } #if defined(FILESYSTEM_FEATURE) if (_fsType == TYPE_FS_STREAM) { @@ -140,11 +143,11 @@ void GcodeHost::startStream() { } if (FSfileHandle.isOpen()) { _totalSize = FSfileHandle.size(); - log_esp3d("File %s opened, size is %d", _fileName.c_str(), _totalSize); + esp3d_log("File %s opened, size is %d", _fileName.c_str(), _totalSize); } else { _error = ERROR_FILE_NOT_FOUND; _step = HOST_ERROR_STREAM; - log_esp3d_e("File not found: %s", _fileName.c_str()); + esp3d_log_e("File not found: %s", _fileName.c_str()); return; } } @@ -155,14 +158,14 @@ void GcodeHost::startStream() { _error = ERROR_FILE_NOT_FOUND; _step = HOST_ERROR_STREAM; _needRelease = false; - log_esp3d_e("File not found: %s", _fileName.c_str()); + esp3d_log_e("File not found: %s", _fileName.c_str()); return; } _needRelease = true; if (ESP_SD::getState(true) == ESP_SDCARD_NOT_PRESENT) { _error = ERROR_FILE_NOT_FOUND; _step = HOST_ERROR_STREAM; - log_esp3d_e("File not found: %s", _fileName.c_str()); + esp3d_log_e("File not found: %s", _fileName.c_str()); return; } ESP_SD::setState(ESP_SDCARD_BUSY); @@ -172,11 +175,11 @@ void GcodeHost::startStream() { } if (SDfileHandle.isOpen()) { _totalSize = SDfileHandle.size(); - log_esp3d("File %s opened, size is %d", _fileName.c_str(), _totalSize); + esp3d_log("File %s opened, size is %d", _fileName.c_str(), _totalSize); } else { _error = ERROR_FILE_NOT_FOUND; _step = HOST_ERROR_STREAM; - log_esp3d_e("File not found: %s", _fileName.c_str()); + esp3d_log_e("File not found: %s", _fileName.c_str()); return; } } @@ -191,7 +194,7 @@ void GcodeHost::startStream() { } void GcodeHost::endStream() { - log_esp3d("Ending Stream"); + esp3d_log("Ending Stream"); #if defined(FILESYSTEM_FEATURE) if (_fsType == TYPE_FS_STREAM) { if (FSfileHandle.isOpen()) { @@ -216,7 +219,7 @@ void GcodeHost::readNextCommand() { _currentCommand = ""; _step = HOST_PROCESS_LINE; if (_fsType == TYPE_SCRIPT_STREAM) { - log_esp3d("Reading next command from script"); + esp3d_log("Reading next command from script"); if (_currentPosition < _script.length()) { if (_script.indexOf(';', _currentPosition) != -1) { _currentCommand = _script.substring( @@ -227,7 +230,7 @@ void GcodeHost::readNextCommand() { _currentPosition = _script.length(); } _processedSize = _currentPosition; - log_esp3d("Command is %s", _currentCommand.c_str()); + esp3d_log("Command is %s", _currentCommand.c_str()); } else { _step = HOST_STOP_STREAM; } @@ -306,49 +309,45 @@ bool GcodeHost::isAckNeeded() { } void GcodeHost::processCommand() { if (!isCommand()) { - log_esp3d_e("Command %s is not valid", _currentCommand.c_str()); + esp3d_log_e("Command %s is not valid", _currentCommand.c_str()); _step = HOST_READ_LINE; } else { - log_esp3d("Command %s is valid", _currentCommand.c_str()); + esp3d_log("Command %s is valid", _currentCommand.c_str()); String cmd = _currentCommand + "\n"; bool isESPcmd = esp3d_commands.is_esp_command( (uint8_t *)_currentCommand.c_str(), _currentCommand.length()); - // TODO need to change if ESP3D -#if COMMUNICATION_PROTOCOL == SOCKET_SERIAL - ESP3DOutput output(ESP_SOCKET_SERIAL_CLIENT); -#endif // COMMUNICATION_PROTOCOL -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - ESP3DOutput output(ESP_SERIAL_CLIENT); -#endif // COMMUNICATION_PROTOCOL == SOCKET_SERIAL - ESP3DOutput outputhost(ESP_STREAM_HOST_CLIENT); if (isESPcmd) { - esp3d_commands.process((uint8_t *)cmd.c_str(), cmd.length(), &outputhost, - _auth_type); - // we display error in output but it is not a blocking error - log_esp3d("Command is ESP command: %s", cmd.c_str()); - _step = HOST_READ_LINE; - } else { -#if COMMUNICATION_PROTOCOL == SOCKET_SERIAL - esp3d_commands.process((uint8_t *)cmd.c_str(), cmd.length(), - &_outputStream, _auth_type, &output, - _outputStream.client() == ESP_ECHO_SERIAL_CLIENT - ? ESP_SOCKET_SERIAL_CLIENT - : 0); -#endif // COMMUNICATION_PROTOCOL == SOCKET_SERIAL -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - log_esp3d("Command is not ESP command:%s, client is %d and only is %d", - cmd.c_str(), (&_outputStream ? _outputStream.client() : 0), - (&output ? output.client() : 0)); - esp3d_commands.process((uint8_t *)cmd.c_str(), cmd.length(), - &_outputStream, _auth_type, &output); -#endif // COMMUNICATION_PROTOCOL == SOCKET_SERIAL - _startTimeOut = millis(); - log_esp3d("Command is GCODE command"); - if (isAckNeeded()) { - _step = HOST_WAIT4_ACK; - log_esp3d("Command wait for ack"); - } else { + ESP3DMessage *msg = ESP3DMessageManager::newMsg( + ESP3DClientType::stream, esp3d_commands.getOutputClient(), + (uint8_t *)_currentCommand.c_str(), _currentCommand.length(), _auth); + if (msg) { + // process command + esp3d_commands.process(msg); + esp3d_log("Command is ESP command: %s", cmd.c_str()); _step = HOST_READ_LINE; + } else { + esp3d_log_e("Cannot create message"); + _step = HOST_ERROR_STREAM; + } + + } else { + ESP3DMessage *msg = ESP3DMessageManager::newMsg( + ESP3DClientType::stream, esp3d_commands.getOutputClient(), + (uint8_t *)_currentCommand.c_str(), _currentCommand.length(), _auth); + if (msg) { + // process command + esp3d_commands.process(msg); + esp3d_log("Command is GCODE command: %s", cmd.c_str()); + _startTimeOut = millis(); + if (isAckNeeded()) { + _step = HOST_WAIT4_ACK; + esp3d_log("Command wait for ack"); + } else { + _step = HOST_READ_LINE; + } + } else { + esp3d_log_e("Cannot create message"); + _step = HOST_ERROR_STREAM; } } } @@ -375,7 +374,7 @@ void GcodeHost::handle() { break; case HOST_WAIT4_ACK: if (millis() - _startTimeOut > ESP_HOST_TIMEOUT) { - log_esp3d("Timeout waiting for ack"); + esp3d_log("Timeout waiting for ack"); _error = ERROR_TIME_OUT; _step = HOST_ERROR_STREAM; } @@ -396,19 +395,16 @@ void GcodeHost::handle() { // TODO check _response to put right error _error = ERROR_UNKNOW; } - log_esp3d_e("Error %d", _error); + esp3d_log_e("Error %d", _error); Error = "error: stream failed: " + String(_error) + "\n"; -#if COMMUNICATION_PROTOCOL == SOCKET_SERIAL - ESP3DOutput output(ESP_SOCKET_SERIAL_CLIENT); -#endif // COMMUNICATION_PROTOCOL -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - ESP3DOutput output(ESP_SERIAL_CLIENT); -#endif // COMMUNICATION_PROTOCOL - output.dispatch((const uint8_t *)Error.c_str(), Error.length()); + esp3d_commands.dispatch(Error.c_str(), ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); _step = HOST_STOP_STREAM; } break; default: // Not handled step - log_esp3d("Not handled step %d", _step); + esp3d_log("Not handled step %d", _step); break; } } @@ -417,7 +413,7 @@ bool GcodeHost::abort() { if (_step == HOST_NO_STREAM) { return false; } - log_esp3d("Aborting script"); + esp3d_log("Aborting script"); // TODO: what to do in addition ? _error = ERROR_STREAM_ABORTED; // we do not use step to do faster abort @@ -461,25 +457,28 @@ String GcodeHost::CheckSumCommand(const char *command, uint32_t commandnb) { bool GcodeHost::resetCommandNumbering() { String resetcmd = "M110 N0"; - if (Settings_ESP3D::GetFirmwareTarget() == SMOOTHIEWARE) { - resetcmd = "N0 M110"; + if (ESP3DSettings::GetFirmwareTarget() == SMOOTHIEWARE) { + resetcmd = "N0 M110\n"; } else { - resetcmd = "M110 N0"; + resetcmd = "M110 N0\n"; } _commandNumber = 1; - // need to use process to send command - return _outputStream.printLN(resetcmd.c_str()); + + return esp3d_commands.dispatch( + resetcmd.c_str(), esp3d_commands.getOutputClient(), no_id, + ESP3DMessageType::unique, ESP3DClientType::stream, + ESP3DAuthenticationLevel::admin); } uint32_t GcodeHost::getCommandNumber(String &response) { uint32_t l = 0; String sresend = "Resend:"; - if (Settings_ESP3D::GetFirmwareTarget() == SMOOTHIEWARE) { + if (ESP3DSettings::GetFirmwareTarget() == SMOOTHIEWARE) { sresend = "rs N"; } int pos = response.indexOf(sresend); if (pos == -1) { - log_esp3d_e("Cannot find label %d", _error); + esp3d_log_e("Cannot find label %d", _error); return -1; } pos += sresend.length(); @@ -488,22 +487,21 @@ uint32_t GcodeHost::getCommandNumber(String &response) { // remove potential unwished char snum.replace("\r", ""); l = snum.toInt(); - log_esp3d_e("Command number to resend is %s", String((uint32_t)l).c_str()); + esp3d_log_e("Command number to resend is %s", String((uint32_t)l).c_str()); return l; } bool GcodeHost::processScript(const char *line, - level_authenticate_type auth_type, - ESP3DOutput *output) { + ESP3DAuthenticationLevel auth_type) { _script = line; _script.trim(); - log_esp3d("Processing script: %s", _script.c_str()); + esp3d_log("Processing script: %s", _script.c_str()); if (_script.length() == 0) { - log_esp3d("No script to process"); + esp3d_log("No script to process"); return false; } if (_step != HOST_NO_STREAM) { - log_esp3d("Streaming already in progress"); + esp3d_log("Streaming already in progress"); return false; } _fsType = TYPE_SCRIPT_STREAM; @@ -513,36 +511,25 @@ bool GcodeHost::processScript(const char *line, } bool GcodeHost::processFile(const char *filename, - level_authenticate_type auth_type, - ESP3DOutput *output) { + ESP3DAuthenticationLevel auth_type) { bool target_found = false; -#if COMMUNICATION_PROTOCOL == SOCKET_SERIAL - log_esp3d("Processing file client is %d", - output ? output->client() : ESP_SOCKET_SERIAL_CLIENT); - _outputStream.client(output ? output->client() : ESP_SOCKET_SERIAL_CLIENT); -#endif // COMMUNICATION_PROTOCOL -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - log_esp3d("Processing file client is %d", - output ? output->client() : ESP_SERIAL_CLIENT); - _outputStream.client(output ? output->client() : ESP_SERIAL_CLIENT); -#endif // COMMUNICATION_PROTOCOL // sanity check _fileName = filename[0] != '/' ? "/" : ""; _fileName += filename; _fileName.trim(); - log_esp3d("Processing file: %s", filename); + esp3d_log("Processing file: %s", filename); if (_fileName.length() == 0) { - log_esp3d("No file to process"); + esp3d_log("No file to process"); return false; } if (_step != HOST_NO_STREAM) { - log_esp3d("Streaming already in progress"); + esp3d_log("Streaming already in progress"); return false; } // TODO UD = USB DISK #if defined(SD_DEVICE) if (_fileName.startsWith(ESP_SD_FS_HEADER)) { - log_esp3d("Processing SD file"); + esp3d_log("Processing SD file"); target_found = true; _fileName = _fileName.substring(strlen(ESP_SD_FS_HEADER), _fileName.length()); @@ -554,12 +541,12 @@ bool GcodeHost::processFile(const char *filename, target_found = true; _fileName = _fileName.substring(strlen(ESP_FLASH_FS_HEADER), _fileName.length()); - log_esp3d("Processing /FS file %s", _fileName.c_str()); + esp3d_log("Processing /FS file %s", _fileName.c_str()); _fsType = TYPE_FS_STREAM; } // if no header it is also an FS file if (!target_found) { - log_esp3d("Processing FS file %s", _fileName.c_str()); + esp3d_log("Processing FS file %s", _fileName.c_str()); _fsType = TYPE_FS_STREAM; target_found = true; } @@ -570,7 +557,7 @@ bool GcodeHost::processFile(const char *filename, _fsType = TYPE_SCRIPT_STREAM; // remove the / _script = &_fileName[1]; - log_esp3d("Processing Script file %s", _script.c_str()); + esp3d_log("Processing Script file %s", _script.c_str()); _fileName = ""; } _step = HOST_START_STREAM; diff --git a/esp3d/src/modules/gcode_host/gcode_host.h b/esp3d/src/modules/gcode_host/gcode_host.h index 66c5230d..9b066a52 100644 --- a/esp3d/src/modules/gcode_host/gcode_host.h +++ b/esp3d/src/modules/gcode_host/gcode_host.h @@ -18,144 +18,119 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - #ifndef _GCODE_HOST_H #define _GCODE_HOST_H #include + #include "../authentication/authentication_service.h" -class ESP3DOutput; -#define ERROR_NO_ERROR 0 -#define ERROR_TIME_OUT 1 -#define ERROR_CANNOT_SEND_DATA 2 -#define ERROR_LINE_NUMBER 3 -#define ERROR_ACK_NUMBER 4 -#define ERROR_MEMORY_PROBLEM 5 -#define ERROR_RESEND 6 -#define ERROR_NUMBER_MISMATCH 7 -#define ERROR_LINE_IGNORED 8 -#define ERROR_FILE_SYSTEM 9 -#define ERROR_CHECKSUM 10 -#define ERROR_UNKNOW 11 -#define ERROR_FILE_NOT_FOUND 12 -#define ERROR_STREAM_ABORTED 13 +#define ERROR_NO_ERROR 0 +#define ERROR_TIME_OUT 1 +#define ERROR_CANNOT_SEND_DATA 2 +#define ERROR_LINE_NUMBER 3 +#define ERROR_ACK_NUMBER 4 +#define ERROR_MEMORY_PROBLEM 5 +#define ERROR_RESEND 6 +#define ERROR_NUMBER_MISMATCH 7 +#define ERROR_LINE_IGNORED 8 +#define ERROR_FILE_SYSTEM 9 +#define ERROR_CHECKSUM 10 +#define ERROR_UNKNOW 11 +#define ERROR_FILE_NOT_FOUND 12 +#define ERROR_STREAM_ABORTED 13 -#define HOST_NO_STREAM 0 -#define HOST_START_STREAM 1 -#define HOST_READ_LINE 2 -#define HOST_PROCESS_LINE 3 -#define HOST_WAIT4_ACK 4 -#define HOST_PAUSE_STREAM 5 +#define HOST_NO_STREAM 0 +#define HOST_START_STREAM 1 +#define HOST_READ_LINE 2 +#define HOST_PROCESS_LINE 3 +#define HOST_WAIT4_ACK 4 +#define HOST_PAUSE_STREAM 5 #define HOST_RESUME_STREAM 6 -#define HOST_STOP_STREAM 7 -#define HOST_ERROR_STREAM 8 -#define HOST_ABORT_STREAM 9 +#define HOST_STOP_STREAM 7 +#define HOST_ERROR_STREAM 8 +#define HOST_ABORT_STREAM 9 #define TYPE_SCRIPT_STREAM 0 -#define TYPE_FS_STREAM 1 -#define TYPE_SD_STREAM 2 +#define TYPE_FS_STREAM 1 +#define TYPE_SD_STREAM 2 -#define ESP_HOST_BUFFER_SIZE 255 +#define ESP_HOST_BUFFER_SIZE 255 -class GcodeHost -{ -public: - GcodeHost(); - ~GcodeHost(); - bool begin(); - void end(); - void handle(); - bool push(const uint8_t * sbuf, size_t len); - void flush(); - /*bool sendCommand(const char* command, bool checksum = false, bool wait4ack = true, const char * ack=nullptr);*/ - uint32_t currentCommandNumber() - { - return _commandNumber; - } - void setCommandNumber(uint32_t n) - { - _commandNumber = n; - } - bool resetCommandNumbering(); - uint8_t Checksum(const char * command, uint32_t commandSize); - String CheckSumCommand(const char* command, uint32_t commandnb); +class GcodeHost { + public: + GcodeHost(); + ~GcodeHost(); + bool begin(); + void end(); + void handle(); + bool push(const uint8_t* sbuf, size_t len); + void flush(); + /*bool sendCommand(const char* command, bool checksum = false, bool wait4ack = + * true, const char * ack=nullptr);*/ + uint32_t currentCommandNumber() { return _commandNumber; } + void setCommandNumber(uint32_t n) { _commandNumber = n; } + bool resetCommandNumbering(); + uint8_t Checksum(const char* command, uint32_t commandSize); + String CheckSumCommand(const char* command, uint32_t commandnb); - /*bool wait_for_ack(uint32_t timeout = DEFAULT_TIMOUT, bool checksum=false, const char * ack=nullptr);*/ + /*bool wait_for_ack(uint32_t timeout = DEFAULT_TIMOUT, bool checksum=false, + * const char * ack=nullptr);*/ - uint32_t getCommandNumber(String & response); + uint32_t getCommandNumber(String& response); - uint8_t getErrorNum() - { - return _error; - } + uint8_t getErrorNum() { return _error; } - void setErrorNum(uint8_t error) - { - _error = error; - } + void setErrorNum(uint8_t error) { _error = error; } - uint8_t getStatus() - { - return _step; - } + uint8_t getStatus() { return _step; } - size_t totalSize() - { - return _totalSize; + size_t totalSize() { return _totalSize; } + size_t processedSize() { return _processedSize; } + uint8_t getFSType() { return _fsType; } + const char* fileName() { + if (_fileName.length() == 0) { + return nullptr; } - size_t processedSize() - { - return _processedSize; - } - uint8_t getFSType() - { - return _fsType; - } - const char * fileName() - { - if (_fileName.length() == 0) { - return nullptr; - } - return _fileName.c_str(); - } - bool processScript(const char * line, level_authenticate_type auth_type = LEVEL_ADMIN, ESP3DOutput * output=nullptr); - bool processFile(const char * filename, level_authenticate_type auth_type= LEVEL_ADMIN, ESP3DOutput * output=nullptr); - bool abort(); - bool pause(); - bool resume(); - void startStream(); - void readNextCommand(); - void endStream(); - void processCommand(); - bool isCommand(); - bool isAckNeeded(); - bool isAck(String & line); + return _fileName.c_str(); + } + bool processScript(const char* line, ESP3DAuthenticationLevel auth_type = + ESP3DAuthenticationLevel::admin); + bool processFile(const char* filename, ESP3DAuthenticationLevel auth_type = + ESP3DAuthenticationLevel::admin); + bool abort(); + bool pause(); + bool resume(); + void startStream(); + void readNextCommand(); + void endStream(); + void processCommand(); + bool isCommand(); + bool isAckNeeded(); + bool isAck(String& line); -private: - uint8_t _buffer [ESP_HOST_BUFFER_SIZE+1]; - size_t _bufferSize; - size_t _totalSize; - size_t _processedSize; - uint32_t _commandNumber; - uint32_t _needCommandNumber; - uint8_t _error; - uint8_t _step; - uint8_t _nextStep; - uint32_t _currentPosition; - String _fileName; - String _script; - uint8_t _fsType; - String _currentCommand; - String _response; - ESP3DOutput _outputStream; - level_authenticate_type _auth_type; - uint64_t _startTimeOut; - bool _needRelease ; + private: + ESP3DAuthenticationLevel _auth; + uint8_t _buffer[ESP_HOST_BUFFER_SIZE + 1]; + size_t _bufferSize; + size_t _totalSize; + size_t _processedSize; + uint32_t _commandNumber; + uint32_t _needCommandNumber; + uint8_t _error; + uint8_t _step; + uint8_t _nextStep; + uint32_t _currentPosition; + String _fileName; + String _script; + uint8_t _fsType; + String _currentCommand; + String _response; + ESP3DAuthenticationLevel _auth_type; + uint64_t _startTimeOut; + bool _needRelease; }; extern GcodeHost esp3d_gcode_host; -#endif //_GCODE_HOST_H - +#endif //_GCODE_HOST_H diff --git a/esp3d/src/modules/http/handlers/handle-SD-files.cpp b/esp3d/src/modules/http/handlers/handle-SD-files.cpp index 58fe3573..52f6075b 100644 --- a/esp3d/src/modules/http/handlers/handle-SD-files.cpp +++ b/esp3d/src/modules/http/handlers/handle-SD-files.cpp @@ -29,15 +29,16 @@ #endif // ARDUINO_ARCH_ESP8266 #include "../../authentication/authentication_service.h" #include "../../filesystem/esp_sd.h" +#include "../../../core/esp3d_string.h" // SD // SD files list and file commands void HTTP_Server::handleSDFileList() { - level_authenticate_type auth_level = - AuthenticationService::authenticated_level(); + ESP3DAuthenticationLevel auth_level = + AuthenticationService::getAuthenticatedLevel(); HTTP_Server::set_http_headers(); - if (auth_level == LEVEL_GUEST) { + if (auth_level == ESP3DAuthenticationLevel::guest) { _upload_status = UPLOAD_STATUS_NONE; _webserver->send(401, "text/plain", "Wrong authentication!"); return; @@ -66,7 +67,7 @@ void HTTP_Server::handleSDFileList() { if (ESP_SD::getState(true) == ESP_SDCARD_NOT_PRESENT) { _webserver->send(200, "text/plain", "{\"status\":\"no SD card\"}"); - log_esp3d("Release Sd called"); + esp3d_log("Release Sd called"); ESP_SD::releaseFS(); return; } @@ -122,7 +123,7 @@ void HTTP_Server::handleSDFileList() { filename.replace("//", "/"); if (filename != "/") { if (ESP_SD::rmdir(filename.c_str())) { - log_esp3d("Deleting %s", filename.c_str()); + esp3d_log("Deleting %s", filename.c_str()); status = shortname; status += " deleted"; } else { @@ -187,7 +188,7 @@ void HTTP_Server::handleSDFileList() { if (sub.isDirectory()) { buffer2send += "-1"; } else { - buffer2send += ESP_SD::formatBytes(sub.size()); + buffer2send += esp3d_string::formatBytes(sub.size()); } #ifdef FILESYSTEM_TIMESTAMP_FEATURE buffer2send += "\",\"time\":\""; @@ -238,15 +239,17 @@ void HTTP_Server::handleSDFileList() { buffer2send += "\"occupation\":\"0\","; } buffer2send += "\"status\":\"" + status + "\","; - buffer2send += - "\"total\":\"" + ESP_SD::formatBytes(ESP_SD::totalBytes()) + "\","; - buffer2send += - "\"used\":\"" + ESP_SD::formatBytes(ESP_SD::usedBytes()) + "\"}"; + buffer2send += "\"total\":\"" ; + buffer2send += esp3d_string::formatBytes(ESP_SD::totalBytes()) ; + buffer2send += "\","; + buffer2send += "\"used\":\""; + buffer2send += esp3d_string::formatBytes(ESP_SD::usedBytes()); + buffer2send += "\"}"; path = ""; _webserver->sendContent_P(buffer2send.c_str(), buffer2send.length()); _webserver->sendContent(""); _upload_status = UPLOAD_STATUS_NONE; - log_esp3d("Release Sd called"); + esp3d_log("Release Sd called"); ESP_SD::releaseFS(); } diff --git a/esp3d/src/modules/http/handlers/handle-command.cpp b/esp3d/src/modules/http/handlers/handle-command.cpp index d4d9e430..b86256c9 100644 --- a/esp3d/src/modules/http/handlers/handle-command.cpp +++ b/esp3d/src/modules/http/handlers/handle-command.cpp @@ -26,12 +26,11 @@ #if defined(ARDUINO_ARCH_ESP8266) #include #endif // ARDUINO_ARCH_ESP8266 -#include "../../../core/commands.h" -#include "../../../core/esp3doutput.h" -#include "../../../core/settings_esp3d.h" +#include "../../../core/esp3d_commands.h" +#include "../../../core/esp3d_message.h" +#include "../../../core/esp3d_settings.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}; @@ -46,19 +45,18 @@ bool isRealTimeCommand(unsigned char c) { // 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) { + ESP3DAuthenticationLevel auth_level = + AuthenticationService::getAuthenticatedLevel(); + if (auth_level == ESP3DAuthenticationLevel::guest) { _webserver->send(401, "text/plain", "Wrong authentication!"); return; } - // log_esp3d("Authentication = %d", auth_level); + // esp3d_log("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) { + if (ESP3DSettings::GetFirmwareTarget() == GRBL) { uint len = cmd.length(); if (!((len == 1 && isRealTimeCommand(cmd[0])) || (len == 2 && isRealTimeCommand(cmd[1])))) { @@ -74,27 +72,27 @@ void HTTP_Server::handle_web_command() { cmd += "\n"; // need to validate command } } - log_esp3d("Web Command: %s", cmd.c_str()); + esp3d_log("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); + ESP3DMessage *msg = ESP3DMessageManager::newMsg( + ESP3DClientType::http, esp3d_commands.getOutputClient(), + (uint8_t *)cmd.c_str(), cmd.length(), auth_level); + if (msg) { + msg->type = ESP3DMessageType::unique; + msg->request_id.code = 200; + // process command + esp3d_commands.process(msg); + } else { + esp3d_log_e("Cannot create message"); + } } 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 + // the command is not ESP3D so it will be forwarded to the output client + // 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); + esp3d_commands.dispatch(cmd.c_str(), esp3d_commands.getOutputClient(), + no_id, ESP3DMessageType::unique, + ESP3DClientType::http, auth_level); } } else if (_webserver->hasArg("ping")) { _webserver->send(200); diff --git a/esp3d/src/modules/http/handlers/handle-config.cpp b/esp3d/src/modules/http/handlers/handle-config.cpp index 8c3425c9..4bddc14c 100644 --- a/esp3d/src/modules/http/handlers/handle-config.cpp +++ b/esp3d/src/modules/http/handlers/handle-config.cpp @@ -18,30 +18,38 @@ 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 "../http_server.h" -#if defined (ARDUINO_ARCH_ESP32) +#if defined(ARDUINO_ARCH_ESP32) #include -#endif //ARDUINO_ARCH_ESP32 -#if defined (ARDUINO_ARCH_ESP8266) +#endif // ARDUINO_ARCH_ESP32 +#if defined(ARDUINO_ARCH_ESP8266) #include -#endif //ARDUINO_ARCH_ESP8266 +#endif // ARDUINO_ARCH_ESP8266 +#include "../../../core/esp3d_commands.h" +#include "../../../core/esp3d_message.h" #include "../../authentication/authentication_service.h" -#include "../../../core/commands.h" -#include "../../../core/esp3doutput.h" -//Handle web command query [ESP420]plain and send answer////////////////////////////// -void HTTP_Server::handle_config () -{ - level_authenticate_type auth_level = AuthenticationService::authenticated_level(); - String cmd = "[ESP420]"; - if (_webserver->hasArg("json")) { - cmd = "[ESP420]json="+_webserver->arg("json"); - } - ESP3DOutput output(_webserver); - output.printMSGLine("
");
-    esp3d_commands.process((uint8_t*)cmd.c_str(), cmd.length(), &output, auth_level);
-    output.printMSGLine("
"); - return; +// Handle web command query [ESP420]plain and send +// answer////////////////////////////// +void HTTP_Server::handle_config() { + ESP3DAuthenticationLevel auth_level = + AuthenticationService::getAuthenticatedLevel(); + String cmd = "[ESP420]addPreTag"; + if (_webserver->hasArg("json")) { + cmd += " json=" + _webserver->arg("json"); + } + ESP3DMessage *msg = ESP3DMessageManager::newMsg( + ESP3DClientType::http, ESP3DClientType::http, (uint8_t *)cmd.c_str(), + cmd.length(), auth_level); + if (msg) { + msg->type = ESP3DMessageType::unique; + msg->request_id.code = 200; + // process command + esp3d_commands.process(msg); + } else { + esp3d_log_e("Cannot create message"); + } + return; } -#endif //HTTP_FEATURE +#endif // HTTP_FEATURE diff --git a/esp3d/src/modules/http/handlers/handle-filenotfound.cpp b/esp3d/src/modules/http/handlers/handle-filenotfound.cpp index 2e4df13e..0a9c825a 100644 --- a/esp3d/src/modules/http/handlers/handle-filenotfound.cpp +++ b/esp3d/src/modules/http/handlers/handle-filenotfound.cpp @@ -43,25 +43,26 @@ void HTTP_Server::handle_not_found() { HTTP_Server::set_http_headers(); - if (AuthenticationService::authenticated_level() == LEVEL_GUEST) { + if (AuthenticationService::getAuthenticatedLevel() == + ESP3DAuthenticationLevel::guest) { _webserver->send(401, "text/plain", "Wrong authentication!"); return; } String path = _webserver->urlDecode(_webserver->uri()); String contentType = esp3d_string::getContentType(path.c_str()); String pathWithGz = path + ".gz"; - log_esp3d("URI: %s", path.c_str()); + esp3d_log("URI: %s", path.c_str()); #if defined(FILESYSTEM_FEATURE) if (ESP_FileSystem::exists(pathWithGz.c_str()) || ESP_FileSystem::exists(path.c_str())) { - log_esp3d("Path found `%s`", path.c_str()); + esp3d_log("Path found `%s`", path.c_str()); if (ESP_FileSystem::exists(pathWithGz.c_str())) { _webserver->sendHeader("Content-Encoding", "gzip"); path = pathWithGz; - log_esp3d("Path is gz `%s`", path.c_str()); + esp3d_log("Path is gz `%s`", path.c_str()); } if (!StreamFSFile(path.c_str(), contentType.c_str())) { - log_esp3d_e("Stream `%s` failed", path.c_str()); + esp3d_log_e("Stream `%s` failed", path.c_str()); } return; } @@ -90,7 +91,7 @@ void HTTP_Server::handle_not_found() { Serial2Socket.pause(); #endif // ESP3DLIB_ENV && COMMUNICATION_PROTOCOL == SOCKET_SERIAL if (!StreamSDFile(path.c_str(), contentType.c_str())) { - log_esp3d_e("Stream `%s` failed", path.c_str()); + esp3d_log_e("Stream `%s` failed", path.c_str()); } #if defined(ESP3DLIB_ENV) && COMMUNICATION_PROTOCOL == SOCKET_SERIAL Serial2Socket.pause(false); @@ -116,7 +117,7 @@ void HTTP_Server::handle_not_found() { path = pathWithGz; } if (!StreamFSFile(path.c_str(), contentType.c_str())) { - log_esp3d_e("Stream `%s` failed", path.c_str()); + esp3d_log_e("Stream `%s` failed", path.c_str()); } return; } diff --git a/esp3d/src/modules/http/handlers/handle-files.cpp b/esp3d/src/modules/http/handlers/handle-files.cpp index c38efa77..9505a715 100644 --- a/esp3d/src/modules/http/handlers/handle-files.cpp +++ b/esp3d/src/modules/http/handlers/handle-files.cpp @@ -33,14 +33,16 @@ #include "../../time/time_service.h" #endif // FILESYSTEM_TIMESTAMP_FEATURE +#include "../../../core/esp3d_string.h" + // 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) { + ESP3DAuthenticationLevel auth_level = + AuthenticationService::getAuthenticatedLevel(); + if (auth_level == ESP3DAuthenticationLevel::guest) { _upload_status = UPLOAD_STATUS_NONE; _webserver->send(401, "text/plain", "Wrong authentication!"); return; @@ -109,7 +111,7 @@ void HTTP_Server::handleFSFileList() { filename.replace("//", "/"); if (filename != "/") { if (ESP_FileSystem::rmdir(filename.c_str())) { - log_esp3d("Deleting %s", filename.c_str()); + esp3d_log("Deleting %s", filename.c_str()); status = shortname; status += " deleted"; } else { @@ -168,7 +170,7 @@ void HTTP_Server::handleFSFileList() { if (sub.isDirectory()) { buffer2send += "-1"; } else { - buffer2send += ESP_FileSystem::formatBytes(sub.size()); + buffer2send += esp3d_string::formatBytes(sub.size()); } #ifdef FILESYSTEM_TIMESTAMP_FEATURE buffer2send += "\",\"time\":\""; @@ -211,12 +213,14 @@ void HTTP_Server::handleFSFileList() { buffer2send += "\"occupation\":\"0\","; } buffer2send += "\"status\":\"" + status + "\","; - buffer2send += "\"total\":\"" + - ESP_FileSystem::formatBytes(ESP_FileSystem::totalBytes()) + - "\","; - buffer2send += "\"used\":\"" + - ESP_FileSystem::formatBytes(ESP_FileSystem::usedBytes()) + - "\"}"; + buffer2send += "\"total\":\""; + buffer2send += esp3d_string::formatBytes(ESP_FileSystem::totalBytes()); + buffer2send += "\","; + + buffer2send += "\"used\":\""; + buffer2send += esp3d_string::formatBytes(ESP_FileSystem::usedBytes()); + + buffer2send += +"\"}"; path = ""; _webserver->sendContent_P(buffer2send.c_str(), buffer2send.length()); _webserver->sendContent(""); diff --git a/esp3d/src/modules/http/handlers/handle-login.cpp b/esp3d/src/modules/http/handlers/handle-login.cpp index 18e5937a..53f61d4c 100644 --- a/esp3d/src/modules/http/handlers/handle-login.cpp +++ b/esp3d/src/modules/http/handlers/handle-login.cpp @@ -26,8 +26,8 @@ #if defined(ARDUINO_ARCH_ESP8266) #include #endif // ARDUINO_ARCH_ESP8266 -#include "../../../core/esp3doutput.h" -#include "../../../core/settings_esp3d.h" +#include "../../../core/esp3d_message.h" +#include "../../../core/esp3d_settings.h" #include "../../authentication/authentication_service.h" // login status check @@ -40,7 +40,7 @@ void HTTP_Server::handle_login() { // Disconnect can be done anytime no need to check credential if (_webserver->hasArg("DISCONNECT") && _webserver->arg("DISCONNECT") == "YES") { - AuthenticationService::ClearCurrentSession(); + AuthenticationService::ClearCurrentHttpSession(); _webserver->sendHeader("Set-Cookie", "ESPSESSIONID=0"); _webserver->sendHeader("Cache-Control", "no-cache"); _webserver->send( @@ -48,8 +48,8 @@ void HTTP_Server::handle_login() { "{\"status\":\"disconnected\",\"authentication_lvl\":\"guest\"}"); return; } - level_authenticate_type auth_level = - AuthenticationService::authenticated_level(); + ESP3DAuthenticationLevel auth_level = + AuthenticationService::getAuthenticatedLevel(); // check is it is a submission or a query if (_webserver->hasArg("SUBMIT")) { // is there a correct list of query? @@ -66,10 +66,10 @@ void HTTP_Server::handle_login() { if (_webserver->hasArg("NEWPASSWORD")) { String newpassword = _webserver->arg("NEWPASSWORD"); // check new password - if (Settings_ESP3D::isValidStringSetting(newpassword.c_str(), - ESP_ADMIN_PWD)) { - if (!Settings_ESP3D::write_string(ESP_ADMIN_PWD, - newpassword.c_str())) { + if (ESP3DSettings::isValidStringSetting(newpassword.c_str(), + ESP_ADMIN_PWD)) { + if (!ESP3DSettings::writeString(ESP_ADMIN_PWD, + newpassword.c_str())) { code = 500; status = "Set failed!"; } else { @@ -87,16 +87,20 @@ void HTTP_Server::handle_login() { 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))) { + if (((auth_level == ESP3DAuthenticationLevel::user) && + (sUser == DEFAULT_USER_LOGIN)) || + ((auth_level == ESP3DAuthenticationLevel::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(); + (sUser == DEFAULT_ADMIN_LOGIN) + ? ESP3DAuthenticationLevel::admin + : ESP3DAuthenticationLevel::user, + ESP3DClientType::http, session.c_str())) { + AuthenticationService::ClearCurrentHttpSession(); code = 200; status = "ok"; String tmps = "ESPSESSIONID="; @@ -108,7 +112,8 @@ void HTTP_Server::handle_login() { } } } else { - if (auth_level == LEVEL_USER || auth_level == LEVEL_ADMIN) { + if (auth_level == ESP3DAuthenticationLevel::user || + auth_level == ESP3DAuthenticationLevel::admin) { status = "Identified"; code = 200; } @@ -117,9 +122,9 @@ void HTTP_Server::handle_login() { String smsg = "{\"status\":\""; smsg += status; smsg += "\",\"authentication_lvl\":\""; - if (auth_level == LEVEL_USER) { + if (auth_level == ESP3DAuthenticationLevel::user) { smsg += "user"; - } else if (auth_level == LEVEL_ADMIN) { + } else if (auth_level == ESP3DAuthenticationLevel::admin) { smsg += "admin"; } else { smsg += "guest"; diff --git a/esp3d/src/modules/http/handlers/handle-mks-files.cpp b/esp3d/src/modules/http/handlers/handle-mks-files.cpp index 19d646d8..483cd3b2 100644 --- a/esp3d/src/modules/http/handlers/handle-mks-files.cpp +++ b/esp3d/src/modules/http/handlers/handle-mks-files.cpp @@ -18,33 +18,34 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../../include/esp3d_config.h" -#if defined (HTTP_FEATURE) && (COMMUNICATION_PROTOCOL == MKS_SERIAL) +#if defined(HTTP_FEATURE) && (COMMUNICATION_PROTOCOL == MKS_SERIAL) #include "../http_server.h" -#if defined (ARDUINO_ARCH_ESP32) +#if defined(ARDUINO_ARCH_ESP32) #include -#endif //ARDUINO_ARCH_ESP32 -#if defined (ARDUINO_ARCH_ESP8266) +#endif // ARDUINO_ARCH_ESP32 +#if defined(ARDUINO_ARCH_ESP8266) #include -#endif //ARDUINO_ARCH_ESP8266 -#include "../../mks/mks_service.h" +#endif // ARDUINO_ARCH_ESP8266 #include "../../authentication/authentication_service.h" +#include "../../mks/mks_service.h" -void HTTP_Server::handleMKSUpload () -{ - 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; - } - if ( (_upload_status == UPLOAD_STATUS_FAILED) || (_upload_status == UPLOAD_STATUS_CANCELLED) ) { - _webserver->send (500, "text/plain", "Upload failed!"); - _upload_status = UPLOAD_STATUS_NONE; - return; - } - //no error - _webserver->send (200, "text/plain", "{\"status\":\"ok\"}"); +void HTTP_Server::handleMKSUpload() { + ESP3DAuthenticationLevel auth_level = + AuthenticationService::getAuthenticatedLevel(); + if (auth_level == ESP3DAuthenticationLevel::guest) { _upload_status = UPLOAD_STATUS_NONE; + _webserver->send(401, "text/plain", "Wrong authentication!"); + return; + } + if ((_upload_status == UPLOAD_STATUS_FAILED) || + (_upload_status == UPLOAD_STATUS_CANCELLED)) { + _webserver->send(500, "text/plain", "Upload failed!"); + _upload_status = UPLOAD_STATUS_NONE; + return; + } + // no error + _webserver->send(200, "text/plain", "{\"status\":\"ok\"}"); + _upload_status = UPLOAD_STATUS_NONE; } -#endif //HTTP_FEATURE && (COMMUNICATION_PROTOCOL == MKS_SERIAL) +#endif // HTTP_FEATURE && (COMMUNICATION_PROTOCOL == MKS_SERIAL) diff --git a/esp3d/src/modules/http/handlers/handle-root.cpp b/esp3d/src/modules/http/handlers/handle-root.cpp index 15f798a6..4e40938c 100644 --- a/esp3d/src/modules/http/handlers/handle-root.cpp +++ b/esp3d/src/modules/http/handlers/handle-root.cpp @@ -50,14 +50,14 @@ void HTTP_Server::handle_root() { ESP_FileSystem::exists(path.c_str())) && !_webserver->hasArg("forcefallback") && _webserver->arg("forcefallback") != "yes") { - log_esp3d("Path found `%s`", path.c_str()); + esp3d_log("Path found `%s`", path.c_str()); if (ESP_FileSystem::exists(pathWithGz.c_str())) { _webserver->sendHeader("Content-Encoding", "gzip"); path = pathWithGz; - log_esp3d("Path is gz `%s`", path.c_str()); + esp3d_log("Path is gz `%s`", path.c_str()); } if (!StreamFSFile(path.c_str(), contentType.c_str())) { - log_esp3d_e("Stream `%s` failed", path.c_str()); + esp3d_log_e("Stream `%s` failed", path.c_str()); } return; } diff --git a/esp3d/src/modules/http/handlers/handle-snap.cpp b/esp3d/src/modules/http/handlers/handle-snap.cpp index dabb19d9..5ff80e9d 100644 --- a/esp3d/src/modules/http/handlers/handle-snap.cpp +++ b/esp3d/src/modules/http/handlers/handle-snap.cpp @@ -18,26 +18,26 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../../include/esp3d_config.h" -#if defined (HTTP_FEATURE) && defined (CAMERA_DEVICE) +#if defined(HTTP_FEATURE) && defined(CAMERA_DEVICE) #include "../../camera/camera.h" #include "../http_server.h" -#if defined (ARDUINO_ARCH_ESP32) +#if defined(ARDUINO_ARCH_ESP32) #include -#endif //ARDUINO_ARCH_ESP32 -#if defined (ARDUINO_ARCH_ESP8266) +#endif // ARDUINO_ARCH_ESP32 +#if defined(ARDUINO_ARCH_ESP8266) #include -#endif //ARDUINO_ARCH_ESP8266 +#endif // ARDUINO_ARCH_ESP8266 +#include "../../../core/esp3d_commands.h" +#include "../../../core/esp3d_message.h" #include "../../authentication/authentication_service.h" -#include "../../../core/commands.h" -#include "../../../core/esp3doutput.h" -void HTTP_Server::handle_snap() -{ - level_authenticate_type auth_level = AuthenticationService::authenticated_level(); - if (auth_level == LEVEL_GUEST) { - _webserver->send (401, "text/plain", "Wrong authentication!"); - return; - } - esp3d_camera.handle_snap(_webserver); +void HTTP_Server::handle_snap() { + ESP3DAuthenticationLevel auth_level = + AuthenticationService::getAuthenticatedLevel(); + if (auth_level == ESP3DAuthenticationLevel::guest) { + _webserver->send(401, "text/plain", "Wrong authentication!"); + return; + } + esp3d_camera.handle_snap(_webserver); } -#endif //HTTP_FEATURE && CAMERA_DEVICE +#endif // HTTP_FEATURE && CAMERA_DEVICE diff --git a/esp3d/src/modules/http/handlers/handle-updatefw.cpp b/esp3d/src/modules/http/handlers/handle-updatefw.cpp index 6688ac0a..dcb085de 100644 --- a/esp3d/src/modules/http/handlers/handle-updatefw.cpp +++ b/esp3d/src/modules/http/handlers/handle-updatefw.cpp @@ -30,11 +30,11 @@ #include "../../authentication/authentication_service.h" // Web Update handler void HTTP_Server::handleUpdate() { - level_authenticate_type auth_level = - AuthenticationService::authenticated_level(); + ESP3DAuthenticationLevel auth_level = + AuthenticationService::getAuthenticatedLevel(); HTTP_Server::set_http_headers(); - if (auth_level != LEVEL_ADMIN) { + if (auth_level != ESP3DAuthenticationLevel::admin) { _upload_status = UPLOAD_STATUS_NONE; _webserver->send(401, "text/plain", "Wrong authentication!"); return; @@ -59,7 +59,7 @@ void HTTP_Server::handleUpdate() { _webserver->send(200, "application/json", jsonfile); // if success restart if (_upload_status == UPLOAD_STATUS_SUCCESSFUL) { - Hal::wait(1000); + ESP3DHal::wait(1000); Esp3D::restart_esp(); } else { _upload_status = UPLOAD_STATUS_NONE; diff --git a/esp3d/src/modules/http/handlers/upload-SD-files.cpp b/esp3d/src/modules/http/handlers/upload-SD-files.cpp index cbfb8ed1..2cf1679f 100644 --- a/esp3d/src/modules/http/handlers/upload-SD-files.cpp +++ b/esp3d/src/modules/http/handlers/upload-SD-files.cpp @@ -31,7 +31,7 @@ #include "../../filesystem/esp_sd.h" #ifdef ESP_BENCHMARK_FEATURE -#include "../../../core/benchmark.h" +#include "../../../core/esp3d_benchmark.h" #endif // ESP_BENCHMARK_FEATURE #if defined(ESP3DLIB_ENV) && COMMUNICATION_PROTOCOL == SOCKET_SERIAL #include "../../serial2socket/serial2socket.h" @@ -46,12 +46,12 @@ void HTTP_Server::SDFileupload() { #endif // ESP_BENCHMARK_FEATURE static uint64_t last_WS_update; // get authentication status - level_authenticate_type auth_level = - AuthenticationService::authenticated_level(); + ESP3DAuthenticationLevel auth_level = + AuthenticationService::getAuthenticatedLevel(); static String filename; static ESP_SDFile fsUploadFile; // Guest cannot upload - only admin - if (auth_level == LEVEL_GUEST) { + if (auth_level == ESP3DAuthenticationLevel::guest) { pushError(ESP_ERROR_AUTHENTICATION, "Upload rejected", 401); _upload_status = UPLOAD_STATUS_FAILED; } else { @@ -76,7 +76,7 @@ void HTTP_Server::SDFileupload() { return; } if (ESP_SD::getState(true) == ESP_SDCARD_NOT_PRESENT) { - log_esp3d("Release Sd called"); + esp3d_log("Release Sd called"); ESP_SD::releaseFS(); _upload_status = UPLOAD_STATUS_FAILED; pushError(ESP_ERROR_NO_SD, "Upload rejected"); @@ -137,7 +137,7 @@ void HTTP_Server::SDFileupload() { fsUploadFile.close(); } String sizeargname = upload.filename + "S"; - log_esp3d("Uploading file %s", filename.c_str()); + esp3d_log("Uploading file %s", filename.c_str()); if (_upload_status != UPLOAD_STATUS_FAILED) { if (_webserver->hasArg(sizeargname.c_str())) { size_t freespace = ESP_SD::totalBytes() - ESP_SD::usedBytes(); @@ -149,19 +149,19 @@ void HTTP_Server::SDFileupload() { } } if (_upload_status != UPLOAD_STATUS_FAILED) { - log_esp3d("Try file creation"); + esp3d_log("Try file creation"); // create file fsUploadFile = ESP_SD::open(filename.c_str(), ESP_FILE_WRITE); // check If creation succeed if (fsUploadFile) { // if yes upload is started _upload_status = UPLOAD_STATUS_ONGOING; - log_esp3d("Try file creation"); + esp3d_log("Try file creation"); } else { // if no set cancel flag _upload_status = UPLOAD_STATUS_FAILED; pushError(ESP_ERROR_FILE_CREATION, "File creation failed"); - log_esp3d_e("File creation failed"); + esp3d_log_e("File creation failed"); } } // Upload write @@ -180,7 +180,7 @@ void HTTP_Server::SDFileupload() { int writeddatanb = fsUploadFile.write(upload.buf, upload.currentSize); if (upload.currentSize != (size_t)writeddatanb) { // we have a problem set flag UPLOAD_STATUS_FAILED - log_esp3d_e("File write failed du to mismatch size %d vs %d", + esp3d_log_e("File write failed du to mismatch size %d vs %d", writeddatanb, upload.currentSize); _upload_status = UPLOAD_STATUS_FAILED; pushError(ESP_ERROR_FILE_WRITE, "File write failed"); @@ -188,7 +188,7 @@ void HTTP_Server::SDFileupload() { } else { // we have a problem set flag UPLOAD_STATUS_FAILED _upload_status = UPLOAD_STATUS_FAILED; - log_esp3d_e("Error detected"); + esp3d_log_e("Error detected"); pushError(ESP_ERROR_FILE_WRITE, "File write failed"); } // Upload end @@ -220,7 +220,7 @@ void HTTP_Server::SDFileupload() { _upload_status = UPLOAD_STATUS_FAILED; pushError(ESP_ERROR_FILE_CLOSE, "File close failed"); } - log_esp3d("Release Sd called"); + esp3d_log("Release Sd called"); ESP_SD::releaseFS(); #if defined(ESP3DLIB_ENV) && COMMUNICATION_PROTOCOL == SOCKET_SERIAL Serial2Socket.pause(false); @@ -229,7 +229,7 @@ void HTTP_Server::SDFileupload() { } else { if (_upload_status == UPLOAD_STATUS_ONGOING) { _upload_status = UPLOAD_STATUS_FAILED; - log_esp3d("Release Sd called"); + esp3d_log("Release Sd called"); ESP_SD::releaseFS(); #if defined(ESP3DLIB_ENV) && COMMUNICATION_PROTOCOL == SOCKET_SERIAL Serial2Socket.pause(false); @@ -244,17 +244,17 @@ void HTTP_Server::SDFileupload() { if (fsUploadFile) { fsUploadFile.close(); } - if (auth_level != LEVEL_GUEST) { + if (auth_level != ESP3DAuthenticationLevel::guest) { if (ESP_SD::exists(filename.c_str())) { ESP_SD::remove(filename.c_str()); } } - log_esp3d("Release Sd called"); + esp3d_log("Release Sd called"); ESP_SD::releaseFS(); #if defined(ESP3DLIB_ENV) && COMMUNICATION_PROTOCOL == SOCKET_SERIAL Serial2Socket.pause(false); #endif // ESP3DLIB_ENV && COMMUNICATION_PROTOCOL == SOCKET_SERIAL } - Hal::wait(5); + ESP3DHal::wait(5); } #endif // HTTP_FEATURE && SD_DEVICE diff --git a/esp3d/src/modules/http/handlers/upload-files.cpp b/esp3d/src/modules/http/handlers/upload-files.cpp index 0cce4473..a4fa5b9a 100644 --- a/esp3d/src/modules/http/handlers/upload-files.cpp +++ b/esp3d/src/modules/http/handlers/upload-files.cpp @@ -35,7 +35,7 @@ #endif // ESP3DLIB_ENV && COMMUNICATION_PROTOCOL == SOCKET_SERIAL #ifdef ESP_BENCHMARK_FEATURE -#include "../../../core/benchmark.h" +#include "../../../core/esp3d_benchmark.h" #endif // ESP_BENCHMARK_FEATURE // FS files uploader handle @@ -45,12 +45,12 @@ void HTTP_Server::FSFileupload() { static size_t bench_transfered; #endif // ESP_BENCHMARK_FEATURE // get authentication status - level_authenticate_type auth_level = - AuthenticationService::authenticated_level(); + ESP3DAuthenticationLevel auth_level = + AuthenticationService::getAuthenticatedLevel(); static String filename; static ESP_File fsUploadFile; // Guest cannot upload - only admin - if (auth_level == LEVEL_GUEST) { + if (auth_level == ESP3DAuthenticationLevel::guest) { pushError(ESP_ERROR_AUTHENTICATION, "Upload rejected", 401); _upload_status = UPLOAD_STATUS_FAILED; } else { @@ -161,7 +161,7 @@ void HTTP_Server::FSFileupload() { } // Upload end } else if (upload.status == UPLOAD_FILE_END) { - log_esp3d("upload end"); + esp3d_log("upload end"); // check if file is still open if (fsUploadFile) { // close it @@ -175,11 +175,11 @@ void HTTP_Server::FSFileupload() { uint32_t filesize = fsUploadFile.size(); _upload_status = UPLOAD_STATUS_SUCCESSFUL; if (_webserver->hasArg(sizeargname.c_str())) { - log_esp3d("Size check: %s vs %s", + esp3d_log("Size check: %s vs %s", _webserver->arg(sizeargname.c_str()).c_str(), String(filesize).c_str()); if (_webserver->arg(sizeargname.c_str()) != String(filesize)) { - log_esp3d_e("Size Error"); + esp3d_log_e("Size Error"); _upload_status = UPLOAD_STATUS_FAILED; pushError(ESP_ERROR_SIZE, "File upload failed"); } @@ -189,7 +189,7 @@ void HTTP_Server::FSFileupload() { } } else { // we have a problem set flag UPLOAD_STATUS_FAILED - log_esp3d_e("Close Error"); + esp3d_log_e("Close Error"); _upload_status = UPLOAD_STATUS_FAILED; pushError(ESP_ERROR_FILE_CLOSE, "File close failed"); } @@ -210,7 +210,7 @@ void HTTP_Server::FSFileupload() { if (fsUploadFile) { fsUploadFile.close(); } - if (auth_level != LEVEL_GUEST) { + if (auth_level != ESP3DAuthenticationLevel::guest) { if (ESP_FileSystem::exists(filename.c_str())) { ESP_FileSystem::remove(filename.c_str()); } diff --git a/esp3d/src/modules/http/handlers/upload-mks-files.cpp b/esp3d/src/modules/http/handlers/upload-mks-files.cpp index 41952cc3..be1b080c 100644 --- a/esp3d/src/modules/http/handlers/upload-mks-files.cpp +++ b/esp3d/src/modules/http/handlers/upload-mks-files.cpp @@ -18,129 +18,128 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../../include/esp3d_config.h" -#if defined (HTTP_FEATURE) && (COMMUNICATION_PROTOCOL == MKS_SERIAL) +#if defined(HTTP_FEATURE) && (COMMUNICATION_PROTOCOL == MKS_SERIAL) #include "../http_server.h" -#if defined (ARDUINO_ARCH_ESP32) +#if defined(ARDUINO_ARCH_ESP32) #include -#endif //ARDUINO_ARCH_ESP32 -#if defined (ARDUINO_ARCH_ESP8266) +#endif // ARDUINO_ARCH_ESP32 +#if defined(ARDUINO_ARCH_ESP8266) #include -#endif //ARDUINO_ARCH_ESP8266 -#include "../../mks/mks_service.h" +#endif // ARDUINO_ARCH_ESP8266 #include "../../authentication/authentication_service.h" +#include "../../mks/mks_service.h" -//MKS files uploader handle -void HTTP_Server::MKSFileupload () -{ - static uint32_t fragmentID = 0; - static uint8_t buf2send[MKS_FRAME_DATA_MAX_SIZE]; - static size_t buf2sendlen = 0; - //get authentication status - level_authenticate_type auth_level= AuthenticationService::authenticated_level(); - //Guest cannot upload - only admin - if (auth_level == LEVEL_GUEST) { - pushError(ESP_ERROR_AUTHENTICATION, "Upload rejected", 401); - _upload_status=UPLOAD_STATUS_FAILED; - } else { - HTTPUpload& upload = _webserver->upload(); - if (upload.status == UPLOAD_FILE_START) { - buf2sendlen = 0; - log_esp3d("Starting upload"); - _upload_status= UPLOAD_STATUS_ONGOING; - size_t fileSize = 0 ; - String filename = upload.filename; - String sfilename = "s"+filename; - log_esp3d("Filename: %s",filename.c_str() ); - //No / in filename - if (filename[0]=='/') { - filename.remove(0,1); - } - //for remote path or device - //if USB on TFT 0: - //if SD on TFT 1: - //if SD on Robin 0: or just +// MKS files uploader handle +void HTTP_Server::MKSFileupload() { + static uint32_t fragmentID = 0; + static uint8_t buf2send[MKS_FRAME_DATA_MAX_SIZE]; + static size_t buf2sendlen = 0; + // get authentication status + ESP3DAuthenticationLevel auth_level = + AuthenticationService::getAuthenticatedLevel(); + // Guest cannot upload - only admin + if (auth_level == ESP3DAuthenticationLevel::guest) { + pushError(ESP_ERROR_AUTHENTICATION, "Upload rejected", 401); + _upload_status = UPLOAD_STATUS_FAILED; + } else { + HTTPUpload& upload = _webserver->upload(); + if (upload.status == UPLOAD_FILE_START) { + buf2sendlen = 0; + esp3d_log("Starting upload"); + _upload_status = UPLOAD_STATUS_ONGOING; + size_t fileSize = 0; + String filename = upload.filename; + String sfilename = "s" + filename; + esp3d_log("Filename: %s", filename.c_str()); + // No / in filename + if (filename[0] == '/') { + filename.remove(0, 1); + } + // for remote path or device + // if USB on TFT 0: + // if SD on TFT 1: + // if SD on Robin 0: or just - if (_webserver->hasArg ("rpath") ) { - String upload_filename = _webserver->arg ("rpath") + "/" + filename; - filename = upload_filename; - if (filename[0]=='/') { - filename.remove(0,1); - } - //this is target device - if (filename.startsWith("USB:") || filename.startsWith("SD:")) { - String cmd = "M998 "; - if (filename.startsWith("USB:")) { - cmd += "0"; - filename.remove(0,strlen("USB:")); - } else { - cmd += "1"; - filename.remove(0,strlen("SD:")); - } - MKSService::sendGcodeFrame(cmd.c_str()); - Hal::wait(10); - } - } - if (_webserver->hasArg(sfilename)) { - fileSize = _webserver->arg(sfilename).toInt(); - } else if (_webserver->hasHeader("Content-Length")) { - fileSize = _webserver->header("Content-Length").toInt(); - } - fragmentID = 0; - log_esp3d("Filename: %s Size:%d",filename.c_str(), fileSize); - if (MKSService::sendFirstFragment(filename.c_str(), fileSize)) { - MKSService::uploadMode(); - } - } else if(upload.status == UPLOAD_FILE_WRITE) { - if (_upload_status == UPLOAD_STATUS_ONGOING) { - uint currentsize = upload.currentSize; - uint8_t * currentBuffer = upload.buf; - while ((currentsize > 0) &&(_upload_status == UPLOAD_STATUS_ONGOING)) { - while ((buf2sendlen 0) { - buf2send[buf2sendlen]=currentBuffer[0]; - buf2sendlen++; - currentsize--; - currentBuffer++; - } - if (buf2sendlen == MKS_FRAME_DATA_MAX_SIZE) { - log_esp3d("Send %d chars in Fragment %d", buf2sendlen, fragmentID); - if (MKSService::sendFragment(buf2send,buf2sendlen,fragmentID)) { - buf2sendlen=0; - fragmentID++; - } else { - _upload_status=UPLOAD_STATUS_FAILED; - pushError(ESP_ERROR_FILE_WRITE, "File write failed"); - } - - } - Hal::wait(0); - } - } - - } else if(upload.status == UPLOAD_FILE_END) { - if (_upload_status == UPLOAD_STATUS_ONGOING) { - log_esp3d("Upload end"); - fragmentID=MKSService::getFragmentID(fragmentID,true); - log_esp3d("Send %d chars in Fragment %d", buf2sendlen, fragmentID); - if(MKSService::sendFragment(buf2send,buf2sendlen,fragmentID)) { - _upload_status=UPLOAD_STATUS_SUCCESSFUL; - } else { - _upload_status=UPLOAD_STATUS_FAILED; - pushError(ESP_ERROR_FILE_CLOSE, "File close failed"); - } - MKSService::commandMode(); - } - } else { - //error - _upload_status=UPLOAD_STATUS_FAILED; - pushError(ESP_ERROR_FILE_WRITE, "File write failed"); + if (_webserver->hasArg("rpath")) { + String upload_filename = _webserver->arg("rpath") + "/" + filename; + filename = upload_filename; + if (filename[0] == '/') { + filename.remove(0, 1); } + // this is target device + if (filename.startsWith("USB:") || filename.startsWith("SD:")) { + String cmd = "M998 "; + if (filename.startsWith("USB:")) { + cmd += "0"; + filename.remove(0, strlen("USB:")); + } else { + cmd += "1"; + filename.remove(0, strlen("SD:")); + } + MKSService::sendGcodeFrame(cmd.c_str()); + ESP3DHal::wait(10); + } + } + if (_webserver->hasArg(sfilename)) { + fileSize = _webserver->arg(sfilename).toInt(); + } else if (_webserver->hasHeader("Content-Length")) { + fileSize = _webserver->header("Content-Length").toInt(); + } + fragmentID = 0; + esp3d_log("Filename: %s Size:%d", filename.c_str(), fileSize); + if (MKSService::sendFirstFragment(filename.c_str(), fileSize)) { + MKSService::uploadMode(); + } + } else if (upload.status == UPLOAD_FILE_WRITE) { + if (_upload_status == UPLOAD_STATUS_ONGOING) { + uint currentsize = upload.currentSize; + uint8_t* currentBuffer = upload.buf; + while ((currentsize > 0) && (_upload_status == UPLOAD_STATUS_ONGOING)) { + while ((buf2sendlen < MKS_FRAME_DATA_MAX_SIZE) && currentsize > 0) { + buf2send[buf2sendlen] = currentBuffer[0]; + buf2sendlen++; + currentsize--; + currentBuffer++; + } + if (buf2sendlen == MKS_FRAME_DATA_MAX_SIZE) { + esp3d_log("Send %d chars in Fragment %d", buf2sendlen, fragmentID); + if (MKSService::sendFragment(buf2send, buf2sendlen, fragmentID)) { + buf2sendlen = 0; + fragmentID++; + } else { + _upload_status = UPLOAD_STATUS_FAILED; + pushError(ESP_ERROR_FILE_WRITE, "File write failed"); + } + } + ESP3DHal::wait(0); + } + } - } - if(_upload_status == UPLOAD_STATUS_FAILED) { - cancelUpload(); - //TBC need to do that - //MKSService::sendFragment(nullptr,0,MKSService::getFragmentID(fragmentID, true)); + } else if (upload.status == UPLOAD_FILE_END) { + if (_upload_status == UPLOAD_STATUS_ONGOING) { + esp3d_log("Upload end"); + fragmentID = MKSService::getFragmentID(fragmentID, true); + esp3d_log("Send %d chars in Fragment %d", buf2sendlen, fragmentID); + if (MKSService::sendFragment(buf2send, buf2sendlen, fragmentID)) { + _upload_status = UPLOAD_STATUS_SUCCESSFUL; + } else { + _upload_status = UPLOAD_STATUS_FAILED; + pushError(ESP_ERROR_FILE_CLOSE, "File close failed"); + } MKSService::commandMode(); + } + } else { + // error + _upload_status = UPLOAD_STATUS_FAILED; + pushError(ESP_ERROR_FILE_WRITE, "File write failed"); } + } + if (_upload_status == UPLOAD_STATUS_FAILED) { + cancelUpload(); + // TBC need to do that + // MKSService::sendFragment(nullptr,0,MKSService::getFragmentID(fragmentID, + // true)); + MKSService::commandMode(); + } } -#endif //HTTP_FEATURE && (COMMUNICATION_PROTOCOL == MKS_SERIAL) +#endif // HTTP_FEATURE && (COMMUNICATION_PROTOCOL == MKS_SERIAL) diff --git a/esp3d/src/modules/http/handlers/upload-updatefw.cpp b/esp3d/src/modules/http/handlers/upload-updatefw.cpp index 74db3628..72b0f23c 100644 --- a/esp3d/src/modules/http/handlers/upload-updatefw.cpp +++ b/esp3d/src/modules/http/handlers/upload-updatefw.cpp @@ -18,128 +18,170 @@ 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) +#if defined(HTTP_FEATURE) && defined(WEB_UPDATE_FEATURE) #include "../http_server.h" -#if defined (ARDUINO_ARCH_ESP32) +#if defined(ARDUINO_ARCH_ESP32) #include #define UPDATE_SIZE #include -#endif //ARDUINO_ARCH_ESP32 -#if defined (ARDUINO_ARCH_ESP8266) +#endif // ARDUINO_ARCH_ESP32 +#if defined(ARDUINO_ARCH_ESP8266) #include #define UPDATE_SIZE ESP_FileSystem::max_update_size() -#endif //ARDUINO_ARCH_ESP8266 -#include "../../filesystem/esp_filesystem.h" +#endif // ARDUINO_ARCH_ESP8266 +#include "../../../core/esp3d_commands.h" #include "../../authentication/authentication_service.h" -#include "../../../core/esp3doutput.h" +#include "../../filesystem/esp_filesystem.h" + #if defined(ESP3DLIB_ENV) && COMMUNICATION_PROTOCOL == SOCKET_SERIAL #include "../../serial2socket/serial2socket.h" -#endif // ESP3DLIB_ENV && COMMUNICATION_PROTOCOL == SOCKET_SERIAL -//File upload for Web update -void HTTP_Server::WebUpdateUpload () -{ - static size_t last_upload_update; - static uint32_t downloadsize = 0; - ESP3DOutput output(ESP_REMOTE_SCREEN_CLIENT); - //only admin can update FW - if (AuthenticationService::authenticated_level() != LEVEL_ADMIN) { - _upload_status = UPLOAD_STATUS_FAILED; - pushError(ESP_ERROR_AUTHENTICATION, "Upload rejected", 401); - output.printERROR("Update rejected!",401); - } else { - //get current file ID - HTTPUpload& upload = _webserver->upload(); - if ((_upload_status != UPLOAD_STATUS_FAILED) || (upload.status == UPLOAD_FILE_START)) { -#if defined(ESP3DLIB_ENV) && COMMUNICATION_PROTOCOL == SOCKET_SERIAL - Serial2Socket.pause(); -#endif // ESP3DLIB_ENV && COMMUNICATION_PROTOCOL == SOCKET_SERIAL - //Upload start - if(upload.status == UPLOAD_FILE_START) { - output.printMSG("Update Firmware"); - _upload_status= UPLOAD_STATUS_ONGOING; - String sizeargname = upload.filename + "S"; - if (_webserver->hasArg (sizeargname.c_str()) ) { - downloadsize = _webserver->arg (sizeargname).toInt(); - } else { - downloadsize = 0; - } - if (downloadsize > ESP_FileSystem::max_update_size()) { - _upload_status=UPLOAD_STATUS_FAILED; - output.printERROR("Update rejected!",500); - pushError(ESP_ERROR_NOT_ENOUGH_SPACE, "Upload rejected"); - } - last_upload_update = 0; - if (_upload_status != UPLOAD_STATUS_FAILED) { - if(!Update.begin(UPDATE_SIZE)) { //start with unknown = max available size - _upload_status=UPLOAD_STATUS_FAILED; - output.printERROR("Update rejected!",500); - pushError(ESP_ERROR_NOT_ENOUGH_SPACE, "Upload rejected"); - } else { - output.printMSG("Update 0%"); - } - } - //Upload write - } else if(upload.status == UPLOAD_FILE_WRITE) { - //check if no error - if (_upload_status == UPLOAD_STATUS_ONGOING) { - //we do not know the total file size yet but we know the available space so let's use it - if (downloadsize != 0) { - if ( ((100 * upload.totalSize) / downloadsize) !=last_upload_update) { - if ( downloadsize > 0) { - last_upload_update = (100 * upload.totalSize) / downloadsize; - } else { - last_upload_update = upload.totalSize; - } - String s = "Update "; - s+= String(last_upload_update); - s+="/100"; - output.printMSG(s.c_str()); - } - } - if(Update.write(upload.buf, upload.currentSize) != upload.currentSize) { - _upload_status=UPLOAD_STATUS_FAILED; - output.printERROR("Update write failed!",500); - pushError(ESP_ERROR_FILE_WRITE, "File write failed"); - } - } - //Upload end +#endif // ESP3DLIB_ENV && COMMUNICATION_PROTOCOL == SOCKET_SERIAL +// File upload for Web update +void HTTP_Server::WebUpdateUpload() { + static size_t last_upload_update; + static uint32_t downloadsize = 0; - } else if(upload.status == UPLOAD_FILE_END) { - if ((downloadsize!=0) && (downloadsize < upload.totalSize)) { - _upload_status=UPLOAD_STATUS_FAILED; - output.printERROR("Update write failed!",500); - pushError(ESP_ERROR_FILE_WRITE, "File write failed"); - } - if (_upload_status == UPLOAD_STATUS_ONGOING) { - if(Update.end(true)) { //true to set the size to the current progress - //Now Reboot - output.printMSG("Update 100%"); - _upload_status=UPLOAD_STATUS_SUCCESSFUL; - } else { - output.printERROR("Update failed!",500); - _upload_status=UPLOAD_STATUS_FAILED; - pushError(ESP_ERROR_UPDATE, "Update FW failed"); - } - } else { - _upload_status=UPLOAD_STATUS_FAILED; - output.printERROR("Update failed!", 500); - pushError(ESP_ERROR_UPDATE, "Update FW failed"); - } + // only admin can update FW + if (AuthenticationService::getAuthenticatedLevel() != + ESP3DAuthenticationLevel::admin) { + _upload_status = UPLOAD_STATUS_FAILED; + pushError(ESP_ERROR_AUTHENTICATION, "Upload rejected", 401); + esp3d_commands.dispatch("Update rejected!", ESP3DClientType::remote_screen, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); + } else { + // get current file ID + HTTPUpload& upload = _webserver->upload(); + if ((_upload_status != UPLOAD_STATUS_FAILED) || + (upload.status == UPLOAD_FILE_START)) { #if defined(ESP3DLIB_ENV) && COMMUNICATION_PROTOCOL == SOCKET_SERIAL - Serial2Socket.pause(false); -#endif // ESP3DLIB_ENV && COMMUNICATION_PROTOCOL == SOCKET_SERIAL - } else { - output.printERROR("Update failed!",500); - _upload_status=UPLOAD_STATUS_FAILED; - } + Serial2Socket.pause(); +#endif // ESP3DLIB_ENV && COMMUNICATION_PROTOCOL == SOCKET_SERIAL + // Upload start + if (upload.status == UPLOAD_FILE_START) { + esp3d_commands.dispatch( + "Update Firmware", ESP3DClientType::remote_screen, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); + _upload_status = UPLOAD_STATUS_ONGOING; + String sizeargname = upload.filename + "S"; + if (_webserver->hasArg(sizeargname.c_str())) { + downloadsize = _webserver->arg(sizeargname).toInt(); + } else { + downloadsize = 0; + } + if (downloadsize > ESP_FileSystem::max_update_size()) { + _upload_status = UPLOAD_STATUS_FAILED; + esp3d_commands.dispatch( + "Update rejected", ESP3DClientType::remote_screen, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); + pushError(ESP_ERROR_NOT_ENOUGH_SPACE, "Upload rejected"); + } + last_upload_update = 0; + if (_upload_status != UPLOAD_STATUS_FAILED) { + if (!Update.begin( + UPDATE_SIZE)) { // start with unknown = max available size + _upload_status = UPLOAD_STATUS_FAILED; + esp3d_commands.dispatch( + "Update rejected", ESP3DClientType::remote_screen, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); + pushError(ESP_ERROR_NOT_ENOUGH_SPACE, "Upload rejected"); + } else { + esp3d_commands.dispatch("Update 0%", ESP3DClientType::remote_screen, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); + } + } + // Upload write + } else if (upload.status == UPLOAD_FILE_WRITE) { + // check if no error + if (_upload_status == UPLOAD_STATUS_ONGOING) { + // we do not know the total file size yet but we know the available + // space so let's use it + if (downloadsize != 0) { + if (((100 * upload.totalSize) / downloadsize) != + last_upload_update) { + if (downloadsize > 0) { + last_upload_update = (100 * upload.totalSize) / downloadsize; + } else { + last_upload_update = upload.totalSize; + } + String s = "Update "; + s += String(last_upload_update); + s += "/100"; + esp3d_commands.dispatch(s.c_str(), ESP3DClientType::remote_screen, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); + } + } + if (Update.write(upload.buf, upload.currentSize) != + upload.currentSize) { + _upload_status = UPLOAD_STATUS_FAILED; + esp3d_commands.dispatch( + "Update write failed", ESP3DClientType::remote_screen, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); + pushError(ESP_ERROR_FILE_WRITE, "File write failed"); + } + } + // Upload end + + } else if (upload.status == UPLOAD_FILE_END) { + if ((downloadsize != 0) && (downloadsize < upload.totalSize)) { + _upload_status = UPLOAD_STATUS_FAILED; + esp3d_commands.dispatch( + "Update write failed", ESP3DClientType::remote_screen, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); + pushError(ESP_ERROR_FILE_WRITE, "File write failed"); + } + if (_upload_status == UPLOAD_STATUS_ONGOING) { + if (Update.end(true)) { // true to set the size to the current + // progress Now Reboot + esp3d_commands.dispatch( + "Update 100%", ESP3DClientType::remote_screen, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); + _upload_status = UPLOAD_STATUS_SUCCESSFUL; + } else { + esp3d_commands.dispatch( + "Update write failed", ESP3DClientType::remote_screen, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); + _upload_status = UPLOAD_STATUS_FAILED; + pushError(ESP_ERROR_UPDATE, "Update FW failed"); + } + } else { + _upload_status = UPLOAD_STATUS_FAILED; + esp3d_commands.dispatch( + "Update write failed", ESP3DClientType::remote_screen, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); + pushError(ESP_ERROR_UPDATE, "Update FW failed"); } - } - if(_upload_status == UPLOAD_STATUS_FAILED) { - cancelUpload(); - Update.end(); #if defined(ESP3DLIB_ENV) && COMMUNICATION_PROTOCOL == SOCKET_SERIAL Serial2Socket.pause(false); -#endif // ESP3DLIB_ENV && COMMUNICATION_PROTOCOL == SOCKET_SERIAL +#endif // ESP3DLIB_ENV && COMMUNICATION_PROTOCOL == SOCKET_SERIAL + } else { + esp3d_commands.dispatch( + "Update write failed", ESP3DClientType::remote_screen, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); + _upload_status = UPLOAD_STATUS_FAILED; + } } + } + if (_upload_status == UPLOAD_STATUS_FAILED) { + cancelUpload(); + Update.end(); +#if defined(ESP3DLIB_ENV) && COMMUNICATION_PROTOCOL == SOCKET_SERIAL + Serial2Socket.pause(false); +#endif // ESP3DLIB_ENV && COMMUNICATION_PROTOCOL == SOCKET_SERIAL + } } -#endif //HTTP_FEATURE && WEB_UPDATE_FEATURE +#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 fb83f9b3..af12856d 100644 --- a/esp3d/src/modules/http/http_server.cpp +++ b/esp3d/src/modules/http/http_server.cpp @@ -29,7 +29,7 @@ #include #define DOWNLOAD_PACKET_SIZE 1024 #endif // ARDUINO_ARCH_ESP8266 -#include "../../core/settings_esp3d.h" +#include "../../core/esp3d_settings.h" #include "../authentication/authentication_service.h" #include "../filesystem/esp_filesystem.h" #include "../network/netconfig.h" @@ -41,9 +41,14 @@ #endif // SD_DEVICE #ifdef ESP_BENCHMARK_FEATURE -#include "../../core/benchmark.h" +#include "../../core/esp3d_benchmark.h" #endif // ESP_BENCHMARK_FEATURE +ESP3DRequest code_200{.code = 200}; +ESP3DRequest code_500{.code = 500}; +ESP3DRequest code_404{.code = 404}; +ESP3DRequest code_401{.code = 401}; + bool HTTP_Server::_started = false; uint16_t HTTP_Server::_port = 0; WEBSERVER* HTTP_Server::_webserver = nullptr; @@ -105,7 +110,7 @@ bool HTTP_Server::StreamFSFile(const char* filename, const char* contentType) { _webserver->send(200, contentType, ""); uint8_t buf[DOWNLOAD_PACKET_SIZE]; while (!done && _webserver->client().connected()) { - Hal::wait(0); + ESP3DHal::wait(0); int v = datafile.read(buf, DOWNLOAD_PACKET_SIZE); if ((v == -1) || (v == 0)) { done = true; @@ -147,7 +152,7 @@ bool HTTP_Server::StreamSDFile(const char* filename, const char* contentType) { _webserver->send(200, contentType, ""); uint8_t buf[DOWNLOAD_PACKET_SIZE]; while (!done && _webserver->client().connected()) { - Hal::wait(0); + ESP3DHal::wait(0); int v = datafile.read(buf, DOWNLOAD_PACKET_SIZE); if ((v == -1) || (v == 0)) { done = true; @@ -181,7 +186,7 @@ bool HTTP_Server::StreamSDFile(const char* filename, const char* contentType) { void HTTP_Server::pushError(int code, const char* st, uint16_t web_error, uint16_t timeout) { - log_esp3d("%s:%d", st, web_error); + esp3d_log("%s:%d", st, web_error); if (websocket_terminal_server.started() && st) { String s = "ERROR:" + String(code) + ":"; s += st; @@ -197,7 +202,7 @@ void HTTP_Server::pushError(int code, const char* st, uint16_t web_error, uint32_t t = millis(); while (millis() - t < timeout) { websocket_terminal_server.handle(); - Hal::wait(10); + ESP3DHal::wait(10); } } } @@ -211,16 +216,16 @@ void HTTP_Server::cancelUpload() { errno = ECONNABORTED; _webserver->client().stop(); #endif - Hal::wait(100); + ESP3DHal::wait(100); } bool HTTP_Server::begin() { bool no_error = true; end(); - if (Settings_ESP3D::read_byte(ESP_HTTP_ON) != 1) { + if (ESP3DSettings::readByte(ESP_HTTP_ON) != 1) { return no_error; } - _port = Settings_ESP3D::read_uint32(ESP_HTTP_PORT); + _port = ESP3DSettings::readUint32(ESP_HTTP_PORT); _webserver = new WEBSERVER(_port); if (!_webserver) { return false; @@ -246,6 +251,50 @@ bool HTTP_Server::begin() { return no_error; } +bool HTTP_Server::dispatch(ESP3DMessage* msg) { + if (!msg || !_started || !_webserver) { + return false; + } + if ((msg->size > 0 && msg->data) || (msg->type == ESP3DMessageType::tail)) { + if (msg->type == ESP3DMessageType::head || + msg->type == ESP3DMessageType::unique) { + set_http_headers(); + int code = 200; + if (msg->request_id.code != 0) { + code = msg->request_id.code; + } +#if defined(AUTHENTICATION_FEATURE) + if (msg->authentication_level == + ESP3DAuthenticationLevel::not_authenticated) { + code = 401; + } +#endif // AUTHENTICATION_FEATURE + esp3d_log("Code is %d", code); + if (msg->type == ESP3DMessageType::head) { + _webserver->setContentLength(CONTENT_LENGTH_UNKNOWN); + // in case of no request id set + + _webserver->send(code); + _webserver->sendContent((const char*)msg->data, msg->size); + } else { // unique + _webserver->send(code, "text/plain", (char*)msg->data); + } + } else { + // core or tail + if (msg->data && msg->size > 0) { + _webserver->sendContent((const char*)msg->data, msg->size); + } + // this is tail so we send end of data + if (msg->type == ESP3DMessageType::tail) { + _webserver->sendContent(""); + } + } + ESP3DMessageManager::deleteMsg(msg); + return true; + } + return false; +} + void HTTP_Server::set_http_headers() { /* User-Agent: ESP3D-WebServer/1.0 (ESP8266; Firmware/3.0.0; Platform/arduino; @@ -258,7 +307,7 @@ Embedded; http://www.esp3d.io) Host: http://192.168.0.1:8181 static String host = ""; if (ua.length() == 0) { ua = "ESP3D-WebServer/1.0 ("; - ua += Settings_ESP3D::TargetBoard(); + ua += ESP3DSettings::TargetBoard(); ua += "; Firmware/"; ua += FW_VERSION; ua += "; Platform/arduino; Embedded; http://www.esp3d.io)"; @@ -274,6 +323,10 @@ Embedded; http://www.esp3d.io) Host: http://192.168.0.1:8181 if (_webserver) { _webserver->sendHeader("User-Agent", ua.c_str()); _webserver->sendHeader("Host", host.c_str()); + _webserver->sendHeader("Cache-Control", "no-cache"); +#ifdef ESP_ACCESS_CONTROL_ALLOW_ORIGIN + _webserver->sendHeader("Access-Control-Allow-Origin", "*"); +#endif // ESP_ACCESS_CONTROL_ALLOw_ORIGIN } } diff --git a/esp3d/src/modules/http/http_server.h b/esp3d/src/modules/http/http_server.h index 48e2f9a9..c0115ccd 100644 --- a/esp3d/src/modules/http/http_server.h +++ b/esp3d/src/modules/http/http_server.h @@ -20,7 +20,9 @@ #ifndef _HTTP_SERVER_H #define _HTTP_SERVER_H +#include "../../core/esp3d_commands.h" #include "../../include/esp3d_config.h" + // class WebSocketsServer; #if defined(ARDUINO_ARCH_ESP32) class WebServer; @@ -48,6 +50,7 @@ class HTTP_Server { static bool started() { return _started; } static uint16_t port() { return _port; } static void set_http_headers(); + static bool dispatch(ESP3DMessage* msg); private: static void pushError(int code, const char* st, uint16_t web_error = 500, @@ -94,4 +97,9 @@ class HTTP_Server { #endif // COMMUNICATION_PROTOCOL == MKS_SERIAL }; +extern ESP3DRequest code_200; +extern ESP3DRequest code_500; +extern ESP3DRequest code_404; +extern ESP3DRequest code_401; + #endif //_HTTP_SERVER_H diff --git a/esp3d/src/modules/input/input.cpp b/esp3d/src/modules/input/input.cpp index 331b1013..ab09912c 100644 --- a/esp3d/src/modules/input/input.cpp +++ b/esp3d/src/modules/input/input.cpp @@ -19,55 +19,39 @@ */ #include "../../include/esp3d_config.h" -#if defined (INPUT_DEVICE) +#if defined(INPUT_DEVICE) +#include "../../core/esp3d_message.h" +#include "../../core/esp3d_settings.h" #include "input.h" -#include "../../core/settings_esp3d.h" -#include "../../core/esp3doutput.h" - Input esp3d_input; +Input::Input() { _started = false; } -Input::Input() -{ - _started = false; -} +Input::~Input() { end(); } -Input::~Input() -{ +bool Input::begin() { + bool res = true; + _started = false; + if (!res) { end(); + } + _started = res; + return _started; } -bool Input::begin() -{ - bool res = true; - _started = false; - if (!res) { - end(); - } - _started = res; - return _started; +void Input::end() { + if (!_started) { + return; + } + _started = false; } -void Input::end() -{ - if(!_started) { - return; - } - _started = false; +bool Input::started() { return _started; } + +void Input::handle() { + if (_started) { + } } -bool Input::started() -{ - return _started; -} - - -void Input::handle() -{ - if (_started) { - - } -} - -#endif //INPUT_DEVICE +#endif // INPUT_DEVICE diff --git a/esp3d/src/modules/lua_interpreter/lua_interpreter_service.cpp b/esp3d/src/modules/lua_interpreter/lua_interpreter_service.cpp index ddcfab01..f24c2361 100644 --- a/esp3d/src/modules/lua_interpreter/lua_interpreter_service.cpp +++ b/esp3d/src/modules/lua_interpreter/lua_interpreter_service.cpp @@ -21,46 +21,35 @@ #include "../../include/esp3d_config.h" #ifdef ESP_LUA_INTERPRETER_FEATURE -#include "lua_interpreter_service.h" -#include "../../core/settings_esp3d.h" -#include "../../core/hal.h" #include +#include "../../core/esp3d_hal.h" +#include "../../core/esp3d_settings.h" +#include "lua_interpreter_service.h" + LuaWrapper luawrapper; LuaInterpreter esp3d_lua_interpreter; -LuaInterpreter::LuaInterpreter() -{ - _started = false; -} +LuaInterpreter::LuaInterpreter() { _started = false; } -bool LuaInterpreter::begin() -{ - if(_started) { - end(); - } - _started = true; - return _started; -} -void LuaInterpreter::end() -{ - if(!_started) { - return; - } - _started = false; -} - - -void LuaInterpreter::handle() -{ - //Nothing to do as handled by ticker / task -} - - -LuaInterpreter::~LuaInterpreter() -{ +bool LuaInterpreter::begin() { + if (_started) { end(); + } + _started = true; + return _started; +} +void LuaInterpreter::end() { + if (!_started) { + return; + } + _started = false; } +void LuaInterpreter::handle() { + // Nothing to do as handled by ticker / task +} -#endif //ESP_LUA_INTERPRETER_FEATURE +LuaInterpreter::~LuaInterpreter() { end(); } + +#endif // ESP_LUA_INTERPRETER_FEATURE diff --git a/esp3d/src/modules/mDNS/mDNS.cpp b/esp3d/src/modules/mDNS/mDNS.cpp index 3a5da49c..130d8f5d 100644 --- a/esp3d/src/modules/mDNS/mDNS.cpp +++ b/esp3d/src/modules/mDNS/mDNS.cpp @@ -22,8 +22,8 @@ #ifdef MDNS_FEATURE -#include "../../core/esp3doutput.h" -#include "../../core/settings_esp3d.h" +#include "../../core/esp3d_commands.h" +#include "../../core/esp3d_settings.h" #include "mDNS.h" #if defined(ARDUINO_ARCH_ESP8266) @@ -70,15 +70,20 @@ bool mDNS_Service::begin(const char* hostname) { if (WiFi.getMode() != WIFI_AP) { _hostname = hostname; _hostname.toLowerCase(); - ESP3DOutput output(ESP_ALL_CLIENTS); - log_esp3d("Start mdsn for %s", _hostname.c_str()); + esp3d_log("Start mdsn for %s", _hostname.c_str()); if (!MDNS.begin(_hostname.c_str())) { - output.printERROR("mDNS failed to start"); + esp3d_commands.dispatch("mDNS failed to start", + ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); _started = false; } else { String stmp = "mDNS started with '" + _hostname + ".local'"; - if (Settings_ESP3D::isVerboseBoot()) { - output.printMSG(stmp.c_str()); + if (ESP3DSettings::isVerboseBoot()) { + esp3d_commands.dispatch(stmp.c_str(), ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } _started = true; } @@ -95,40 +100,40 @@ void mDNS_Service::end() { #if defined(ARDUINO_ARCH_ESP8266) if (_hMDNSServiceQuery) { - log_esp3d("Remove mdns service for %s", _hostname.c_str()); + esp3d_log("Remove mdns service for %s", _hostname.c_str()); if (!MDNS.removeServiceQuery(_hMDNSServiceQuery)) { - log_esp3d_e("failed"); + esp3d_log_e("failed"); } } _hMDNSServiceQuery = 0; - log_esp3d("Remove mdns for %s", _hostname.c_str()); + esp3d_log("Remove mdns for %s", _hostname.c_str()); if (!MDNS.removeService(_hostname.c_str(), MDNS_SERVICE_NAME, MDNS_SERVICE_TYPE)) { - log_esp3d_e("failed"); + esp3d_log_e("failed"); } #if defined(HTTP_FEATURE) if (!MDNS.removeService(_hostname.c_str(), "http", "tcp")) { - log_esp3d_e("failed"); + esp3d_log_e("failed"); } #endif // HTTP_FEATURE #if defined(FTP_FEATURE) if (!MDNS.removeService(_hostname.c_str(), "ftp", "tcp")) { - log_esp3d_e("failed"); + esp3d_log_e("failed"); } #endif // FTP_FEATURE #if defined(TELNET_FEATURE) if (!MDNS.removeService(_hostname.c_str(), "telnet", "tcp")) { - log_esp3d_e("failed"); + esp3d_log_e("failed"); } #endif // TELNET_FEATURE #if defined(WEBDAV_FEATURE) if (!MDNS.removeService(_hostname.c_str(), "webdav", "tcp")) { - log_esp3d_e("failed"); + esp3d_log_e("failed"); } #endif // WEBDAV_FEATURE #if defined(WS_DATA_FEATURE) if (!MDNS.removeService(_hostname.c_str(), "websocket", "tcp")) { - log_esp3d_e("failed"); + esp3d_log_e("failed"); } #endif // WS_DATA_FEATURE #endif // ARDUINO_ARCH_ESP8266 @@ -192,9 +197,9 @@ void mDNS_Service::addESP3DServices(uint16_t port) { _hMDNSServiceQuery = MDNS.installServiceQuery( MDNS_SERVICE_NAME, MDNS_SERVICE_TYPE, MDNSServiceQueryCallback); if (_hMDNSServiceQuery) { - log_esp3d("MDNS Service query services installed."); + esp3d_log("MDNS Service query services installed."); } else { - log_esp3d_e("MDNS Service query services installation failed."); + esp3d_log_e("MDNS Service query services installation failed."); } #endif // ARDUINO_ARCH_ESP8266 } @@ -308,7 +313,7 @@ const char* mDNS_Service::answerTxtKey(uint16_t index, uint16_t txtIndex) { #endif // ARDUINO_ARCH_ESP32 #if defined(ARDUINO_ARCH_ESP8266) String txt = MDNS.answerTxts(_hMDNSServiceQuery, index); - log_esp3d("txt: %s", txt.c_str()); + esp3d_log("txt: %s", txt.c_str()); String keyValue = ""; bool found = false; if (txt.indexOf(";") == -1) { @@ -352,7 +357,7 @@ const char* mDNS_Service::answerTxt(uint16_t index, uint16_t txtIndex) { #endif // ARDUINO_ARCH_ESP32 #if defined(ARDUINO_ARCH_ESP8266) String txt = MDNS.answerTxts(_hMDNSServiceQuery, index); - log_esp3d("txt: %s", txt.c_str()); + esp3d_log("txt: %s", txt.c_str()); String keyValue = ""; bool found = false; if (txt.indexOf(";") == -1) { diff --git a/esp3d/src/modules/mks/mks_service.cpp b/esp3d/src/modules/mks/mks_service.cpp index a45dde3e..7de53b12 100644 --- a/esp3d/src/modules/mks/mks_service.cpp +++ b/esp3d/src/modules/mks/mks_service.cpp @@ -20,8 +20,8 @@ #include "../../include/esp3d_config.h" #if COMMUNICATION_PROTOCOL == MKS_SERIAL -#include "../../core/esp3doutput.h" -#include "../../core/settings_esp3d.h" +#include "../../core/esp3d_message.h" +#include "../../core/esp3d_settings.h" #include "../http/http_server.h" #include "../network/netconfig.h" #include "../serial/serial_service.h" @@ -113,6 +113,20 @@ bool MKSService::isFrame(const char c) { } return false; } + +bool MKSService::dispatch(ESP3DMessage *message) { + if (!message || !_started) { + return false; + } + if (message->size > 0 && message->data) { + if (sendGcodeFrame((const char *)message->data)) { + ESP3DMessageManager::deleteMsg(message); + return true; + } + } + return false; +} + bool MKSService::begin() { // setup the pins pinMode(BOARD_FLAG_PIN, INPUT); @@ -128,26 +142,26 @@ bool MKSService::begin() { void MKSService::commandMode(bool fromSettings) { if (fromSettings) { - _commandBaudRate = Settings_ESP3D::read_uint32(ESP_BAUD_RATE); + _commandBaudRate = ESP3DSettings::readUint32(ESP_BAUD_RATE); } - log_esp3d("Cmd Mode"); + esp3d_log("Cmd Mode"); _uploadMode = false; - serial_service.updateBaudRate(_commandBaudRate); + esp3d_serial_service.updateBaudRate(_commandBaudRate); } void MKSService::uploadMode() { - log_esp3d("Upload Mode"); + esp3d_log("Upload Mode"); _uploadMode = true; - serial_service.updateBaudRate(UPLOAD_BAUD_RATE); + esp3d_serial_service.updateBaudRate(UPLOAD_BAUD_RATE); } uint MKSService::getFragmentID(uint32_t fragmentNumber, bool isLast) { - log_esp3d("Fragment: %d %s", fragmentNumber, isLast ? " is last" : ""); + esp3d_log("Fragment: %d %s", fragmentNumber, isLast ? " is last" : ""); if (isLast) { fragmentNumber |= (1 << 31); } else { fragmentNumber &= ~(1 << 31); } - log_esp3d("Fragment is now: %d", fragmentNumber); + esp3d_log("Fragment is now: %d", fragmentNumber); return fragmentNumber; } @@ -173,21 +187,20 @@ bool MKSService::sendFirstFragment(const char *filename, size_t filesize) { strncpy((char *)&_frame[MKS_FRAME_DATA_OFFSET + 5], filename, fileNameLen); // Tail Flag _frame[dataLen + 4] = MKS_FRAME_TAIL_FLAG; - log_esp3d("Filename: %s Filesize: %d", filename, filesize); + esp3d_log("Filename: %s Filesize: %d", filename, filesize); for (uint i = 0; i < dataLen + 5; i++) { - log_esp3d("%c %x", _frame[i], _frame[i]); + esp3d_log("%c %x", _frame[i], _frame[i]); } _uploadStatus = UNKNOW_STATE; if (canSendFrame()) { - ESP3DOutput output(ESP_SERIAL_CLIENT); _uploadStatus = UNKNOW_STATE; - if (output.write(_frame, dataLen + 5) == (dataLen + 5)) { - log_esp3d("First fragment Ok"); + if (esp3d_serial_service.writeBytes(_frame, dataLen + 5) == (dataLen + 5)) { + esp3d_log("First fragment Ok"); sendFrameDone(); return true; } } - log_esp3d("Failed"); + esp3d_log("Failed"); sendFrameDone(); return false; } @@ -195,7 +208,7 @@ bool MKSService::sendFirstFragment(const char *filename, size_t filesize) { bool MKSService::sendFragment(const uint8_t *dataFrame, const size_t dataSize, uint fragmentID) { uint dataLen = dataSize + 4; - log_esp3d("Fragment datalen:%d", dataSize); + esp3d_log("Fragment datalen:%d", dataSize); // Head Flag _frame[MKS_FRAME_HEAD_OFFSET] = MKS_FRAME_HEAD_FLAG; // Type Flag @@ -218,19 +231,19 @@ bool MKSService::sendFragment(const uint8_t *dataFrame, const size_t dataSize, // Tail Flag _frame[dataLen + 4] = MKS_FRAME_TAIL_FLAG; /* for (uint i =0; i< dataLen + 5 ; i++) { - log_esp3d("%c %x",_frame[i],_frame[i]); + esp3d_log("%c %x",_frame[i],_frame[i]); }*/ if (canSendFrame()) { - ESP3DOutput output(ESP_SERIAL_CLIENT); _uploadStatus = UNKNOW_STATE; - if (output.write(_frame, MKS_FRAME_SIZE) == MKS_FRAME_SIZE) { - log_esp3d("Ok"); + if (esp3d_serial_service.writeBytes(_frame, MKS_FRAME_SIZE) == + MKS_FRAME_SIZE) { + esp3d_log("Ok"); sendFrameDone(); return true; } - log_esp3d_e("Error with size sent"); + esp3d_log_e("Error with size sent"); } - log_esp3d_e("Failed"); + esp3d_log_e("Failed"); sendFrameDone(); return false; } @@ -247,11 +260,11 @@ void MKSService::sendWifiHotspots() { // clean memory WiFi.scanDelete(); int n = WiFi.scanNetworks(); - log_esp3d("scan done"); + esp3d_log("scan done"); if (n == 0) { - log_esp3d("no networks found"); + esp3d_log("no networks found"); } else { - log_esp3d("%d networks found", n); + esp3d_log("%d networks found", n); clearFrame(); _frame[MKS_FRAME_HEAD_OFFSET] = MKS_FRAME_HEAD_FLAG; _frame[MKS_FRAME_TYPE_OFFSET] = MKS_FRAME_DATA_HOTSPOTS_LIST_TYPE; @@ -262,15 +275,15 @@ void MKSService::sendWifiHotspots() { } signal_rssi = WiFi.RSSI(i); // Print SSID and RSSI for each network found - log_esp3d("%d: %s (%d) %s", i + 1, WiFi.SSID(i).c_str(), signal_rssi, + esp3d_log("%d: %s (%d) %s", i + 1, WiFi.SSID(i).c_str(), signal_rssi, (WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : "*"); ssid_name_length = WiFi.SSID(i).length(); if (ssid_name_length > MAX_SSID_LENGTH) { - log_esp3d_e("Name too long, ignored"); + esp3d_log_e("Name too long, ignored"); continue; } if (signal_rssi < MIN_RSSI) { - log_esp3d("Signal too low, ignored"); + esp3d_log("Signal too low, ignored"); continue; } _frame[MKS_FRAME_DATA_OFFSET + dataOffset] = ssid_name_length; @@ -286,20 +299,20 @@ void MKSService::sendWifiHotspots() { _frame[MKS_FRAME_DATA_OFFSET + dataOffset] = MKS_FRAME_TAIL_FLAG; _frame[MKS_FRAME_DATALEN_OFFSET] = dataOffset & 0xff; _frame[MKS_FRAME_DATALEN_OFFSET + 1] = dataOffset >> 8; - log_esp3d("Size of data in frame %d ", dataOffset); + esp3d_log("Size of data in frame %d ", dataOffset); for (uint i = 0; i < dataOffset + 5; i++) { - log_esp3d("%c %x", _frame[i], _frame[i]); + esp3d_log("%c %x", _frame[i], _frame[i]); } if (canSendFrame()) { - ESP3DOutput output(ESP_SERIAL_CLIENT); - if (output.write(_frame, dataOffset + 5) == (dataOffset + 5)) { - log_esp3d("Ok"); + if (esp3d_serial_service.writeBytes(_frame, dataOffset + 5) == + (dataOffset + 5)) { + esp3d_log("Ok"); sendFrameDone(); } else { - log_esp3d_e("Send scan failed"); + esp3d_log_e("Send scan failed"); } } else { - log_esp3d_e("Cannot send scan"); + esp3d_log_e("Cannot send scan"); } // clean memory WiFi.scanDelete(); @@ -311,57 +324,57 @@ void MKSService::sendWifiHotspots() { void MKSService::handleFrame(const uint8_t type, const uint8_t *dataFrame, const size_t dataSize) { - log_esp3d("Command is %d", type); + esp3d_log("Command is %d", type); switch (type) { // wifi setup case MKS_TYPE_NET: - log_esp3d("************MKS_TYPE_NET*************"); + esp3d_log("************MKS_TYPE_NET*************"); messageWiFiConfig(dataFrame, dataSize); break; // not supported in Marlin // Confirmed as private source case MKS_TYPE_PRINTER: // ignored - log_esp3d("************MKS_TYPE_PRINTER*************"); + esp3d_log("************MKS_TYPE_PRINTER*************"); break; // File transfer if not command case MKS_TYPE_TRANSFER: // todo - log_esp3d("************MKS_TYPE_TRANSFER*************"); + esp3d_log("************MKS_TYPE_TRANSFER*************"); break; // Error when doing transfer case MKS_TYPE_EXCEPTION: - log_esp3d("************MKS_TYPE_EXCEPTION*************"); + esp3d_log("************MKS_TYPE_EXCEPTION*************"); messageException(dataFrame, dataSize); break; // not supported (cloud) case MKS_TYPE_CLOUD: // ignored - log_esp3d("************MKS_TYPE_CLOUD*************"); + esp3d_log("************MKS_TYPE_CLOUD*************"); break; // not supported (cloud) case MKS_TYPE_WID: // ignored - log_esp3d("************MKS_TYPE_WID*************"); + esp3d_log("************MKS_TYPE_WID*************"); break; // hot spot list case MKS_TYPE_SCAN_WIFI: - log_esp3d("************MKS_TYPE_SCAN_WIFI*************"); + esp3d_log("************MKS_TYPE_SCAN_WIFI*************"); sendWifiHotspots(); break; // setup Manual IP // not supported in Marlin, so do same for the moment case MKS_TYPE_MANUAL_IP: // ignored - log_esp3d("************MKS_TYPE_MANUAL_IP*************"); + esp3d_log("************MKS_TYPE_MANUAL_IP*************"); break; // On/Off Wifi case MKS_TYPE_WIFI_CTRL: - log_esp3d("************MKS_TYPE_WIFI_CTRL*************"); + esp3d_log("************MKS_TYPE_WIFI_CTRL*************"); messageWiFiControl(dataFrame, dataSize); break; default: - log_esp3d_e("Unknow type"); + esp3d_log_e("Unknow type"); } } @@ -372,26 +385,26 @@ void MKSService::messageWiFiControl(const uint8_t *dataFrame, } switch (dataFrame[0]) { case CONNECT_STA: - log_esp3d("CONNECT_STA"); + esp3d_log("CONNECT_STA"); if (!NetConfig::started()) { NetConfig::begin(); } break; case DISCONNECT_STA: - log_esp3d("CONNECT_STA"); + esp3d_log("CONNECT_STA"); if (NetConfig::started()) { NetConfig::end(); } break; case REMOVE_STA_INFO: - log_esp3d("REMOVE_STA_INFO"); + esp3d_log("REMOVE_STA_INFO"); if (NetConfig::started()) { NetConfig::end(); } - Settings_ESP3D::reset(true); + ESP3DSettings::reset(true); break; default: - log_esp3d_e("WiFi control flag not supported"); + esp3d_log_e("WiFi control flag not supported"); } } // Exception handle - but actually not used @@ -402,10 +415,10 @@ void MKSService::messageException(const uint8_t *dataFrame, } if ((dataFrame[0] == ERROR_STATE) || (dataFrame[0] == SUCCESS_STATE)) { _uploadStatus = dataFrame[0]; - log_esp3d("Tranfer: %s", dataFrame[0] == ERROR_STATE ? "Error" : "Success"); + esp3d_log("Tranfer: %s", dataFrame[0] == ERROR_STATE ? "Error" : "Success"); } else { _uploadStatus = UNKNOW_STATE; - log_esp3d_e("Tranfer state unknown"); + esp3d_log_e("Tranfer state unknown"); } } @@ -418,25 +431,25 @@ void MKSService::messageWiFiConfig(const uint8_t *dataFrame, bool needrestart = false; // Sanity check if (dataSize < 2) { - log_esp3d_e("Invalid data"); + esp3d_log_e("Invalid data"); return; } if ((dataFrame[0] != MKS_FRAME_NETWORK_AP_MODE) && (dataFrame[0] != MKS_FRAME_NETWORK_STA_MODE)) { - log_esp3d_e("Invalid mode"); + esp3d_log_e("Invalid mode"); return; } if ((dataFrame[1] > dataSize - 3) || (dataFrame[1] == 0) || (dataFrame[1] > MAX_SSID_LENGTH)) { - log_esp3d_e("Invalid ssid size"); + esp3d_log_e("Invalid ssid size"); return; } if ((uint)(dataFrame[1] + 3) > dataSize) { - log_esp3d_e("Overflow password size"); + esp3d_log_e("Overflow password size"); return; } if ((dataFrame[dataFrame[1] + 2]) > MAX_PASSWORD_LENGTH) { - log_esp3d_e("Invalid password size"); + esp3d_log_e("Invalid password size"); return; } // get SSID and password @@ -447,58 +460,58 @@ void MKSService::messageWiFiConfig(const uint8_t *dataFrame, password += (char)dataFrame[3 + j + dataFrame[1]]; } if (dataFrame[0] == MKS_FRAME_NETWORK_AP_MODE) { - if (Settings_ESP3D::read_byte(ESP_RADIO_MODE) != ESP_WIFI_AP) { - Settings_ESP3D::write_byte(ESP_RADIO_MODE, ESP_WIFI_AP); + if (ESP3DSettings::readByte(ESP_RADIO_MODE) != ESP_WIFI_AP) { + ESP3DSettings::writeByte(ESP_RADIO_MODE, ESP_WIFI_AP); needrestart = true; } - savedSsid = Settings_ESP3D::read_string(ESP_AP_SSID); - savedPassword = Settings_ESP3D::read_string(ESP_AP_PASSWORD); + savedSsid = ESP3DSettings::readString(ESP_AP_SSID); + savedPassword = ESP3DSettings::readString(ESP_AP_PASSWORD); if (savedSsid != ssid) { - Settings_ESP3D::write_string(ESP_AP_SSID, ssid.c_str()); + ESP3DSettings::writeString(ESP_AP_SSID, ssid.c_str()); needrestart = true; } if (savedPassword != password) { - Settings_ESP3D::write_string(ESP_AP_PASSWORD, password.c_str()); + ESP3DSettings::writeString(ESP_AP_PASSWORD, password.c_str()); needrestart = true; } } else { - if (Settings_ESP3D::read_byte(ESP_RADIO_MODE) != ESP_WIFI_STA) { - Settings_ESP3D::write_byte(ESP_RADIO_MODE, ESP_WIFI_STA); + if (ESP3DSettings::readByte(ESP_RADIO_MODE) != ESP_WIFI_STA) { + ESP3DSettings::writeByte(ESP_RADIO_MODE, ESP_WIFI_STA); needrestart = true; } - savedSsid = Settings_ESP3D::read_string(ESP_STA_SSID); - savedPassword = Settings_ESP3D::read_string(ESP_STA_PASSWORD); + savedSsid = ESP3DSettings::readString(ESP_STA_SSID); + savedPassword = ESP3DSettings::readString(ESP_STA_PASSWORD); if (savedSsid != ssid) { - Settings_ESP3D::write_string(ESP_STA_SSID, ssid.c_str()); + ESP3DSettings::writeString(ESP_STA_SSID, ssid.c_str()); needrestart = true; } if (savedPassword != password) { - Settings_ESP3D::write_string(ESP_STA_PASSWORD, password.c_str()); + ESP3DSettings::writeString(ESP_STA_PASSWORD, password.c_str()); needrestart = true; } if (needrestart) { // change also to DHCP for new value - Settings_ESP3D::write_byte(ESP_STA_IP_MODE, DHCP_MODE); + ESP3DSettings::writeByte(ESP_STA_IP_MODE, DHCP_MODE); } } if (needrestart) { - log_esp3d("Modifications done - restarting network"); + esp3d_log("Modifications done - restarting network"); NetConfig::begin(); } } bool MKSService::canSendFrame() { - log_esp3d("Is board ready for frame?"); + esp3d_log("Is board ready for frame?"); digitalWrite(ESP_FLAG_PIN, BOARD_READY_FLAG_VALUE); uint32_t startTime = millis(); while ((millis() - startTime) < FRAME_WAIT_TO_SEND_TIMEOUT) { if (digitalRead(BOARD_FLAG_PIN) == BOARD_READY_FLAG_VALUE) { - log_esp3d("Yes"); + esp3d_log("Yes"); return true; } - Hal::wait(0); + ESP3DHal::wait(0); } - log_esp3d("Time out no board answer"); + esp3d_log("Time out no board answer"); return false; } @@ -514,7 +527,7 @@ bool MKSService::sendGcodeFrame(const char *cmd) { if (tmp.endsWith("\n")) { tmp[tmp.length() - 1] = '\0'; } - log_esp3d("Packing: *%s*, size=%d", tmp.c_str(), strlen(tmp.c_str())); + esp3d_log("Packing: *%s*, size=%d", tmp.c_str(), strlen(tmp.c_str())); clearFrame(); _frame[MKS_FRAME_HEAD_OFFSET] = MKS_FRAME_HEAD_FLAG; _frame[MKS_FRAME_TYPE_OFFSET] = MKS_FRAME_DATA_COMMAND_TYPE; @@ -528,21 +541,20 @@ bool MKSService::sendGcodeFrame(const char *cmd) { _frame[MKS_FRAME_DATALEN_OFFSET + 1] = ((strlen(tmp.c_str()) + 2) >> 8) & 0xff; - log_esp3d("Size of data in frame %d ", strlen(tmp.c_str()) + 2); + esp3d_log("Size of data in frame %d ", strlen(tmp.c_str()) + 2); // for (uint i =0; i< strlen(tmp.c_str())+7;i++){ - // log_esp3d("%c %x",_frame[i],_frame[i]); + // esp3d_log("%c %x",_frame[i],_frame[i]); // } if (canSendFrame()) { - ESP3DOutput output(ESP_SERIAL_CLIENT); - if (output.write(_frame, strlen(tmp.c_str()) + 7) == + if (esp3d_serial_service.writeBytes(_frame, strlen(tmp.c_str()) + 7) == (strlen(tmp.c_str()) + 7)) { - log_esp3d("Ok"); + esp3d_log("Ok"); sendFrameDone(); return true; } } - _e("Failed"); + esp3d_log_e("Failed"); sendFrameDone(); return false; } @@ -556,13 +568,13 @@ bool MKSService::sendNetworkFrame() { } if ((millis() - lastsend) > NET_FRAME_REFRESH_TIME) { lastsend = millis(); - log_esp3d("Network frame preparation"); + esp3d_log("Network frame preparation"); // Prepare clearFrame(); _frame[MKS_FRAME_HEAD_OFFSET] = MKS_FRAME_HEAD_FLAG; _frame[MKS_FRAME_TYPE_OFFSET] = MKS_FRAME_DATA_NETWORK_TYPE; if (NetConfig::getMode() == ESP_WIFI_STA) { - log_esp3d("STA Mode"); + esp3d_log("STA Mode"); if (WiFi.status() == WL_CONNECTED) { /////////////////////////////////// // IP Segment @@ -572,7 +584,7 @@ bool MKSService::sendNetworkFrame() { _frame[MKS_FRAME_DATA_OFFSET + 1] = ip[1]; _frame[MKS_FRAME_DATA_OFFSET + 2] = ip[2]; _frame[MKS_FRAME_DATA_OFFSET + 3] = ip[3]; - log_esp3d("IP %d.%d.%d.%d", _frame[MKS_FRAME_DATA_OFFSET], + esp3d_log("IP %d.%d.%d.%d", _frame[MKS_FRAME_DATA_OFFSET], _frame[MKS_FRAME_DATA_OFFSET + 1], _frame[MKS_FRAME_DATA_OFFSET + 2], _frame[MKS_FRAME_DATA_OFFSET + 3]); @@ -594,7 +606,7 @@ bool MKSService::sendNetworkFrame() { _frame[MKS_FRAME_DATA_OFFSET + 7] = MKS_FRAME_NETWORK_STA_MODE; ////////////////////////////////// // Wifi_name_len Segment - s = Settings_ESP3D::read_string(ESP_STA_SSID); + s = ESP3DSettings::readString(ESP_STA_SSID); _frame[MKS_FRAME_DATA_OFFSET + 8] = s.length(); dataOffset = MKS_FRAME_DATA_OFFSET + 9; ////////////////////////////////// @@ -603,7 +615,7 @@ bool MKSService::sendNetworkFrame() { dataOffset += s.length(); ////////////////////////////////// // Wifi_key_len Segment - s = Settings_ESP3D::read_string(ESP_STA_PASSWORD); + s = ESP3DSettings::readString(ESP_STA_PASSWORD); _frame[dataOffset] = s.length(); dataOffset++; ////////////////////////////////// @@ -612,7 +624,7 @@ bool MKSService::sendNetworkFrame() { dataOffset += s.length(); } else if (NetConfig::getMode() == ESP_WIFI_AP || (NetConfig::getMode() == ESP_AP_SETUP)) { - log_esp3d("AP Mode"); + esp3d_log("AP Mode"); /////////////////////////////////// // IP Segment // IP value @@ -630,7 +642,7 @@ bool MKSService::sendNetworkFrame() { _frame[MKS_FRAME_DATA_OFFSET + 7] = MKS_FRAME_NETWORK_AP_MODE; ////////////////////////////////// // Wifi_name_len Segment - String s = Settings_ESP3D::read_string(ESP_AP_SSID); + String s = ESP3DSettings::readString(ESP_AP_SSID); _frame[MKS_FRAME_DATA_OFFSET + 8] = s.length(); dataOffset = MKS_FRAME_DATA_OFFSET + 9; ////////////////////////////////// @@ -639,7 +651,7 @@ bool MKSService::sendNetworkFrame() { dataOffset += s.length(); ////////////////////////////////// // Wifi_key_len Segment - s = Settings_ESP3D::read_string(ESP_AP_PASSWORD); + s = ESP3DSettings::readString(ESP_AP_PASSWORD); _frame[dataOffset] = s.length(); dataOffset++; ////////////////////////////////// @@ -648,7 +660,7 @@ bool MKSService::sendNetworkFrame() { dataOffset += s.length(); } else { // not supported - log_esp3d_e("Mode not supported : %d ", NetConfig::getMode()); + esp3d_log_e("Mode not supported : %d ", NetConfig::getMode()); return false; } ////////////////////////////////// @@ -656,7 +668,7 @@ bool MKSService::sendNetworkFrame() { // hard coded _frame[MKS_FRAME_DATA_OFFSET + 4] = (telnet_server.port()) & 0xff; _frame[MKS_FRAME_DATA_OFFSET + 5] = ((telnet_server.port()) >> 8) & 0xff; - log_esp3d("Cloud port: %d", (telnet_server.port())); + esp3d_log("Cloud port: %d", (telnet_server.port())); ////////////////////////////////// // Cloud State Segment @@ -707,17 +719,17 @@ bool MKSService::sendNetworkFrame() { // Calculated from above _frame[MKS_FRAME_DATALEN_OFFSET] = (dataOffset - 4) & 0xff; _frame[MKS_FRAME_DATALEN_OFFSET + 1] = ((dataOffset - 4) >> 8) & 0xff; - log_esp3d("Size of data in frame %d ", dataOffset - 4); + esp3d_log("Size of data in frame %d ", dataOffset - 4); if (canSendFrame()) { - ESP3DOutput output(ESP_SERIAL_CLIENT); - if (output.write(_frame, dataOffset + 1) == (dataOffset + 1)) { - log_esp3d("Ok"); + if (esp3d_serial_service.writeBytes(_frame, dataOffset + 1) == + (dataOffset + 1)) { + esp3d_log("Ok"); sendFrameDone(); return true; } } sendFrameDone(); - log_esp3d_e("Failed"); + esp3d_log_e("Failed"); } return false; diff --git a/esp3d/src/modules/mks/mks_service.h b/esp3d/src/modules/mks/mks_service.h index 55bc8c14..b154c3fe 100644 --- a/esp3d/src/modules/mks/mks_service.h +++ b/esp3d/src/modules/mks/mks_service.h @@ -21,47 +21,47 @@ #ifndef _MKS_SERVICES_H #define _MKS_SERVICES_H -#define MKS_FRAME_SIZE 1024 -#define MKS_FRAME_DATA_MAX_SIZE (MKS_FRAME_SIZE - 5 - 4) +#define MKS_FRAME_SIZE 1024 +#define MKS_FRAME_DATA_MAX_SIZE (MKS_FRAME_SIZE - 5 - 4) +#include "../../core/esp3d_message.h" +class MKSService { + public: + static bool begin(); + static bool sendNetworkFrame(); + static bool dispatch(ESP3DMessage* message); + static bool sendGcodeFrame(const char* cmd); + static void handle(); + static void handleFrame(const uint8_t type, const uint8_t* dataFrame, + const size_t dataSize); + static void end(); + static bool started() { return _started; } + static bool isHead(const char c); + static bool isTail(const char c); + static bool isFrame(const char c); + static bool isCommand(const char c); + static bool sendFirstFragment(const char* filename, size_t filesize); + static bool sendFragment(const uint8_t* dataFrame, const size_t dataSize, + uint fragmentID); + static uint getFragmentID(uint32_t fragmentNumber, bool isLast = false); + static void commandMode(bool fromSettings = false); + static void uploadMode(); -class MKSService -{ -public: - static bool begin(); - static bool sendNetworkFrame(); - static bool sendGcodeFrame(const char* cmd); - static void handle(); - static void handleFrame(const uint8_t type, const uint8_t * dataFrame, const size_t dataSize ); - static void end(); - static bool started() - { - return _started; - } - static bool isHead(const char c); - static bool isTail(const char c); - static bool isFrame(const char c); - static bool isCommand(const char c); - static bool sendFirstFragment(const char* filename, size_t filesize); - static bool sendFragment(const uint8_t * dataFrame, const size_t dataSize,uint fragmentID); - static uint getFragmentID(uint32_t fragmentNumber, bool isLast=false); - static void commandMode(bool fromSettings=false); - static void uploadMode(); -private: - static uint8_t _uploadStatus; - static long _commandBaudRate; - static void sendWifiHotspots(); - static void messageWiFiControl(const uint8_t * dataFrame, const size_t dataSize); - static void messageException(const uint8_t * dataFrame, const size_t dataSize); - static void messageWiFiConfig(const uint8_t * dataFrame, const size_t dataSize); - static void clearFrame(uint start=0); - static bool canSendFrame(); - static void sendFrameDone(); - static bool _started; - static uint8_t _frame[MKS_FRAME_SIZE]; - static char _moduleId[22]; - static bool _uploadMode; + private: + static uint8_t _uploadStatus; + static long _commandBaudRate; + static void sendWifiHotspots(); + static void messageWiFiControl(const uint8_t* dataFrame, + const size_t dataSize); + static void messageException(const uint8_t* dataFrame, const size_t dataSize); + static void messageWiFiConfig(const uint8_t* dataFrame, + const size_t dataSize); + static void clearFrame(uint start = 0); + static bool canSendFrame(); + static void sendFrameDone(); + static bool _started; + static uint8_t _frame[MKS_FRAME_SIZE]; + static char _moduleId[22]; + static bool _uploadMode; }; - -#endif //_SERIAL_SERVICES_H - +#endif //_SERIAL_SERVICES_H diff --git a/esp3d/src/modules/network/netconfig.cpp b/esp3d/src/modules/network/netconfig.cpp index c05b8b17..89f68891 100644 --- a/esp3d/src/modules/network/netconfig.cpp +++ b/esp3d/src/modules/network/netconfig.cpp @@ -40,8 +40,8 @@ #if defined(BLUETOOTH_FEATURE) #include "../bluetooth/BT_service.h" #endif // BLUETOOTH_FEATURE -#include "../../core/esp3doutput.h" -#include "../../core/settings_esp3d.h" +#include "../../core/esp3d_commands.h" +#include "../../core/esp3d_settings.h" #include "netservices.h" String NetConfig::_hostname = ""; @@ -124,26 +124,102 @@ String NetConfig::localIP() { return currentIP; } +/** + * Get Gateway IP string what ever is enabled + */ +String NetConfig::localGW() { + static String currentIP = ""; +#if defined(WIFI_FEATURE) + if (WiFi.getMode() == WIFI_STA) { + currentIP = WiFi.localIP().toString(); + } else if (WiFi.getMode() == WIFI_AP) { + currentIP = WiFiConfig::getAPGateway().toString(); + } +#endif // WIFI_FEATURE +#if defined(ETH_FEATURE) + if (EthConfig::started()) { + currentIP = ETH.localIP().toString(); + } +#endif // ETH_FEATURE + if (currentIP.length() == 0) { + currentIP = "0.0.0.0"; + } + return currentIP; +} + +/** + * Get Network mask string what ever is enabled + */ +String NetConfig::localMSK() { + static String currentIP = ""; +#if defined(WIFI_FEATURE) + if (WiFi.getMode() == WIFI_STA) { + currentIP = WiFi.subnetMask().toString(); + } else if (WiFi.getMode() == WIFI_AP) { + currentIP = WiFiConfig::getAPSubnet().toString(); + } +#endif // WIFI_FEATURE +#if defined(ETH_FEATURE) + if (EthConfig::started()) { + currentIP = ETH.subnetMask().toString(); + } +#endif // ETH_FEATURE + if (currentIP.length() == 0) { + currentIP = "0.0.0.0"; + } + return currentIP; +} + +/** + * Get DNS IP string what ever is enabled + */ +String NetConfig::localDNS() { + static String currentIP = ""; +#if defined(WIFI_FEATURE) + if (WiFi.getMode() == WIFI_STA) { + currentIP = WiFi.dnsIP().toString(); + } else if (WiFi.getMode() == WIFI_AP) { + currentIP = WiFi.softAPIP().toString(); + } +#endif // WIFI_FEATURE +#if defined(ETH_FEATURE) + if (EthConfig::started()) { + currentIP = ETH.dnsIP().toString(); + } +#endif // ETH_FEATURE + if (currentIP.length() == 0) { + currentIP = "0.0.0.0"; + } + return currentIP; +} + // wifi event void NetConfig::onWiFiEvent(WiFiEvent_t event) { - ESP3DOutput output(ESP_ALL_CLIENTS); switch (event) { case WIFI_EVENT_STAMODE_CONNECTED: _needReconnect2AP = false; break; case WIFI_EVENT_STAMODE_DISCONNECTED: { if (_started) { - output.printMSG("Disconnected"); + esp3d_commands.dispatch("Disconnected", ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); //_needReconnect2AP = true; } } break; case WIFI_EVENT_STAMODE_GOT_IP: { #if COMMUNICATION_PROTOCOL != MKS_SERIAL - output.printMSG(WiFi.localIP().toString().c_str()); + esp3d_commands.dispatch(WiFi.localIP().toString().c_str(), + ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); #endif // #if COMMUNICATION_PROTOCOL == MKS_SERIAL } break; case WIFI_EVENT_SOFTAPMODE_STACONNECTED: { - output.printMSG("New client"); + esp3d_commands.dispatch("New client", ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } break; #ifdef ARDUINO_ARCH_ESP32 case ARDUINO_EVENT_WIFI_STA_LOST_IP: @@ -154,20 +230,32 @@ void NetConfig::onWiFiEvent(WiFiEvent_t event) { #ifdef ETH_FEATURE case ARDUINO_EVENT_ETH_START: { EthConfig::setConnected(false); - if (Settings_ESP3D::isVerboseBoot()) { - output.printMSG("Checking connection"); + if (ESP3DSettings::isVerboseBoot()) { + esp3d_commands.dispatch( + "Checking connection", ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } } break; case ARDUINO_EVENT_ETH_CONNECTED: { - output.printMSG("Cable connected"); + esp3d_commands.dispatch("Cable connected", ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); EthConfig::setConnected(true); } break; case ARDUINO_EVENT_ETH_DISCONNECTED: { - output.printMSG("Cable disconnected"); + esp3d_commands.dispatch("Cable disconnected", + ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); EthConfig::setConnected(false); } break; case ARDUINO_EVENT_ETH_GOT_IP: - output.printMSG(ETH.localIP().toString().c_str()); + esp3d_commands.dispatch(ETH.localIP().toString().c_str(), + ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); EthConfig::setConnected(true); break; case ARDUINO_EVENT_ETH_STOP: @@ -191,12 +279,14 @@ bool NetConfig::begin() { bool res = false; // clear everything end(); - int8_t espMode = Settings_ESP3D::read_byte(ESP_RADIO_MODE); - ESP3DOutput output(ESP_ALL_CLIENTS); - log_esp3d("Starting Network"); + int8_t espMode = ESP3DSettings::readByte(ESP_RADIO_MODE); + esp3d_log("Starting Network"); if (espMode != ESP_NO_NETWORK) { - if (Settings_ESP3D::isVerboseBoot()) { - output.printMSG("Starting Network"); + if (ESP3DSettings::isVerboseBoot()) { + esp3d_commands.dispatch("Starting Network", ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } } // setup events @@ -214,23 +304,35 @@ bool NetConfig::begin() { _events_registered = true; } // Get hostname - _hostname = Settings_ESP3D::read_string(ESP_HOSTNAME); + _hostname = ESP3DSettings::readString(ESP_HOSTNAME); _mode = espMode; if (espMode == ESP_NO_NETWORK) { - output.printMSG("Disable Network"); + esp3d_commands.dispatch("Disable Network", ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); WiFi.mode(WIFI_OFF); - ESP3DOutput::toScreen(ESP_OUTPUT_IP_ADDRESS, nullptr); - if (Settings_ESP3D::isVerboseBoot()) { - ESP3DOutput output(ESP_ALL_CLIENTS); - output.printMSG(RADIO_OFF_MSG); - output.flush(); +#if defined(DISPLAY_DEVICE) + ESP3DRequest reqId = { + .id = ESP_OUTPUT_IP_ADDRESS, + }; + esp3d_commands.dispatch(" ", ESP3DClientType::rendering, reqId, + ESP3DMessageType::unique); +#endif // DISPLAY_DEVICE + if (ESP3DSettings::isVerboseBoot()) { + esp3d_commands.dispatch(RADIO_OFF_MSG, ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } return true; } #if defined(WIFI_FEATURE) if ((espMode == ESP_AP_SETUP) || (espMode == ESP_WIFI_AP) || (espMode == ESP_WIFI_STA)) { - output.printMSG("Setup wifi"); + esp3d_commands.dispatch("Setup wifi", ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); res = WiFiConfig::begin(espMode); } #endif // WIFI_FEATURE @@ -251,7 +353,13 @@ bool NetConfig::begin() { if (espMode == ESP_BT) { WiFi.mode(WIFI_OFF); String msg = "BT On"; - ESP3DOutput::toScreen(ESP_OUTPUT_STATUS, msg.c_str()); +#if defined(DISPLAY_DEVICE) + ESP3DRequest reqId = { + .id = ESP_OUTPUT_STATUS, + }; + esp3d_commands.dispatch(msg.c_str(), ESP3DClientType::rendering, reqId, + ESP3DMessageType::unique); +#endif // DISPLAY_DEVICE res = bt_service.begin(); } #else @@ -262,13 +370,23 @@ bool NetConfig::begin() { #endif // BLUETOOTH_FEATURE if (espMode == ESP_NO_NETWORK) { - output.printMSG("Disable Network"); + esp3d_commands.dispatch("Disable Network", ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); WiFi.mode(WIFI_OFF); - ESP3DOutput::toScreen(ESP_OUTPUT_IP_ADDRESS, nullptr); - if (Settings_ESP3D::isVerboseBoot()) { - ESP3DOutput output(ESP_ALL_CLIENTS); - output.printMSG(RADIO_OFF_MSG); - output.flush(); +#if defined(DISPLAY_DEVICE) + ESP3DRequest reqId = { + .id = ESP_OUTPUT_IP_ADDRESS, + }; + esp3d_commands.dispatch(" ", ESP3DClientType::rendering, reqId, + ESP3DMessageType::unique); +#endif // DISPLAY_DEVICE + if (ESP3DSettings::isVerboseBoot()) { + esp3d_commands.dispatch(RADIO_OFF_MSG, ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } return true; } @@ -287,7 +405,7 @@ bool NetConfig::begin() { } #endif // WIFI_FEATURE if (start_services) { - log_esp3d("Starting service"); + esp3d_log("Starting service"); res = NetServices::begin(); } } @@ -299,15 +417,21 @@ bool NetConfig::begin() { } #endif // WIFI_FEATURE #endif // ARDUINO_ARCH_ESP32 - LOG_ESP3D_NETWORK_INIT + ESP3D_LOG_NETWORK_INIT_FN if (res) { - log_esp3d("Network config started"); + esp3d_log("Network config started"); } else { end(); - log_esp3d_e("Network config failed"); + esp3d_log_e("Network config failed"); } - ESP3DOutput::toScreen(ESP_OUTPUT_IP_ADDRESS, nullptr); +#if defined(DISPLAY_DEVICE) + ESP3DRequest reqId = { + .id = ESP_OUTPUT_IP_ADDRESS, + }; + esp3d_commands.dispatch(" ", ESP3DClientType::rendering, reqId, + ESP3DMessageType::unique); +#endif // DISPLAY_DEVICE return res; } @@ -317,7 +441,7 @@ bool NetConfig::begin() { void NetConfig::end() { NetServices::end(); - LOG_ESP3D_NETWORK_END + ESP3D_LOG_NETWORK_END_FN _mode = ESP_NO_NETWORK; #if defined(WIFI_FEATURE) WiFiConfig::end(); @@ -337,7 +461,7 @@ void NetConfig::end() { const char* NetConfig::hostname(bool fromsettings) { if (fromsettings) { - _hostname = Settings_ESP3D::read_string(ESP_HOSTNAME); + _hostname = ESP3DSettings::readString(ESP_HOSTNAME); return _hostname.c_str(); } #if defined(WIFI_FEATURE) @@ -382,7 +506,7 @@ void NetConfig::handle() { #endif // BLUETOOTH_FEATURE NetServices::handle(); // Debug - LOG_ESP3D_NETWORK_HANDLE + ESP3D_LOG_NETWORK_HANDLE_FN } } diff --git a/esp3d/src/modules/network/netconfig.h b/esp3d/src/modules/network/netconfig.h index 313c7ec2..d886ecaf 100644 --- a/esp3d/src/modules/network/netconfig.h +++ b/esp3d/src/modules/network/netconfig.h @@ -58,6 +58,9 @@ class NetConfig { static void setMode(uint8_t mode); static bool started() { return _started; } static String localIP(); + static String localGW(); + static String localMSK(); + static String localDNS(); static IPAddress localIPAddress(); private: diff --git a/esp3d/src/modules/network/netservices.cpp b/esp3d/src/modules/network/netservices.cpp index 569f4b8c..df5c1dcc 100644 --- a/esp3d/src/modules/network/netservices.cpp +++ b/esp3d/src/modules/network/netservices.cpp @@ -20,8 +20,8 @@ #include "netservices.h" -#include "../../core/esp3doutput.h" -#include "../../core/settings_esp3d.h" +#include "../../core/esp3d_commands.h" +#include "../../core/esp3d_settings.h" #include "../../include/esp3d_config.h" #include "netconfig.h" @@ -83,20 +83,26 @@ 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); + String hostname = ESP3DSettings::readString(ESP_HOSTNAME); end(); #ifdef TIMESTAMP_FEATURE if (WiFi.getMode() != WIFI_AP) { if (!timeService.begin()) { - if (timeService.is_internet_time()) { - output.printERROR("Failed contact time servers!"); + if (timeService.isInternetTime()) { + esp3d_commands.dispatch( + "Failed contact time servers!", ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); + esp3d_log_e("Failed contact time servers!"); } } else { String tmp = "Current time :"; tmp += timeService.getCurrentTime(); - if (Settings_ESP3D::isVerboseBoot()) { - output.printMSG(tmp.c_str()); + if (ESP3DSettings::isVerboseBoot()) { + esp3d_commands.dispatch(tmp.c_str(), ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } } } @@ -109,7 +115,6 @@ bool NetServices::begin() { #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"; @@ -121,36 +126,64 @@ bool NetServices::begin() { ESP_FileSystem::end(); #endif // FILESYSTEM_FEATURE } - output.printMSG(type.c_str()); + esp3d_commands.dispatch(type.c_str(), ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); }); ArduinoOTA.onEnd([]() { - ESP3DOutput output(ESP_ALL_CLIENTS); - output.printMSG("End OTA"); + esp3d_commands.dispatch("End OTA", ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); }); 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()); + esp3d_commands.dispatch(prg.c_str(), ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); }); ArduinoOTA.onError([](ota_error_t error) { String stmp = "OTA Error: " + String(error); - ESP3DOutput output(ESP_ALL_CLIENTS); - output.printERROR(stmp.c_str()); + esp3d_commands.dispatch(stmp.c_str(), ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); if (error == OTA_AUTH_ERROR) { - output.printERROR("Auth Failed"); + esp3d_commands.dispatch("Auth Failed", ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); + esp3d_log_e("Auth Failed"); } else if (error == OTA_BEGIN_ERROR) { - output.printERROR("Begin Failed"); + esp3d_log_e("Begin Failed"); + esp3d_commands.dispatch("Begin Failed", ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } else if (error == OTA_CONNECT_ERROR) { - output.printERROR("Connect Failed"); + esp3d_log_e("Connect Failed"); + esp3d_commands.dispatch("Connect Failed", ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } else if (error == OTA_RECEIVE_ERROR) { - output.printERROR("Receive Failed"); + esp3d_log_e("Receive Failed"); + esp3d_commands.dispatch("Receive Failed", ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } else if (error == OTA_END_ERROR) { - output.printERROR("End Failed"); + esp3d_log_e("End Failed"); + esp3d_commands.dispatch("End Failed", ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } }); - if (Settings_ESP3D::isVerboseBoot()) { - output.printMSG("OTA service started"); + if (ESP3DSettings::isVerboseBoot()) { + esp3d_commands.dispatch("OTA service started", + ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } String lhostname = hostname; lhostname.toLowerCase(); @@ -168,11 +201,18 @@ bool NetServices::begin() { // 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"); + if (ESP3DSettings::isVerboseBoot()) { + esp3d_commands.dispatch( + "Captive Portal started", ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } } else { - output.printERROR("Failed start Captive Portal"); + esp3d_log_e("Failed start Captive Portal"); + esp3d_commands.dispatch("Failed start Captive Portal", + ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } } #endif // CAPTIVE_PORTAL_FEATURE @@ -180,12 +220,19 @@ bool NetServices::begin() { #ifdef HTTP_FEATURE if (!HTTP_Server::begin()) { res = false; - output.printERROR("HTTP server failed"); + esp3d_log_e("HTTP server failed"); + esp3d_commands.dispatch("HTTP server failed", ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } 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 (ESP3DSettings::isVerboseBoot()) { + esp3d_commands.dispatch(stmp.c_str(), ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } } } @@ -193,13 +240,20 @@ bool NetServices::begin() { #ifdef TELNET_FEATURE if (!telnet_server.begin()) { res = false; - output.printERROR("Telnet server failed"); + esp3d_log_e("Telnet server failed"); + esp3d_commands.dispatch("Telnet server failed", + ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } 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 (ESP3DSettings::isVerboseBoot()) { + esp3d_commands.dispatch(stmp.c_str(), ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } } } @@ -207,59 +261,85 @@ bool NetServices::begin() { #ifdef FTP_FEATURE if (!ftp_server.begin()) { res = false; - output.printERROR("Ftp server failed"); + esp3d_log_e("Ftp server failed"); + esp3d_commands.dispatch("Ftp server failed", ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } 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 (ESP3DSettings::isVerboseBoot()) { + esp3d_commands.dispatch(stmp.c_str(), ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } } } #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"); + ESP3DSettings::readUint32(ESP_WEBSOCKET_PORT))) { + esp3d_log_e("Failed start Terminal Web Socket"); + esp3d_commands.dispatch("Failed start Terminal Web Socket", + ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } 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 (ESP3DSettings::isVerboseBoot()) { + esp3d_commands.dispatch(stmp.c_str(), ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } } } #endif // WS_DATA_FEATURE #ifdef WEBDAV_FEATURE if (!webdav_server.begin()) { - output.printMSG("Failed start Terminal Web Socket"); + esp3d_log("Failed start Terminal Web Socket"); + esp3d_commands.dispatch("Failed start Terminal Web Socket", + ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } 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 (ESP3DSettings::isVerboseBoot()) { + esp3d_commands.dispatch(stmp.c_str(), ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } } } #endif // WEBDAV_FEATURE #if defined(HTTP_FEATURE) if (!websocket_terminal_server.begin()) { - output.printMSG("Failed start Terminal Web Socket"); + esp3d_log_e("Failed start Terminal Web Socket"); + esp3d_commands.dispatch("Failed start Terminal Web Socket", + ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } #endif // HTTP_FEATURE -#ifdef MDNS_FEATURE +#if defined(MDNS_FEATURE) && defined(HTTP_FEATURE) esp3d_mDNS.addESP3DServices(HTTP_Server::port()); #endif // MDNS_FEATURE +#if defined(MDNS_FEATURE) && defined(HTTP_FEATURE) #ifdef SSDP_FEATURE // SSDP service presentation if (WiFi.getMode() != WIFI_AP && HTTP_Server::started()) { // Add specific for SSDP - String stmp = String(Hal::getChipID()); + String stmp = String(ESP3DHal::getChipID()); SSDP.setSchemaURL("description.xml"); SSDP.setHTTPPort(HTTP_Server::port()); SSDP.setName(hostname.c_str()); @@ -278,18 +358,25 @@ bool NetServices::begin() { SSDP.setManufacturerURL(ESP_MANUFACTURER_URL); SSDP.begin(); stmp = "SSDP started with '" + hostname + "'"; - if (Settings_ESP3D::isVerboseBoot()) { - output.printMSG(stmp.c_str()); + if (ESP3DSettings::isVerboseBoot()) { + esp3d_commands.dispatch(stmp.c_str(), ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } } -#endif // SSDP_FEATURE +#endif // defined(MDNS_FEATURE) && defined(HTTP_FEATURE) +#endif // MDNS_FEATURE #ifdef 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"); + esp3d_log_e("Failed start camera streaming server"); + esp3d_commands.dispatch("Failed start camera streaming server", + ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } #endif // CAMERA_DEVICE #if COMMUNICATION_PROTOCOL == MKS_SERIAL @@ -298,9 +385,12 @@ bool NetServices::begin() { if (!res) { end(); } - Hal::wait(1000); + ESP3DHal::wait(1000); #if COMMUNICATION_PROTOCOL != MKS_SERIAL - output.printMSG(NetConfig::localIP().c_str()); + esp3d_commands.dispatch(NetConfig::localIP().c_str(), + ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); #endif // #if COMMUNICATION_PROTOCOL == MKS_SERIAL _started = res; return _started; diff --git a/esp3d/src/modules/notifications/notifications_service.cpp b/esp3d/src/modules/notifications/notifications_service.cpp index c2a24978..242da43d 100644 --- a/esp3d/src/modules/notifications/notifications_service.cpp +++ b/esp3d/src/modules/notifications/notifications_service.cpp @@ -30,13 +30,15 @@ //* Telegram // - // https://medium.com/@xabaras/sending-a-message-to-a-telegram-channel-the-easy-way-eb0a0b32968 +//* Home Assistant +// - https://developers.home-assistant.io/docs/api/rest/ #include "../../include/esp3d_config.h" #ifdef NOTIFICATION_FEATURE #include -#include "../../core/esp3doutput.h" -#include "../../core/settings_esp3d.h" +#include "../../core/esp3d_message.h" +#include "../../core/esp3d_settings.h" #include "../network/netconfig.h" #include "notifications_service.h" @@ -79,6 +81,8 @@ extern "C" { #define IFTTTSERVER "maker.ifttt.com" #define IFTTTPORT 443 +#define HOMEASSISTANTTIMEOUT 5000 + #define EMAILTIMEOUT 5000 NotificationsService notificationsservice; @@ -87,17 +91,18 @@ NotificationsService notificationsservice; void NotificationsService::BearSSLSetup(WiFiClientSecure& Notificationclient) { if (Notificationclient.probeMaxFragmentLength(_serveraddress.c_str(), _port, BEARSSL_MFLN_SIZE)) { - log_esp3d("Handshake success"); + esp3d_log("Handshake success"); Notificationclient.setBufferSizes(BEARSSL_MFLN_SIZE, 512); } else { - log_esp3d_e("Handshake failed"); + esp3d_log_e("Handshake failed"); Notificationclient.setBufferSizes(BEARSSL_MFLN_SIZE_FALLBACK, 512); } } #endif // ARDUINO_ARCH_ESP8266 // TODO: put error in variable to allow better error handling -bool NotificationsService::Wait4Answer(WiFiClientSecure& client, +template +bool NotificationsService::Wait4Answer(T& client, const char* linetrigger, const char* expected_answer, uint32_t timeout) { @@ -106,32 +111,32 @@ bool NotificationsService::Wait4Answer(WiFiClientSecure& client, uint32_t starttimeout = millis(); while (client.connected() && ((millis() - starttimeout) < timeout)) { answer = client.readStringUntil('\n'); - log_esp3d("Answer: %s", answer.c_str()); + esp3d_log("Answer: %s", answer.c_str()); if ((answer.indexOf(linetrigger) != -1) || (strlen(linetrigger) == 0)) { break; } - Hal::wait(10); + ESP3DHal::wait(10); } if (strlen(expected_answer) == 0) { - log_esp3d("Answer ignored as requested"); + esp3d_log("Answer ignored as requested"); return true; } if (answer.indexOf(expected_answer) == -1) { - log_esp3d("Did not got answer!"); + esp3d_log("Did not got answer!"); return false; } else { - log_esp3d("Got expected answer"); + esp3d_log("Got expected answer"); return true; } } - log_esp3d_e("Failed to send message"); + esp3d_log_e("Failed to send message"); return false; } bool NotificationsService::sendAutoNotification(const char* msg) { if (!(NetConfig::started()) || (NetConfig::getMode() != ESP_WIFI_STA) || (!_started) || (!_autonotification)) { - log_esp3d("Auto notification rejected"); + esp3d_log("Auto notification rejected"); return false; } String msgtpl = msg; @@ -141,10 +146,10 @@ bool NotificationsService::sendAutoNotification(const char* msg) { msgtpl.replace("%ESP_NAME%", NetConfig::hostname()); } if (!sendMSG(ESP_NOTIFICATION_TITLE, msgtpl.c_str())) { - log_esp3d_e("Auto notification failed"); + esp3d_log_e("Auto notification failed"); return false; } else { - log_esp3d("Auto notification sent"); + esp3d_log("Auto notification sent"); return true; } } @@ -172,6 +177,8 @@ const char* NotificationsService::getTypeString() { return "telegram"; case ESP_IFTTT_NOTIFICATION: return "IFTTT"; + case ESP_HOMEASSISTANT_NOTIFICATION: + return "HomeAssistant"; default: break; } @@ -180,20 +187,21 @@ const char* NotificationsService::getTypeString() { bool NotificationsService::sendMSG(const char* title, const char* message) { if (!_started) { - log_esp3d_e("Error notification not started"); + esp3d_log_e("Error notification not started"); return false; } if (!((strlen(title) == 0) && (strlen(message) == 0))) { - // push to webui by default -#if defined(HTTP_FEATURE) || defined(WS_DATA_FEATURE) - String msg = "NOTIFICATION:"; - - msg += message; - websocket_terminal_server.pushMSG(msg.c_str()); -#endif // HTTP_FEATURE || WS_DATA_FEATURE -#ifdef DISPLAY_DEVICE - esp3d_display.setStatus(message); -#endif // DISPLAY_DEVICE + if (_notificationType != ESP_HOMEASSISTANT_NOTIFICATION) { + // push to webui by default + #if defined(HTTP_FEATURE) || defined(WS_DATA_FEATURE) + String msg = "NOTIFICATION:"; + msg += message; + websocket_terminal_server.pushMSG(msg.c_str()); + #endif // HTTP_FEATURE || WS_DATA_FEATURE + #ifdef DISPLAY_DEVICE + esp3d_display.setStatus(message); + #endif // DISPLAY_DEVICE + } switch (_notificationType) { case ESP_PUSHOVER_NOTIFICATION: return sendPushoverMSG(title, message); @@ -210,6 +218,9 @@ bool NotificationsService::sendMSG(const char* title, const char* message) { case ESP_IFTTT_NOTIFICATION: return sendIFTTTMSG(title, message); break; + case ESP_HOMEASSISTANT_NOTIFICATION: + return sendHomeAssistantMSG(title, message); + break; default: break; } @@ -233,7 +244,7 @@ bool NotificationsService::sendPushoverMSG(const char* title, BearSSLSetup(Notificationclient); #endif // ARDUINO_ARCH_ESP8266 if (!Notificationclient.connect(_serveraddress.c_str(), _port)) { - log_esp3d_e("Error connecting server %s:%d", _serveraddress.c_str(), + esp3d_log_e("Error connecting server %s:%d", _serveraddress.c_str(), _port); return false; } @@ -257,7 +268,7 @@ bool NotificationsService::sendPushoverMSG(const char* title, postcmd += data.length(); postcmd += "\r\n\r\n"; postcmd += data; - log_esp3d("Query: %s", postcmd.c_str()); + esp3d_log("Query: %s", postcmd.c_str()); // send query Notificationclient.print(postcmd); res = Wait4Answer(Notificationclient, "{", "\"status\":1", PUSHOVERTIMEOUT); @@ -281,7 +292,7 @@ bool NotificationsService::sendTelegramMSG(const char* title, BearSSLSetup(Notificationclient); #endif // ARDUINO_ARCH_ESP8266 if (!Notificationclient.connect(_serveraddress.c_str(), _port)) { - log_esp3d("Error connecting server %s:%d", _serveraddress.c_str(), _port); + esp3d_log("Error connecting server %s:%d", _serveraddress.c_str(), _port); return false; } (void)title; @@ -304,7 +315,7 @@ bool NotificationsService::sendTelegramMSG(const char* title, postcmd += data.length(); postcmd += "\r\n\r\n"; postcmd += data; - log_esp3d("Query: %s", postcmd.c_str()); + esp3d_log("Query: %s", postcmd.c_str()); // send query Notificationclient.print(postcmd); res = Wait4Answer(Notificationclient, "{", "\"ok\":true", TELEGRAMTIMEOUT); @@ -323,85 +334,85 @@ bool NotificationsService::sendEmailMSG(const char* title, #if defined(ARDUINO_ARCH_ESP8266) BearSSLSetup(Notificationclient); #endif // ARDUINO_ARCH_ESP8266 - log_esp3d("Connect to server"); + esp3d_log("Connect to server"); if (!Notificationclient.connect(_serveraddress.c_str(), _port)) { - log_esp3d_e("Error connecting server %s:%d", _serveraddress.c_str(), + esp3d_log_e("Error connecting server %s:%d", _serveraddress.c_str(), _port); return false; } // Check answer of connection if (!Wait4Answer(Notificationclient, "220", "220", EMAILTIMEOUT)) { - log_esp3d_e("Connection failed!"); + esp3d_log_e("Connection failed!"); return false; } // Do HELO - log_esp3d("HELO"); + esp3d_log("HELO"); Notificationclient.print("HELO friend\r\n"); if (!Wait4Answer(Notificationclient, "250", "250", EMAILTIMEOUT)) { - log_esp3d_e("HELO failed!"); + esp3d_log_e("HELO failed!"); return false; } - log_esp3d("AUTH LOGIN"); + esp3d_log("AUTH LOGIN"); // Request AUthentication Notificationclient.print("AUTH LOGIN\r\n"); if (!Wait4Answer(Notificationclient, "334", "334", EMAILTIMEOUT)) { - log_esp3d("AUTH LOGIN failed!"); + esp3d_log("AUTH LOGIN failed!"); return false; } - log_esp3d("Send LOGIN"); + esp3d_log("Send LOGIN"); // sent Login Notificationclient.printf("%s\r\n", _token1.c_str()); if (!Wait4Answer(Notificationclient, "334", "334", EMAILTIMEOUT)) { - log_esp3d_e("Sent login failed!"); + esp3d_log_e("Sent login failed!"); return false; } - log_esp3d("Send PASSWORD"); + esp3d_log("Send PASSWORD"); // Send password Notificationclient.printf("%s\r\n", _token2.c_str()); if (!Wait4Answer(Notificationclient, "235", "235", EMAILTIMEOUT)) { - log_esp3d_e("Sent password failed!"); + esp3d_log_e("Sent password failed!"); return false; } - log_esp3d("MAIL FROM"); + esp3d_log("MAIL FROM"); // Send From Notificationclient.printf("MAIL FROM: <%s>\r\n", _settings.c_str()); if (!Wait4Answer(Notificationclient, "250", "250", EMAILTIMEOUT)) { - log_esp3d_e("MAIL FROM failed!"); + esp3d_log_e("MAIL FROM failed!"); return false; } - log_esp3d("RCPT TO"); + esp3d_log("RCPT TO"); // Send To Notificationclient.printf("RCPT TO: <%s>\r\n", _settings.c_str()); if (!Wait4Answer(Notificationclient, "250", "250", EMAILTIMEOUT)) { - log_esp3d_e("RCPT TO failed!"); + esp3d_log_e("RCPT TO failed!"); return false; } - log_esp3d("DATA"); + esp3d_log("DATA"); // Send Data Notificationclient.print("DATA\r\n"); if (!Wait4Answer(Notificationclient, "354", "354", EMAILTIMEOUT)) { - log_esp3d_e("Preparing DATA failed!"); + esp3d_log_e("Preparing DATA failed!"); return false; } - log_esp3d("Send message"); + esp3d_log("Send message"); // Send message Notificationclient.printf("From:ESP3D<%s>\r\n", _settings.c_str()); Notificationclient.printf("To: <%s>\r\n", _settings.c_str()); Notificationclient.printf("Subject: %s\r\n\r\n", title); Notificationclient.println(message); - log_esp3d("Send final dot"); + esp3d_log("Send final dot"); // Send Final dot Notificationclient.print(".\r\n"); if (!Wait4Answer(Notificationclient, "250", "250", EMAILTIMEOUT)) { - log_esp3d_e("Sending final dot failed!"); + esp3d_log_e("Sending final dot failed!"); return false; } - log_esp3d("QUIT"); + esp3d_log("QUIT"); // Quit Notificationclient.print("QUIT\r\n"); if (!Wait4Answer(Notificationclient, "221", "221", EMAILTIMEOUT)) { - log_esp3d_e("QUIT failed!"); + esp3d_log_e("QUIT failed!"); return false; } @@ -422,7 +433,7 @@ bool NotificationsService::sendLineMSG(const char* title, const char* message) { #endif // ARDUINO_ARCH_ESP8266 (void)title; if (!Notificationclient.connect(_serveraddress.c_str(), _port)) { - log_esp3d_e("Error connecting server %s:%d", _serveraddress.c_str(), + esp3d_log_e("Error connecting server %s:%d", _serveraddress.c_str(), _port); return false; } @@ -441,7 +452,7 @@ bool NotificationsService::sendLineMSG(const char* title, const char* message) { postcmd += data.length(); postcmd += "\r\n\r\n"; postcmd += data; - log_esp3d("Query: %s", postcmd.c_str()); + esp3d_log("Query: %s", postcmd.c_str()); // send query Notificationclient.print(postcmd); res = Wait4Answer(Notificationclient, "{", "\"status\":200", LINETIMEOUT); @@ -465,7 +476,7 @@ bool NotificationsService::sendIFTTTMSG(const char* title, #endif // ARDUINO_ARCH_ESP8266 (void)title; if (!Notificationclient.connect(_serveraddress.c_str(), _port)) { - log_esp3d_e("Error connecting server %s:%d", _serveraddress.c_str(), + esp3d_log_e("Error connecting server %s:%d", _serveraddress.c_str(), _port); return false; } @@ -490,7 +501,7 @@ bool NotificationsService::sendIFTTTMSG(const char* title, postcmd += "\r\n\r\n"; postcmd += data; - // log_esp3d("Query: %s", postcmd.c_str()); + // esp3d_log("Query: %s", postcmd.c_str()); // send query Notificationclient.print(postcmd); res = Wait4Answer(Notificationclient, "Congratulations", "Congratulations", @@ -499,44 +510,73 @@ bool NotificationsService::sendIFTTTMSG(const char* title, return res; } -// Email#serveraddress:port +// Home Assistant +bool NotificationsService::sendHomeAssistantMSG(const char* title, + const char* message) { + WiFiClient Notificationclient; + (void)title; + if (!Notificationclient.connect(_serveraddress.c_str(), _port)) { + esp3d_log_e("Error connecting server %s:%d", _serveraddress.c_str(), + _port); + return false; + } + String tmp = message; + int pos = tmp.indexOf('#'); + if (pos == -1) return false; + String path = tmp.substring(0, pos); + String json = tmp.substring(pos + 1); + // build post query + String postcmd = "POST " + path + " HTTP/1.1\r\n" + "Host: " + _serveraddress.c_str() + "\r\n" + "Connection: close\r\n" + "Cache-Control: no-cache\r\n" + "User-Agent: ESP3D\r\n" + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n" + "Authorization: Bearer " + _token1 + "\r\n" + "Content-Type: application/json\r\n" + "Content-Length: " + json.length() + "\r\n" + "\r\n" + json; + + // esp3d_log("Query: %s", postcmd.c_str()); + // send query + Notificationclient.print(postcmd); + bool res = Wait4Answer(Notificationclient, "200 OK", "200 OK", HOMEASSISTANTTIMEOUT); + Notificationclient.stop(); + return res; +} + +// Email#serveraddress:port or serveraddress:port bool NotificationsService::getPortFromSettings() { - String tmp = Settings_ESP3D::read_string(ESP_NOTIFICATION_SETTINGS); + String tmp = ESP3DSettings::readString(ESP_NOTIFICATION_SETTINGS); int pos = tmp.lastIndexOf(':'); if (pos == -1) { return false; } _port = tmp.substring(pos + 1).toInt(); - log_esp3d("port : %d", _port); + esp3d_log("port : %d", _port); if (_port > 0) { return true; } else { return false; } } -// Email#serveraddress:port +// Email#serveraddress:port or serveraddress:port bool NotificationsService::getServerAddressFromSettings() { - String tmp = Settings_ESP3D::read_string(ESP_NOTIFICATION_SETTINGS); - int pos1 = tmp.indexOf('#'); + String tmp = ESP3DSettings::readString(ESP_NOTIFICATION_SETTINGS); + int pos1 = tmp.indexOf('#'); // The "#" is optional int pos2 = tmp.lastIndexOf(':'); - if ((pos1 == -1) || (pos2 == -1)) { - return false; - } - - // TODO add a check for valid email ? + if (pos2 == -1) return false; _serveraddress = tmp.substring(pos1 + 1, pos2); - log_esp3d("server : %s", _serveraddress.c_str()); + esp3d_log("server : %s", _serveraddress.c_str()); return true; } // Email#serveraddress:port bool NotificationsService::getEmailFromSettings() { - String tmp = Settings_ESP3D::read_string(ESP_NOTIFICATION_SETTINGS); + String tmp = ESP3DSettings::readString(ESP_NOTIFICATION_SETTINGS); int pos = tmp.indexOf('#'); - if (pos == -1) { - return false; - } + if (pos == -1) return false; _settings = tmp.substring(0, pos); - log_esp3d("email : %s", _settings.c_str()); + esp3d_log("email : %s", _settings.c_str()); // TODO add a check for valid email ? return true; } @@ -544,8 +584,8 @@ bool NotificationsService::getEmailFromSettings() { bool NotificationsService::decode64(const char* encodedURL, char* decodedURL) { size_t out_len = 0; out_len = base64_decode_chars(encodedURL, strlen(encodedURL), decodedURL); - log_esp3d("URLE: %s", encodedURL); - log_esp3d("URLD: %s", decodedURL); + esp3d_log("URLE: %s", encodedURL); + esp3d_log("URLD: %s", decodedURL); return (out_len > 0); } @@ -559,7 +599,7 @@ bool NotificationsService::GET(const char* URL64) { if (decode64(URL64, (char*)decodedurl)) { http.begin(client, (const char*)decodedurl); int httpCode = http.GET(); - log_esp3d("HTTP code: %d", httpCode); + esp3d_log("HTTP code: %d", httpCode); if (httpCode > 0) { if (httpCode == HTTP_CODE_OK) { res = true; @@ -573,41 +613,47 @@ bool NotificationsService::GET(const char* URL64) { bool NotificationsService::begin() { bool res = true; end(); - _notificationType = Settings_ESP3D::read_byte(ESP_NOTIFICATION_TYPE); + _notificationType = ESP3DSettings::readByte(ESP_NOTIFICATION_TYPE); switch (_notificationType) { case 0: // no notification = no error but no start _started = true; return true; case ESP_PUSHOVER_NOTIFICATION: - _token1 = Settings_ESP3D::read_string(ESP_NOTIFICATION_TOKEN1); - _token2 = Settings_ESP3D::read_string(ESP_NOTIFICATION_TOKEN2); + _token1 = ESP3DSettings::readString(ESP_NOTIFICATION_TOKEN1); + _token2 = ESP3DSettings::readString(ESP_NOTIFICATION_TOKEN2); _port = PUSHOVERPORT; _serveraddress = PUSHOVERSERVER; break; case ESP_TELEGRAM_NOTIFICATION: - _token1 = Settings_ESP3D::read_string(ESP_NOTIFICATION_TOKEN1); - _token2 = Settings_ESP3D::read_string(ESP_NOTIFICATION_TOKEN2); + _token1 = ESP3DSettings::readString(ESP_NOTIFICATION_TOKEN1); + _token2 = ESP3DSettings::readString(ESP_NOTIFICATION_TOKEN2); _port = TELEGRAMPORT; _serveraddress = TELEGRAMSERVER; break; case ESP_LINE_NOTIFICATION: - _token1 = Settings_ESP3D::read_string(ESP_NOTIFICATION_TOKEN1); + _token1 = ESP3DSettings::readString(ESP_NOTIFICATION_TOKEN1); _port = LINEPORT; _serveraddress = LINESERVER; break; case ESP_IFTTT_NOTIFICATION: - _token1 = Settings_ESP3D::read_string(ESP_NOTIFICATION_TOKEN1); - _token2 = Settings_ESP3D::read_string(ESP_NOTIFICATION_TOKEN2); + _token1 = ESP3DSettings::readString(ESP_NOTIFICATION_TOKEN1); + _token2 = ESP3DSettings::readString(ESP_NOTIFICATION_TOKEN2); _port = IFTTTPORT; _serveraddress = IFTTTSERVER; break; + case ESP_HOMEASSISTANT_NOTIFICATION: + _token1 = ESP3DSettings::readString(ESP_NOTIFICATION_TOKEN1); + if (!getPortFromSettings() || !getServerAddressFromSettings()) { + return false; + } + break; case ESP_EMAIL_NOTIFICATION: _token1 = - base64::encode(Settings_ESP3D::read_string(ESP_NOTIFICATION_TOKEN1)); + base64::encode(ESP3DSettings::readString(ESP_NOTIFICATION_TOKEN1)); _token2 = - base64::encode(Settings_ESP3D::read_string(ESP_NOTIFICATION_TOKEN2)); - // log_esp3d("%s",Settings_ESP3D::read_string(ESP_NOTIFICATION_TOKEN1)); - // log_esp3d("%s",Settings_ESP3D::read_string(ESP_NOTIFICATION_TOKEN2)); + base64::encode(ESP3DSettings::readString(ESP_NOTIFICATION_TOKEN2)); + // esp3d_log("%s",ESP3DSettings::readString(ESP_NOTIFICATION_TOKEN1)); + // esp3d_log("%s",ESP3DSettings::readString(ESP_NOTIFICATION_TOKEN2)); if (!getEmailFromSettings() || !getPortFromSettings() || !getServerAddressFromSettings()) { return false; @@ -618,7 +664,7 @@ bool NotificationsService::begin() { break; } _autonotification = - (Settings_ESP3D::read_byte(ESP_AUTO_NOTIFICATION) == 0) ? false : true; + (ESP3DSettings::readByte(ESP_AUTO_NOTIFICATION) == 0) ? false : true; if (!res) { end(); } diff --git a/esp3d/src/modules/notifications/notifications_service.h b/esp3d/src/modules/notifications/notifications_service.h index 979a9da3..86bc7d8b 100644 --- a/esp3d/src/modules/notifications/notifications_service.h +++ b/esp3d/src/modules/notifications/notifications_service.h @@ -18,60 +18,53 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - #ifndef _NOTIFICATIONS_SERVICE_H #define _NOTIFICATIONS_SERVICE_H #include +class NotificationsService { + public: + NotificationsService(); + ~NotificationsService(); + bool begin(); + void end(); + void handle(); + bool sendMSG(const char* title, const char* message); + bool GET(const char* URL64); + const char* getTypeString(); + bool started(); + bool isAutonotification() { return _autonotification; }; + void setAutonotification(bool value) { _autonotification = value; }; + bool sendAutoNotification(const char* msg); -class NotificationsService -{ -public: - NotificationsService(); - ~NotificationsService(); - bool begin(); - void end(); - void handle(); - bool sendMSG(const char * title, const char * message); - bool GET(const char * URL64); - const char * getTypeString(); - bool started(); - bool isAutonotification() - { - return _autonotification; - }; - void setAutonotification(bool value) - { - _autonotification = value; - }; - bool sendAutoNotification(const char * msg); -private: - bool _started; - bool _autonotification; - uint8_t _notificationType; - String _token1; - String _token2; - String _settings; - String _serveraddress; - uint16_t _port; + private: + bool _started; + bool _autonotification; + uint8_t _notificationType; + String _token1; + String _token2; + String _settings; + String _serveraddress; + uint16_t _port; #if defined(ARDUINO_ARCH_ESP8266) - void BearSSLSetup(WiFiClientSecure & Notificationclient); -#endif//ARDUINO_ARCH_ESP8266 - bool decode64(const char* encodedURL, char *decodedURL); - bool sendPushoverMSG(const char * title, const char * message); - bool sendEmailMSG(const char * title, const char * message); - bool sendLineMSG(const char * title, const char * message); - bool sendTelegramMSG(const char * title, const char * message); - bool sendIFTTTMSG(const char * title, const char * message); - bool getPortFromSettings(); - bool getServerAddressFromSettings(); - bool getEmailFromSettings(); - bool Wait4Answer(WiFiClientSecure & client, const char * linetrigger, const char * expected_answer, uint32_t timeout); + void BearSSLSetup(WiFiClientSecure& Notificationclient); +#endif // ARDUINO_ARCH_ESP8266 + bool decode64(const char* encodedURL, char* decodedURL); + bool sendPushoverMSG(const char* title, const char* message); + bool sendEmailMSG(const char* title, const char* message); + bool sendLineMSG(const char* title, const char* message); + bool sendTelegramMSG(const char* title, const char* message); + bool sendIFTTTMSG(const char* title, const char* message); + bool sendHomeAssistantMSG(const char* title, const char* message); + bool getPortFromSettings(); + bool getServerAddressFromSettings(); + bool getEmailFromSettings(); + template + bool Wait4Answer(T& client, const char* linetrigger, + const char* expected_answer, uint32_t timeout); }; extern NotificationsService notificationsservice; -#endif //_NOTIFICATIONS_SERVICE_H - +#endif //_NOTIFICATIONS_SERVICE_H diff --git a/esp3d/src/modules/recovery/recovery_service.cpp b/esp3d/src/modules/recovery/recovery_service.cpp index a2308e52..341ba2f3 100644 --- a/esp3d/src/modules/recovery/recovery_service.cpp +++ b/esp3d/src/modules/recovery/recovery_service.cpp @@ -20,86 +20,77 @@ #include "../../include/esp3d_config.h" #if defined(RECOVERY_FEATURE) +#include "../../core/esp3d_commands.h" +#include "../../core/esp3d_settings.h" #include "recovery_service.h" -#include "../../core/settings_esp3d.h" -#include "../../core/esp3doutput.h" + RecoveryService recovery_service; -#if defined(PIN_RESET_FEATURE)&& defined(ESP3D_RESET_PIN) && ESP3D_RESET_PIN !=-1 +#if defined(PIN_RESET_FEATURE) && defined(ESP3D_RESET_PIN) && \ + ESP3D_RESET_PIN != -1 #include "../../core/esp3d.h" -bool interruptswitch =false; +bool interruptswitch = false; +RecoveryService::RecoveryService() { _started = false; } +RecoveryService::~RecoveryService() { end(); } -RecoveryService::RecoveryService() -{ - _started = false; -} -RecoveryService::~RecoveryService() -{ +bool RecoveryService::begin() { + bool res = true; + end(); + +#if defined(PIN_RESET_FEATURE) && defined(ESP3D_RESET_PIN) && \ + ESP3D_RESET_PIN != -1 + pinMode(ESP3D_RESET_PIN, INPUT_PULLUP); + // attach interrupt to pin is conflicting with camera device because it + // already attach interrupt to pin +#endif // PIN_RESET_FEATURE + if (!res) { end(); + } + _started = res; + _servicetimeout = millis(); + return _started; } -bool RecoveryService::begin() -{ - bool res = true; - end(); +void RecoveryService::end() { + if (!_started) { + return; + } + _started = false; +} -#if defined (PIN_RESET_FEATURE) && defined(ESP3D_RESET_PIN) && ESP3D_RESET_PIN !=-1 - pinMode(ESP3D_RESET_PIN, INPUT_PULLUP); - //attach interrupt to pin is conflicting with camera device because it already attach interrupt to pin -#endif //PIN_RESET_FEATURE - if (!res) { - end(); +bool RecoveryService::started() { return _started; } + +void RecoveryService::handle() { + if (_started) { + // Stop service 1000 ms after started to be sure pin can be used for + // something else and avoid unwished reset + if (millis() - _servicetimeout > 5000) { + _started = false; + return; } - _started = res; - _servicetimeout = millis(); - return _started; -} - - -void RecoveryService::end() -{ - if(!_started) { - return; +#if defined(PIN_RESET_FEATURE) && defined(ESP3D_RESET_PIN) && \ + ESP3D_RESET_PIN != -1 + // attach interrupt to pin is conflicting with camera device because it + // already attach interrupt to pin so use digitalread to check pin state + interruptswitch = !digitalRead(ESP3D_RESET_PIN); +#endif // PIN_RESET_FEATURE + if (interruptswitch) { + static uint32_t lastreset = 0; + interruptswitch = false; + if ((millis() - lastreset) > 1000) { + lastreset = millis(); + esp3d_commands.dispatch("Reset requested", ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); + Esp3D::reset(); + ESP3DHal::wait(100); + Esp3D::restart_esp(); + } } - _started = false; +#endif // PIN_RESET_FEATURE + } } - -bool RecoveryService::started() -{ - return _started; -} - -void RecoveryService::handle() -{ - if (_started) { - //Stop service 1000 ms after started to be sure pin can be used for something else - //and avoid unwished reset - if (millis()-_servicetimeout> 5000) { - _started = false; - return; - } -#if defined(PIN_RESET_FEATURE) && defined(ESP3D_RESET_PIN) && ESP3D_RESET_PIN !=-1 - //attach interrupt to pin is conflicting with camera device because it already attach interrupt to pin - //so use digitalread to check pin state - interruptswitch = !digitalRead(ESP3D_RESET_PIN); -#endif //PIN_RESET_FEATURE - if (interruptswitch) { - static uint32_t lastreset = 0; - interruptswitch = false; - if ((millis() - lastreset) > 1000) { - lastreset = millis(); - ESP3DOutput output(ESP_ALL_CLIENTS); - output.printMSG("Reset requested"); - Esp3D::reset(); - output.flush(); - Hal::wait(100); - Esp3D::restart_esp(); - } - } -#endif //PIN_RESET_FEATURE - } -} - -#endif //RECOVERY_FEATURE +#endif // RECOVERY_FEATURE diff --git a/esp3d/src/modules/sensor/analogsensor.cpp b/esp3d/src/modules/sensor/analogsensor.cpp index 48f79a0f..227d4a49 100644 --- a/esp3d/src/modules/sensor/analogsensor.cpp +++ b/esp3d/src/modules/sensor/analogsensor.cpp @@ -20,79 +20,55 @@ #include "../../include/esp3d_config.h" #ifdef SENSOR_DEVICE -#if SENSOR_DEVICE==ANALOG_DEVICE +#if SENSOR_DEVICE == ANALOG_DEVICE +#include "../../core/esp3d_message.h" +#include "../../core/esp3d_settings.h" #include "analogsensor.h" -#include "../../core/settings_esp3d.h" -#include "../../core/esp3doutput.h" -AnalogSensorDevice::AnalogSensorDevice() -{ -} +AnalogSensorDevice::AnalogSensorDevice() {} -AnalogSensorDevice::~AnalogSensorDevice() -{ -} +AnalogSensorDevice::~AnalogSensorDevice() {} -bool AnalogSensorDevice::begin() -{ +bool AnalogSensorDevice::begin() { return true; } +void AnalogSensorDevice::end() {} + +bool AnalogSensorDevice::isModelValid(uint8_t model) { + if (model == ANALOG_DEVICE) { return true; + } + return false; } -void AnalogSensorDevice::end() -{ -} - -bool AnalogSensorDevice::isModelValid(uint8_t model) -{ - if (model == ANALOG_DEVICE) { - return true; - } - return false; -} - -uint8_t AnalogSensorDevice::getIDFromString(const char *s) -{ - if (strcmp(s, "ANALOG")== 0 ) { - return ANALOG_DEVICE; - } else { - return 0; - } -} - -uint8_t AnalogSensorDevice::nbType() -{ - return 1; -} - -uint8_t AnalogSensorDevice::GetModel(uint8_t i) -{ +uint8_t AnalogSensorDevice::getIDFromString(const char *s) { + if (strcmp(s, "ANALOG") == 0) { return ANALOG_DEVICE; + } else { + return 0; + } } -const char *AnalogSensorDevice::GetCurrentModelString() -{ - uint8_t sensortype= Settings_ESP3D::read_byte(ESP_SENSOR_TYPE); - if (sensortype==ANALOG_DEVICE) { - return GetModelString(); - } - return "NONE"; +uint8_t AnalogSensorDevice::nbType() { return 1; } + +uint8_t AnalogSensorDevice::GetModel(uint8_t i) { return ANALOG_DEVICE; } + +const char *AnalogSensorDevice::GetCurrentModelString() { + uint8_t sensortype = ESP3DSettings::readByte(ESP_SENSOR_TYPE); + if (sensortype == ANALOG_DEVICE) { + return GetModelString(); + } + return "NONE"; } -const char * AnalogSensorDevice::GetModelString(uint8_t i) -{ - return "ANALOG"; +const char *AnalogSensorDevice::GetModelString(uint8_t i) { return "ANALOG"; } + +const char *AnalogSensorDevice::GetData() { + static String s; + s = String(SENSOR_CONVERTER(analogRead(ESP3D_SENSOR_PIN))) + "["; + s += SENSOR__UNIT; + s += "]"; + return s.c_str(); } -const char * AnalogSensorDevice::GetData() -{ - static String s; - s = String(SENSOR_CONVERTER(analogRead(ESP3D_SENSOR_PIN))) + "["; - s += SENSOR__UNIT; - s +="]"; - return s.c_str(); -} - - -#endif //ANALOG_DEVICE -#endif //SENSOR_DEVICE +#endif // ANALOG_DEVICE +#endif // SENSOR_DEVICE diff --git a/esp3d/src/modules/sensor/bmx280.cpp b/esp3d/src/modules/sensor/bmx280.cpp index 3ea47cf2..01a0ac52 100644 --- a/esp3d/src/modules/sensor/bmx280.cpp +++ b/esp3d/src/modules/sensor/bmx280.cpp @@ -24,11 +24,10 @@ #include #include -#include "../../core/esp3doutput.h" -#include "../../core/settings_esp3d.h" +#include "../../core/esp3d_message.h" +#include "../../core/esp3d_settings.h" #include "bmx280.h" - #define NB_TYPE_SENSOR 2 const char *SENSOR_NAME[NB_TYPE_SENSOR] = {"BMP280", "BME280"}; const uint8_t SENSOR_ID[NB_TYPE_SENSOR] = {BMP280_DEVICE, BME280_DEVICE}; @@ -40,25 +39,25 @@ BMX280SensorDevice::~BMX280SensorDevice() { end(); } bool BMX280SensorDevice::begin() { end(); - uint8_t sensortype = Settings_ESP3D::read_byte(ESP_SENSOR_TYPE); + uint8_t sensortype = ESP3DSettings::readByte(ESP_SENSOR_TYPE); if (sensortype == 0) { - log_esp3d("No Sensor active"); + esp3d_log("No Sensor active"); return true; } if (!isModelValid(sensortype)) { - log_esp3d_e("No valid id "); + esp3d_log_e("No valid id "); return false; } // Setup Wire pins first as lib does setup wire Wire.begin(ESP_SDA_PIN, ESP_SCL_PIN); - log_esp3d("Starting wire SDA:%d SCL:%d", ESP_SDA_PIN, ESP_SCL_PIN); + esp3d_log("Starting wire SDA:%d SCL:%d", ESP_SDA_PIN, ESP_SCL_PIN); bmx280_device = new BMx280I2C(SENSOR_ADDR); if (!bmx280_device) { - log_esp3d_e("Cannot instanciate sensor"); + esp3d_log_e("Cannot instanciate sensor"); return false; } if (!bmx280_device->begin()) { - log_esp3d("No valid sensor status"); + esp3d_log("No valid sensor status"); return false; } // reset sensor to default parameters. @@ -96,9 +95,9 @@ bool BMX280SensorDevice::isModelValid(uint8_t model) { uint8_t BMX280SensorDevice::getIDFromString(const char *s) { for (uint8_t i = 0; i < NB_TYPE_SENSOR; i++) { - log_esp3d("checking %s with %s", s, SENSOR_NAME[i]); + esp3d_log("checking %s with %s", s, SENSOR_NAME[i]); if (strcmp(s, SENSOR_NAME[i]) == 0) { - log_esp3d("found %d", SENSOR_ID[i]); + esp3d_log("found %d", SENSOR_ID[i]); return SENSOR_ID[i]; } } @@ -116,7 +115,7 @@ uint8_t BMX280SensorDevice::GetModel(uint8_t i) { } const char *BMX280SensorDevice::GetCurrentModelString() { - uint8_t sensortype = Settings_ESP3D::read_byte(ESP_SENSOR_TYPE); + uint8_t sensortype = ESP3DSettings::readByte(ESP_SENSOR_TYPE); for (uint8_t i = 0; i < NB_TYPE_SENSOR; i++) { if ((sensortype == SENSOR_TYPE[i]) { return SENSOR_NAME[i]; @@ -140,12 +139,12 @@ const char *BMX280SensorDevice::GetData() { if (bmx280_device) { if (!bmx280_device->measure()) { s = "BUSY"; - log_esp3d("sensor is busy"); + esp3d_log("sensor is busy"); } else { uint8_t nbtry = 0; do { - log_esp3d("try sensor %d", nbtry); - Hal::wait(100); + esp3d_log("try sensor %d", nbtry); + ESP3DHal::wait(100); nbtry++; } while (!bmx280_device->hasValue() && nbtry < 3); if (bmx280_device->hasValue()) { @@ -155,7 +154,7 @@ const char *BMX280SensorDevice::GetData() { if (bmx280_device->isBME280()) { humidity = bmx280_device->getHumidity(); } - log_esp3d("T %f P %f H %f", temperature, pressure, humidity); + esp3d_log("T %f P %f H %f", temperature, pressure, humidity); if (String(temperature, 1) != "nan") { if (strcmp(SENSOR__UNIT, "F") == 0) { temperature = toFahrenheit(temperature); @@ -170,7 +169,7 @@ const char *BMX280SensorDevice::GetData() { } } else { s = "DISCONNECTED"; - log_esp3d_e("No valid data"); + esp3d_log_e("No valid data"); } } else { s = "DISCONNECTED"; @@ -179,7 +178,7 @@ const char *BMX280SensorDevice::GetData() { } } else { s = "DISCONNECTED"; - log_esp3d_e("No device"); + esp3d_log_e("No device"); } return s.c_str(); } diff --git a/esp3d/src/modules/sensor/dht.cpp b/esp3d/src/modules/sensor/dht.cpp index 2d0e8db4..117d7970 100644 --- a/esp3d/src/modules/sensor/dht.cpp +++ b/esp3d/src/modules/sensor/dht.cpp @@ -23,8 +23,8 @@ #if SENSOR_DEVICE == DHT11_DEVICE || SENSOR_DEVICE == DHT22_DEVICE #include -#include "../../core/esp3doutput.h" -#include "../../core/settings_esp3d.h" +#include "../../core/esp3d_message.h" +#include "../../core/esp3d_settings.h" #include "dht.h" #define NB_TYPE_SENSOR 2 @@ -40,33 +40,33 @@ DHTSensorDevice::~DHTSensorDevice() { end(); } bool DHTSensorDevice::begin() { end(); - uint8_t dhttype = Settings_ESP3D::read_byte(ESP_SENSOR_TYPE); - log_esp3d("Read %d, %s", dhttype, + uint8_t dhttype = ESP3DSettings::readByte(ESP_SENSOR_TYPE); + esp3d_log("Read %d, %s", dhttype, dhttype == 1 ? "DHT11" : dhttype == 2 ? "DHT22" : dhttype == 0 ? "NONE" : "Unknow type"); if (dhttype == 0) { - log_esp3d("No Sensor active"); + esp3d_log("No Sensor active"); return true; } if (!isModelValid(dhttype)) { - log_esp3d_e("No valid id "); + esp3d_log_e("No valid id "); return false; } dht_device = new DHTesp; if (!dht_device) { - log_esp3d_e("Cannot instanciate dht"); + esp3d_log_e("Cannot instanciate dht"); return false; } - log_esp3d("DHT PIN %d", ESP3D_SENSOR_PIN); + esp3d_log("DHT PIN %d", ESP3D_SENSOR_PIN); dht_device->setup(ESP3D_SENSOR_PIN, (DHTesp::DHT_MODEL_t)dhttype); if (strcmp(dht_device->getStatusString(), "OK") != 0) { - log_esp3d_e("No valid dht status: %d, %s", dht_device->getStatus(), + esp3d_log_e("No valid dht status: %d, %s", dht_device->getStatus(), dht_device->getStatusString()); return false; } - log_esp3d("DHT ok"); + esp3d_log("DHT ok"); return true; } @@ -88,9 +88,9 @@ bool DHTSensorDevice::isModelValid(uint8_t model) { uint8_t DHTSensorDevice::getIDFromString(const char *s) { for (uint8_t i = 0; i < NB_TYPE_SENSOR; i++) { - log_esp3d("checking %s with %s", s, SENSOR_NAME[i]); + esp3d_log("checking %s with %s", s, SENSOR_NAME[i]); if (strcmp(s, SENSOR_NAME[i]) == 0) { - log_esp3d("found %d", SENSOR_ID[i]); + esp3d_log("found %d", SENSOR_ID[i]); return SENSOR_ID[i]; } } @@ -108,7 +108,7 @@ uint8_t DHTSensorDevice::GetModel(uint8_t i) { } const char *DHTSensorDevice::GetCurrentModelString() { - uint8_t dhttype = Settings_ESP3D::read_byte(ESP_SENSOR_TYPE); + uint8_t dhttype = ESP3DSettings::readByte(ESP_SENSOR_TYPE); for (uint8_t i = 0; i < NB_TYPE_SENSOR; i++) { if ((DHTesp::DHT_MODEL_t)dhttype == SENSOR_TYPE[i]) { return SENSOR_NAME[i]; @@ -129,7 +129,7 @@ const char *DHTSensorDevice::GetData() { if (dht_device) { float temperature = dht_device->getTemperature(); float humidity = dht_device->getHumidity(); - log_esp3d("T %f H %f", temperature, humidity); + esp3d_log("T %f H %f", temperature, humidity); if (strcmp(SENSOR__UNIT, "F") == 0) { temperature = dht_device->toFahrenheit(temperature); } @@ -140,11 +140,11 @@ const char *DHTSensorDevice::GetData() { s += "] " + String(humidity, 1) + "[%]"; } else { s = "DISCONNECTED"; - log_esp3d_e("No valid data"); + esp3d_log_e("No valid data"); } } else { s = "DISCONNECTED"; - log_esp3d_e("No device"); + esp3d_log_e("No device"); } return s.c_str(); } diff --git a/esp3d/src/modules/sensor/sensor.cpp b/esp3d/src/modules/sensor/sensor.cpp index 4e14bc1a..bc29927a 100644 --- a/esp3d/src/modules/sensor/sensor.cpp +++ b/esp3d/src/modules/sensor/sensor.cpp @@ -20,8 +20,8 @@ #include "../../include/esp3d_config.h" #ifdef SENSOR_DEVICE -#include "../../core/esp3doutput.h" -#include "../../core/settings_esp3d.h" +#include "../../core/esp3d_commands.h" +#include "../../core/esp3d_settings.h" #include "sensor.h" // Include file according sensor @@ -35,10 +35,6 @@ #include "bmx280.h" #endif // BMP280_DEVICE || BME280_DEVICE -#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) -#include "../websocket/websocket_server.h" -#endif // WIFI_FEATURE || ETH_FEATURE - ESP3DSensor esp3d_sensor; ESP3DSensor::ESP3DSensor() { @@ -50,7 +46,7 @@ ESP3DSensor::ESP3DSensor() { ESP3DSensor::~ESP3DSensor() { end(); } bool ESP3DSensor::begin() { - log_esp3d("Sensor Begin"); + esp3d_log("Sensor Begin"); bool res = true; end(); // new _device @@ -64,18 +60,18 @@ bool ESP3DSensor::begin() { _device = (ESP3DSensorDevice*)new BMX280SensorDevice(); #endif // DHT11_DEVICE || DHT22_DEVICE if (!_device) { - log_esp3d_e("No device created"); + esp3d_log_e("No device created"); return false; } - log_esp3d("Sensor Device created"); - uint8_t sensortype = Settings_ESP3D::read_byte(ESP_SENSOR_TYPE); - log_esp3d("Sensor %d", sensortype); + esp3d_log("Sensor Device created"); + uint8_t sensortype = ESP3DSettings::readByte(ESP_SENSOR_TYPE); + esp3d_log("Sensor %d", sensortype); // No Sensor defined - exit is not an error if (sensortype == 0) { - log_esp3d("Sensor Device is not active at start"); + esp3d_log("Sensor Device is not active at start"); return true; } - _interval = Settings_ESP3D::read_uint32(ESP_SENSOR_INTERVAL); + _interval = ESP3DSettings::readUint32(ESP_SENSOR_INTERVAL); if (!_device->begin()) { res = false; } @@ -158,7 +154,9 @@ void ESP3DSensor::handle() { _lastReadTime = millis(); #if defined(WIFI_FEATURE) || defined(ETH_FEATURE) String s = "SENSOR:" + data; - websocket_terminal_server.pushMSG(s.c_str()); + esp3d_commands.dispatch(s.c_str(), ESP3DClientType::webui_websocket, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system); #endif // WIFI_FEATURE || ETH_FEATURE } } diff --git a/esp3d/src/modules/serial/serial_service.cpp b/esp3d/src/modules/serial/serial_service.cpp index 194c8efb..eef6c51b 100644 --- a/esp3d/src/modules/serial/serial_service.cpp +++ b/esp3d/src/modules/serial/serial_service.cpp @@ -1,5 +1,5 @@ /* - serial_service.cpp - serial services functions class + esp3d_serial_service.cpp - serial services functions class Copyright (c) 2014 Luc Lebosse. All rights reserved. @@ -21,9 +21,8 @@ #include "../../include/esp3d_config.h" #if COMMUNICATION_PROTOCOL == MKS_SERIAL || \ COMMUNICATION_PROTOCOL == RAW_SERIAL || defined(ESP_SERIAL_BRIDGE_OUTPUT) -#include "../../core/commands.h" -#include "../../core/esp3doutput.h" -#include "../../core/settings_esp3d.h" +#include "../../core/esp3d_commands.h" +#include "../../core/esp3d_settings.h" #include "serial_service.h" #if COMMUNICATION_PROTOCOL == MKS_SERIAL @@ -54,83 +53,101 @@ HardwareSerial *Serials[MAX_SERIAL] = {&Serial, &Serial1, &Serial2}; #define ESP3DSERIAL_RUNNING_CORE 1 #define SERIAL_YIELD 10 -SerialService serial_service = SerialService(MAIN_SERIAL); +ESP3DSerialService esp3d_serial_service = ESP3DSerialService(MAIN_SERIAL); #if defined(ESP_SERIAL_BRIDGE_OUTPUT) -SerialService serial_bridge_service = SerialService(BRIDGE_SERIAL); +ESP3DSerialService serial_bridge_service = ESP3DSerialService(BRIDGE_SERIAL); #endif // ESP_SERIAL_BRIDGE_OUTPUT #if defined(ARDUINO_ARCH_ESP32) && defined(SERIAL_INDEPENDANT_TASK) TaskHandle_t _hserialtask = nullptr; #endif // ARDUINO_ARCH_ESP32 -const long SupportedBaudList[] = {9600, 19200, 38400, 57600, - 74880, 115200, 230400, 250000, - 500000, 921600, 1958400}; +const uint32_t SupportedBaudList[] = {9600, 19200, 38400, 57600, + 74880, 115200, 230400, 250000, + 500000, 921600, 1958400}; const size_t SupportedBaudListSize = sizeof(SupportedBaudList) / sizeof(long); #define TIMEOUT_SERIAL_FLUSH 1500 // Constructor -SerialService::SerialService(uint8_t id) { +ESP3DSerialService::ESP3DSerialService(uint8_t id) { _buffer_size = 0; _started = false; +#if defined(AUTHENTICATION_FEATURE) _needauthentication = true; +#else + _needauthentication = false; +#endif // AUTHENTICATION_FEATURE _id = id; switch (_id) { case MAIN_SERIAL: _rxPin = ESP_RX_PIN; _txPin = ESP_TX_PIN; - _client = ESP_SERIAL_CLIENT; + _origin = ESP3DClientType::serial; break; #if defined(ESP_SERIAL_BRIDGE_OUTPUT) case BRIDGE_SERIAL: _rxPin = ESP_BRIDGE_RX_PIN; _txPin = ESP_BRIDGE_TX_PIN; - _client = ESP_SERIAL_BRIDGE_CLIENT; + _origin = ESP3DClientType::serial_bridge; break; #endif // ESP_SERIAL_BRIDGE_OUTPUT default: _rxPin = ESP_RX_PIN; _txPin = ESP_TX_PIN; - _client = ESP_SERIAL_CLIENT; + _origin = ESP3DClientType::serial; break; } } // Destructor -SerialService::~SerialService() { end(); } +ESP3DSerialService::~ESP3DSerialService() { end(); } // dedicated serial task #if defined(ARDUINO_ARCH_ESP32) && defined(SERIAL_INDEPENDANT_TASK) void ESP3DSerialTaskfn(void *parameter) { for (;;) { - serial_service.process(); - Hal::wait(SERIAL_YIELD); // Yield to other tasks + esp3d_serial_service.process(); + ESP3DHal::wait(SERIAL_YIELD); // Yield to other tasks } vTaskDelete(NULL); } #endif // ARDUINO_ARCH_ESP32 // extra parameters that do not need a begin -void SerialService::setParameters() { +void ESP3DSerialService::setParameters() { #if defined(AUTHENTICATION_FEATURE) _needauthentication = - (Settings_ESP3D::read_byte(ESP_SECURE_SERIAL) == 0) ? false : true; + (ESP3DSettings::readByte(ESP_SECURE_SERIAL) == 0) ? false : true; #else _needauthentication = false; #endif // AUTHENTICATION_FEATURE } +void ESP3DSerialService::initAuthentication() { +#if defined(AUTHENTICATION_FEATURE) + _auth = ESP3DAuthenticationLevel::guest; +#else + _auth = ESP3DAuthenticationLevel::admin; +#endif // AUTHENTICATION_FEATURE +} +ESP3DAuthenticationLevel ESP3DSerialService::getAuthentication() { + if (_needauthentication) { + return _auth; + } + return ESP3DAuthenticationLevel::admin; +} + // Setup Serial -bool SerialService::begin(uint8_t serialIndex) { +bool ESP3DSerialService::begin(uint8_t serialIndex) { _serialIndex = serialIndex - 1; - log_esp3d("Serial %d begin for %d", _serialIndex, _id); + esp3d_log("Serial %d begin for %d", _serialIndex, _id); if (_id == BRIDGE_SERIAL && - Settings_ESP3D::read_byte(ESP_SERIAL_BRIDGE_ON) == 0) { - log_esp3d("Serial %d for %d is disabled", _serialIndex, _id); + ESP3DSettings::readByte(ESP_SERIAL_BRIDGE_ON) == 0) { + esp3d_log("Serial %d for %d is disabled", _serialIndex, _id); return true; } if (_serialIndex >= MAX_SERIAL) { - log_esp3d_e("Serial %d begin for %d failed, index out of range", + esp3d_log_e("Serial %d begin for %d failed, index out of range", _serialIndex, _id); return false; } @@ -140,27 +157,27 @@ bool SerialService::begin(uint8_t serialIndex) { long defaultBr = 0; switch (_id) { case MAIN_SERIAL: - br = Settings_ESP3D::read_uint32(ESP_BAUD_RATE); - defaultBr = Settings_ESP3D::getDefaultIntegerSetting(ESP_BAUD_RATE); + br = ESP3DSettings::readUint32(ESP_BAUD_RATE); + defaultBr = ESP3DSettings::getDefaultIntegerSetting(ESP_BAUD_RATE); break; #if defined(ESP_SERIAL_BRIDGE_OUTPUT) case BRIDGE_SERIAL: - br = Settings_ESP3D::read_uint32(ESP_SERIAL_BRIDGE_BAUD); + br = ESP3DSettings::readUint32(ESP_SERIAL_BRIDGE_BAUD); defaultBr = - Settings_ESP3D::getDefaultIntegerSetting(ESP_SERIAL_BRIDGE_BAUD); + ESP3DSettings::getDefaultIntegerSetting(ESP_SERIAL_BRIDGE_BAUD); break; #endif // ESP_SERIAL_BRIDGE_OUTPUT default: - log_esp3d_e("Serial %d begin for %d failed, unknown id", _serialIndex, + esp3d_log_e("Serial %d begin for %d failed, unknown id", _serialIndex, _id); return false; } setParameters(); - log_esp3d("Baud rate is %d , default is %d", br, defaultBr); + esp3d_log("Baud rate is %d , default is %d", br, defaultBr); _buffer_size = 0; // change only if different from current if (br != baudRate() || (_rxPin != -1) || (_txPin != -1)) { - if (!Settings_ESP3D::isValidIntegerSetting(br, ESP_BAUD_RATE)) { + if (!ESP3DSettings::isValidIntegerSetting(br, ESP_BAUD_RATE)) { br = defaultBr; } Serials[_serialIndex]->setRxBufferSize(SERIAL_RX_BUFFER_SIZE); @@ -176,7 +193,7 @@ bool SerialService::begin(uint8_t serialIndex) { Serials[_serialIndex]->begin(br, ESP_SERIAL_PARAM, ESP_RX_PIN, ESP_TX_PIN); #if defined(SERIAL_INDEPENDANT_TASK) // create serial task once - log_esp3d("Serial %d for %d Task creation", _serialIndex, _id); + esp3d_log("Serial %d for %d Task creation", _serialIndex, _id); if (_hserialtask == nullptr && _id == MAIN_SERIAL) { xTaskCreatePinnedToCore( ESP3DSerialTaskfn, /* Task function. */ @@ -189,29 +206,30 @@ bool SerialService::begin(uint8_t serialIndex) { ); } if (_hserialtask == nullptr) { - log_esp3d_e("Serial %d for %d Task creation failed", _serialIndex, _id); + esp3d_log_e("Serial %d for %d Task creation failed", _serialIndex, _id); return false; } #endif // SERIAL_INDEPENDANT_TASK #endif // ARDUINO_ARCH_ESP32 } _started = true; - log_esp3d("Serial %d for %d is started", _serialIndex, _id); + esp3d_log("Serial %d for %d is started", _serialIndex, _id); return true; } // End serial -bool SerialService::end() { +bool ESP3DSerialService::end() { flush(); delay(100); swap(); Serials[_serialIndex]->end(); _buffer_size = 0; _started = false; + initAuthentication(); return true; } -// return the array of long and array size -const long *SerialService::get_baudratelist(uint8_t *count) { +// return the array of uint32_t and array size +const uint32_t *ESP3DSerialService::get_baudratelist(uint8_t *count) { if (count) { *count = sizeof(SupportedBaudList) / sizeof(long); } @@ -219,15 +237,15 @@ const long *SerialService::get_baudratelist(uint8_t *count) { } // Function which could be called in other loop -void SerialService::process() { +void ESP3DSerialService::process() { if (!_started) { return; } // Do we have some data waiting - size_t len = available(); + size_t len = Serials[_serialIndex]->available(); if (len > 0) { // if yes read them - log_esp3d("Got %d chars in serial", len); + esp3d_log("Got %d chars in serial", len); uint8_t *sbuf = (uint8_t *)malloc(len); if (sbuf) { size_t count = readBytes(sbuf, len); @@ -247,7 +265,7 @@ void SerialService::process() { } // Function which could be called in other loop -void SerialService::handle() { +void ESP3DSerialService::handle() { // the serial bridge do not use independant task // not sure if it is sill necessary to do it for the main serial // TBC.. @@ -259,24 +277,32 @@ void SerialService::handle() { process(); } -void SerialService::flushbuffer() { - ESP3DOutput output(_client); +void ESP3DSerialService::flushbuffer() { _buffer[_buffer_size] = 0x0; + // dispatch command if (_started) { - esp3d_commands.process(_buffer, _buffer_size, &output, - _needauthentication ? LEVEL_GUEST : LEVEL_ADMIN); + ESP3DMessage *message = ESP3DMessageManager::newMsg( + _origin, ESP3DClientType::all_clients, (uint8_t *)_buffer, _buffer_size, + getAuthentication()); + if (message) { + // process command + message->type = ESP3DMessageType::unique; + esp3d_commands.process(message); + } else { + esp3d_log_e("Cannot create message"); + } } _lastflush = millis(); _buffer_size = 0; } // push collected data to buffer and proceed accordingly -void SerialService::push2buffer(uint8_t *sbuf, size_t len) { +void ESP3DSerialService::push2buffer(uint8_t *sbuf, size_t len) { if (!_started) { return; } - log_esp3d("buffer get %d data ", len); + esp3d_log("buffer get %d data ", len); #if COMMUNICATION_PROTOCOL == MKS_SERIAL static bool isFrameStarted = false; static bool isCommandFrame = false; @@ -286,25 +312,25 @@ void SerialService::push2buffer(uint8_t *sbuf, size_t len) { // currently received static uint datalen = 0; for (size_t i = 0; i < len; i++) { - log_esp3d("Data : %c %x", sbuf[i], sbuf[i]); + esp3d_log("Data : %c %x", sbuf[i], sbuf[i]); framePos++; _lastflush = millis(); // so frame head was detected if (isFrameStarted) { // checking it is a valid Frame header if (framePos == 1) { - log_esp3d("type = %x", sbuf[i]); + esp3d_log("type = %x", sbuf[i]); if (MKSService::isFrame(char(sbuf[i]))) { if (MKSService::isCommand(char(sbuf[i]))) { isCommandFrame = true; - log_esp3d("type: Command"); + esp3d_log("type: Command"); } else { - log_esp3d("type: other"); + esp3d_log("type: other"); type = sbuf[i]; isCommandFrame = false; } } else { - log_esp3d_e("wrong frame type"); + esp3d_log_e("wrong frame type"); isFrameStarted = false; _buffer_size = 0; } @@ -314,20 +340,20 @@ void SerialService::push2buffer(uint8_t *sbuf, size_t len) { datalen = sbuf[i]; } else { datalen += (sbuf[i] << 8); - log_esp3d("Data len: %d", datalen); + esp3d_log("Data len: %d", datalen); if (datalen > (ESP3D_SERIAL_BUFFER_SIZE - 5)) { - log_esp3d_e("Overflow in data len"); + esp3d_log_e("Overflow in data len"); isFrameStarted = false; _buffer_size = 0; } } } else if (MKSService::isTail(char(sbuf[i]))) { - log_esp3d("got tail"); + esp3d_log("got tail"); _buffer[_buffer_size] = '\0'; - log_esp3d("size is %d", _buffer_size); + esp3d_log("size is %d", _buffer_size); // let check integrity if (_buffer_size == datalen) { - log_esp3d("Flushing buffer"); + esp3d_log("Flushing buffer"); if (isCommandFrame) { flushbuffer(); } else { @@ -335,7 +361,7 @@ void SerialService::push2buffer(uint8_t *sbuf, size_t len) { _buffer_size); } } else { - log_esp3d_e("Error in data len"); + esp3d_log_e("Error in data len"); } // clear frame infos _buffer_size = 0; @@ -347,7 +373,7 @@ void SerialService::push2buffer(uint8_t *sbuf, size_t len) { _buffer[_buffer_size] = sbuf[i]; _buffer_size++; } else { - log_esp3d_e("Overflow in data len"); + esp3d_log_e("Overflow in data len"); isFrameStarted = false; _buffer_size = 0; } @@ -355,7 +381,7 @@ void SerialService::push2buffer(uint8_t *sbuf, size_t len) { } else { // frame is not started let see if it is a head if (MKSService::isHead(char(sbuf[i]))) { - log_esp3d("got head"); + esp3d_log("got head"); // yes it is isFrameStarted = true; framePos = 0; @@ -363,7 +389,7 @@ void SerialService::push2buffer(uint8_t *sbuf, size_t len) { } else { // no so let reset all and just ignore it // TODO should we handle these data ? - log_esp3d_e("Unidentified data : %c %x", sbuf[i], sbuf[i]); + esp3d_log_e("Unidentified data : %c %x", sbuf[i], sbuf[i]); isCommandFrame = false; framePos = -1; datalen = 0; @@ -404,30 +430,30 @@ void SerialService::push2buffer(uint8_t *sbuf, size_t len) { } // Reset Serial Setting (baud rate) -bool SerialService::reset() { - log_esp3d("Reset serial"); +bool ESP3DSerialService::reset() { + esp3d_log("Reset serial"); bool res = false; switch (_id) { case MAIN_SERIAL: - return Settings_ESP3D::write_uint32( + return ESP3DSettings::writeUint32( ESP_BAUD_RATE, - Settings_ESP3D::getDefaultIntegerSetting(ESP_BAUD_RATE)); + ESP3DSettings::getDefaultIntegerSetting(ESP_BAUD_RATE)); #if defined(ESP_SERIAL_BRIDGE_OUTPUT) case BRIDGE_SERIAL: - res = Settings_ESP3D::write_byte( + res = ESP3DSettings::writeByte( ESP_SERIAL_BRIDGE_ON, - Settings_ESP3D::getDefaultByteSetting(ESP_SERIAL_BRIDGE_ON)); - return res && Settings_ESP3D::write_uint32( - ESP_SERIAL_BRIDGE_BAUD, - Settings_ESP3D::getDefaultIntegerSetting( - ESP_SERIAL_BRIDGE_BAUD)); + ESP3DSettings::getDefaultByteSetting(ESP_SERIAL_BRIDGE_ON)); + return res && + ESP3DSettings::writeUint32(ESP_SERIAL_BRIDGE_BAUD, + ESP3DSettings::getDefaultIntegerSetting( + ESP_SERIAL_BRIDGE_BAUD)); #endif // ESP_SERIAL_BRIDGE_OUTPUT default: return res; } } -void SerialService::updateBaudRate(long br) { +void ESP3DSerialService::updateBaudRate(long br) { if (br != baudRate()) { Serials[_serialIndex]->flush(); Serials[_serialIndex]->updateBaudRate(br); @@ -435,7 +461,7 @@ void SerialService::updateBaudRate(long br) { } // Get current baud rate -long SerialService::baudRate() { +long ESP3DSerialService::baudRate() { long br = 0; br = Serials[_serialIndex]->baudRate(); #ifdef ARDUINO_ARCH_ESP32 @@ -450,14 +476,7 @@ long SerialService::baudRate() { return br; } -size_t SerialService::write(uint8_t c) { - if (!_started) { - return 0; - } - return Serials[_serialIndex]->write(c); -} - -size_t SerialService::write(const uint8_t *buffer, size_t size) { +size_t ESP3DSerialService::writeBytes(const uint8_t *buffer, size_t size) { if (!_started) { return 0; } @@ -480,53 +499,58 @@ size_t SerialService::write(const uint8_t *buffer, size_t size) { sizesent += available; starttime = millis(); } else { - Hal::wait(5); + ESP3DHal::wait(5); } } return sizesent; } } -int SerialService::availableForWrite() { - if (!_started) { - return 0; - } - return Serials[_serialIndex]->availableForWrite(); -} - -int SerialService::available() { - if (!_started) { - return 0; - } - return Serials[_serialIndex]->available(); -} - -int SerialService::read() { - if (!_started) { - return -1; - } - return Serials[_serialIndex]->read(); -} - -size_t SerialService::readBytes(uint8_t *sbuf, size_t len) { +size_t ESP3DSerialService::readBytes(uint8_t *sbuf, size_t len) { if (!_started) { return -1; } return Serials[_serialIndex]->readBytes(sbuf, len); } -void SerialService::flush() { +void ESP3DSerialService::flush() { if (!_started) { return; } Serials[_serialIndex]->flush(); } -void SerialService::swap() { +void ESP3DSerialService::swap() { #ifdef ARDUINO_ARCH_ESP8266 Serials[_serialIndex]->swap(); #endif // ARDUINO_ARCH_ESP8266 } +bool ESP3DSerialService::dispatch(ESP3DMessage *message) { + bool done = false; + // Only is serial service is started + if (_started) { + // Only if message is not null + if (message) { + // if message is not null + if (message->data && message->size != 0) { + if (writeBytes(message->data, message->size) == message->size) { + flush(); + // Delete message now + ESP3DMessageManager::deleteMsg(message); + done = true; + } else { + esp3d_log_e("Error while sending data"); + } + } else { + esp3d_log_e("Error null data"); + } + } else { + esp3d_log_e("Error null message"); + } + } + return done; +} + #endif // COMMUNICATION_PROTOCOL == MKS_SERIAL || COMMUNICATION_PROTOCOL == // RAW_SERIAL diff --git a/esp3d/src/modules/serial/serial_service.h b/esp3d/src/modules/serial/serial_service.h index 7361f9f5..10163830 100644 --- a/esp3d/src/modules/serial/serial_service.h +++ b/esp3d/src/modules/serial/serial_service.h @@ -21,17 +21,18 @@ #ifndef _SERIAL_SERVICES_H #define _SERIAL_SERVICES_H -#include "Print.h" +#include "../../core/esp3d_client_types.h" +#include "../../core/esp3d_message.h" #define ESP3D_SERIAL_BUFFER_SIZE 1024 -extern const long SupportedBaudList[]; +extern const uint32_t SupportedBaudList[]; extern const size_t SupportedBaudListSize; -class SerialService : public Print { +class ESP3DSerialService final { public: - SerialService(uint8_t id); - ~SerialService(); + ESP3DSerialService(uint8_t id); + ~ESP3DSerialService(); void setParameters(); bool begin(uint8_t serialIndex); bool end(); @@ -41,25 +42,21 @@ class SerialService : public Print { bool reset(); long baudRate(); uint8_t serialIndex() { return _serialIndex; } - const long *get_baudratelist(uint8_t *count); + const uint32_t *get_baudratelist(uint8_t *count); void flush(); void swap(); - int availableForWrite(); - int available(); - size_t write(uint8_t c); - size_t write(const uint8_t *buffer, size_t size); - inline size_t write(const char *s) { return write((uint8_t *)s, strlen(s)); } - inline size_t write(unsigned long n) { return write((uint8_t)n); } - inline size_t write(long n) { return write((uint8_t)n); } - inline size_t write(unsigned int n) { return write((uint8_t)n); } - inline size_t write(int n) { return write((uint8_t)n); } - int read(); + size_t writeBytes(const uint8_t *buffer, size_t size); size_t readBytes(uint8_t *sbuf, size_t len); inline bool started() { return _started; } + bool dispatch(ESP3DMessage *message); + void initAuthentication(); + void setAuthentication(ESP3DAuthenticationLevel auth) { _auth = auth; } + ESP3DAuthenticationLevel getAuthentication(); private: + ESP3DAuthenticationLevel _auth; uint8_t _serialIndex; - uint8_t _client; + ESP3DClientType _origin; uint8_t _id; int8_t _rxPin; int8_t _txPin; @@ -72,10 +69,10 @@ class SerialService : public Print { void flushbuffer(); }; -extern SerialService serial_service; +extern ESP3DSerialService esp3d_serial_service; #if defined(ESP_SERIAL_BRIDGE_OUTPUT) -extern SerialService serial_bridge_service; +extern ESP3DSerialService serial_bridge_service; #endif // ESP_SERIAL_BRIDGE_OUTPUT #endif //_SERIAL_SERVICES_H diff --git a/esp3d/src/modules/serial2socket/serial2socket.cpp b/esp3d/src/modules/serial2socket/serial2socket.cpp index 81836b6f..0a4eb5e8 100644 --- a/esp3d/src/modules/serial2socket/serial2socket.cpp +++ b/esp3d/src/modules/serial2socket/serial2socket.cpp @@ -23,9 +23,8 @@ #if defined(ESP3DLIB_ENV) && COMMUNICATION_PROTOCOL == SOCKET_SERIAL #include - -#include "../../core/commands.h" -#include "../../core/esp3doutput.h" +#include "../../core/esp3d_message.h" +#include "../../core/esp3d_commands.h" #include "serial2socket.h" Serial_2_Socket Serial2Socket; @@ -56,6 +55,11 @@ void Serial_2_Socket::end() { _started = false; _paused = false; _lastflush = millis(); +#if defined(AUTHENTICATION_FEATURE) + _auth = ESP3DAuthenticationLevel::guest; +#else + _auth = ESP3DAuthenticationLevel::admin; +#endif // AUTHENTICATION_FEATURE } long Serial_2_Socket::baudRate() { return 0; } @@ -80,7 +84,7 @@ size_t Serial_2_Socket::write(uint8_t c) { size_t Serial_2_Socket::write(const uint8_t *buffer, size_t size) { if (buffer == NULL || size == 0 || !_started || _paused) { - log_esp3d("Serial2Socket: no data, not started or paused"); + esp3d_log("Serial2Socket: no data, not started or paused"); return size; } if (_TXbufferSize == 0) { @@ -95,7 +99,7 @@ size_t Serial_2_Socket::write(const uint8_t *buffer, size_t size) { _TXbuffer[_TXbufferSize] = buffer[i]; _TXbufferSize++; if (buffer[i] == (const uint8_t)'\n' || buffer[i] == (const uint8_t)'\r') { - log_esp3d("S2S: %s TXSize: %d", (const char *)_TXbuffer, _TXbufferSize); + esp3d_log("S2S: %s TXSize: %d", (const char *)_TXbuffer, _TXbufferSize); flush(); } } @@ -155,16 +159,24 @@ void Serial_2_Socket::handle_flush() { if (_TXbufferSize > 0 && _started && !_paused) { if ((_TXbufferSize >= S2S_TXBUFFERSIZE) || ((millis() - _lastflush) > S2S_FLUSHTIMEOUT)) { - log_esp3d("force socket flush"); + esp3d_log("force socket flush"); flush(); } } } void Serial_2_Socket::flush(void) { if (_TXbufferSize > 0 && _started && !_paused) { - ESP3DOutput output(ESP_SOCKET_SERIAL_CLIENT); + ESP3DMessage *msg = ESP3DMessageManager::newMsg( + ESP3DClientType::socket_serial, ESP3DClientType::all_clients, + _TXbuffer, _TXbufferSize, _auth); // dispatch command - esp3d_commands.process(_TXbuffer, _TXbufferSize, &output); + if (msg) { + // process command + msg->type = ESP3DMessageType::unique; + esp3d_commands.process(msg); + } else { + esp3d_log_e("Cannot create message"); + } // refresh timout _lastflush = millis(); // reset buffer @@ -172,4 +184,21 @@ void Serial_2_Socket::flush(void) { } } +bool Serial_2_Socket::dispatch(ESP3DMessage *message) { + if (!message || !_started) { + esp3d_log_e("Serial2Socket: no message or not started"); + return false; + } + if (message->size > 0 && message->data) { + if (!push(message->data, message->size)) { + esp3d_log_e("Serial2Socket: cannot push all data"); + return false; + } + ESP3DMessageManager::deleteMsg(message); + return true; + } + esp3d_log_e("Serial2Socket: no data in message"); + return false; +} + #endif // ESP3DLIB_ENV diff --git a/esp3d/src/modules/serial2socket/serial2socket.h b/esp3d/src/modules/serial2socket/serial2socket.h index 224b173c..1007827d 100644 --- a/esp3d/src/modules/serial2socket/serial2socket.h +++ b/esp3d/src/modules/serial2socket/serial2socket.h @@ -18,69 +18,60 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - #ifndef _SERIAL_2_SOCKET_H_ #define _SERIAL_2_SOCKET_H_ #include +#include "../authentication/authentication_level_types.h" #define S2S_TXBUFFERSIZE 1200 #define S2S_RXBUFFERSIZE 128 #define S2S_FLUSHTIMEOUT 500 -class Serial_2_Socket: public Stream -{ -public: - Serial_2_Socket(); - ~Serial_2_Socket(); - size_t write(uint8_t c); - size_t write(const uint8_t *buffer, size_t size); - inline size_t write(const char * s) - { - return write((uint8_t*) s, strlen(s)); - } - inline size_t write(unsigned long n) - { - return write((uint8_t) n); - } - inline size_t write(long n) - { - return write((uint8_t) n); - } - inline size_t write(unsigned int n) - { - return write((uint8_t) n); - } - inline size_t write(int n) - { - return write((uint8_t) n); - } - long baudRate(); - void begin(long speed); - void end(); - void enable(bool enable=true); - bool started(); - int available(); - int peek(void); - int read(void); - bool push (const uint8_t *buffer, size_t size); - void flush(void); - void handle_flush(); - void handle(); - operator bool() const; - void pause(bool state=true); - bool isPaused(); -private: - bool _started; - bool _paused; - uint32_t _lastflush; - uint8_t _TXbuffer[S2S_TXBUFFERSIZE]; - uint16_t _TXbufferSize; - uint8_t _RXbuffer[S2S_RXBUFFERSIZE]; - uint16_t _RXbufferSize; - uint16_t _RXbufferpos; + +class ESP3DMessage; // forward declaration + + +class Serial_2_Socket : public Stream { + public: + Serial_2_Socket(); + ~Serial_2_Socket(); + size_t write(uint8_t c); + size_t write(const uint8_t *buffer, size_t size); + bool dispatch(ESP3DMessage *message); + + inline size_t write(const char *s) { return write((uint8_t *)s, strlen(s)); } + inline size_t write(unsigned long n) { return write((uint8_t)n); } + inline size_t write(long n) { return write((uint8_t)n); } + inline size_t write(unsigned int n) { return write((uint8_t)n); } + inline size_t write(int n) { return write((uint8_t)n); } + long baudRate(); + void begin(long speed); + void end(); + void enable(bool enable = true); + bool started(); + int available(); + int peek(void); + int read(void); + bool push(const uint8_t *buffer, size_t size); + void flush(void); + void handle_flush(); + void handle(); + operator bool() const; + void pause(bool state = true); + bool isPaused(); + + private: + bool _started; + bool _paused; + ESP3DAuthenticationLevel _auth; + uint32_t _lastflush; + uint8_t _TXbuffer[S2S_TXBUFFERSIZE]; + uint16_t _TXbufferSize; + uint8_t _RXbuffer[S2S_RXBUFFERSIZE]; + uint16_t _RXbufferSize; + uint16_t _RXbufferpos; }; - extern Serial_2_Socket Serial2Socket; #endif diff --git a/esp3d/src/modules/telnet/telnet_server.cpp b/esp3d/src/modules/telnet/telnet_server.cpp index 22483e17..60536ea4 100644 --- a/esp3d/src/modules/telnet/telnet_server.cpp +++ b/esp3d/src/modules/telnet/telnet_server.cpp @@ -20,19 +20,29 @@ #include "../../include/esp3d_config.h" -#if defined(TELNET_FEATURE) +#if defined(TELNET_FEATURE) || \ + (defined(ESP_LOG_FEATURE) && ESP_LOG_FEATURE == LOG_OUTPUT_TELNET) #include #include -#include "../../core/commands.h" -#include "../../core/esp3doutput.h" -#include "../../core/settings_esp3d.h" +#include "../../core/esp3d_commands.h" +#include "../../core/esp3d_message.h" +#include "../../core/esp3d_settings.h" +#include "../../include/esp3d_version.h" #include "telnet_server.h" Telnet_Server telnet_server; #define TIMEOUT_TELNET_FLUSH 1500 +#if defined(AUTHENTICATION_FEATURE) +#define TELNET_WELCOME_MESSAGE \ + ";Welcome to ESP3D-TFT V" FW_VERSION \ + ", please enter a command with credentials.\r\n" +#else +#define TELNET_WELCOME_MESSAGE ";Welcome to ESP3D-TFT V" FW_VERSION ".\r\n" +#endif // AUTHENTICATION_FEATURE + void Telnet_Server::closeClient() { if (_telnetClients) { _telnetClients.stop(); @@ -52,6 +62,9 @@ bool Telnet_Server::isConnected() { } _telnetClients = _telnetserver->accept(); // new client + writeBytes((uint8_t *)TELNET_WELCOME_MESSAGE, + strlen(TELNET_WELCOME_MESSAGE)); + initAuthentication(); } } if (_telnetserver->hasClient()) { @@ -77,6 +90,7 @@ Telnet_Server::Telnet_Server() { _port = 0; _buffer = nullptr; _telnetserver = nullptr; + initAuthentication(); } Telnet_Server::~Telnet_Server() { end(); } @@ -85,12 +99,12 @@ Telnet_Server::~Telnet_Server() { end(); } */ bool Telnet_Server::begin(uint16_t port, bool debug) { end(); - if (Settings_ESP3D::read_byte(ESP_TELNET_ON) != 1) { + if (ESP3DSettings::readByte(ESP_TELNET_ON) != 1) { return true; } // Get telnet port if (port == 0) { - _port = Settings_ESP3D::read_uint32(ESP_TELNET_PORT); + _port = ESP3DSettings::readUint32(ESP_TELNET_PORT); } else { _port = port; } @@ -131,6 +145,11 @@ void Telnet_Server::end() { free(_buffer); _buffer = nullptr; } +#if defined(AUTHENTICATION_FEATURE) + _auth = ESP3DAuthenticationLevel::guest; +#else + _auth = ESP3DAuthenticationLevel::admin; +#endif // AUTHENTICATION_FEATURE } /** @@ -144,7 +163,7 @@ bool Telnet_Server::reset() { bool Telnet_Server::started() { return _started; } void Telnet_Server::handle() { - Hal::wait(0); + ESP3DHal::wait(0); if (isConnected()) { // check clients for data size_t len = _telnetClients.available(); @@ -169,15 +188,46 @@ void Telnet_Server::handle() { } } +bool Telnet_Server::dispatch(ESP3DMessage *message) { + if (!message || !_started) { + return false; + } + if (message->size > 0 && message->data) { + size_t sentcnt = writeBytes(message->data, message->size); + if (sentcnt != message->size) { + return false; + } + ESP3DMessageManager::deleteMsg(message); + return true; + } + return false; +} + +void Telnet_Server::initAuthentication() { +#if defined(AUTHENTICATION_FEATURE) + _auth = ESP3DAuthenticationLevel::guest; +#else + _auth = ESP3DAuthenticationLevel::admin; +#endif // AUTHENTICATION_FEATURE +} +ESP3DAuthenticationLevel Telnet_Server::getAuthentication() { return _auth; } + 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); + ESP3DMessage *msg = ESP3DMessageManager::newMsg( + ESP3DClientType::telnet, esp3d_commands.getOutputClient(), _buffer, + _buffer_size, _auth); + if (msg) { + // process command + esp3d_commands.process(msg); + } else { + esp3d_log_e("Cannot create message"); + } + _lastflush = millis(); _buffer_size = 0; } @@ -217,9 +267,7 @@ void Telnet_Server::push2buffer(uint8_t *sbuf, size_t len) { } } -size_t Telnet_Server::write(uint8_t c) { return write(&c, 1); } - -size_t Telnet_Server::write(const uint8_t *buffer, size_t size) { +size_t Telnet_Server::writeBytes(const uint8_t *buffer, size_t size) { if (isConnected() && (size > 0) && _started) { if ((size_t)availableForWrite() >= size) { // push data to connected telnet client @@ -241,7 +289,7 @@ size_t Telnet_Server::write(const uint8_t *buffer, size_t size) { sizesent += available; starttime = millis(); } else { - Hal::wait(5); + ESP3DHal::wait(5); } } return sizesent; @@ -269,15 +317,6 @@ int Telnet_Server::available() { return 0; } -int Telnet_Server::read(void) { - if (isConnected()) { - if (_telnetClients.available() > 0) { - return _telnetClients.read(); - } - } - return -1; -} - size_t Telnet_Server::readBytes(uint8_t *sbuf, size_t len) { if (isConnected()) { if (_telnetClients.available() > 0) { diff --git a/esp3d/src/modules/telnet/telnet_server.h b/esp3d/src/modules/telnet/telnet_server.h index 7d5de5fe..a70508a4 100644 --- a/esp3d/src/modules/telnet/telnet_server.h +++ b/esp3d/src/modules/telnet/telnet_server.h @@ -23,68 +23,47 @@ class WiFiServer; class WiFiClient; -#include "Print.h" +#include "../../core/esp3d_message.h" #define ESP3D_TELNET_BUFFER_SIZE 1200 -class Telnet_Server : public Print -{ -public: - Telnet_Server(); - ~Telnet_Server(); - bool begin(uint16_t port = 0, bool debug=false); - void end(); - void handle(); - bool reset(); - bool started(); - bool isConnected(); - const char* clientIPAddress(); - size_t write(uint8_t c); - size_t write(const uint8_t *buffer, size_t size); - inline size_t write(const char * s) - { - return write((uint8_t*) s, strlen(s)); - } - inline size_t write(unsigned long n) - { - return write((uint8_t) n); - } - inline size_t write(long n) - { - return write((uint8_t) n); - } - inline size_t write(unsigned int n) - { - return write((uint8_t) n); - } - inline size_t write(int n) - { - return write((uint8_t) n); - } - int available(); - int availableForWrite(); - void flush(); - int read(void); - size_t readBytes (uint8_t * sbuf, size_t len); - uint16_t port() - { - return _port; - } - void closeClient(); -private: - bool _started; - WiFiServer * _telnetserver; - WiFiClient _telnetClients; - uint16_t _port; - bool _isdebug; - uint32_t _lastflush; - uint8_t *_buffer; - size_t _buffer_size; - void push2buffer(uint8_t * sbuf, size_t len); - void flushbuffer(); +class Telnet_Server { + public: + Telnet_Server(); + ~Telnet_Server(); + bool begin(uint16_t port = 0, bool debug = false); + void end(); + void handle(); + bool reset(); + bool started(); + bool isConnected(); + const char* clientIPAddress(); + size_t writeBytes(const uint8_t* buffer, size_t size); + bool dispatch(ESP3DMessage* message); + int available(); + int availableForWrite(); + void flush(); + size_t readBytes(uint8_t* sbuf, size_t len); + uint16_t port() { return _port; } + void closeClient(); + void initAuthentication(); + void setAuthentication(ESP3DAuthenticationLevel auth) { _auth = auth; } + ESP3DAuthenticationLevel getAuthentication(); + + private: + bool _started; + WiFiServer* _telnetserver; + WiFiClient _telnetClients; + ESP3DAuthenticationLevel _auth; + uint16_t _port; + bool _isdebug; + uint32_t _lastflush; + uint8_t* _buffer; + size_t _buffer_size; + void push2buffer(uint8_t* sbuf, size_t len); + void flushbuffer(); }; extern Telnet_Server telnet_server; #endif - diff --git a/esp3d/src/modules/time/time_service.cpp b/esp3d/src/modules/time/time_service.cpp index 519064ad..3cf1fe45 100644 --- a/esp3d/src/modules/time/time_service.cpp +++ b/esp3d/src/modules/time/time_service.cpp @@ -21,8 +21,8 @@ #ifdef TIMESTAMP_FEATURE #include -#include "../../core/esp3doutput.h" -#include "../../core/settings_esp3d.h" +#include "../../core/esp3d_message.h" +#include "../../core/esp3d_settings.h" #include "time_service.h" #if defined(WIFI_FEATURE) @@ -50,12 +50,11 @@ const uint8_t SupportedTimeZonesSize = TimeService::TimeService() { _started = false; - _is_internet_time = false; + _isInternetTime = false; _time_zone = "+00:00"; } TimeService::~TimeService() { end(); } -// 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)); @@ -63,25 +62,23 @@ const char* TimeService::getDateTime(time_t t) { return buff; } -bool TimeService::is_internet_time(bool readfromsettings) { +bool TimeService::isInternetTime(bool readfromsettings) { if (readfromsettings) { - _is_internet_time = - Settings_ESP3D::read_byte(ESP_INTERNET_TIME) ? true : false; - log_esp3d("Internet time is %s", - _is_internet_time ? "enabled" : "disabled"); + _isInternetTime = ESP3DSettings::readByte(ESP_INTERNET_TIME) ? true : false; + esp3d_log("Internet time is %s", _isInternetTime ? "enabled" : "disabled"); } - return _is_internet_time; + return _isInternetTime; } bool TimeService::begin() { + esp3d_log("Starting TimeService"); end(); String s1, s2, s3, t1; - byte d1; updateTimeZone(true); #if defined(WIFI_FEATURE) // no time server in AP mode if (WiFi.getMode() == WIFI_AP) { - log_esp3d("No Internet time in AP mode"); + esp3d_log("No Internet time in AP mode"); return false; } #endif // WIFI_FEATURE @@ -105,13 +102,12 @@ bool TimeService::begin() { #endif // WIFI_FEATURE } #endif // ETH_FEATURE - if (!is_internet_time(true)) { + if (!isInternetTime(true)) { return true; } - s1 = Settings_ESP3D::read_string(ESP_TIME_SERVER1); - s2 = Settings_ESP3D::read_string(ESP_TIME_SERVER2); - s3 = Settings_ESP3D::read_string(ESP_TIME_SERVER3); - // d1 = Settings_ESP3D::read_byte(ESP_TIME_IS_DST); + s1 = ESP3DSettings::readString(ESP_TIME_SERVER1); + s2 = ESP3DSettings::readString(ESP_TIME_SERVER2); + s3 = ESP3DSettings::readString(ESP_TIME_SERVER3); #if defined(ARDUINO_ARCH_ESP32) configTzTime(_time_zone.c_str(), s1.c_str(), s2.c_str(), s3.c_str()); #endif // ARDUINO_ARCH_ESP32 @@ -143,14 +139,13 @@ bool TimeService::setTimeZone(const char* stime) { } if (valid) { _time_zone = stime; - return Settings_ESP3D::write_string(ESP_TIME_ZONE, _time_zone.c_str()); + return ESP3DSettings::writeString(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); + _time_zone = ESP3DSettings::readString(ESP_TIME_ZONE); bool valid = false; for (uint8_t i = 0; i < SupportedTimeZonesSize; i++) { @@ -161,7 +156,7 @@ bool TimeService::updateTimeZone(bool fromsettings) { } if (!valid) { - log_esp3d_e("Invalid time zone %s", _time_zone.c_str()); + esp3d_log_e("Invalid time zone %s", _time_zone.c_str()); _time_zone = "+00:00"; } String stmp = _time_zone; @@ -192,23 +187,23 @@ const char* TimeService::getCurrentTime() { 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); + esp3d_log("Time string is %s", buf); return buf; } // the string date time need to be iso-8601 // the time zone part will be ignored bool TimeService::setTime(const char* stime) { - log_esp3d("Set time to %s", stime); + esp3d_log("Set time to %s", stime); String stmp = stime; struct tm tmstruct; struct timeval time_val = {0, 0}; memset(&tmstruct, 0, sizeof(struct tm)); if (strptime(stime, "%Y-%m-%dT%H:%M:%S", &tmstruct) == nullptr) { - log_esp3d("Invalid time format, try without seconds"); + esp3d_log("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("Invalid time format"); + esp3d_log("Invalid time format"); return false; } } @@ -231,7 +226,7 @@ bool TimeService::started() { return _started; } // currently not used void TimeService::end() { _started = false; - _is_internet_time = false; + _isInternetTime = false; _time_zone = "+00:00"; } diff --git a/esp3d/src/modules/time/time_service.h b/esp3d/src/modules/time/time_service.h index ae0c0bf9..65de9660 100644 --- a/esp3d/src/modules/time/time_service.h +++ b/esp3d/src/modules/time/time_service.h @@ -21,8 +21,9 @@ #ifndef _TIME_SERVICE_H #define _TIME_SERVICE_H -#include #include +#include + class TimeService { public: @@ -38,12 +39,12 @@ class TimeService { bool setTimeZone(const char* stime); bool setTime(const char* stime); bool started(); - bool is_internet_time(bool readfromsettings = false); + bool isInternetTime(bool readfromsettings = false); private: int _get_time_zone_offset_min(); bool _started; - bool _is_internet_time; + bool _isInternetTime; String _time_zone; }; diff --git a/esp3d/src/modules/update/esp_config_file.cpp b/esp3d/src/modules/update/esp_config_file.cpp index 91f1e7eb..dd00def0 100644 --- a/esp3d/src/modules/update/esp_config_file.cpp +++ b/esp3d/src/modules/update/esp_config_file.cpp @@ -42,7 +42,7 @@ ESP_ConfigFile::ESP_ConfigFile(const char *path, TProcessingFunction fn) { bool ESP_ConfigFile::processFile() { bool res = true; if (!ESP_SD::exists(_filename)) { - log_esp3d_e("No ini file"); + esp3d_log_e("No ini file"); return false; } ESP_SDFile rFile = ESP_SD::open(_filename); @@ -95,7 +95,7 @@ bool ESP_ConfigFile::processFile() { rFile.close(); return res; } - log_esp3d_e("Cannot open ini file"); + esp3d_log_e("Cannot open ini file"); return false; } @@ -195,7 +195,7 @@ bool ESP_ConfigFile::isScrambleKey(const char *key, const char *str) { bool ESP_ConfigFile::revokeFile() { char *filename; if (!ESP_SD::exists(_filename)) { - log_esp3d("No ini file to revoke"); + esp3d_log("No ini file to revoke"); return false; } filename = (char *)malloc(strlen(_filename) + 1); @@ -252,7 +252,7 @@ bool ESP_ConfigFile::revokeFile() { ESP_SD::remove(_filename); return true; } - log_esp3d_e("Cannot open / create revoked file"); + esp3d_log_e("Cannot open / create revoked file"); if (wFile) { wFile.close(); } diff --git a/esp3d/src/modules/update/update_service.cpp b/esp3d/src/modules/update/update_service.cpp index b453bee7..210f522c 100644 --- a/esp3d/src/modules/update/update_service.cpp +++ b/esp3d/src/modules/update/update_service.cpp @@ -20,9 +20,9 @@ #include "../../include/esp3d_config.h" #ifdef SD_UPDATE_FEATURE -#include "../../core/commands.h" -#include "../../core/esp3doutput.h" -#include "../../core/settings_esp3d.h" +#include "../../core/esp3d_commands.h" +#include "../../core/esp3d_message.h" +#include "../../core/esp3d_settings.h" #include "../filesystem/esp_filesystem.h" #include "../filesystem/esp_sd.h" #include "esp_config_file.h" @@ -91,45 +91,26 @@ const char* SysintKeysVal[] = {"Baud_rate", "Boot_delay"}; const uint16_t SysintKeysPos[] = {ESP_BAUD_RATE, ESP_BOOT_DELAY}; -const char* ServboolKeysVal[] = {"Serial_Bridge_active", - "AUTONOTIFICATION", - "HTTP_active", - "TELNET_active", - "WebSocket_active", - "WebDav_active", - "Time_DST", - "CHECK_FOR_UPDATE", - "Active_buzzer", - "Active_Internet_time", - "Radio_enabled"}; +const char* ServboolKeysVal[] = {"Serial_Bridge_active", "AUTONOTIFICATION", + "HTTP_active", "TELNET_active", + "WebSocket_active", "WebDav_active", + "CHECK_FOR_UPDATE", "Active_buzzer", + "Active_Internet_time", "Radio_enabled"}; -const uint16_t ServboolKeysPos[] = { - ESP_SERIAL_BRIDGE_ON, ESP_AUTO_NOTIFICATION, - ESP_HTTP_ON, ESP_TELNET_ON, - ESP_WEBSOCKET_ON, ESP_WEBDAV_ON, - ESP_TIME_IS_DST, ESP_SD_CHECK_UPDATE_AT_BOOT, - ESP_BUZZER, ESP_INTERNET_TIME, - ESP_BOOT_RADIO_STATE}; +const uint16_t ServboolKeysPos[] = {ESP_SERIAL_BRIDGE_ON, + ESP_AUTO_NOTIFICATION, + ESP_HTTP_ON, + ESP_TELNET_ON, + ESP_WEBSOCKET_ON, + ESP_WEBDAV_ON, + ESP_SD_CHECK_UPDATE_AT_BOOT, + ESP_BUZZER, + ESP_INTERNET_TIME, + ESP_BOOT_RADIO_STATE}; -const char* SysboolKeysVal[] = {"Active_Serial_Bridge", - "Active_Remote_Screen", - "Active_ESP3D_Screen", - "Active_Serial ", - "Active_WebSocket", - "Active_Telnet", - "Active_BT", - "Boot_verbose", - "Secure_serial"}; +const char* SysboolKeysVal[] = {"Boot_verbose", "Secure_serial"}; -const uint16_t SysboolKeysPos[] = {ESP_SERIAL_BRIDGE_FLAG, - ESP_REMOTE_SCREEN_FLAG, - ESP_SCREEN_FLAG, - ESP_SERIAL_FLAG, - ESP_WEBSOCKET_FLAG, - ESP_TELNET_FLAG, - ESP_BT_FLAG, - ESP_VERBOSE_BOOT, - ESP_SECURE_SERIAL}; +const uint16_t SysboolKeysPos[] = {ESP_VERBOSE_BOOT, ESP_SECURE_SERIAL}; const char* NetbyteKeysVal[] = {"AP_channel"}; @@ -202,7 +183,7 @@ bool processingFileFunction(const char* section, const char* key, uint32_t v = 0; byte b = 0; bool done = false; - log_esp3d("[%s]%s=%s", section, key, value); + esp3d_log("[%s]%s=%s", section, key, value); // network / services / system sections if (strcasecmp("network", section) == 0) { if (!done) { @@ -307,7 +288,7 @@ bool processingFileFunction(const char* section, const char* key, b = v; } } - // Notification type None / PushOver / Line / Email / Telegram / IFTTT + // Notification type None / PushOver / Line / Email / Telegram / IFTTT / HomeAssistant if (!done) { if (strcasecmp("NOTIF_TYPE", key) == 0) { T = 'B'; @@ -325,6 +306,8 @@ bool processingFileFunction(const char* section, const char* key, b = ESP_TELEGRAM_NOTIFICATION; } else if (strcasecmp("IFTTT", value) == 0) { b = ESP_IFTTT_NOTIFICATION; + } else if (strcasecmp("HOMEASSISTANT", value) == 0) { + b = ESP_HOMEASSISTANT_NOTIFICATION; } else { P = -1; // invalide value } @@ -394,21 +377,21 @@ bool processingFileFunction(const char* section, const char* key, if (P != -1) { switch (T) { case 'S': - log_esp3d("Saving setting to ESP3D"); - res = Settings_ESP3D::write_string(P, value); + esp3d_log("Saving setting to ESP3D"); + res = ESP3DSettings::writeString(P, value); break; case 'B': case 'F': - res = Settings_ESP3D::write_byte(P, b); + res = ESP3DSettings::writeByte(P, b); break; case 'I': - res = Settings_ESP3D::write_uint32(P, v); + res = ESP3DSettings::writeUint32(P, v); break; case 'A': - res = Settings_ESP3D::write_IP_String(P, value); + res = ESP3DSettings::writeIPString(P, value); break; default: - log_esp3d("Unknown flag"); + esp3d_log("Unknown flag"); } } return res; @@ -420,7 +403,7 @@ UpdateService::~UpdateService() {} bool UpdateService::flash(const char* filename, int type) { bool res = false; if (ESP_SD::exists(filename)) { - log_esp3d("Update found"); + esp3d_log("Update found"); bool issucess = false; ESP_SDFile sdfile; String finalName = filename; @@ -430,27 +413,27 @@ bool UpdateService::flash(const char* filename, int type) { size_t rs = 0; uint8_t v[1]; if (Update.begin(s, type)) { - log_esp3d("Update started"); + esp3d_log("Update started"); while (sdfile.available() && (rs <= (s + 1))) { rs++; v[0] = sdfile.read(); Update.write(v, 1); - Hal::wait(0); + ESP3DHal::wait(0); } if (rs == s) { - log_esp3d("Update done"); + esp3d_log("Update done"); if (Update.end(true)) { - log_esp3d("Update success"); + esp3d_log("Update success"); issucess = true; } } else { Update.end(); - log_esp3d_e("Wrong size"); + esp3d_log_e("Wrong size"); } } sdfile.close(); } else { - log_esp3d_e("Cannot open file"); + esp3d_log_e("Cannot open file"); } if (issucess) { res = true; @@ -461,7 +444,7 @@ bool UpdateService::flash(const char* filename, int type) { if (ESP_SD::exists(finalName.c_str())) { String name = filename; uint8_t n = 1; - log_esp3d("Final name already exists, backup existing"); + esp3d_log("Final name already exists, backup existing"); name.replace("bin", String(n).c_str()); while (ESP_SD::exists(name.c_str())) { n++; @@ -476,22 +459,22 @@ bool UpdateService::flash(const char* filename, int type) { bool UpdateService::begin() { bool res = false; - if (Settings_ESP3D::read_byte(ESP_SD_CHECK_UPDATE_AT_BOOT) != 0) { + if (ESP3DSettings::readByte(ESP_SD_CHECK_UPDATE_AT_BOOT) != 0) { if (ESP_SD::accessFS()) { - log_esp3d("Update SD for update requestest"); + esp3d_log("Update SD for update requestest"); if (ESP_SD::getState(true) != ESP_SDCARD_NOT_PRESENT) { ESP_SD::setState(ESP_SDCARD_BUSY); ESP_ConfigFile updateConfig(CONFIG_FILE, processingFileFunction); if (updateConfig.processFile()) { - log_esp3d("Processing ini file done"); + esp3d_log("Processing ini file done"); if (updateConfig.revokeFile()) { - log_esp3d("Revoking ini file done"); + esp3d_log("Revoking ini file done"); res = true; } else { - log_esp3d_e("Revoking ini file failed"); + esp3d_log_e("Revoking ini file failed"); } } else { - log_esp3d_e("Processing ini file failed"); + esp3d_log_e("Processing ini file failed"); } if (flash(FW_FILE, U_FLASH)) { res = true; @@ -504,7 +487,7 @@ bool UpdateService::begin() { ESP_SD::releaseFS(); } } else { - log_esp3d("No need to check for update"); + esp3d_log("No need to check for update"); } return res; diff --git a/esp3d/src/modules/webdav/handlers/handler_copy.cpp b/esp3d/src/modules/webdav/handlers/handler_copy.cpp index 13f843fa..7780ee83 100644 --- a/esp3d/src/modules/webdav/handlers/handler_copy.cpp +++ b/esp3d/src/modules/webdav/handlers/handler_copy.cpp @@ -25,22 +25,23 @@ #include "../webdav_server.h" void WebdavServer::handler_copy(const char* url) { - log_esp3d("Processing COPY"); + esp3d_log("Processing COPY"); int code = 201; size_t sp = clearPayload(); - log_esp3d("Payload size: %d", sp); + (void)sp; + esp3d_log("Payload size: %d", sp); uint8_t fsTypeOrigin = WebDavFS::getFSType(url); - log_esp3d("FS type of %s : %d", url, fsTypeOrigin); + esp3d_log("FS type of %s : %d", url, fsTypeOrigin); String destination = ""; if (hasHeader("Destination")) { destination = getHeader("Destination"); - log_esp3d("Destination: %s", destination.c_str()); + esp3d_log("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()); + esp3d_log("Destination trimmed: %s", destination.c_str()); if (destination != "/") { if (destination.endsWith("/")) { destination = destination.substring(0, destination.length() - 1); @@ -48,15 +49,15 @@ void WebdavServer::handler_copy(const char* url) { } } uint8_t fsTypeDestination = WebDavFS::getFSType(destination.c_str()); - log_esp3d("FS type of %s : %d", destination.c_str(), fsTypeDestination); + esp3d_log("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"); + esp3d_log_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"); + esp3d_log("Overwrite: %s", overwrite ? "true" : "false"); } // url cannot be root if (!isRoot(url) && !isRoot(destination.c_str())) { @@ -68,7 +69,7 @@ void WebdavServer::handler_copy(const char* url) { if (fileOrigin) { if (fileOrigin.isDirectory()) { code = 413; - log_esp3d_e("File %s is a directory", url); + esp3d_log_e("File %s is a directory", url); } else { // check if destination exists WebDavFile fileDestination = @@ -76,12 +77,12 @@ void WebdavServer::handler_copy(const char* url) { if (fileDestination) { if (fileDestination.isDirectory()) { code = 412; - log_esp3d_e("File %s is a directory", destination.c_str()); + esp3d_log_e("File %s is a directory", destination.c_str()); } fileDestination.close(); overwrite = false; } else { - log_esp3d("Destination does not exist"); + esp3d_log("Destination does not exist"); overwrite = true; } // check available space @@ -90,7 +91,7 @@ void WebdavServer::handler_copy(const char* url) { if (WebDavFS::freeBytes(fsTypeOrigin) + fileOrigin.size() < fileDestination.size()) { code = 507; - log_esp3d_e("Not enough space"); + esp3d_log_e("Not enough space"); overwrite = false; } else { // there is enough space to overwrite code = 204; @@ -98,17 +99,17 @@ void WebdavServer::handler_copy(const char* url) { } else { if (WebDavFS::freeBytes(fsTypeOrigin) < fileOrigin.size()) { code = 507; - log_esp3d_e("Not enough space"); + esp3d_log_e("Not enough space"); overwrite = false; } } if (overwrite) { - log_esp3d("Overwrite allowed"); + esp3d_log("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()); + esp3d_log_e("Failed to remove %s", destination.c_str()); overwrite = false; } else { // copy file @@ -118,7 +119,7 @@ void WebdavServer::handler_copy(const char* url) { size_t data_read = 0; size_t data_to_read = fileOrigin.size(); while (data_read < data_to_read) { - Hal::wait(0); + ESP3DHal::wait(0); #if defined(ARDUINO_ARCH_ESP32) uint8_t buff[2048]; #endif // ARDUINO_ARCH_ESP32 @@ -132,7 +133,7 @@ void WebdavServer::handler_copy(const char* url) { // write if (read_size != fileDestination.write(buff, read_size)) { - log_esp3d_e("Failed to write data"); + esp3d_log_e("Failed to write data"); code = 500; break; } @@ -145,13 +146,13 @@ void WebdavServer::handler_copy(const char* url) { fileDestination.close(); if (data_read != data_to_read) { code = 500; - log_esp3d_e("Failed to copy %s to %s", url, + esp3d_log_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()); + esp3d_log_e("Failed to open %s", destination.c_str()); overwrite = false; } } @@ -160,7 +161,7 @@ void WebdavServer::handler_copy(const char* url) { if (overwrite) { if (!WebDavFS::rename(url, destination.c_str())) { code = 500; - log_esp3d_e("Failed to move %s to %s", url, + esp3d_log_e("Failed to move %s to %s", url, destination.c_str()); } } @@ -168,28 +169,28 @@ void WebdavServer::handler_copy(const char* url) { fileOrigin.close(); } else { code = 500; - log_esp3d_e("Failed to open %s", url); + esp3d_log_e("Failed to open %s", url); } } else { code = 404; - log_esp3d_e("File not found"); + esp3d_log_e("File not found"); } WebDavFS::releaseFS(fsTypeOrigin); } else { code = 503; - log_esp3d_e("FS not available"); + esp3d_log_e("FS not available"); } } else { code = 400; - log_esp3d_e("Root cannot be deleted"); + esp3d_log_e("Root cannot be deleted"); } } } else { code = 400; - log_esp3d_e("Destination not set"); + esp3d_log_e("Destination not set"); } - log_esp3d_e("Sending response code %d", code); + esp3d_log_e("Sending response code %d", code); send_response_code(code); send_webdav_headers(); } diff --git a/esp3d/src/modules/webdav/handlers/handler_delete.cpp b/esp3d/src/modules/webdav/handlers/handler_delete.cpp index 87dc1350..fe154019 100644 --- a/esp3d/src/modules/webdav/handlers/handler_delete.cpp +++ b/esp3d/src/modules/webdav/handlers/handler_delete.cpp @@ -24,12 +24,13 @@ #include "../webdav_server.h" void WebdavServer::handler_delete(const char* url) { - log_esp3d("Processing DELETE"); + esp3d_log("Processing DELETE"); int code = 204; size_t sp = clearPayload(); - log_esp3d("Payload size: %d", sp); + esp3d_log("Payload size: %d", sp); + (void)sp; uint8_t fsType = WebDavFS::getFSType(url); - log_esp3d("FS type of %s : %d", url, fsType); + esp3d_log("FS type of %s : %d", url, fsType); // url cannot be root if (!isRoot(url)) { if (WebDavFS::accessFS(fsType)) { @@ -37,30 +38,30 @@ void WebdavServer::handler_delete(const char* url) { 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"); + esp3d_log("Failed to remove file %s", url); + esp3d_log("Trying to remove as directory"); // if failed try remove as directory if (!WebDavFS::rmdir(url)) { - log_esp3d("Failed to remove directory %s", url); + esp3d_log("Failed to remove directory %s", url); code = 500; - log_esp3d_e("Failed to remove %s", url); + esp3d_log_e("Failed to remove %s", url); } } } else { code = 404; - log_esp3d_e("File not found"); + esp3d_log_e("File not found"); } WebDavFS::releaseFS(fsType); } else { code = 503; - log_esp3d_e("FS not available"); + esp3d_log_e("FS not available"); } } else { code = 400; - log_esp3d_e("Root cannot be deleted"); + esp3d_log_e("Root cannot be deleted"); } - log_esp3d_e("Sending response code %d", code); + esp3d_log_e("Sending response code %d", code); send_response_code(code); send_webdav_headers(); } diff --git a/esp3d/src/modules/webdav/handlers/handler_get.cpp b/esp3d/src/modules/webdav/handlers/handler_get.cpp index d32ed1a3..b6f69f0c 100644 --- a/esp3d/src/modules/webdav/handlers/handler_get.cpp +++ b/esp3d/src/modules/webdav/handlers/handler_get.cpp @@ -28,12 +28,13 @@ #include "../webdav_server.h" void WebdavServer::handler_get(const char* url) { - log_esp3d("Processing GET"); + esp3d_log("Processing GET"); int code = 200; size_t sp = clearPayload(); - log_esp3d("Payload size: %d", sp); + (void)sp; + esp3d_log("Payload size: %d", sp); uint8_t fsType = WebDavFS::getFSType(url); - log_esp3d("FS type of %s : %d", url, fsType); + esp3d_log("FS type of %s : %d", url, fsType); // url cannot be root if (!isRoot(url)) { if (WebDavFS::accessFS(fsType)) { @@ -63,12 +64,12 @@ void WebdavServer::handler_get(const char* url) { Esp3dTimout updateWS(2000); #endif // HTTP_FEATURE while (sent < toSend && _client.connected()) { - Hal::wait(0); + ESP3DHal::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"); + esp3d_log_e("Failed to send data"); break; } sent += read; @@ -86,28 +87,28 @@ void WebdavServer::handler_get(const char* url) { } // 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); + esp3d_log_e("Failed to send data, sent %d of %d", sent, toSend); } file.close(); } else { code = 500; - log_esp3d_e("Failed to open %s", url); + esp3d_log_e("Failed to open %s", url); } } else { code = 404; - log_esp3d_e("File not found"); + esp3d_log_e("File not found"); } WebDavFS::releaseFS(fsType); } else { code = 503; - log_esp3d_e("FS not available"); + esp3d_log_e("FS not available"); } } else { code = 400; - log_esp3d_e("Root cannot be used as it is"); + esp3d_log_e("Root cannot be used as it is"); } if (code != 200) { - log_esp3d_e("Sending response code %d", code); + esp3d_log_e("Sending response code %d", code); send_response_code(code); send_webdav_headers(); } diff --git a/esp3d/src/modules/webdav/handlers/handler_head.cpp b/esp3d/src/modules/webdav/handlers/handler_head.cpp index df4b57dd..d4e59474 100644 --- a/esp3d/src/modules/webdav/handlers/handler_head.cpp +++ b/esp3d/src/modules/webdav/handlers/handler_head.cpp @@ -25,12 +25,13 @@ #include "../webdav_server.h" void WebdavServer::handler_head(const char* url) { - log_esp3d("Processing HEAD"); + esp3d_log("Processing HEAD"); int code = 200; size_t sp = clearPayload(); - log_esp3d("Payload size: %d", sp); + (void)sp; + esp3d_log("Payload size: %d", sp); uint8_t fsType = WebDavFS::getFSType(url); - log_esp3d("FS type of %s : %d", url, fsType); + esp3d_log("FS type of %s : %d", url, fsType); // url cannot be root if (!isRoot(url)) { if (WebDavFS::accessFS(fsType)) { @@ -48,23 +49,23 @@ void WebdavServer::handler_head(const char* url) { file.close(); } else { code = 500; - log_esp3d_e("Failed to open %s", url); + esp3d_log_e("Failed to open %s", url); } } else { code = 404; - log_esp3d_e("File not found"); + esp3d_log_e("File not found"); } WebDavFS::releaseFS(fsType); } else { code = 503; - log_esp3d_e("FS not available"); + esp3d_log_e("FS not available"); } } else { code = 400; - log_esp3d_e("Root cannot be deleted"); + esp3d_log_e("Root cannot be deleted"); } if (code != 200) { - log_esp3d_e("Sending response code %d", code); + esp3d_log_e("Sending response code %d", code); send_response_code(code); send_webdav_headers(); } diff --git a/esp3d/src/modules/webdav/handlers/handler_lock.cpp b/esp3d/src/modules/webdav/handlers/handler_lock.cpp index 011b07ec..d81e25c2 100644 --- a/esp3d/src/modules/webdav/handlers/handler_lock.cpp +++ b/esp3d/src/modules/webdav/handlers/handler_lock.cpp @@ -31,14 +31,15 @@ "" void WebdavServer::handler_lock(const char* url) { - log_esp3d("Processing LOCK"); + esp3d_log("Processing LOCK"); int code = 200; size_t sp = clearPayload(); - log_esp3d("Payload size: %d", sp); + (void)sp; + esp3d_log("Payload size: %d", sp); uint8_t fsType = WebDavFS::getFSType(url); - log_esp3d("FS type of %s : %d", url, fsType); + esp3d_log("FS type of %s : %d", url, fsType); if (!isRoot(url)) { if (WebDavFS::accessFS(fsType)) { if (WebDavFS::exists(url)) { @@ -56,22 +57,22 @@ void WebdavServer::handler_lock(const char* url) { body += LOCK_RESPONSE_BODY_PART_2; // send body send_response(body.c_str()); - log_esp3d("%s", body.c_str()); + esp3d_log("%s", body.c_str()); } else { code = 404; - log_esp3d_e("File not found"); + esp3d_log_e("File not found"); } WebDavFS::releaseFS(fsType); } else { code = 503; - log_esp3d_e("FS not available"); + esp3d_log_e("FS not available"); } } else { code = 400; - log_esp3d_e("Root cannot be locked"); + esp3d_log_e("Root cannot be locked"); } if (code != 200) { - log_esp3d_e("Sending response code %d", code); + esp3d_log_e("Sending response code %d", code); send_response_code(code); send_webdav_headers(); } diff --git a/esp3d/src/modules/webdav/handlers/handler_mkcol.cpp b/esp3d/src/modules/webdav/handlers/handler_mkcol.cpp index d9629b5c..33b8158a 100644 --- a/esp3d/src/modules/webdav/handlers/handler_mkcol.cpp +++ b/esp3d/src/modules/webdav/handlers/handler_mkcol.cpp @@ -24,12 +24,13 @@ #include "../webdav_server.h" void WebdavServer::handler_mkcol(const char* url) { - log_esp3d("Processing MKCOL"); + esp3d_log("Processing MKCOL"); int code = 201; size_t sp = clearPayload(); - log_esp3d("Payload size: %d", sp); + (void)sp; + esp3d_log("Payload size: %d", sp); uint8_t fsType = WebDavFS::getFSType(url); - log_esp3d("FS type of %s : %d", url, fsType); + esp3d_log("FS type of %s : %d", url, fsType); // url cannot be root if (!isRoot(url)) { if (WebDavFS::accessFS(fsType)) { @@ -38,23 +39,23 @@ void WebdavServer::handler_mkcol(const char* url) { // Create dir if (!WebDavFS::mkdir(url)) { code = 500; - log_esp3d_e("Creation failed"); + esp3d_log_e("Creation failed"); } } else { code = 409; - log_esp3d_e("File not found"); + esp3d_log_e("File not found"); } WebDavFS::releaseFS(fsType); } else { code = 503; - log_esp3d_e("FS not available"); + esp3d_log_e("FS not available"); } } else { code = 400; - log_esp3d_e("Root cannot be created"); + esp3d_log_e("Root cannot be created"); } - log_esp3d_e("Sending response code %d", code); + esp3d_log_e("Sending response code %d", code); send_response_code(code); send_webdav_headers(); } diff --git a/esp3d/src/modules/webdav/handlers/handler_move.cpp b/esp3d/src/modules/webdav/handlers/handler_move.cpp index 065daa2c..2ad6b2fb 100644 --- a/esp3d/src/modules/webdav/handlers/handler_move.cpp +++ b/esp3d/src/modules/webdav/handlers/handler_move.cpp @@ -25,12 +25,13 @@ #include "../webdav_server.h" void WebdavServer::handler_move(const char* url) { - log_esp3d("Processing MOVE"); + esp3d_log("Processing MOVE"); int code = 201; size_t sp = clearPayload(); - log_esp3d("Payload size: %d", sp); + (void)sp; + esp3d_log("Payload size: %d", sp); uint8_t fsTypeOrigin = WebDavFS::getFSType(url); - log_esp3d("FS type of %s : %d", url, fsTypeOrigin); + esp3d_log("FS type of %s : %d", url, fsTypeOrigin); String destination = ""; if (hasHeader("Destination")) { destination = getHeader("Destination"); @@ -39,78 +40,78 @@ void WebdavServer::handler_move(const char* url) { destination.startsWith("https://")) { destination = destination.substring(destination.indexOf("/", 8)); destination = destination.substring(destination.indexOf("/")); - log_esp3d("Destination trimmed: %s", destination.c_str()); + esp3d_log("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()); + esp3d_log("Destination: %s", destination.c_str()); uint8_t fsTypeDestination = WebDavFS::getFSType(destination.c_str()); - log_esp3d("FS type of %s : %d", destination.c_str(), fsTypeDestination); + esp3d_log("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"); + esp3d_log_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"); + esp3d_log("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); + esp3d_log("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()); + esp3d_log("Checking if %s exists", destination.c_str()); if (WebDavFS::exists(destination.c_str())) { - log_esp3d("Destination already exists"); + esp3d_log("Destination already exists"); if (!overwrite) { code = 412; - log_esp3d_e("Overwrite not allowed"); + esp3d_log_e("Overwrite not allowed"); } else { - log_esp3d("Overwrite allowed"); + esp3d_log("Overwrite allowed"); code = 204; if (!WebDavFS::remove(destination.c_str())) { code = 500; - log_esp3d_e("Failed to remove %s", destination.c_str()); + esp3d_log_e("Failed to remove %s", destination.c_str()); overwrite = false; } } } else { - log_esp3d("Destination does not exist"); + esp3d_log("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, + esp3d_log_e("Failed to move %s to %s", url, destination.c_str()); } } } else { code = 404; - log_esp3d_e("File not found"); + esp3d_log_e("File not found"); } WebDavFS::releaseFS(fsTypeOrigin); } else { code = 503; - log_esp3d_e("FS not available"); + esp3d_log_e("FS not available"); } } else { code = 400; - log_esp3d_e("Root cannot be deleted"); + esp3d_log_e("Root cannot be deleted"); } } } else { code = 400; - log_esp3d_e("Destination not set"); + esp3d_log_e("Destination not set"); } - log_esp3d_e("Sending response code %d", code); + esp3d_log_e("Sending response code %d", code); send_response_code(code); send_webdav_headers(); } diff --git a/esp3d/src/modules/webdav/handlers/handler_options.cpp b/esp3d/src/modules/webdav/handlers/handler_options.cpp index c59efd32..ee716640 100644 --- a/esp3d/src/modules/webdav/handlers/handler_options.cpp +++ b/esp3d/src/modules/webdav/handlers/handler_options.cpp @@ -24,7 +24,7 @@ #include "../webdav_server.h" void WebdavServer::handler_options(const char* url) { - log_esp3d("Processing OPTIONS"); + esp3d_log("Processing OPTIONS"); clearPayload(); send_response_code(200); send_webdav_headers(); diff --git a/esp3d/src/modules/webdav/handlers/handler_propfind.cpp b/esp3d/src/modules/webdav/handlers/handler_propfind.cpp index 81f77ed7..477a3443 100644 --- a/esp3d/src/modules/webdav/handlers/handler_propfind.cpp +++ b/esp3d/src/modules/webdav/handlers/handler_propfind.cpp @@ -32,29 +32,30 @@ #define PROPFIND_RESPONSE_BODY_FOOTER "" void WebdavServer::handler_propfind(const char* url) { - log_esp3d("Processing PROPFIND"); + esp3d_log("Processing PROPFIND"); int code = 207; String depth = "0"; String requestedDepth = "0"; if (hasHeader("Depth")) { depth = getHeader("Depth"); - log_esp3d("Depth: %s", depth.c_str()); + esp3d_log("Depth: %s", depth.c_str()); requestedDepth = depth; if (depth == "infinity") { depth = "1"; - log_esp3d("Depth set to 1"); + esp3d_log("Depth set to 1"); } } else { - log_esp3d("Depth not set"); + esp3d_log("Depth not set"); } size_t sp = clearPayload(); - log_esp3d("Payload size: %d", sp); + (void)sp; + esp3d_log("Payload size: %d", sp); uint8_t fsType = WebDavFS::getFSType(url); - log_esp3d("FS type of %s : %d", url, fsType); + esp3d_log("FS type of %s : %d", url, fsType); if (WebDavFS::accessFS(fsType)) { - if (WebDavFS::exists(url) || url == "/") { + if (WebDavFS::exists(url) || strcmp(url, "/") == 0) { WebDavFile root = WebDavFS::open(url); if (root) { send_response_code(code); @@ -97,22 +98,22 @@ void WebdavServer::handler_propfind(const char* url) { if (depth == "0") { body += PROPFIND_RESPONSE_BODY_FOOTER; send_response(body.c_str()); - log_esp3d("%s", body.c_str()); + esp3d_log("%s", body.c_str()); } else { send_chunk_content(body.c_str()); - log_esp3d("%s", body.c_str()); + esp3d_log("%s", body.c_str()); if (depth == "1" && root.isDirectory()) { - log_esp3d("Depth 1, parsing directory"); + esp3d_log("Depth 1, parsing directory"); WebDavFile entry = root.openNextFile(); while (entry) { yield(); - log_esp3d("Processing %s from %s", entry.name(), url); + esp3d_log("Processing %s from %s", entry.name(), url); body = ""; body += ""; body += url; if (strcmp(url, "/") != 0) { body += "/"; - log_esp3d("Adding / to *%s*", url); + esp3d_log("Adding / to *%s*", url); } body += entry.name()[0] == '/' ? entry.name() + 1 : entry.name(); body += ""; @@ -139,12 +140,12 @@ void WebdavServer::handler_propfind(const char* url) { body += "HTTP/1.1 200 OK"; body += ""; body += ""; - log_esp3d("%s", body.c_str()); + esp3d_log("%s", body.c_str()); send_chunk_content(body.c_str()); entry.close(); entry = root.openNextFile(); } - log_esp3d("%s", PROPFIND_RESPONSE_BODY_FOOTER); + esp3d_log("%s", PROPFIND_RESPONSE_BODY_FOOTER); send_chunk_content(PROPFIND_RESPONSE_BODY_FOOTER); // End of chunk send_chunk_content(""); @@ -153,20 +154,20 @@ void WebdavServer::handler_propfind(const char* url) { root.close(); } else { code = 503; - log_esp3d_e("File not opened"); + esp3d_log_e("File not opened"); } } else { code = 404; - log_esp3d_e("File not found"); + esp3d_log_e("File not found"); } WebDavFS::releaseFS(fsType); } else { code = 503; - log_esp3d_e("FS not available"); + esp3d_log_e("FS not available"); } if (code != 207) { - log_esp3d_e("Sending response code %d", code); + esp3d_log_e("Sending response code %d", code); send_response_code(code); send_webdav_headers(); } diff --git a/esp3d/src/modules/webdav/handlers/handler_proppatch.cpp b/esp3d/src/modules/webdav/handlers/handler_proppatch.cpp index b3f5d56f..97db4cd7 100644 --- a/esp3d/src/modules/webdav/handlers/handler_proppatch.cpp +++ b/esp3d/src/modules/webdav/handlers/handler_proppatch.cpp @@ -24,7 +24,7 @@ #include "../webdav_server.h" void WebdavServer::handler_proppatch(const char* url) { - log_esp3d("Processing PROPPATCH"); + esp3d_log("Processing PROPPATCH"); // No support for the moment, so redirect to propfind handler_propfind(url); } diff --git a/esp3d/src/modules/webdav/handlers/handler_put.cpp b/esp3d/src/modules/webdav/handlers/handler_put.cpp index 80cc3398..9fce0ed2 100644 --- a/esp3d/src/modules/webdav/handlers/handler_put.cpp +++ b/esp3d/src/modules/webdav/handlers/handler_put.cpp @@ -28,16 +28,16 @@ #endif // HTTP_FEATURE void WebdavServer::handler_put(const char* url) { - log_esp3d("Processing PUT"); + esp3d_log("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); + esp3d_log("FS type of %s : %d", url, fsType); if (hasHeader("Content-Length")) { content_length = atoi(getHeader("Content-Length")); - log_esp3d("Content-Length: %d", content_length); + esp3d_log("Content-Length: %d", content_length); } else { - log_esp3d("Content-Length not set"); + esp3d_log("Content-Length not set"); } // url cannot be root @@ -46,13 +46,13 @@ void WebdavServer::handler_put(const char* url) { bool hasError = false; // check if file exists if (WebDavFS::exists(url)) { - log_esp3d("File %s already exists", url); + esp3d_log("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); + esp3d_log_e("File %s is a directory", url); hasError = true; } file.close(); @@ -60,13 +60,13 @@ void WebdavServer::handler_put(const char* url) { // check size available if (WebDavFS::freeBytes(fsType) + file.size() < content_length) { code = 507; - log_esp3d_e("Not enough space"); + esp3d_log_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); + esp3d_log_e("Failed to remove %s", url); hasError = true; } } @@ -74,13 +74,13 @@ void WebdavServer::handler_put(const char* url) { } else { hasError = true; code = 500; - log_esp3d_e("Failed to open %s", url); + esp3d_log_e("Failed to open %s", url); } } else { // check size available if (WebDavFS::freeBytes(fsType) < content_length) { code = 507; - log_esp3d_e("Not enough space"); + esp3d_log_e("Not enough space"); hasError = true; } } @@ -98,11 +98,11 @@ void WebdavServer::handler_put(const char* url) { Esp3dTimout updateWS(2000); #endif // HTTP_FEATURE while (_client.available() && received < content_length) { - Hal::wait(0); + ESP3DHal::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); + esp3d_log_e("Failed to write %s", url); break; } else { received += received_bytes; @@ -118,9 +118,9 @@ void WebdavServer::handler_put(const char* url) { } if (received != content_length) { code = 500; - log_esp3d_e("Failed to write %s", url); + esp3d_log_e("Failed to write %s", url); } else { - log_esp3d("File %s written", url); + esp3d_log("File %s written", url); send_response_code(code); // 201 or 204 send_webdav_headers(); time_t now = time(nullptr); @@ -131,20 +131,20 @@ void WebdavServer::handler_put(const char* url) { file.close(); } else { code = 500; - log_esp3d_e("Failed to open %s for writing", url); + esp3d_log_e("Failed to open %s for writing", url); } } WebDavFS::releaseFS(fsType); } else { code = 503; - log_esp3d_e("FS not available"); + esp3d_log_e("FS not available"); } } else { code = 400; - log_esp3d_e("Root cannot be deleted"); + esp3d_log_e("Root cannot be deleted"); } if (code != 201 && code != 204) { - log_esp3d_e("Sending response code %d", code); + esp3d_log_e("Sending response code %d", code); send_response_code(code); send_webdav_headers(); } diff --git a/esp3d/src/modules/webdav/handlers/handler_unlock.cpp b/esp3d/src/modules/webdav/handlers/handler_unlock.cpp index 208da174..63a4052e 100644 --- a/esp3d/src/modules/webdav/handlers/handler_unlock.cpp +++ b/esp3d/src/modules/webdav/handlers/handler_unlock.cpp @@ -24,31 +24,32 @@ #include "../webdav_server.h" void WebdavServer::handler_unlock(const char* url) { - log_esp3d("Processing UNLOCK"); + esp3d_log("Processing UNLOCK"); int code = 204; size_t sp = clearPayload(); - log_esp3d("Payload size: %d", sp); + (void)sp; + esp3d_log("Payload size: %d", sp); uint8_t fsType = WebDavFS::getFSType(url); - log_esp3d("FS type of %s : %d", url, fsType); + esp3d_log("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"); + esp3d_log_e("File not found"); } WebDavFS::releaseFS(fsType); } else { code = 503; - log_esp3d_e("FS not available"); + esp3d_log_e("FS not available"); } } else { code = 400; - log_esp3d_e("Root cannot be unlocked"); + esp3d_log_e("Root cannot be unlocked"); } - log_esp3d_e("Sending response code %d", code); + esp3d_log_e("Sending response code %d", code); send_response_code(code); send_webdav_headers(); } diff --git a/esp3d/src/modules/webdav/webdav_server.cpp b/esp3d/src/modules/webdav/webdav_server.cpp index 3c77ac62..f4286ac9 100644 --- a/esp3d/src/modules/webdav/webdav_server.cpp +++ b/esp3d/src/modules/webdav/webdav_server.cpp @@ -24,9 +24,9 @@ #include #include -#include "../../core/hal.h" -#include "../../core/settings_esp3d.h" -#include "../../include/version.h" +#include "../../core/esp3d_hal.h" +#include "../../core/esp3d_settings.h" +#include "../../include/esp3d_version.h" #include "../network/netconfig.h" #include "webdav_server.h" @@ -88,11 +88,11 @@ WebdavServer::~WebdavServer() { end(); } */ bool WebdavServer::begin() { end(); - if (Settings_ESP3D::read_byte(ESP_WEBDAV_ON) != 1) { + if (ESP3DSettings::readByte(ESP_WEBDAV_ON) != 1) { return true; } // Get webdav port - _port = Settings_ESP3D::read_uint32(ESP_WEBDAV_PORT); + _port = ESP3DSettings::readUint32(ESP_WEBDAV_PORT); // create instance _tcpServer = new WiFiServer(_port); @@ -121,7 +121,7 @@ void WebdavServer::end() { bool WebdavServer::started() { return _started; } void WebdavServer::handle() { - Hal::wait(0); + ESP3DHal::wait(0); if (isConnected()) { parseRequest(); closeClient(); @@ -136,7 +136,7 @@ void WebdavServer::parseRequest() { _headers.clear(); // read the first line of the request to get the request method, URL and // HTTP - log_esp3d("Parsing new request:\n"); + esp3d_log("Parsing new request:\n"); if (_client.connected() && _client.available()) { bool hasError = false; bool lineIsRead = false; @@ -147,7 +147,7 @@ void WebdavServer::parseRequest() { if (c == -1) { if (timeout.isTimeout()) { hasError = true; - log_esp3d_e("Timeout"); + esp3d_log_e("Timeout"); lineIsRead = true; } } else { @@ -155,7 +155,7 @@ void WebdavServer::parseRequest() { lineIsRead = true; if (has_r != 1) { hasError = true; - log_esp3d_e("Bad line ending"); + esp3d_log_e("Bad line ending"); } } else if (c != '\r') { line += (char)c; @@ -168,16 +168,16 @@ void WebdavServer::parseRequest() { send_response_code(400); send_webdav_headers(); _client.print("\r\n"); // empty line - log_esp3d_e("Bad request line: %s", line.c_str()); + esp3d_log_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); + esp3d_log("Request: %s", line.c_str()); + int pos1 = line.indexOf(' '); + int pos2 = line.indexOf(' ', pos1 + 1); if (pos1 == -1 || pos2 == -1) { send_response_code(400); - log_esp3d_e("Bad request line: %s", line.c_str()); + esp3d_log_e("Bad request line: %s", line.c_str()); send_webdav_headers(); _client.print("\r\n"); // empty line return; @@ -194,7 +194,7 @@ void WebdavServer::parseRequest() { } // if encoded url = urlDecode(url.c_str()); - log_esp3d("url ini: %s", url.c_str()); + esp3d_log("url ini: %s", url.c_str()); if (url != "/" && url[url.length() - 1] == '/') { url = url.substring(0, url.length() - 1); } @@ -202,7 +202,7 @@ void WebdavServer::parseRequest() { if (url[0] != '/') { url = "/" + url; } - log_esp3d("url clean: %s", url.c_str()); + esp3d_log("url clean: %s", url.c_str()); // Now list all headers bool headers_read = false; @@ -216,7 +216,7 @@ void WebdavServer::parseRequest() { if (c == -1) { if (timeout.isTimeout()) { hasError = true; - log_esp3d_e("Timeout"); + esp3d_log_e("Timeout"); lineIsRead = true; } } else { @@ -224,7 +224,7 @@ void WebdavServer::parseRequest() { lineIsRead = true; if (has_r != 1) { hasError = true; - log_esp3d_e("Bad line ending %d r, %s", has_r, line.c_str()); + esp3d_log_e("Bad line ending %d r, %s", has_r, line.c_str()); } } else if (c != '\r') { line += (char)c; @@ -233,12 +233,12 @@ void WebdavServer::parseRequest() { } } } - log_esp3d("Line: %s", line.c_str()); + esp3d_log("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()); + esp3d_log_e("Bad request line: %s", line.c_str()); return; } if (line.length() == 0) { @@ -249,7 +249,7 @@ void WebdavServer::parseRequest() { 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()); + esp3d_log("Header: %s = %s", header_name.c_str(), header_value.c_str()); _headers.push_back(std::make_pair(header_name, header_value)); } } @@ -260,11 +260,11 @@ void WebdavServer::parseRequest() { bool WebdavServer::send_response_code(int code) { if (_headers_sent) { - log_esp3d_e("Headers already sent"); + esp3d_log_e("Headers already sent"); return false; } if (_response_code_sent) { - log_esp3d_e("Response code already sent"); + esp3d_log_e("Response code already sent"); return false; } @@ -324,7 +324,7 @@ bool WebdavServer::send_response_code(int code) { default: _client.print("Unknown"); _client.print("\r\n\r\n"); - log_esp3d_e("Unknown code %d", code); + esp3d_log_e("Unknown code %d", code); return false; break; } @@ -362,14 +362,14 @@ const char* WebdavServer::urlDecode(const char* url) { decoded[p] = 0x0; return decoded; } else { - log_esp3d_e("Can't allocate memory for decoded url"); + esp3d_log_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"); + esp3d_log_e("Headers already sent"); return false; } if (!_response_code_sent) { @@ -384,7 +384,7 @@ bool WebdavServer::send_header(const char* name, const char* value) { bool WebdavServer::send_webdav_headers() { if (_headers_sent) { - log_esp3d_e("Headers already sent"); + esp3d_log_e("Headers already sent"); return false; } if (!_response_code_sent) { @@ -400,7 +400,7 @@ bool WebdavServer::send_webdav_headers() { static String host = ""; if (ua.length() == 0) { ua = "ESP3D-WebdavServer/1.0 ("; - ua += Settings_ESP3D::TargetBoard(); + ua += ESP3DSettings::TargetBoard(); ua += "; Firmware/"; ua += FW_VERSION; ua += "; Platform/arduino; Embedded; http://www.esp3d.io)"; @@ -424,7 +424,7 @@ 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"); + esp3d_log_e("Can't send chunked header"); return false; } _headers_sent = true; @@ -455,8 +455,8 @@ bool WebdavServer::send_response(const char* response) { } bool WebdavServer::selectHandler(const char* method, const char* url) { - log_esp3d("Method: %s", method); - log_esp3d("URL: %s", url); + esp3d_log("Method: %s", method); + esp3d_log("URL: %s", url); if (strcasecmp(method, "OPTIONS") == 0) { handler_options(url); return true; @@ -505,7 +505,7 @@ bool WebdavServer::selectHandler(const char* method, const char* url) { handler_proppatch(url); return true; } - log_esp3d_e("Unknown method %s for %s", method, url); + esp3d_log_e("Unknown method %s for %s", method, url); send_response_code(405); send_webdav_headers(); _client.print("\r\n"); // empty line @@ -525,7 +525,7 @@ 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()); + esp3d_log("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; @@ -541,7 +541,7 @@ const char* WebdavServer::getHeader(const char* 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()); + esp3d_log("Header %s found value %s", name, header.second.c_str()); res = header.second; return res.c_str(); } diff --git a/esp3d/src/modules/websocket/websocket_server.cpp b/esp3d/src/modules/websocket/websocket_server.cpp index 769306ff..55dbc2e9 100644 --- a/esp3d/src/modules/websocket/websocket_server.cpp +++ b/esp3d/src/modules/websocket/websocket_server.cpp @@ -20,25 +20,28 @@ #include "../../include/esp3d_config.h" -#if defined(HTTP_FEATURE) || defined(WS_DATA_FEATURE) +#if defined(HTTP_FEATURE) || defined(WS_DATA_FEATURE) || \ + (defined(ESP_LOG_FEATURE) && ESP_LOG_FEATURE == LOG_OUTPUT_WEBSOCKET) #include -#include "../../core/commands.h" -#include "../../core/esp3doutput.h" -#include "../../core/settings_esp3d.h" +#include "../../core/esp3d_commands.h" +#include "../../core/esp3d_message.h" +#include "../../core/esp3d_settings.h" #include "../authentication/authentication_service.h" #include "websocket_server.h" -WebSocket_Server websocket_terminal_server("webui-v3"); +WebSocket_Server websocket_terminal_server("webui-v3", + ESP3DClientType::webui_websocket); #if defined(WS_DATA_FEATURE) -WebSocket_Server websocket_data_server("arduino"); +WebSocket_Server websocket_data_server("arduino", ESP3DClientType::websocket); #endif // WS_DATA_FEATURE -void WebSocket_Server::pushMSG(const char *data) { +bool WebSocket_Server::pushMSG(const char *data) { if (_websocket_server) { - _websocket_server->broadcastTXT(data); - log_esp3d("[%u]Broadcast %s", _current_id, data); + esp3d_log("[%u]Broadcast %s", _current_id, data); + return _websocket_server->broadcastTXT(data); } + return false; } void WebSocket_Server::enableOnly(uint num) { @@ -51,11 +54,34 @@ void WebSocket_Server::enableOnly(uint num) { } } -void WebSocket_Server::pushMSG(uint num, const char *data) { - if (_websocket_server) { - _websocket_server->sendTXT(num, data); - log_esp3d("[%u]Send %s", num, data); +bool WebSocket_Server::dispatch(ESP3DMessage *message) { + if (!message || !_started) { + return false; } + if (message->size > 0 && message->data) { + size_t sentcnt = writeBytes(message->data, message->size); + if (sentcnt != message->size) { + return false; + } + ESP3DMessageManager::deleteMsg(message); + return true; + } + return false; +} + +bool WebSocket_Server::pushMSG(uint num, const char *data) { + if (_websocket_server) { + esp3d_log("[%u]Send %s", num, data); + return _websocket_server->sendTXT(num, data); + } + return false; +} + +bool WebSocket_Server::isConnected(){ + if (_websocket_server) { + return _websocket_server->connectedClients(true) > 0; + } + return false; } void WebSocket_Server::closeClients() { @@ -70,20 +96,21 @@ void handle_Websocket_Server_Event(uint8_t num, uint8_t type, uint8_t *payload, (void)num; switch (type) { case WStype_DISCONNECTED: - log_esp3d("[%u] Disconnected! port %d", num, + esp3d_log("[%u] Disconnected! port %d", num, websocket_data_server.port()); break; case WStype_CONNECTED: { - log_esp3d("[%u] Connected! port %d, %s", num, + websocket_data_server.initAuthentication(); + esp3d_log("[%u] Connected! port %d, %s", num, websocket_data_server.port(), payload); } break; case WStype_TEXT: - log_esp3d("[%u] get Text: %s port %d", num, payload, + esp3d_log("[%u] get Text: %s port %d", num, payload, websocket_data_server.port()); websocket_data_server.push2RXbuffer(payload, length); break; case WStype_BIN: - log_esp3d("[%u] get binary length: %u port %d", num, length, + esp3d_log("[%u] get binary length: %u port %d", num, length, websocket_data_server.port()); websocket_data_server.push2RXbuffer(payload, length); break; @@ -101,11 +128,11 @@ void handle_Websocket_Terminal_Event(uint8_t num, uint8_t type, String msg; switch (type) { case WStype_DISCONNECTED: - log_esp3d("[%u] Socket Disconnected port %d!", num, + esp3d_log("[%u] Socket Disconnected port %d!", num, websocket_terminal_server.port()); break; case WStype_CONNECTED: { - log_esp3d("[%u] Connected! port %d, %s", num, + esp3d_log("[%u] Connected! port %d, %s", num, websocket_terminal_server.port(), (const char *)payload); msg = "currentID:" + String(num); // send message to client @@ -114,7 +141,7 @@ void handle_Websocket_Terminal_Event(uint8_t num, uint8_t type, msg = "activeID:" + String(num); websocket_terminal_server.pushMSG(msg.c_str()); websocket_terminal_server.enableOnly(num); - log_esp3d("[%u] Socket connected port %d", num, + esp3d_log("[%u] Socket connected port %d", num, websocket_terminal_server.port()); } break; case WStype_TEXT: @@ -132,13 +159,13 @@ void handle_Websocket_Terminal_Event(uint8_t num, uint8_t type, } } #endif // AUTHENTICATION_FEATURE - // log_esp3d("[IGNORED][%u] get Text: %s port %d", num, payload, + // esp3d_log("[IGNORED][%u] get Text: %s port %d", num, payload, // websocket_terminal_server.port()); break; case WStype_BIN: // we do not expect any input - // log_esp3d("[IGNORED][%u] get binary length: %u port %d", num, length, - // websocket_terminal_server.port()); + // esp3d_log("[IGNORED][%u] get binary length: %u port %d", num, + // length, websocket_terminal_server.port()); break; default: break; @@ -150,7 +177,7 @@ int WebSocket_Server::available() { return _RXbufferSize; } int WebSocket_Server::availableForWrite() { return TXBUFFERSIZE - _TXbufferSize; } -WebSocket_Server::WebSocket_Server(const char *protocol) { +WebSocket_Server::WebSocket_Server(const char *protocol, ESP3DClientType type) { _websocket_server = nullptr; _started = false; _port = 0; @@ -158,15 +185,17 @@ WebSocket_Server::WebSocket_Server(const char *protocol) { _RXbuffer = nullptr; _RXbufferSize = 0; _protocol = protocol; + _type = type; + initAuthentication(); } WebSocket_Server::~WebSocket_Server() { end(); } bool WebSocket_Server::begin(uint16_t port) { end(); if (port == 0) { - _port = Settings_ESP3D::read_uint32(ESP_HTTP_PORT) + 1; + _port = ESP3DSettings::readUint32(ESP_HTTP_PORT) + 1; } else { _port = port; - if (Settings_ESP3D::read_byte(ESP_WEBSOCKET_ON) == 0) { + if (ESP3DSettings::readByte(ESP_WEBSOCKET_ON) == 0) { return true; } } @@ -209,6 +238,7 @@ void WebSocket_Server::end() { _port = 0; } _started = false; + initAuthentication(); } WebSocket_Server::operator bool() const { return _started; } @@ -218,9 +248,9 @@ void WebSocket_Server::set_currentID(uint8_t current_id) { } uint8_t WebSocket_Server::get_currentID() { return _current_id; } -size_t WebSocket_Server::write(uint8_t c) { return write(&c, 1); } +// size_t WebSocket_Server::write(uint8_t c) { return write(&c, 1); } -size_t WebSocket_Server::write(const uint8_t *buffer, size_t size) { +size_t WebSocket_Server::writeBytes(const uint8_t *buffer, size_t size) { if (_started) { if ((buffer == nullptr) || (!_websocket_server) || (size == 0)) { return 0; @@ -280,21 +310,35 @@ void WebSocket_Server::push2RXbuffer(uint8_t *sbuf, size_t len) { } } +void WebSocket_Server::initAuthentication() { +#if defined(AUTHENTICATION_FEATURE) + _auth = ESP3DAuthenticationLevel::guest; +#else + _auth = ESP3DAuthenticationLevel::admin; +#endif // AUTHENTICATION_FEATURE +} +ESP3DAuthenticationLevel WebSocket_Server::getAuthentication() { return _auth; } + void WebSocket_Server::flushRXbuffer() { if (!_RXbuffer || !_started) { _RXbufferSize = 0; return; } - ESP3DOutput output(ESP_WEBSOCKET_CLIENT); _RXbuffer[_RXbufferSize] = 0x0; - // dispatch command - esp3d_commands.process(_RXbuffer, _RXbufferSize, &output); + ESP3DMessage *msg = ESP3DMessageManager::newMsg( + _type, esp3d_commands.getOutputClient(), _RXbuffer, _RXbufferSize, _auth); + if (msg) { + // process command + esp3d_commands.process(msg); + } else { + esp3d_log_e("Cannot create message"); + } _lastRXflush = millis(); _RXbufferSize = 0; } void WebSocket_Server::handle() { - Hal::wait(0); + ESP3DHal::wait(0); if (_started) { if (_TXbufferSize > 0) { if ((_TXbufferSize >= TXBUFFERSIZE) || @@ -324,7 +368,7 @@ void WebSocket_Server::flushTXbuffer(void) { if ((_TXbufferSize > 0) && (_websocket_server->connectedClients() > 0)) { if (_websocket_server) { _websocket_server->broadcastBIN(_TXbuffer, _TXbufferSize); - log_esp3d("WS Broadcast bin port %d: %d bytes", port(), _TXbufferSize); + esp3d_log("WS Broadcast bin port %d: %d bytes", port(), _TXbufferSize); } // refresh timout _lastTXflush = millis(); diff --git a/esp3d/src/modules/websocket/websocket_server.h b/esp3d/src/modules/websocket/websocket_server.h index ddfd1660..64794324 100644 --- a/esp3d/src/modules/websocket/websocket_server.h +++ b/esp3d/src/modules/websocket/websocket_server.h @@ -18,92 +18,65 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - #ifndef _WEBSOCKET_SERVER_H_ #define _WEBSOCKET_SERVER_H_ -#include "Print.h" +#include "../../core/esp3d_message.h" #define TXBUFFERSIZE 1200 #define RXBUFFERSIZE 256 #define FLUSHTIMEOUT 500 class WebSocketsServer; -class WebSocket_Server: public Print -{ -public: - WebSocket_Server(const char* protocol="arduino"); - ~WebSocket_Server(); - size_t write(uint8_t c); - size_t write(const uint8_t *buffer, size_t size); +class WebSocket_Server { + public: + WebSocket_Server(const char *protocol = "arduino", + ESP3DClientType type = ESP3DClientType::websocket); + ~WebSocket_Server(); + size_t writeBytes(const uint8_t *buffer, size_t size); + bool begin(uint16_t port = 0); + uint16_t port() { return _port; } + void end(); + int available(); + int availableForWrite(); + bool pushMSG(const char *data); + bool pushMSG(uint num, const char *data); + bool dispatch(ESP3DMessage *message); + void flush(void); + void handle(); + operator bool() const; + void set_currentID(uint8_t current_id); + uint8_t get_currentID(); + void closeClients(); + void enableOnly(uint num); + bool started() { return _started; } + void push2RXbuffer(uint8_t *sbuf, size_t len); + const char *getProtocol() { return _protocol.c_str(); } + uint16_t getPort() { return _port; } + void initAuthentication(); + void setAuthentication(ESP3DAuthenticationLevel auth) { _auth = auth; } + ESP3DAuthenticationLevel getAuthentication(); + bool isConnected(); - inline size_t write(const char * s) - { - return write((uint8_t*) s, strlen(s)); - } - inline size_t write(unsigned long n) - { - return write((uint8_t) n); - } - inline size_t write(long n) - { - return write((uint8_t) n); - } - inline size_t write(unsigned int n) - { - return write((uint8_t) n); - } - inline size_t write(int n) - { - return write((uint8_t) n); - } - bool begin(uint16_t port=0); - uint16_t port() - { - return _port; - } - void end(); - int available(); - int availableForWrite(); - void pushMSG (const char * data); - void pushMSG (uint num, const char * data); - void flush(void); - void handle(); - operator bool() const; - void set_currentID(uint8_t current_id); - uint8_t get_currentID(); - void closeClients(); - void enableOnly (uint num); - bool started() - { - return _started; - } - void push2RXbuffer(uint8_t * sbuf, size_t len); - const char * getProtocol() - { - return _protocol.c_str(); - } - uint16_t getPort() - { - return _port; - } -private: - bool _started; - uint16_t _port; - uint32_t _lastTXflush; - uint32_t _lastRXflush; - WebSocketsServer * _websocket_server; - String _protocol; - uint8_t _TXbuffer[TXBUFFERSIZE]; - uint16_t _TXbufferSize; - uint8_t _current_id; - void flushTXbuffer(); - void flushRXbuffer(); - uint8_t *_RXbuffer; - uint16_t _RXbufferSize; + private: + ESP3DClientType _type; + ESP3DAuthenticationLevel _auth; + bool _started; + uint16_t _port; + uint32_t _lastTXflush; + uint32_t _lastRXflush; + WebSocketsServer *_websocket_server; + String _protocol; + uint8_t _TXbuffer[TXBUFFERSIZE]; + uint16_t _TXbufferSize; + uint8_t _current_id; + void flushTXbuffer(); + void flushRXbuffer(); + uint8_t *_RXbuffer; + uint16_t _RXbufferSize; }; extern WebSocket_Server websocket_terminal_server; #if defined(WS_DATA_FEATURE) -extern WebSocket_Server websocket_data_server; -#endif //WS_DATA_FEATURE -#endif //_WEBSOCKET_SERVER_H_ +extern WebSocket_Server websocket_data_server; +#endif // WS_DATA_FEATURE +#endif //_WEBSOCKET_SERVER_H_ diff --git a/esp3d/src/modules/wifi/wificonfig.cpp b/esp3d/src/modules/wifi/wificonfig.cpp index 81c2c7b4..68c69c62 100644 --- a/esp3d/src/modules/wifi/wificonfig.cpp +++ b/esp3d/src/modules/wifi/wificonfig.cpp @@ -25,13 +25,16 @@ #endif // ARDUINO_ARCH_ESP32 #ifdef ARDUINO_ARCH_ESP8266 #endif // ARDUINO_ARCH_ESP8266 -#include "../../core/esp3doutput.h" -#include "../../core/settings_esp3d.h" +#include "../../core/esp3d_commands.h" +#include "../../core/esp3d_settings.h" #include "../network/netconfig.h" #include "../wifi/wificonfig.h" const uint8_t DEFAULT_AP_MASK_VALUE[] = {255, 255, 255, 0}; +IPAddress WiFiConfig::_ap_gateway; +IPAddress WiFiConfig::_ap_subnet; + const char* WiFiConfig::hostname() { static String tmp; #if defined(ARDUINO_ARCH_ESP8266) @@ -80,12 +83,12 @@ bool WiFiConfig::ConnectSTA2AP() { uint8_t count = 0; uint8_t dot = 0; wl_status_t status = WiFi.status(); - ESP3DOutput output(ESP_ALL_CLIENTS); - log_esp3d("Connecting"); + esp3d_log("Connecting"); #if COMMUNICATION_PROTOCOL != MKS_SERIAL - if (!Settings_ESP3D::isVerboseBoot()) { - output.printMSG("Connecting"); - output.flush(); + if (!ESP3DSettings::isVerboseBoot()) { + esp3d_commands.dispatch("Connecting", ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } #endif // #if COMMUNICATION_PROTOCOL == MKS_SERIAL while (status != WL_CONNECTED && count < 40) { @@ -105,15 +108,16 @@ bool WiFiConfig::ConnectSTA2AP() { } msg_out += "."; msg = msg_out; - log_esp3d("..."); + esp3d_log("..."); dot++; break; } - if (Settings_ESP3D::isVerboseBoot()) { - output.printMSG(msg.c_str()); - output.flush(); + if (ESP3DSettings::isVerboseBoot()) { + esp3d_commands.dispatch(msg.c_str(), ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } - Hal::wait(500); + ESP3DHal::wait(500); count++; status = WiFi.status(); } @@ -124,7 +128,7 @@ bool WiFiConfig::ConnectSTA2AP() { * Start client mode (Station) */ bool WiFiConfig::StartSTA() { - log_esp3d("StartSTA"); + esp3d_log("StartSTA"); if ((WiFi.getMode() == WIFI_AP) || (WiFi.getMode() == WIFI_AP_STA)) { WiFi.softAPdisconnect(); } @@ -138,23 +142,24 @@ bool WiFiConfig::StartSTA() { WiFi.setSortMethod(WIFI_CONNECT_AP_BY_SIGNAL); #endif // ARDUINO_ARCH_ESP32 // Get parameters for STA - String SSID = Settings_ESP3D::read_string(ESP_STA_SSID); - String password = Settings_ESP3D::read_string(ESP_STA_PASSWORD); + String SSID = ESP3DSettings::readString(ESP_STA_SSID); + String password = ESP3DSettings::readString(ESP_STA_PASSWORD); - if (Settings_ESP3D::read_byte(ESP_STA_IP_MODE) != DHCP_MODE) { - int32_t IP = Settings_ESP3D::read_IP(ESP_STA_IP_VALUE); - int32_t GW = Settings_ESP3D::read_IP(ESP_STA_GATEWAY_VALUE); - int32_t MK = Settings_ESP3D::read_IP(ESP_STA_MASK_VALUE); - int32_t DNS = Settings_ESP3D::read_IP(ESP_STA_DNS_VALUE); + if (ESP3DSettings::readByte(ESP_STA_IP_MODE) != DHCP_MODE) { + int32_t IP = ESP3DSettings::read_IP(ESP_STA_IP_VALUE); + int32_t GW = ESP3DSettings::read_IP(ESP_STA_GATEWAY_VALUE); + int32_t MK = ESP3DSettings::read_IP(ESP_STA_MASK_VALUE); + int32_t DNS = ESP3DSettings::read_IP(ESP_STA_DNS_VALUE); IPAddress ip(IP), mask(MK), gateway(GW), dns(DNS); WiFi.config(ip, gateway, mask, dns); } - ESP3DOutput output(ESP_ALL_CLIENTS); - if (Settings_ESP3D::isVerboseBoot()) { + + if (ESP3DSettings::isVerboseBoot()) { String stmp; stmp = "Connecting to '" + SSID + "'"; - ; - output.printMSG(stmp.c_str()); + esp3d_commands.dispatch(stmp.c_str(), ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } if (WiFi.begin(SSID.c_str(), (password.length() > 0) ? password.c_str() : nullptr)) { @@ -168,7 +173,7 @@ bool WiFiConfig::StartSTA() { #endif // ARDUINO_ARCH_ESP32 return ConnectSTA2AP(); } else { - output.printERROR("Starting client failed"); + esp3d_log_e("Starting client failed"); return false; } } @@ -178,7 +183,6 @@ bool WiFiConfig::StartSTA() { */ bool WiFiConfig::StartAP(bool setupMode) { - ESP3DOutput output(ESP_ALL_CLIENTS); // Sanity check if ((WiFi.getMode() == WIFI_STA) || (WiFi.getMode() == WIFI_AP_STA)) { if (WiFi.isConnected()) { @@ -196,25 +200,35 @@ bool WiFiConfig::StartAP(bool setupMode) { WiFi.setSleepMode(WIFI_NONE_SLEEP); #endif // ARDUINO_ARCH_ESP8266 - String SSID = Settings_ESP3D::read_string(ESP_AP_SSID); - String password = Settings_ESP3D::read_string(ESP_AP_PASSWORD); + String SSID = ESP3DSettings::readString(ESP_AP_SSID); + String password = ESP3DSettings::readString(ESP_AP_PASSWORD); // channel - int8_t channel = Settings_ESP3D::read_byte(ESP_AP_CHANNEL); + int8_t channel = ESP3DSettings::readByte(ESP_AP_CHANNEL); // IP - int32_t IP = Settings_ESP3D::read_IP(ESP_AP_IP_VALUE); + int32_t IP = ESP3DSettings::read_IP(ESP_AP_IP_VALUE); IPAddress ip(IP); IPAddress gw(0, 0, 0, 0); IPAddress mask(DEFAULT_AP_MASK_VALUE); #if defined(ARDUINO_ARCH_ESP8266) - log_esp3d("Use: %s / %s / %s", ip.toString().c_str(), ip.toString().c_str(), + esp3d_log("Use: %s / %s / %s", ip.toString().c_str(), ip.toString().c_str(), mask.toString().c_str()); if (!WiFi.softAPConfig(ip, setupMode ? ip : gw, mask)) { - output.printERROR("Set IP to AP failed"); + esp3d_log_e("Set IP to AP failed"); + esp3d_commands.dispatch("Set IP to AP failed", ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } else { - output.printMSG(ip.toString().c_str()); + esp3d_commands.dispatch(ip.toString().c_str(), ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } + _ap_gateway = setupMode ? ip : gw; + _ap_subnet = mask; #endif // ARDUINO_ARCH_ESP8266 + // Start AP if (WiFi.softAP(SSID.c_str(), (password.length() > 0) ? password.c_str() : nullptr, @@ -228,28 +242,42 @@ bool WiFiConfig::StartAP(bool setupMode) { if (setupMode) { stmp += " (setup mode)"; } - output.printMSG(stmp.c_str()); - log_esp3d("%s", stmp.c_str()); + esp3d_commands.dispatch(stmp.c_str(), ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); + esp3d_log("%s", stmp.c_str()); #if defined(ARDUINO_ARCH_ESP32) // must be done after starting AP not before // https://github.com/espressif/arduino-esp32/issues/4222 // on some phone 100 is ok but on some other it is not enough so 2000 is ok - Hal::wait(2000); + ESP3DHal::wait(2000); // Set static IP - log_esp3d("Use: %s / %s / %s", ip.toString().c_str(), ip.toString().c_str(), + esp3d_log("Use: %s / %s / %s", ip.toString().c_str(), ip.toString().c_str(), mask.toString().c_str()); if (!WiFi.softAPConfig(ip, setupMode ? ip : gw, mask)) { - output.printERROR("Set IP to AP failed"); + esp3d_log_e("Set IP to AP failed"); + esp3d_commands.dispatch("Set IP to AP failed", + ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } else { - output.printMSG(ip.toString().c_str()); + esp3d_commands.dispatch(ip.toString().c_str(), + ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } WiFi.setSleep(false); WiFi.softAPsetHostname(NetConfig::hostname(true)); + _ap_gateway = setupMode ? ip : gw; + _ap_subnet = mask; #endif // ARDUINO_ARCH_ESP32 return true; } else { - output.printERROR("Starting AP failed"); - log_esp3d_e("Starting AP failed"); + esp3d_commands.dispatch("Starting AP failed", ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); + esp3d_log_e("Starting AP failed"); return false; } } @@ -262,27 +290,32 @@ bool WiFiConfig::started() { return (WiFi.getMode() != WIFI_OFF); } bool WiFiConfig::begin(int8_t& espMode) { bool res = false; end(); - log_esp3d("Starting Wifi Config"); - ESP3DOutput output(ESP_ALL_CLIENTS); - if (Settings_ESP3D::isVerboseBoot()) { - output.printMSG("Starting WiFi"); + esp3d_log("Starting Wifi Config"); + if (ESP3DSettings::isVerboseBoot()) { + esp3d_commands.dispatch("Starting WiFi", ESP3DClientType::all_clients, + no_id, ESP3DMessageType::unique, + ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } int8_t wifiMode = espMode; if (wifiMode == ESP_WIFI_AP || wifiMode == ESP_AP_SETUP) { - log_esp3d("Starting AP mode"); + esp3d_log("Starting AP mode"); res = StartAP(wifiMode == ESP_AP_SETUP); } else if (wifiMode == ESP_WIFI_STA) { - log_esp3d("Starting STA"); + esp3d_log("Starting STA"); res = StartSTA(); // AP is backup mode if (!res) { - if (Settings_ESP3D::isVerboseBoot()) { - output.printMSG("Starting fallback mode"); + if (ESP3DSettings::isVerboseBoot()) { + esp3d_commands.dispatch( + "Starting fallback mode", ESP3DClientType::all_clients, no_id, + ESP3DMessageType::unique, ESP3DClientType::system, + ESP3DAuthenticationLevel::admin); } - espMode = Settings_ESP3D::read_byte(ESP_STA_FALLBACK_MODE); + espMode = ESP3DSettings::readByte(ESP_STA_FALLBACK_MODE); NetConfig::setMode(espMode); if (espMode == ESP_AP_SETUP) { - log_esp3d("Starting AP mode in setup mode"); + esp3d_log("Starting AP mode in setup mode"); res = StartAP(true); } else { // let setup to handle the change @@ -434,7 +467,7 @@ const char* WiFiConfig::AP_Gateway_String() { #ifdef ARDUINO_ARCH_ESP8266 struct ip_info ip_AP; if (!wifi_get_ip_info(SOFTAP_IF, &ip_AP)) { - log_esp3d_e("Error getting gateway ip"); + esp3d_log_e("Error getting gateway ip"); } tmp = IPAddress(ip_AP.gw).toString(); #endif // ARDUINO_ARCH_ESP8266 @@ -451,7 +484,7 @@ const char* WiFiConfig::AP_Mask_String() { #ifdef ARDUINO_ARCH_ESP8266 struct ip_info ip_AP; if (!wifi_get_ip_info(SOFTAP_IF, &ip_AP)) { - log_esp3d_e("Error getting mask ip"); + esp3d_log_e("Error getting mask ip"); } tmp = IPAddress(ip_AP.netmask).toString(); #endif // ARDUINO_ARCH_ESP8266 diff --git a/esp3d/src/modules/wifi/wificonfig.h b/esp3d/src/modules/wifi/wificonfig.h index 21c1d5e5..9c6df443 100644 --- a/esp3d/src/modules/wifi/wificonfig.h +++ b/esp3d/src/modules/wifi/wificonfig.h @@ -72,9 +72,13 @@ class WiFiConfig { static bool begin(int8_t& espMode); static void end(); static void handle(); + static IPAddress getAPGateway() { return _ap_gateway; } + static IPAddress getAPSubnet() { return _ap_subnet; } private: static bool ConnectSTA2AP(); + static IPAddress _ap_gateway; + static IPAddress _ap_subnet; }; #endif //_WIFI_CONFIG_H diff --git a/libraries/lvgl-8.2.0/Kconfig b/libraries/lvgl-8.2.0/Kconfig index 8fe14ec1..2d04faf4 100644 --- a/libraries/lvgl-8.2.0/Kconfig +++ b/libraries/lvgl-8.2.0/Kconfig @@ -264,7 +264,7 @@ menu "LVGL configuration" bool "Log if something unwanted happened but didn't cause a problem" config LV_LOG_LEVEL_ERROR bool "Only critical issues, when the system may fail" - config LV_LOG_LEVEL_USER + config LV_LOG_user bool "Only logs added by the user" config LV_LOG_LEVEL_NONE bool "Do not log anything" @@ -276,7 +276,7 @@ menu "LVGL configuration" default 1 if LV_LOG_LEVEL_INFO default 2 if LV_LOG_LEVEL_WARN default 3 if LV_LOG_LEVEL_ERROR - default 4 if LV_LOG_LEVEL_USER + default 4 if LV_LOG_user default 5 if LV_LOG_LEVEL_NONE config LV_LOG_PRINTF diff --git a/libraries/lvgl-8.2.0/docs/porting/log.md b/libraries/lvgl-8.2.0/docs/porting/log.md index fac928d2..5212dc82 100644 --- a/libraries/lvgl-8.2.0/docs/porting/log.md +++ b/libraries/lvgl-8.2.0/docs/porting/log.md @@ -12,7 +12,7 @@ To enable logging, set `LV_USE_LOG 1` in `lv_conf.h` and set `LV_LOG_LEVEL` to - `LV_LOG_LEVEL_INFO` Log important events - `LV_LOG_LEVEL_WARN` Log if something unwanted happened but didn't cause a problem - `LV_LOG_LEVEL_ERROR` Only critical issues, where the system may fail -- `LV_LOG_LEVEL_USER` Only user messages +- `LV_LOG_user` Only user messages - `LV_LOG_LEVEL_NONE` Do not log anything The events which have a higher level than the set log level will be logged too. E.g. if you `LV_LOG_LEVEL_WARN`, errors will be also logged. diff --git a/libraries/lvgl-8.2.0/env_support/cmsis-pack/lv_conf_cmsis.h b/libraries/lvgl-8.2.0/env_support/cmsis-pack/lv_conf_cmsis.h index 6a48b420..4bfb9663 100644 --- a/libraries/lvgl-8.2.0/env_support/cmsis-pack/lv_conf_cmsis.h +++ b/libraries/lvgl-8.2.0/env_support/cmsis-pack/lv_conf_cmsis.h @@ -208,7 +208,7 @@ *LV_LOG_LEVEL_INFO Log important events *LV_LOG_LEVEL_WARN Log if something unwanted happened but didn't cause a problem *LV_LOG_LEVEL_ERROR Only critical issue, when the system may fail - *LV_LOG_LEVEL_USER Only logs added by the user + *LV_LOG_user Only logs added by the user *LV_LOG_LEVEL_NONE Do not log anything*/ #define LV_LOG_LEVEL LV_LOG_LEVEL_WARN diff --git a/libraries/lvgl-8.2.0/lv_conf_template.h b/libraries/lvgl-8.2.0/lv_conf_template.h index c268d269..e5caebea 100644 --- a/libraries/lvgl-8.2.0/lv_conf_template.h +++ b/libraries/lvgl-8.2.0/lv_conf_template.h @@ -202,7 +202,7 @@ *LV_LOG_LEVEL_INFO Log important events *LV_LOG_LEVEL_WARN Log if something unwanted happened but didn't cause a problem *LV_LOG_LEVEL_ERROR Only critical issue, when the system may fail - *LV_LOG_LEVEL_USER Only logs added by the user + *LV_LOG_user Only logs added by the user *LV_LOG_LEVEL_NONE Do not log anything*/ #define LV_LOG_LEVEL LV_LOG_LEVEL_WARN diff --git a/libraries/lvgl-8.2.0/src/core/lv_disp.h b/libraries/lvgl-8.2.0/src/core/lv_disp.h index 01766b34..ee434e3d 100644 --- a/libraries/lvgl-8.2.0/src/core/lv_disp.h +++ b/libraries/lvgl-8.2.0/src/core/lv_disp.h @@ -13,7 +13,7 @@ extern "C" { /********************* * INCLUDES *********************/ -#include "../hal/lv_hal.h" +#include "../hal/lv_esp3d_hal.h" #include "lv_obj.h" #include "lv_theme.h" @@ -26,16 +26,16 @@ extern "C" { **********************/ typedef enum { - LV_SCR_LOAD_ANIM_NONE, - LV_SCR_LOAD_ANIM_OVER_LEFT, - LV_SCR_LOAD_ANIM_OVER_RIGHT, - LV_SCR_LOAD_ANIM_OVER_TOP, - LV_SCR_LOAD_ANIM_OVER_BOTTOM, - LV_SCR_LOAD_ANIM_MOVE_LEFT, - LV_SCR_LOAD_ANIM_MOVE_RIGHT, - LV_SCR_LOAD_ANIM_MOVE_TOP, - LV_SCR_LOAD_ANIM_MOVE_BOTTOM, - LV_SCR_LOAD_ANIM_FADE_ON, + LV_SCR_LOAD_ANIM_NONE, + LV_SCR_LOAD_ANIM_OVER_LEFT, + LV_SCR_LOAD_ANIM_OVER_RIGHT, + LV_SCR_LOAD_ANIM_OVER_TOP, + LV_SCR_LOAD_ANIM_OVER_BOTTOM, + LV_SCR_LOAD_ANIM_MOVE_LEFT, + LV_SCR_LOAD_ANIM_MOVE_RIGHT, + LV_SCR_LOAD_ANIM_MOVE_TOP, + LV_SCR_LOAD_ANIM_MOVE_BOTTOM, + LV_SCR_LOAD_ANIM_FADE_ON, } lv_scr_load_anim_t; /********************** @@ -44,103 +44,110 @@ typedef enum { /** * Return with a pointer to the active screen - * @param disp pointer to display which active screen should be get. (NULL to use the default - * screen) + * @param disp pointer to display which active screen should be get. (NULL to + * use the default screen) * @return pointer to the active screen object (loaded by 'lv_scr_load()') */ -lv_obj_t * lv_disp_get_scr_act(lv_disp_t * disp); +lv_obj_t* lv_disp_get_scr_act(lv_disp_t* disp); /** - * Return with a pointer to the previous screen. Only used during screen transitions. - * @param disp pointer to display which previous screen should be get. (NULL to use the default - * screen) + * Return with a pointer to the previous screen. Only used during screen + * transitions. + * @param disp pointer to display which previous screen should be get. (NULL to + * use the default screen) * @return pointer to the previous screen object or NULL if not used now */ -lv_obj_t * lv_disp_get_scr_prev(lv_disp_t * disp); +lv_obj_t* lv_disp_get_scr_prev(lv_disp_t* disp); /** * Make a screen active * @param scr pointer to a screen */ -void lv_disp_load_scr(lv_obj_t * scr); +void lv_disp_load_scr(lv_obj_t* scr); /** - * Return with the top layer. (Same on every screen and it is above the normal screen layer) - * @param disp pointer to display which top layer should be get. (NULL to use the default screen) + * Return with the top layer. (Same on every screen and it is above the normal + * screen layer) + * @param disp pointer to display which top layer should be get. (NULL to use + * the default screen) * @return pointer to the top layer object (transparent screen sized lv_obj) */ -lv_obj_t * lv_disp_get_layer_top(lv_disp_t * disp); +lv_obj_t* lv_disp_get_layer_top(lv_disp_t* disp); /** - * Return with the sys. layer. (Same on every screen and it is above the normal screen and the top - * layer) - * @param disp pointer to display which sys. layer should be retrieved. (NULL to use the default screen) + * Return with the sys. layer. (Same on every screen and it is above the normal + * screen and the top layer) + * @param disp pointer to display which sys. layer should be retrieved. (NULL to + * use the default screen) * @return pointer to the sys layer object (transparent screen sized lv_obj) */ -lv_obj_t * lv_disp_get_layer_sys(lv_disp_t * disp); +lv_obj_t* lv_disp_get_layer_sys(lv_disp_t* disp); /** * Set the theme of a display * @param disp pointer to a display */ -void lv_disp_set_theme(lv_disp_t * disp, lv_theme_t * th); +void lv_disp_set_theme(lv_disp_t* disp, lv_theme_t* th); /** * Get the theme of a display * @param disp pointer to a display * @return the display's theme (can be NULL) */ -lv_theme_t * lv_disp_get_theme(lv_disp_t * disp); +lv_theme_t* lv_disp_get_theme(lv_disp_t* disp); /** * Set the background color of a display * @param disp pointer to a display * @param color color of the background */ -void lv_disp_set_bg_color(lv_disp_t * disp, lv_color_t color); +void lv_disp_set_bg_color(lv_disp_t* disp, lv_color_t color); /** * Set the background image of a display * @param disp pointer to a display * @param img_src path to file or pointer to an `lv_img_dsc_t` variable */ -void lv_disp_set_bg_image(lv_disp_t * disp, const void * img_src); +void lv_disp_set_bg_image(lv_disp_t* disp, const void* img_src); /** * Set opacity of the background * @param disp pointer to a display * @param opa opacity (0..255) */ -void lv_disp_set_bg_opa(lv_disp_t * disp, lv_opa_t opa); +void lv_disp_set_bg_opa(lv_disp_t* disp, lv_opa_t opa); /** * Switch screen with animation * @param scr pointer to the new screen to load - * @param anim_type type of the animation from `lv_scr_load_anim_t`. E.g. `LV_SCR_LOAD_ANIM_MOVE_LEFT` + * @param anim_type type of the animation from `lv_scr_load_anim_t`. E.g. + * `LV_SCR_LOAD_ANIM_MOVE_LEFT` * @param time time of the animation * @param delay delay before the transition * @param auto_del true: automatically delete the old screen */ -void lv_scr_load_anim(lv_obj_t * scr, lv_scr_load_anim_t anim_type, uint32_t time, uint32_t delay, bool auto_del); +void lv_scr_load_anim(lv_obj_t* scr, lv_scr_load_anim_t anim_type, + uint32_t time, uint32_t delay, bool auto_del); /** * Get elapsed time since last user activity on a display (e.g. click) - * @param disp pointer to a display (NULL to get the overall smallest inactivity) + * @param disp pointer to a display (NULL to get the overall smallest + * inactivity) * @return elapsed ticks (milliseconds) since the last activity */ -uint32_t lv_disp_get_inactive_time(const lv_disp_t * disp); +uint32_t lv_disp_get_inactive_time(const lv_disp_t* disp); /** * Manually trigger an activity on a display * @param disp pointer to a display (NULL to use the default display) */ -void lv_disp_trig_activity(lv_disp_t * disp); +void lv_disp_trig_activity(lv_disp_t* disp); /** * Clean any CPU cache that is related to the display. * @param disp pointer to a display (NULL to use the default display) */ -void lv_disp_clean_dcache(lv_disp_t * disp); +void lv_disp_clean_dcache(lv_disp_t* disp); /** * Get a pointer to the screen refresher timer to @@ -148,7 +155,7 @@ void lv_disp_clean_dcache(lv_disp_t * disp); * @param disp pointer to a display * @return pointer to the display refresher timer. (NULL on error) */ -lv_timer_t * _lv_disp_get_refr_timer(lv_disp_t * disp); +lv_timer_t* _lv_disp_get_refr_timer(lv_disp_t* disp); /*------------------------------------------------ * To improve backward compatibility @@ -159,33 +166,27 @@ lv_timer_t * _lv_disp_get_refr_timer(lv_disp_t * disp); * Get the active screen of the default display * @return pointer to the active screen */ -static inline lv_obj_t * lv_scr_act(void) -{ - return lv_disp_get_scr_act(lv_disp_get_default()); +static inline lv_obj_t* lv_scr_act(void) { + return lv_disp_get_scr_act(lv_disp_get_default()); } /** * Get the top layer of the default display * @return pointer to the top layer */ -static inline lv_obj_t * lv_layer_top(void) -{ - return lv_disp_get_layer_top(lv_disp_get_default()); +static inline lv_obj_t* lv_layer_top(void) { + return lv_disp_get_layer_top(lv_disp_get_default()); } /** * Get the active screen of the default display * @return pointer to the sys layer */ -static inline lv_obj_t * lv_layer_sys(void) -{ - return lv_disp_get_layer_sys(lv_disp_get_default()); +static inline lv_obj_t* lv_layer_sys(void) { + return lv_disp_get_layer_sys(lv_disp_get_default()); } -static inline void lv_scr_load(lv_obj_t * scr) -{ - lv_disp_load_scr(scr); -} +static inline void lv_scr_load(lv_obj_t* scr) { lv_disp_load_scr(scr); } /********************** * MACROS @@ -211,30 +212,26 @@ static inline void lv_scr_load(lv_obj_t * scr) #endif /** - * Scale the given number of pixels (a distance or size) relative to a 160 DPI display - * considering the DPI of the default display. - * It ensures that e.g. `lv_dpx(100)` will have the same physical size regardless to the - * DPI of the display. + * Scale the given number of pixels (a distance or size) relative to a 160 DPI + * display considering the DPI of the default display. It ensures that e.g. + * `lv_dpx(100)` will have the same physical size regardless to the DPI of the + * display. * @param n the number of pixels to scale * @return `n x current_dpi/160` */ -static inline lv_coord_t lv_dpx(lv_coord_t n) -{ - return LV_DPX(n); -} +static inline lv_coord_t lv_dpx(lv_coord_t n) { return LV_DPX(n); } /** - * Scale the given number of pixels (a distance or size) relative to a 160 DPI display - * considering the DPI of the given display. - * It ensures that e.g. `lv_dpx(100)` will have the same physical size regardless to the - * DPI of the display. + * Scale the given number of pixels (a distance or size) relative to a 160 DPI + * display considering the DPI of the given display. It ensures that e.g. + * `lv_dpx(100)` will have the same physical size regardless to the DPI of the + * display. * @param obj a display whose dpi should be considered * @param n the number of pixels to scale * @return `n x current_dpi/160` */ -static inline lv_coord_t lv_disp_dpx(const lv_disp_t * disp, lv_coord_t n) -{ - return _LV_DPX_CALC(lv_disp_get_dpi(disp), n); +static inline lv_coord_t lv_disp_dpx(const lv_disp_t* disp, lv_coord_t n) { + return _LV_DPX_CALC(lv_disp_get_dpi(disp), n); } #ifdef __cplusplus diff --git a/libraries/lvgl-8.2.0/src/core/lv_obj.c b/libraries/lvgl-8.2.0/src/core/lv_obj.c index 0b5f27a8..227151d1 100644 --- a/libraries/lvgl-8.2.0/src/core/lv_obj.c +++ b/libraries/lvgl-8.2.0/src/core/lv_obj.c @@ -7,41 +7,44 @@ * INCLUDES *********************/ #include "lv_obj.h" -#include "lv_indev.h" -#include "lv_refr.h" -#include "lv_group.h" -#include "lv_disp.h" -#include "lv_theme.h" -#include "../misc/lv_assert.h" -#include "../draw/lv_draw.h" -#include "../misc/lv_anim.h" -#include "../misc/lv_timer.h" -#include "../misc/lv_async.h" -#include "../misc/lv_fs.h" -#include "../misc/lv_gc.h" -#include "../misc/lv_math.h" -#include "../misc/lv_log.h" -#include "../hal/lv_hal.h" -#include "../extra/lv_extra.h" + #include #include +#include "../draw/lv_draw.h" +#include "../extra/lv_extra.h" +#include "../hal/lv_esp3d_hal.h" +#include "../misc/lv_anim.h" +#include "../misc/lv_assert.h" +#include "../misc/lv_async.h" +#include "../misc/lv_fs.h" +#include "../misc/lv_gc.h" +#include "../misc/lv_log.h" +#include "../misc/lv_math.h" +#include "../misc/lv_timer.h" +#include "lv_disp.h" +#include "lv_group.h" +#include "lv_indev.h" +#include "lv_refr.h" +#include "lv_theme.h" + + #if LV_USE_GPU_STM32_DMA2D - #include "../draw/stm32_dma2d/lv_gpu_stm32_dma2d.h" +#include "../draw/stm32_dma2d/lv_gpu_stm32_dma2d.h" #endif #if LV_USE_GPU_NXP_PXP && LV_USE_GPU_NXP_PXP_AUTO_INIT - #include "../gpu/lv_gpu_nxp_pxp.h" - #include "../gpu/lv_gpu_nxp_pxp_osa.h" +#include "../gpu/lv_gpu_nxp_pxp.h" +#include "../gpu/lv_gpu_nxp_pxp_osa.h" #endif /********************* * DEFINES *********************/ #define MY_CLASS &lv_obj_class -#define LV_OBJ_DEF_WIDTH (LV_DPX(100)) -#define LV_OBJ_DEF_HEIGHT (LV_DPX(50)) -#define GRID_DEBUG 0 /*Draw rectangles on grid cells*/ +#define LV_OBJ_DEF_WIDTH (LV_DPX(100)) +#define LV_OBJ_DEF_HEIGHT (LV_DPX(50)) +#define GRID_DEBUG 0 /*Draw rectangles on grid cells*/ #define STYLE_TRANSITION_MAX 32 /********************** @@ -51,14 +54,15 @@ /********************** * STATIC PROTOTYPES **********************/ -static void lv_obj_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj); -static void lv_obj_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj); -static void lv_obj_draw(lv_event_t * e); -static void lv_obj_event(const lv_obj_class_t * class_p, lv_event_t * e); -static void draw_scrollbar(lv_obj_t * obj, lv_draw_ctx_t * draw_ctx); -static lv_res_t scrollbar_init_draw_dsc(lv_obj_t * obj, lv_draw_rect_dsc_t * dsc); -static bool obj_valid_child(const lv_obj_t * parent, const lv_obj_t * obj_to_find); -static void lv_obj_set_state(lv_obj_t * obj, lv_state_t new_state); +static void lv_obj_constructor(const lv_obj_class_t *class_p, lv_obj_t *obj); +static void lv_obj_destructor(const lv_obj_class_t *class_p, lv_obj_t *obj); +static void lv_obj_draw(lv_event_t *e); +static void lv_obj_event(const lv_obj_class_t *class_p, lv_event_t *e); +static void draw_scrollbar(lv_obj_t *obj, lv_draw_ctx_t *draw_ctx); +static lv_res_t scrollbar_init_draw_dsc(lv_obj_t *obj, lv_draw_rect_dsc_t *dsc); +static bool obj_valid_child(const lv_obj_t *parent, + const lv_obj_t *obj_to_find); +static void lv_obj_set_state(lv_obj_t *obj, lv_state_t new_state); /********************** * STATIC VARIABLES @@ -84,125 +88,127 @@ const lv_obj_class_t lv_obj_class = { * GLOBAL FUNCTIONS **********************/ -bool lv_is_initialized(void) -{ - return lv_initialized; -} +bool lv_is_initialized(void) { return lv_initialized; } -void lv_init(void) -{ - /*Do nothing if already initialized*/ - if(lv_initialized) { - LV_LOG_WARN("lv_init: already inited"); - return; - } +void lv_init(void) { + /*Do nothing if already initialized*/ + if (lv_initialized) { + LV_LOG_WARN("lv_init: already inited"); + return; + } - LV_LOG_INFO("begin"); + LV_LOG_INFO("begin"); - /*Initialize the misc modules*/ - lv_mem_init(); + /*Initialize the misc modules*/ + lv_mem_init(); - _lv_timer_core_init(); + _lv_timer_core_init(); - _lv_fs_init(); + _lv_fs_init(); - _lv_anim_core_init(); + _lv_anim_core_init(); - _lv_group_init(); + _lv_group_init(); - lv_draw_init(); + lv_draw_init(); #if LV_USE_GPU_STM32_DMA2D - /*Initialize DMA2D GPU*/ - lv_draw_stm32_dma2d_init(); + /*Initialize DMA2D GPU*/ + lv_draw_stm32_dma2d_init(); #endif #if LV_USE_GPU_NXP_PXP && LV_USE_GPU_NXP_PXP_AUTO_INIT - if(lv_gpu_nxp_pxp_init(&pxp_default_cfg) != LV_RES_OK) { - LV_LOG_ERROR("PXP init error. STOP.\n"); - for(; ;) ; - } + if (lv_gpu_nxp_pxp_init(&pxp_default_cfg) != LV_RES_OK) { + LV_LOG_ERROR("PXP init error. STOP.\n"); + for (;;) + ; + } #endif - _lv_obj_style_init(); - _lv_ll_init(&LV_GC_ROOT(_lv_disp_ll), sizeof(lv_disp_t)); - _lv_ll_init(&LV_GC_ROOT(_lv_indev_ll), sizeof(lv_indev_t)); + _lv_obj_style_init(); + _lv_ll_init(&LV_GC_ROOT(_lv_disp_ll), sizeof(lv_disp_t)); + _lv_ll_init(&LV_GC_ROOT(_lv_indev_ll), sizeof(lv_indev_t)); - /*Initialize the screen refresh system*/ - _lv_refr_init(); + /*Initialize the screen refresh system*/ + _lv_refr_init(); - _lv_img_decoder_init(); + _lv_img_decoder_init(); #if LV_IMG_CACHE_DEF_SIZE - lv_img_cache_set_size(LV_IMG_CACHE_DEF_SIZE); + lv_img_cache_set_size(LV_IMG_CACHE_DEF_SIZE); #endif - /*Test if the IDE has UTF-8 encoding*/ - char * txt = "Á"; + /*Test if the IDE has UTF-8 encoding*/ + char *txt = "Á"; - uint8_t * txt_u8 = (uint8_t *)txt; - if(txt_u8[0] != 0xc3 || txt_u8[1] != 0x81 || txt_u8[2] != 0x00) { - LV_LOG_WARN("The strings have no UTF-8 encoding. Non-ASCII characters won't be displayed."); - } + uint8_t *txt_u8 = (uint8_t *)txt; + if (txt_u8[0] != 0xc3 || txt_u8[1] != 0x81 || txt_u8[2] != 0x00) { + LV_LOG_WARN( + "The strings have no UTF-8 encoding. Non-ASCII characters won't be " + "displayed."); + } - uint32_t endianess_test = 0x11223344; - uint8_t * endianess_test_p = (uint8_t *) &endianess_test; - bool big_endian = endianess_test_p[0] == 0x11 ? true : false; + uint32_t endianess_test = 0x11223344; + uint8_t *endianess_test_p = (uint8_t *)&endianess_test; + bool big_endian = endianess_test_p[0] == 0x11 ? true : false; - if(big_endian) { - LV_ASSERT_MSG(LV_BIG_ENDIAN_SYSTEM == 1, - "It's a big endian system but LV_BIG_ENDIAN_SYSTEM is not enabled in lv_conf.h"); - } - else { - LV_ASSERT_MSG(LV_BIG_ENDIAN_SYSTEM == 0, - "It's a little endian system but LV_BIG_ENDIAN_SYSTEM is enabled in lv_conf.h"); - } + if (big_endian) { + LV_ASSERT_MSG(LV_BIG_ENDIAN_SYSTEM == 1, + "It's a big endian system but LV_BIG_ENDIAN_SYSTEM is not " + "enabled in lv_conf.h"); + } else { + LV_ASSERT_MSG(LV_BIG_ENDIAN_SYSTEM == 0, + "It's a little endian system but LV_BIG_ENDIAN_SYSTEM is " + "enabled in lv_conf.h"); + } #if LV_USE_ASSERT_MEM_INTEGRITY - LV_LOG_WARN("Memory integrity checks are enabled via LV_USE_ASSERT_MEM_INTEGRITY which makes LVGL much slower"); + LV_LOG_WARN( + "Memory integrity checks are enabled via LV_USE_ASSERT_MEM_INTEGRITY " + "which makes LVGL much slower"); #endif #if LV_USE_ASSERT_OBJ - LV_LOG_WARN("Object sanity checks are enabled via LV_USE_ASSERT_OBJ which makes LVGL much slower"); + LV_LOG_WARN( + "Object sanity checks are enabled via LV_USE_ASSERT_OBJ which makes LVGL " + "much slower"); #endif #if LV_USE_ASSERT_STYLE - LV_LOG_WARN("Style sanity checks are enabled that uses more RAM"); + LV_LOG_WARN("Style sanity checks are enabled that uses more RAM"); #endif #if LV_LOG_LEVEL == LV_LOG_LEVEL_TRACE - LV_LOG_WARN("Log level is set to 'Trace' which makes LVGL much slower"); + LV_LOG_WARN("Log level is set to 'Trace' which makes LVGL much slower"); #endif - lv_extra_init(); + lv_extra_init(); - lv_initialized = true; + lv_initialized = true; - LV_LOG_TRACE("finished"); + LV_LOG_TRACE("finished"); } #if LV_ENABLE_GC || !LV_MEM_CUSTOM -void lv_deinit(void) -{ - _lv_gc_clear_roots(); +void lv_deinit(void) { + _lv_gc_clear_roots(); - lv_disp_set_default(NULL); - lv_mem_deinit(); - lv_initialized = false; + lv_disp_set_default(NULL); + lv_mem_deinit(); + lv_initialized = false; - LV_LOG_INFO("lv_deinit done"); + LV_LOG_INFO("lv_deinit done"); #if LV_USE_LOG - lv_log_register_print_cb(NULL); + lv_log_register_print_cb(NULL); #endif } #endif -lv_obj_t * lv_obj_create(lv_obj_t * parent) -{ - LV_LOG_INFO("begin"); - lv_obj_t * obj = lv_obj_class_create_obj(MY_CLASS, parent); - lv_obj_class_init_obj(obj); - return obj; +lv_obj_t *lv_obj_create(lv_obj_t *parent) { + LV_LOG_INFO("begin"); + lv_obj_t *obj = lv_obj_class_create_obj(MY_CLASS, parent); + lv_obj_class_init_obj(obj); + return obj; } /*===================== @@ -213,744 +219,750 @@ lv_obj_t * lv_obj_create(lv_obj_t * parent) * Attribute set *----------------*/ -void lv_obj_add_flag(lv_obj_t * obj, lv_obj_flag_t f) -{ - LV_ASSERT_OBJ(obj, MY_CLASS); +void lv_obj_add_flag(lv_obj_t *obj, lv_obj_flag_t f) { + LV_ASSERT_OBJ(obj, MY_CLASS); - bool was_on_layout = lv_obj_is_layout_positioned(obj); + bool was_on_layout = lv_obj_is_layout_positioned(obj); - if(f & LV_OBJ_FLAG_HIDDEN) lv_obj_invalidate(obj); + if (f & LV_OBJ_FLAG_HIDDEN) lv_obj_invalidate(obj); - obj->flags |= f; + obj->flags |= f; - if(f & LV_OBJ_FLAG_HIDDEN) { - lv_obj_invalidate(obj); - } + if (f & LV_OBJ_FLAG_HIDDEN) { + lv_obj_invalidate(obj); + } - if((was_on_layout != lv_obj_is_layout_positioned(obj)) || (f & (LV_OBJ_FLAG_LAYOUT_1 | LV_OBJ_FLAG_LAYOUT_2))) { - lv_obj_mark_layout_as_dirty(lv_obj_get_parent(obj)); - lv_obj_mark_layout_as_dirty(obj); - } + if ((was_on_layout != lv_obj_is_layout_positioned(obj)) || + (f & (LV_OBJ_FLAG_LAYOUT_1 | LV_OBJ_FLAG_LAYOUT_2))) { + lv_obj_mark_layout_as_dirty(lv_obj_get_parent(obj)); + lv_obj_mark_layout_as_dirty(obj); + } - if(f & LV_OBJ_FLAG_SCROLLABLE) { - lv_area_t hor_area, ver_area; - lv_obj_get_scrollbar_area(obj, &hor_area, &ver_area); - lv_obj_invalidate_area(obj, &hor_area); - lv_obj_invalidate_area(obj, &ver_area); - } + if (f & LV_OBJ_FLAG_SCROLLABLE) { + lv_area_t hor_area, ver_area; + lv_obj_get_scrollbar_area(obj, &hor_area, &ver_area); + lv_obj_invalidate_area(obj, &hor_area); + lv_obj_invalidate_area(obj, &ver_area); + } } -void lv_obj_clear_flag(lv_obj_t * obj, lv_obj_flag_t f) -{ - LV_ASSERT_OBJ(obj, MY_CLASS); +void lv_obj_clear_flag(lv_obj_t *obj, lv_obj_flag_t f) { + LV_ASSERT_OBJ(obj, MY_CLASS); - bool was_on_layout = lv_obj_is_layout_positioned(obj); - if(f & LV_OBJ_FLAG_SCROLLABLE) { - lv_area_t hor_area, ver_area; - lv_obj_get_scrollbar_area(obj, &hor_area, &ver_area); - lv_obj_invalidate_area(obj, &hor_area); - lv_obj_invalidate_area(obj, &ver_area); + bool was_on_layout = lv_obj_is_layout_positioned(obj); + if (f & LV_OBJ_FLAG_SCROLLABLE) { + lv_area_t hor_area, ver_area; + lv_obj_get_scrollbar_area(obj, &hor_area, &ver_area); + lv_obj_invalidate_area(obj, &hor_area); + lv_obj_invalidate_area(obj, &ver_area); + } + + obj->flags &= (~f); + + if (f & LV_OBJ_FLAG_HIDDEN) { + lv_obj_invalidate(obj); + if (lv_obj_is_layout_positioned(obj)) { + lv_obj_mark_layout_as_dirty(lv_obj_get_parent(obj)); + lv_obj_mark_layout_as_dirty(obj); } + } - obj->flags &= (~f); - - if(f & LV_OBJ_FLAG_HIDDEN) { - lv_obj_invalidate(obj); - if(lv_obj_is_layout_positioned(obj)) { - lv_obj_mark_layout_as_dirty(lv_obj_get_parent(obj)); - lv_obj_mark_layout_as_dirty(obj); - } - } - - if((was_on_layout != lv_obj_is_layout_positioned(obj)) || (f & (LV_OBJ_FLAG_LAYOUT_1 | LV_OBJ_FLAG_LAYOUT_2))) { - lv_obj_mark_layout_as_dirty(lv_obj_get_parent(obj)); - } + if ((was_on_layout != lv_obj_is_layout_positioned(obj)) || + (f & (LV_OBJ_FLAG_LAYOUT_1 | LV_OBJ_FLAG_LAYOUT_2))) { + lv_obj_mark_layout_as_dirty(lv_obj_get_parent(obj)); + } } -void lv_obj_add_state(lv_obj_t * obj, lv_state_t state) -{ - LV_ASSERT_OBJ(obj, MY_CLASS); +void lv_obj_add_state(lv_obj_t *obj, lv_state_t state) { + LV_ASSERT_OBJ(obj, MY_CLASS); - lv_state_t new_state = obj->state | state; - if(obj->state != new_state) { - lv_obj_set_state(obj, new_state); - } + lv_state_t new_state = obj->state | state; + if (obj->state != new_state) { + lv_obj_set_state(obj, new_state); + } } -void lv_obj_clear_state(lv_obj_t * obj, lv_state_t state) -{ - LV_ASSERT_OBJ(obj, MY_CLASS); +void lv_obj_clear_state(lv_obj_t *obj, lv_state_t state) { + LV_ASSERT_OBJ(obj, MY_CLASS); - lv_state_t new_state = obj->state & (~state); - if(obj->state != new_state) { - lv_obj_set_state(obj, new_state); - } + lv_state_t new_state = obj->state & (~state); + if (obj->state != new_state) { + lv_obj_set_state(obj, new_state); + } } /*======================= * Getter functions *======================*/ -bool lv_obj_has_flag(const lv_obj_t * obj, lv_obj_flag_t f) -{ - LV_ASSERT_OBJ(obj, MY_CLASS); +bool lv_obj_has_flag(const lv_obj_t *obj, lv_obj_flag_t f) { + LV_ASSERT_OBJ(obj, MY_CLASS); - return (obj->flags & f) == f ? true : false; + return (obj->flags & f) == f ? true : false; } -bool lv_obj_has_flag_any(const lv_obj_t * obj, lv_obj_flag_t f) -{ - LV_ASSERT_OBJ(obj, MY_CLASS); +bool lv_obj_has_flag_any(const lv_obj_t *obj, lv_obj_flag_t f) { + LV_ASSERT_OBJ(obj, MY_CLASS); - return (obj->flags & f) ? true : false; + return (obj->flags & f) ? true : false; } -lv_state_t lv_obj_get_state(const lv_obj_t * obj) -{ - LV_ASSERT_OBJ(obj, MY_CLASS); +lv_state_t lv_obj_get_state(const lv_obj_t *obj) { + LV_ASSERT_OBJ(obj, MY_CLASS); - return obj->state; + return obj->state; } -bool lv_obj_has_state(const lv_obj_t * obj, lv_state_t state) -{ - LV_ASSERT_OBJ(obj, MY_CLASS); +bool lv_obj_has_state(const lv_obj_t *obj, lv_state_t state) { + LV_ASSERT_OBJ(obj, MY_CLASS); - return obj->state & state ? true : false; + return obj->state & state ? true : false; } -void * lv_obj_get_group(const lv_obj_t * obj) -{ - LV_ASSERT_OBJ(obj, MY_CLASS); +void *lv_obj_get_group(const lv_obj_t *obj) { + LV_ASSERT_OBJ(obj, MY_CLASS); - if(obj->spec_attr) return obj->spec_attr->group_p; - else return NULL; + if (obj->spec_attr) + return obj->spec_attr->group_p; + else + return NULL; } /*------------------- * OTHER FUNCTIONS *------------------*/ -void lv_obj_allocate_spec_attr(lv_obj_t * obj) -{ - LV_ASSERT_OBJ(obj, MY_CLASS); +void lv_obj_allocate_spec_attr(lv_obj_t *obj) { + LV_ASSERT_OBJ(obj, MY_CLASS); - if(obj->spec_attr == NULL) { - static uint32_t x = 0; - x++; - obj->spec_attr = lv_mem_alloc(sizeof(_lv_obj_spec_attr_t)); - LV_ASSERT_MALLOC(obj->spec_attr); - if(obj->spec_attr == NULL) return; + if (obj->spec_attr == NULL) { + static uint32_t x = 0; + x++; + obj->spec_attr = lv_mem_alloc(sizeof(_lv_obj_spec_attr_t)); + LV_ASSERT_MALLOC(obj->spec_attr); + if (obj->spec_attr == NULL) return; - lv_memset_00(obj->spec_attr, sizeof(_lv_obj_spec_attr_t)); + lv_memset_00(obj->spec_attr, sizeof(_lv_obj_spec_attr_t)); - obj->spec_attr->scroll_dir = LV_DIR_ALL; - obj->spec_attr->scrollbar_mode = LV_SCROLLBAR_MODE_AUTO; - } + obj->spec_attr->scroll_dir = LV_DIR_ALL; + obj->spec_attr->scrollbar_mode = LV_SCROLLBAR_MODE_AUTO; + } } -bool lv_obj_check_type(const lv_obj_t * obj, const lv_obj_class_t * class_p) -{ - if(obj == NULL) return false; - return obj->class_p == class_p ? true : false; +bool lv_obj_check_type(const lv_obj_t *obj, const lv_obj_class_t *class_p) { + if (obj == NULL) return false; + return obj->class_p == class_p ? true : false; } -bool lv_obj_has_class(const lv_obj_t * obj, const lv_obj_class_t * class_p) -{ - const lv_obj_class_t * obj_class = obj->class_p; - while(obj_class) { - if(obj_class == class_p) return true; - obj_class = obj_class->base_class; +bool lv_obj_has_class(const lv_obj_t *obj, const lv_obj_class_t *class_p) { + const lv_obj_class_t *obj_class = obj->class_p; + while (obj_class) { + if (obj_class == class_p) return true; + obj_class = obj_class->base_class; + } + + return false; +} + +const lv_obj_class_t *lv_obj_get_class(const lv_obj_t *obj) { + return obj->class_p; +} + +bool lv_obj_is_valid(const lv_obj_t *obj) { + lv_disp_t *disp = lv_disp_get_next(NULL); + while (disp) { + uint32_t i; + for (i = 0; i < disp->screen_cnt; i++) { + if (disp->screens[i] == obj) return true; + bool found = obj_valid_child(disp->screens[i], obj); + if (found) return true; } - return false; -} + disp = lv_disp_get_next(disp); + } -const lv_obj_class_t * lv_obj_get_class(const lv_obj_t * obj) -{ - return obj->class_p; -} - -bool lv_obj_is_valid(const lv_obj_t * obj) -{ - lv_disp_t * disp = lv_disp_get_next(NULL); - while(disp) { - uint32_t i; - for(i = 0; i < disp->screen_cnt; i++) { - if(disp->screens[i] == obj) return true; - bool found = obj_valid_child(disp->screens[i], obj); - if(found) return true; - } - - disp = lv_disp_get_next(disp); - } - - return false; + return false; } /********************** * STATIC FUNCTIONS **********************/ -static void lv_obj_constructor(const lv_obj_class_t * class_p, lv_obj_t * obj) -{ - LV_UNUSED(class_p); - LV_TRACE_OBJ_CREATE("begin"); +static void lv_obj_constructor(const lv_obj_class_t *class_p, lv_obj_t *obj) { + LV_UNUSED(class_p); + LV_TRACE_OBJ_CREATE("begin"); - lv_obj_t * parent = obj->parent; - if(parent) { - lv_coord_t sl = lv_obj_get_scroll_left(parent); - lv_coord_t st = lv_obj_get_scroll_top(parent); + lv_obj_t *parent = obj->parent; + if (parent) { + lv_coord_t sl = lv_obj_get_scroll_left(parent); + lv_coord_t st = lv_obj_get_scroll_top(parent); - obj->coords.y1 = parent->coords.y1 + lv_obj_get_style_pad_top(parent, LV_PART_MAIN) - st; - obj->coords.y2 = obj->coords.y1 - 1; - obj->coords.x1 = parent->coords.x1 + lv_obj_get_style_pad_left(parent, LV_PART_MAIN) - sl; - obj->coords.x2 = obj->coords.x1 - 1; - } + obj->coords.y1 = + parent->coords.y1 + lv_obj_get_style_pad_top(parent, LV_PART_MAIN) - st; + obj->coords.y2 = obj->coords.y1 - 1; + obj->coords.x1 = parent->coords.x1 + + lv_obj_get_style_pad_left(parent, LV_PART_MAIN) - sl; + obj->coords.x2 = obj->coords.x1 - 1; + } - /*Set attributes*/ - obj->flags = LV_OBJ_FLAG_CLICKABLE; - obj->flags |= LV_OBJ_FLAG_SNAPPABLE; - if(parent) obj->flags |= LV_OBJ_FLAG_PRESS_LOCK; - if(parent) obj->flags |= LV_OBJ_FLAG_SCROLL_CHAIN; - obj->flags |= LV_OBJ_FLAG_CLICK_FOCUSABLE; - obj->flags |= LV_OBJ_FLAG_SCROLLABLE; - obj->flags |= LV_OBJ_FLAG_SCROLL_ELASTIC; - obj->flags |= LV_OBJ_FLAG_SCROLL_MOMENTUM; - obj->flags |= LV_OBJ_FLAG_SCROLL_WITH_ARROW; - if(parent) obj->flags |= LV_OBJ_FLAG_GESTURE_BUBBLE; + /*Set attributes*/ + obj->flags = LV_OBJ_FLAG_CLICKABLE; + obj->flags |= LV_OBJ_FLAG_SNAPPABLE; + if (parent) obj->flags |= LV_OBJ_FLAG_PRESS_LOCK; + if (parent) obj->flags |= LV_OBJ_FLAG_SCROLL_CHAIN; + obj->flags |= LV_OBJ_FLAG_CLICK_FOCUSABLE; + obj->flags |= LV_OBJ_FLAG_SCROLLABLE; + obj->flags |= LV_OBJ_FLAG_SCROLL_ELASTIC; + obj->flags |= LV_OBJ_FLAG_SCROLL_MOMENTUM; + obj->flags |= LV_OBJ_FLAG_SCROLL_WITH_ARROW; + if (parent) obj->flags |= LV_OBJ_FLAG_GESTURE_BUBBLE; - LV_TRACE_OBJ_CREATE("finished"); + LV_TRACE_OBJ_CREATE("finished"); } -static void lv_obj_destructor(const lv_obj_class_t * class_p, lv_obj_t * obj) -{ - LV_UNUSED(class_p); +static void lv_obj_destructor(const lv_obj_class_t *class_p, lv_obj_t *obj) { + LV_UNUSED(class_p); - _lv_event_mark_deleted(obj); + _lv_event_mark_deleted(obj); - /*Remove all style*/ - lv_obj_enable_style_refresh(false); /*No need to refresh the style because the object will be deleted*/ - lv_obj_remove_style_all(obj); - lv_obj_enable_style_refresh(true); + /*Remove all style*/ + lv_obj_enable_style_refresh(false); /*No need to refresh the style because the + object will be deleted*/ + lv_obj_remove_style_all(obj); + lv_obj_enable_style_refresh(true); - /*Remove the animations from this object*/ - lv_anim_del(obj, NULL); + /*Remove the animations from this object*/ + lv_anim_del(obj, NULL); - /*Delete from the group*/ - lv_group_t * group = lv_obj_get_group(obj); - if(group) lv_group_remove_obj(obj); + /*Delete from the group*/ + lv_group_t *group = lv_obj_get_group(obj); + if (group) lv_group_remove_obj(obj); - if(obj->spec_attr) { - if(obj->spec_attr->children) { - lv_mem_free(obj->spec_attr->children); - obj->spec_attr->children = NULL; - } - if(obj->spec_attr->event_dsc) { - lv_mem_free(obj->spec_attr->event_dsc); - obj->spec_attr->event_dsc = NULL; - } - - lv_mem_free(obj->spec_attr); - obj->spec_attr = NULL; + if (obj->spec_attr) { + if (obj->spec_attr->children) { + lv_mem_free(obj->spec_attr->children); + obj->spec_attr->children = NULL; } + if (obj->spec_attr->event_dsc) { + lv_mem_free(obj->spec_attr->event_dsc); + obj->spec_attr->event_dsc = NULL; + } + + lv_mem_free(obj->spec_attr); + obj->spec_attr = NULL; + } } -static void lv_obj_draw(lv_event_t * e) -{ - lv_event_code_t code = lv_event_get_code(e); - lv_obj_t * obj = lv_event_get_target(e); - if(code == LV_EVENT_COVER_CHECK) { - lv_cover_check_info_t * info = lv_event_get_param(e); - if(info->res == LV_COVER_RES_MASKED) return; - if(lv_obj_get_style_clip_corner(obj, LV_PART_MAIN)) { - info->res = LV_COVER_RES_MASKED; - return; - } - - /*Most trivial test. Is the mask fully IN the object? If no it surely doesn't cover it*/ - lv_coord_t r = lv_obj_get_style_radius(obj, LV_PART_MAIN); - lv_coord_t w = lv_obj_get_style_transform_width(obj, LV_PART_MAIN); - lv_coord_t h = lv_obj_get_style_transform_height(obj, LV_PART_MAIN); - lv_area_t coords; - lv_area_copy(&coords, &obj->coords); - coords.x1 -= w; - coords.x2 += w; - coords.y1 -= h; - coords.y2 += h; - - if(_lv_area_is_in(info->area, &coords, r) == false) { - info->res = LV_COVER_RES_NOT_COVER; - return; - } - - if(lv_obj_get_style_bg_opa(obj, LV_PART_MAIN) < LV_OPA_MAX) { - info->res = LV_COVER_RES_NOT_COVER; - return; - } - -#if LV_DRAW_COMPLEX - if(lv_obj_get_style_blend_mode(obj, LV_PART_MAIN) != LV_BLEND_MODE_NORMAL) { - info->res = LV_COVER_RES_NOT_COVER; - return; - } -#endif - if(lv_obj_get_style_opa(obj, LV_PART_MAIN) < LV_OPA_MAX) { - info->res = LV_COVER_RES_NOT_COVER; - return; - } - - info->res = LV_COVER_RES_COVER; - +static void lv_obj_draw(lv_event_t *e) { + lv_event_code_t code = lv_event_get_code(e); + lv_obj_t *obj = lv_event_get_target(e); + if (code == LV_EVENT_COVER_CHECK) { + lv_cover_check_info_t *info = lv_event_get_param(e); + if (info->res == LV_COVER_RES_MASKED) return; + if (lv_obj_get_style_clip_corner(obj, LV_PART_MAIN)) { + info->res = LV_COVER_RES_MASKED; + return; } - else if(code == LV_EVENT_DRAW_MAIN) { - lv_draw_ctx_t * draw_ctx = lv_event_get_draw_ctx(e); - lv_draw_rect_dsc_t draw_dsc; - lv_draw_rect_dsc_init(&draw_dsc); - /*If the border is drawn later disable loading its properties*/ - if(lv_obj_get_style_border_post(obj, LV_PART_MAIN)) { - draw_dsc.border_post = 1; - } - lv_obj_init_draw_rect_dsc(obj, LV_PART_MAIN, &draw_dsc); - lv_coord_t w = lv_obj_get_style_transform_width(obj, LV_PART_MAIN); - lv_coord_t h = lv_obj_get_style_transform_height(obj, LV_PART_MAIN); - lv_area_t coords; - lv_area_copy(&coords, &obj->coords); - coords.x1 -= w; - coords.x2 += w; - coords.y1 -= h; - coords.y2 += h; + /*Most trivial test. Is the mask fully IN the object? If no it surely + * doesn't cover it*/ + lv_coord_t r = lv_obj_get_style_radius(obj, LV_PART_MAIN); + lv_coord_t w = lv_obj_get_style_transform_width(obj, LV_PART_MAIN); + lv_coord_t h = lv_obj_get_style_transform_height(obj, LV_PART_MAIN); + lv_area_t coords; + lv_area_copy(&coords, &obj->coords); + coords.x1 -= w; + coords.x2 += w; + coords.y1 -= h; + coords.y2 += h; - lv_obj_draw_part_dsc_t part_dsc; - lv_obj_draw_dsc_init(&part_dsc, draw_ctx); - part_dsc.class_p = MY_CLASS; - part_dsc.type = LV_OBJ_DRAW_PART_RECTANGLE; - part_dsc.rect_dsc = &draw_dsc; - part_dsc.draw_area = &coords; - part_dsc.part = LV_PART_MAIN; - lv_event_send(obj, LV_EVENT_DRAW_PART_BEGIN, &part_dsc); - - -#if LV_DRAW_COMPLEX - /*With clip corner enabled draw the bg img separately to make it clipped*/ - bool clip_corner = (lv_obj_get_style_clip_corner(obj, LV_PART_MAIN) && draw_dsc.radius != 0) ? true : false; - const void * bg_img_src = draw_dsc.bg_img_src; - if(clip_corner) { - draw_dsc.bg_img_src = NULL; - } -#endif - - lv_draw_rect(draw_ctx, &draw_dsc, &coords); - - -#if LV_DRAW_COMPLEX - if(clip_corner) { - lv_draw_mask_radius_param_t * mp = lv_mem_buf_get(sizeof(lv_draw_mask_radius_param_t)); - lv_draw_mask_radius_init(mp, &obj->coords, draw_dsc.radius, false); - /*Add the mask and use `obj+8` as custom id. Don't use `obj` directly because it might be used by the user*/ - lv_draw_mask_add(mp, obj + 8); - - if(bg_img_src) { - draw_dsc.bg_opa = LV_OPA_TRANSP; - draw_dsc.border_opa = LV_OPA_TRANSP; - draw_dsc.outline_opa = LV_OPA_TRANSP; - draw_dsc.shadow_opa = LV_OPA_TRANSP; - draw_dsc.bg_img_src = bg_img_src; - lv_draw_rect(draw_ctx, &draw_dsc, &coords); - } - - } -#endif - lv_event_send(obj, LV_EVENT_DRAW_PART_END, &part_dsc); + if (_lv_area_is_in(info->area, &coords, r) == false) { + info->res = LV_COVER_RES_NOT_COVER; + return; + } + + if (lv_obj_get_style_bg_opa(obj, LV_PART_MAIN) < LV_OPA_MAX) { + info->res = LV_COVER_RES_NOT_COVER; + return; } - else if(code == LV_EVENT_DRAW_POST) { - lv_draw_ctx_t * draw_ctx = lv_event_get_draw_ctx(e); - draw_scrollbar(obj, draw_ctx); #if LV_DRAW_COMPLEX - if(lv_obj_get_style_clip_corner(obj, LV_PART_MAIN)) { - lv_draw_mask_radius_param_t * param = lv_draw_mask_remove_custom(obj + 8); - if(param) { - lv_draw_mask_free_param(param); - lv_mem_buf_release(param); - } - } -#endif - - /*If the border is drawn later disable loading other properties*/ - if(lv_obj_get_style_border_post(obj, LV_PART_MAIN)) { - lv_draw_rect_dsc_t draw_dsc; - lv_draw_rect_dsc_init(&draw_dsc); - draw_dsc.bg_opa = LV_OPA_TRANSP; - draw_dsc.bg_img_opa = LV_OPA_TRANSP; - draw_dsc.outline_opa = LV_OPA_TRANSP; - draw_dsc.shadow_opa = LV_OPA_TRANSP; - lv_obj_init_draw_rect_dsc(obj, LV_PART_MAIN, &draw_dsc); - - lv_coord_t w = lv_obj_get_style_transform_width(obj, LV_PART_MAIN); - lv_coord_t h = lv_obj_get_style_transform_height(obj, LV_PART_MAIN); - lv_area_t coords; - lv_area_copy(&coords, &obj->coords); - coords.x1 -= w; - coords.x2 += w; - coords.y1 -= h; - coords.y2 += h; - - lv_obj_draw_part_dsc_t part_dsc; - lv_obj_draw_dsc_init(&part_dsc, draw_ctx); - part_dsc.class_p = MY_CLASS; - part_dsc.type = LV_OBJ_DRAW_PART_BORDER_POST; - part_dsc.rect_dsc = &draw_dsc; - part_dsc.draw_area = &coords; - part_dsc.part = LV_PART_MAIN; - lv_event_send(obj, LV_EVENT_DRAW_PART_BEGIN, &part_dsc); - - lv_draw_rect(draw_ctx, &draw_dsc, &coords); - lv_event_send(obj, LV_EVENT_DRAW_PART_END, &part_dsc); - } + if (lv_obj_get_style_blend_mode(obj, LV_PART_MAIN) != + LV_BLEND_MODE_NORMAL) { + info->res = LV_COVER_RES_NOT_COVER; + return; + } +#endif + if (lv_obj_get_style_opa(obj, LV_PART_MAIN) < LV_OPA_MAX) { + info->res = LV_COVER_RES_NOT_COVER; + return; } -} -static void draw_scrollbar(lv_obj_t * obj, lv_draw_ctx_t * draw_ctx) -{ - - lv_area_t hor_area; - lv_area_t ver_area; - lv_obj_get_scrollbar_area(obj, &hor_area, &ver_area); - - if(lv_area_get_size(&hor_area) <= 0 && lv_area_get_size(&ver_area) <= 0) return; + info->res = LV_COVER_RES_COVER; + } else if (code == LV_EVENT_DRAW_MAIN) { + lv_draw_ctx_t *draw_ctx = lv_event_get_draw_ctx(e); lv_draw_rect_dsc_t draw_dsc; - lv_res_t sb_res = scrollbar_init_draw_dsc(obj, &draw_dsc); - if(sb_res != LV_RES_OK) return; + lv_draw_rect_dsc_init(&draw_dsc); + /*If the border is drawn later disable loading its properties*/ + if (lv_obj_get_style_border_post(obj, LV_PART_MAIN)) { + draw_dsc.border_post = 1; + } + + lv_obj_init_draw_rect_dsc(obj, LV_PART_MAIN, &draw_dsc); + lv_coord_t w = lv_obj_get_style_transform_width(obj, LV_PART_MAIN); + lv_coord_t h = lv_obj_get_style_transform_height(obj, LV_PART_MAIN); + lv_area_t coords; + lv_area_copy(&coords, &obj->coords); + coords.x1 -= w; + coords.x2 += w; + coords.y1 -= h; + coords.y2 += h; lv_obj_draw_part_dsc_t part_dsc; lv_obj_draw_dsc_init(&part_dsc, draw_ctx); part_dsc.class_p = MY_CLASS; - part_dsc.type = LV_OBJ_DRAW_PART_SCROLLBAR; + part_dsc.type = LV_OBJ_DRAW_PART_RECTANGLE; part_dsc.rect_dsc = &draw_dsc; - part_dsc.part = LV_PART_SCROLLBAR; + part_dsc.draw_area = &coords; + part_dsc.part = LV_PART_MAIN; + lv_event_send(obj, LV_EVENT_DRAW_PART_BEGIN, &part_dsc); - if(lv_area_get_size(&hor_area) > 0) { - part_dsc.draw_area = &hor_area; - lv_event_send(obj, LV_EVENT_DRAW_PART_BEGIN, &part_dsc); - lv_draw_rect(draw_ctx, &draw_dsc, &hor_area); - lv_event_send(obj, LV_EVENT_DRAW_PART_END, &part_dsc); +#if LV_DRAW_COMPLEX + /*With clip corner enabled draw the bg img separately to make it clipped*/ + bool clip_corner = (lv_obj_get_style_clip_corner(obj, LV_PART_MAIN) && + draw_dsc.radius != 0) + ? true + : false; + const void *bg_img_src = draw_dsc.bg_img_src; + if (clip_corner) { + draw_dsc.bg_img_src = NULL; } - if(lv_area_get_size(&ver_area) > 0) { - part_dsc.draw_area = &ver_area; - lv_event_send(obj, LV_EVENT_DRAW_PART_BEGIN, &part_dsc); - part_dsc.draw_area = &ver_area; - lv_draw_rect(draw_ctx, &draw_dsc, &ver_area); - lv_event_send(obj, LV_EVENT_DRAW_PART_END, &part_dsc); +#endif + + lv_draw_rect(draw_ctx, &draw_dsc, &coords); + +#if LV_DRAW_COMPLEX + if (clip_corner) { + lv_draw_mask_radius_param_t *mp = + lv_mem_buf_get(sizeof(lv_draw_mask_radius_param_t)); + lv_draw_mask_radius_init(mp, &obj->coords, draw_dsc.radius, false); + /*Add the mask and use `obj+8` as custom id. Don't use `obj` directly + * because it might be used by the user*/ + lv_draw_mask_add(mp, obj + 8); + + if (bg_img_src) { + draw_dsc.bg_opa = LV_OPA_TRANSP; + draw_dsc.border_opa = LV_OPA_TRANSP; + draw_dsc.outline_opa = LV_OPA_TRANSP; + draw_dsc.shadow_opa = LV_OPA_TRANSP; + draw_dsc.bg_img_src = bg_img_src; + lv_draw_rect(draw_ctx, &draw_dsc, &coords); + } } +#endif + lv_event_send(obj, LV_EVENT_DRAW_PART_END, &part_dsc); + } else if (code == LV_EVENT_DRAW_POST) { + lv_draw_ctx_t *draw_ctx = lv_event_get_draw_ctx(e); + draw_scrollbar(obj, draw_ctx); + +#if LV_DRAW_COMPLEX + if (lv_obj_get_style_clip_corner(obj, LV_PART_MAIN)) { + lv_draw_mask_radius_param_t *param = lv_draw_mask_remove_custom(obj + 8); + if (param) { + lv_draw_mask_free_param(param); + lv_mem_buf_release(param); + } + } +#endif + + /*If the border is drawn later disable loading other properties*/ + if (lv_obj_get_style_border_post(obj, LV_PART_MAIN)) { + lv_draw_rect_dsc_t draw_dsc; + lv_draw_rect_dsc_init(&draw_dsc); + draw_dsc.bg_opa = LV_OPA_TRANSP; + draw_dsc.bg_img_opa = LV_OPA_TRANSP; + draw_dsc.outline_opa = LV_OPA_TRANSP; + draw_dsc.shadow_opa = LV_OPA_TRANSP; + lv_obj_init_draw_rect_dsc(obj, LV_PART_MAIN, &draw_dsc); + + lv_coord_t w = lv_obj_get_style_transform_width(obj, LV_PART_MAIN); + lv_coord_t h = lv_obj_get_style_transform_height(obj, LV_PART_MAIN); + lv_area_t coords; + lv_area_copy(&coords, &obj->coords); + coords.x1 -= w; + coords.x2 += w; + coords.y1 -= h; + coords.y2 += h; + + lv_obj_draw_part_dsc_t part_dsc; + lv_obj_draw_dsc_init(&part_dsc, draw_ctx); + part_dsc.class_p = MY_CLASS; + part_dsc.type = LV_OBJ_DRAW_PART_BORDER_POST; + part_dsc.rect_dsc = &draw_dsc; + part_dsc.draw_area = &coords; + part_dsc.part = LV_PART_MAIN; + lv_event_send(obj, LV_EVENT_DRAW_PART_BEGIN, &part_dsc); + + lv_draw_rect(draw_ctx, &draw_dsc, &coords); + lv_event_send(obj, LV_EVENT_DRAW_PART_END, &part_dsc); + } + } +} + +static void draw_scrollbar(lv_obj_t *obj, lv_draw_ctx_t *draw_ctx) { + lv_area_t hor_area; + lv_area_t ver_area; + lv_obj_get_scrollbar_area(obj, &hor_area, &ver_area); + + if (lv_area_get_size(&hor_area) <= 0 && lv_area_get_size(&ver_area) <= 0) + return; + + lv_draw_rect_dsc_t draw_dsc; + lv_res_t sb_res = scrollbar_init_draw_dsc(obj, &draw_dsc); + if (sb_res != LV_RES_OK) return; + + lv_obj_draw_part_dsc_t part_dsc; + lv_obj_draw_dsc_init(&part_dsc, draw_ctx); + part_dsc.class_p = MY_CLASS; + part_dsc.type = LV_OBJ_DRAW_PART_SCROLLBAR; + part_dsc.rect_dsc = &draw_dsc; + part_dsc.part = LV_PART_SCROLLBAR; + + if (lv_area_get_size(&hor_area) > 0) { + part_dsc.draw_area = &hor_area; + lv_event_send(obj, LV_EVENT_DRAW_PART_BEGIN, &part_dsc); + lv_draw_rect(draw_ctx, &draw_dsc, &hor_area); + lv_event_send(obj, LV_EVENT_DRAW_PART_END, &part_dsc); + } + if (lv_area_get_size(&ver_area) > 0) { + part_dsc.draw_area = &ver_area; + lv_event_send(obj, LV_EVENT_DRAW_PART_BEGIN, &part_dsc); + part_dsc.draw_area = &ver_area; + lv_draw_rect(draw_ctx, &draw_dsc, &ver_area); + lv_event_send(obj, LV_EVENT_DRAW_PART_END, &part_dsc); + } } /** * Initialize the draw descriptor for the scrollbar * @param obj pointer to an object * @param dsc the draw descriptor to initialize - * @return LV_RES_OK: the scrollbar is visible; LV_RES_INV: the scrollbar is not visible + * @return LV_RES_OK: the scrollbar is visible; LV_RES_INV: the scrollbar is not + * visible */ -static lv_res_t scrollbar_init_draw_dsc(lv_obj_t * obj, lv_draw_rect_dsc_t * dsc) -{ - lv_draw_rect_dsc_init(dsc); - dsc->bg_opa = lv_obj_get_style_bg_opa(obj, LV_PART_SCROLLBAR); - if(dsc->bg_opa > LV_OPA_MIN) { - dsc->bg_color = lv_obj_get_style_bg_color(obj, LV_PART_SCROLLBAR); - } +static lv_res_t scrollbar_init_draw_dsc(lv_obj_t *obj, + lv_draw_rect_dsc_t *dsc) { + lv_draw_rect_dsc_init(dsc); + dsc->bg_opa = lv_obj_get_style_bg_opa(obj, LV_PART_SCROLLBAR); + if (dsc->bg_opa > LV_OPA_MIN) { + dsc->bg_color = lv_obj_get_style_bg_color(obj, LV_PART_SCROLLBAR); + } - dsc->border_opa = lv_obj_get_style_border_opa(obj, LV_PART_SCROLLBAR); - if(dsc->border_opa > LV_OPA_MIN) { - dsc->border_width = lv_obj_get_style_border_width(obj, LV_PART_SCROLLBAR); - if(dsc->border_width > 0) { - dsc->border_color = lv_obj_get_style_border_color(obj, LV_PART_SCROLLBAR); - } - else { - dsc->border_opa = LV_OPA_TRANSP; - } + dsc->border_opa = lv_obj_get_style_border_opa(obj, LV_PART_SCROLLBAR); + if (dsc->border_opa > LV_OPA_MIN) { + dsc->border_width = lv_obj_get_style_border_width(obj, LV_PART_SCROLLBAR); + if (dsc->border_width > 0) { + dsc->border_color = lv_obj_get_style_border_color(obj, LV_PART_SCROLLBAR); + } else { + dsc->border_opa = LV_OPA_TRANSP; } + } #if LV_DRAW_COMPLEX - dsc->shadow_opa = lv_obj_get_style_shadow_opa(obj, LV_PART_SCROLLBAR); - if(dsc->shadow_opa > LV_OPA_MIN) { - dsc->shadow_width = lv_obj_get_style_shadow_width(obj, LV_PART_SCROLLBAR); - if(dsc->shadow_width > 0) { - dsc->shadow_spread = lv_obj_get_style_shadow_spread(obj, LV_PART_SCROLLBAR); - dsc->shadow_color = lv_obj_get_style_shadow_color(obj, LV_PART_SCROLLBAR); - } - else { - dsc->shadow_opa = LV_OPA_TRANSP; - } + dsc->shadow_opa = lv_obj_get_style_shadow_opa(obj, LV_PART_SCROLLBAR); + if (dsc->shadow_opa > LV_OPA_MIN) { + dsc->shadow_width = lv_obj_get_style_shadow_width(obj, LV_PART_SCROLLBAR); + if (dsc->shadow_width > 0) { + dsc->shadow_spread = + lv_obj_get_style_shadow_spread(obj, LV_PART_SCROLLBAR); + dsc->shadow_color = lv_obj_get_style_shadow_color(obj, LV_PART_SCROLLBAR); + } else { + dsc->shadow_opa = LV_OPA_TRANSP; } + } - lv_opa_t opa = lv_obj_get_style_opa(obj, LV_PART_SCROLLBAR); - if(opa < LV_OPA_MAX) { - dsc->bg_opa = (dsc->bg_opa * opa) >> 8; - dsc->border_opa = (dsc->bg_opa * opa) >> 8; - dsc->shadow_opa = (dsc->bg_opa * opa) >> 8; - } + lv_opa_t opa = lv_obj_get_style_opa(obj, LV_PART_SCROLLBAR); + if (opa < LV_OPA_MAX) { + dsc->bg_opa = (dsc->bg_opa * opa) >> 8; + dsc->border_opa = (dsc->bg_opa * opa) >> 8; + dsc->shadow_opa = (dsc->bg_opa * opa) >> 8; + } - if(dsc->bg_opa != LV_OPA_TRANSP || dsc->border_opa != LV_OPA_TRANSP || dsc->shadow_opa != LV_OPA_TRANSP) { - dsc->radius = lv_obj_get_style_radius(obj, LV_PART_SCROLLBAR); - return LV_RES_OK; - } - else { - return LV_RES_INV; - } + if (dsc->bg_opa != LV_OPA_TRANSP || dsc->border_opa != LV_OPA_TRANSP || + dsc->shadow_opa != LV_OPA_TRANSP) { + dsc->radius = lv_obj_get_style_radius(obj, LV_PART_SCROLLBAR); + return LV_RES_OK; + } else { + return LV_RES_INV; + } #else - if(dsc->bg_opa != LV_OPA_TRANSP || dsc->border_opa != LV_OPA_TRANSP) return LV_RES_OK; - else return LV_RES_INV; + if (dsc->bg_opa != LV_OPA_TRANSP || dsc->border_opa != LV_OPA_TRANSP) + return LV_RES_OK; + else + return LV_RES_INV; #endif } -static void lv_obj_event(const lv_obj_class_t * class_p, lv_event_t * e) -{ - LV_UNUSED(class_p); +static void lv_obj_event(const lv_obj_class_t *class_p, lv_event_t *e) { + LV_UNUSED(class_p); - lv_event_code_t code = lv_event_get_code(e); - lv_obj_t * obj = lv_event_get_current_target(e); - if(code == LV_EVENT_PRESSED) { - lv_obj_add_state(obj, LV_STATE_PRESSED); - } - else if(code == LV_EVENT_RELEASED) { - lv_obj_clear_state(obj, LV_STATE_PRESSED); - void * param = lv_event_get_param(e); - /*Go the checked state if enabled*/ - if(lv_indev_get_scroll_obj(param) == NULL && lv_obj_has_flag(obj, LV_OBJ_FLAG_CHECKABLE)) { - if(!(lv_obj_get_state(obj) & LV_STATE_CHECKED)) lv_obj_add_state(obj, LV_STATE_CHECKED); - else lv_obj_clear_state(obj, LV_STATE_CHECKED); + lv_event_code_t code = lv_event_get_code(e); + lv_obj_t *obj = lv_event_get_current_target(e); + if (code == LV_EVENT_PRESSED) { + lv_obj_add_state(obj, LV_STATE_PRESSED); + } else if (code == LV_EVENT_RELEASED) { + lv_obj_clear_state(obj, LV_STATE_PRESSED); + void *param = lv_event_get_param(e); + /*Go the checked state if enabled*/ + if (lv_indev_get_scroll_obj(param) == NULL && + lv_obj_has_flag(obj, LV_OBJ_FLAG_CHECKABLE)) { + if (!(lv_obj_get_state(obj) & LV_STATE_CHECKED)) + lv_obj_add_state(obj, LV_STATE_CHECKED); + else + lv_obj_clear_state(obj, LV_STATE_CHECKED); - lv_res_t res = lv_event_send(obj, LV_EVENT_VALUE_CHANGED, NULL); - if(res != LV_RES_OK) return; - } + lv_res_t res = lv_event_send(obj, LV_EVENT_VALUE_CHANGED, NULL); + if (res != LV_RES_OK) return; } - else if(code == LV_EVENT_PRESS_LOST) { - lv_obj_clear_state(obj, LV_STATE_PRESSED); + } else if (code == LV_EVENT_PRESS_LOST) { + lv_obj_clear_state(obj, LV_STATE_PRESSED); + } else if (code == LV_EVENT_STYLE_CHANGED) { + uint32_t child_cnt = lv_obj_get_child_cnt(obj); + for (uint32_t i = 0; i < child_cnt; i++) { + lv_obj_t *child = obj->spec_attr->children[i]; + lv_obj_mark_layout_as_dirty(child); } - else if(code == LV_EVENT_STYLE_CHANGED) { - uint32_t child_cnt = lv_obj_get_child_cnt(obj); - for(uint32_t i = 0; i < child_cnt; i++) { - lv_obj_t * child = obj->spec_attr->children[i]; - lv_obj_mark_layout_as_dirty(child); - } - } - else if(code == LV_EVENT_KEY) { - if(lv_obj_has_flag(obj, LV_OBJ_FLAG_CHECKABLE)) { - char c = *((char *)lv_event_get_param(e)); - if(c == LV_KEY_RIGHT || c == LV_KEY_UP) { - lv_obj_add_state(obj, LV_STATE_CHECKED); - } - else if(c == LV_KEY_LEFT || c == LV_KEY_DOWN) { - lv_obj_clear_state(obj, LV_STATE_CHECKED); - } + } else if (code == LV_EVENT_KEY) { + if (lv_obj_has_flag(obj, LV_OBJ_FLAG_CHECKABLE)) { + char c = *((char *)lv_event_get_param(e)); + if (c == LV_KEY_RIGHT || c == LV_KEY_UP) { + lv_obj_add_state(obj, LV_STATE_CHECKED); + } else if (c == LV_KEY_LEFT || c == LV_KEY_DOWN) { + lv_obj_clear_state(obj, LV_STATE_CHECKED); + } - /*With Enter LV_EVENT_RELEASED will send VALUE_CHANGE event*/ - if(c != LV_KEY_ENTER) { - lv_res_t res = lv_event_send(obj, LV_EVENT_VALUE_CHANGED, NULL); - if(res != LV_RES_OK) return; - } - } - else if(lv_obj_has_flag(obj, LV_OBJ_FLAG_SCROLLABLE | LV_OBJ_FLAG_SCROLL_WITH_ARROW) && !lv_obj_is_editable(obj)) { - /*scroll by keypad or encoder*/ - lv_anim_enable_t anim_enable = LV_ANIM_OFF; - lv_coord_t sl = lv_obj_get_scroll_left(obj); - lv_coord_t sr = lv_obj_get_scroll_right(obj); - char c = *((char *)lv_event_get_param(e)); - if(c == LV_KEY_DOWN) { - /*use scroll_to_x/y functions to enforce scroll limits*/ - lv_obj_scroll_to_y(obj, lv_obj_get_scroll_y(obj) + lv_obj_get_height(obj) / 4, anim_enable); - } - else if(c == LV_KEY_UP) { - lv_obj_scroll_to_y(obj, lv_obj_get_scroll_y(obj) - lv_obj_get_height(obj) / 4, anim_enable); - } - else if(c == LV_KEY_RIGHT) { - /*If the object can't be scrolled horizontally then scroll it vertically*/ - if(!((lv_obj_get_scroll_dir(obj) & LV_DIR_HOR) && (sl > 0 || sr > 0))) - lv_obj_scroll_to_y(obj, lv_obj_get_scroll_y(obj) + lv_obj_get_height(obj) / 4, anim_enable); - else - lv_obj_scroll_to_x(obj, lv_obj_get_scroll_x(obj) + lv_obj_get_width(obj) / 4, anim_enable); - } - else if(c == LV_KEY_LEFT) { - /*If the object can't be scrolled horizontally then scroll it vertically*/ - if(!((lv_obj_get_scroll_dir(obj) & LV_DIR_HOR) && (sl > 0 || sr > 0))) - lv_obj_scroll_to_y(obj, lv_obj_get_scroll_y(obj) - lv_obj_get_height(obj) / 4, anim_enable); - else - lv_obj_scroll_to_x(obj, lv_obj_get_scroll_x(obj) - lv_obj_get_width(obj) / 4, anim_enable); - } - } + /*With Enter LV_EVENT_RELEASED will send VALUE_CHANGE event*/ + if (c != LV_KEY_ENTER) { + lv_res_t res = lv_event_send(obj, LV_EVENT_VALUE_CHANGED, NULL); + if (res != LV_RES_OK) return; + } + } else if (lv_obj_has_flag(obj, LV_OBJ_FLAG_SCROLLABLE | + LV_OBJ_FLAG_SCROLL_WITH_ARROW) && + !lv_obj_is_editable(obj)) { + /*scroll by keypad or encoder*/ + lv_anim_enable_t anim_enable = LV_ANIM_OFF; + lv_coord_t sl = lv_obj_get_scroll_left(obj); + lv_coord_t sr = lv_obj_get_scroll_right(obj); + char c = *((char *)lv_event_get_param(e)); + if (c == LV_KEY_DOWN) { + /*use scroll_to_x/y functions to enforce scroll limits*/ + lv_obj_scroll_to_y( + obj, lv_obj_get_scroll_y(obj) + lv_obj_get_height(obj) / 4, + anim_enable); + } else if (c == LV_KEY_UP) { + lv_obj_scroll_to_y( + obj, lv_obj_get_scroll_y(obj) - lv_obj_get_height(obj) / 4, + anim_enable); + } else if (c == LV_KEY_RIGHT) { + /*If the object can't be scrolled horizontally then scroll it + * vertically*/ + if (!((lv_obj_get_scroll_dir(obj) & LV_DIR_HOR) && (sl > 0 || sr > 0))) + lv_obj_scroll_to_y( + obj, lv_obj_get_scroll_y(obj) + lv_obj_get_height(obj) / 4, + anim_enable); + else + lv_obj_scroll_to_x( + obj, lv_obj_get_scroll_x(obj) + lv_obj_get_width(obj) / 4, + anim_enable); + } else if (c == LV_KEY_LEFT) { + /*If the object can't be scrolled horizontally then scroll it + * vertically*/ + if (!((lv_obj_get_scroll_dir(obj) & LV_DIR_HOR) && (sl > 0 || sr > 0))) + lv_obj_scroll_to_y( + obj, lv_obj_get_scroll_y(obj) - lv_obj_get_height(obj) / 4, + anim_enable); + else + lv_obj_scroll_to_x( + obj, lv_obj_get_scroll_x(obj) - lv_obj_get_width(obj) / 4, + anim_enable); + } + } + } else if (code == LV_EVENT_FOCUSED) { + if (lv_obj_has_flag(obj, LV_OBJ_FLAG_SCROLL_ON_FOCUS)) { + lv_obj_scroll_to_view_recursive(obj, LV_ANIM_ON); } - else if(code == LV_EVENT_FOCUSED) { - if(lv_obj_has_flag(obj, LV_OBJ_FLAG_SCROLL_ON_FOCUS)) { - lv_obj_scroll_to_view_recursive(obj, LV_ANIM_ON); - } - bool editing = false; - editing = lv_group_get_editing(lv_obj_get_group(obj)); - lv_state_t state = LV_STATE_FOCUSED; + bool editing = false; + editing = lv_group_get_editing(lv_obj_get_group(obj)); + lv_state_t state = LV_STATE_FOCUSED; - /* Use the indev for then indev handler. - * But if the obj was focused manually it returns NULL so try to - * use the indev from the event*/ - lv_indev_t * indev = lv_indev_get_act(); - if(indev == NULL) indev = lv_event_get_indev(e); + /* Use the indev for then indev handler. + * But if the obj was focused manually it returns NULL so try to + * use the indev from the event*/ + lv_indev_t *indev = lv_indev_get_act(); + if (indev == NULL) indev = lv_event_get_indev(e); - lv_indev_type_t indev_type = lv_indev_get_type(indev); - if(indev_type == LV_INDEV_TYPE_KEYPAD || indev_type == LV_INDEV_TYPE_ENCODER) state |= LV_STATE_FOCUS_KEY; - if(editing) { - state |= LV_STATE_EDITED; - lv_obj_add_state(obj, state); - } - else { - lv_obj_add_state(obj, state); - lv_obj_clear_state(obj, LV_STATE_EDITED); - } + lv_indev_type_t indev_type = lv_indev_get_type(indev); + if (indev_type == LV_INDEV_TYPE_KEYPAD || + indev_type == LV_INDEV_TYPE_ENCODER) + state |= LV_STATE_FOCUS_KEY; + if (editing) { + state |= LV_STATE_EDITED; + lv_obj_add_state(obj, state); + } else { + lv_obj_add_state(obj, state); + lv_obj_clear_state(obj, LV_STATE_EDITED); } - else if(code == LV_EVENT_SCROLL_BEGIN) { - lv_obj_add_state(obj, LV_STATE_SCROLLED); + } else if (code == LV_EVENT_SCROLL_BEGIN) { + lv_obj_add_state(obj, LV_STATE_SCROLLED); + } else if (code == LV_EVENT_SCROLL_END) { + lv_obj_clear_state(obj, LV_STATE_SCROLLED); + if (lv_obj_get_scrollbar_mode(obj) == LV_SCROLLBAR_MODE_ACTIVE) { + lv_area_t hor_area, ver_area; + lv_obj_get_scrollbar_area(obj, &hor_area, &ver_area); + lv_obj_invalidate_area(obj, &hor_area); + lv_obj_invalidate_area(obj, &ver_area); } - else if(code == LV_EVENT_SCROLL_END) { - lv_obj_clear_state(obj, LV_STATE_SCROLLED); - if(lv_obj_get_scrollbar_mode(obj) == LV_SCROLLBAR_MODE_ACTIVE) { - lv_area_t hor_area, ver_area; - lv_obj_get_scrollbar_area(obj, &hor_area, &ver_area); - lv_obj_invalidate_area(obj, &hor_area); - lv_obj_invalidate_area(obj, &ver_area); - } + } else if (code == LV_EVENT_DEFOCUSED) { + lv_obj_clear_state(obj, + LV_STATE_FOCUSED | LV_STATE_EDITED | LV_STATE_FOCUS_KEY); + } else if (code == LV_EVENT_SIZE_CHANGED) { + lv_coord_t align = lv_obj_get_style_align(obj, LV_PART_MAIN); + uint16_t layout = lv_obj_get_style_layout(obj, LV_PART_MAIN); + if (layout || align) { + lv_obj_mark_layout_as_dirty(obj); } - else if(code == LV_EVENT_DEFOCUSED) { - lv_obj_clear_state(obj, LV_STATE_FOCUSED | LV_STATE_EDITED | LV_STATE_FOCUS_KEY); - } - else if(code == LV_EVENT_SIZE_CHANGED) { - lv_coord_t align = lv_obj_get_style_align(obj, LV_PART_MAIN); - uint16_t layout = lv_obj_get_style_layout(obj, LV_PART_MAIN); - if(layout || align) { - lv_obj_mark_layout_as_dirty(obj); - } - uint32_t i; - uint32_t child_cnt = lv_obj_get_child_cnt(obj); - for(i = 0; i < child_cnt; i++) { - lv_obj_t * child = obj->spec_attr->children[i]; - lv_obj_mark_layout_as_dirty(child); - } + uint32_t i; + uint32_t child_cnt = lv_obj_get_child_cnt(obj); + for (i = 0; i < child_cnt; i++) { + lv_obj_t *child = obj->spec_attr->children[i]; + lv_obj_mark_layout_as_dirty(child); } - else if(code == LV_EVENT_CHILD_CHANGED) { - lv_coord_t w = lv_obj_get_style_width(obj, LV_PART_MAIN); - lv_coord_t h = lv_obj_get_style_height(obj, LV_PART_MAIN); - lv_coord_t align = lv_obj_get_style_align(obj, LV_PART_MAIN); - uint16_t layout = lv_obj_get_style_layout(obj, LV_PART_MAIN); - if(layout || align || w == LV_SIZE_CONTENT || h == LV_SIZE_CONTENT) { - lv_obj_mark_layout_as_dirty(obj); - } - } - else if(code == LV_EVENT_REFR_EXT_DRAW_SIZE) { - lv_coord_t * s = lv_event_get_param(e); - lv_coord_t d = lv_obj_calculate_ext_draw_size(obj, LV_PART_MAIN); - *s = LV_MAX(*s, d); - } - else if(code == LV_EVENT_DRAW_MAIN || code == LV_EVENT_DRAW_POST || code == LV_EVENT_COVER_CHECK) { - lv_obj_draw(e); + } else if (code == LV_EVENT_CHILD_CHANGED) { + lv_coord_t w = lv_obj_get_style_width(obj, LV_PART_MAIN); + lv_coord_t h = lv_obj_get_style_height(obj, LV_PART_MAIN); + lv_coord_t align = lv_obj_get_style_align(obj, LV_PART_MAIN); + uint16_t layout = lv_obj_get_style_layout(obj, LV_PART_MAIN); + if (layout || align || w == LV_SIZE_CONTENT || h == LV_SIZE_CONTENT) { + lv_obj_mark_layout_as_dirty(obj); } + } else if (code == LV_EVENT_REFR_EXT_DRAW_SIZE) { + lv_coord_t *s = lv_event_get_param(e); + lv_coord_t d = lv_obj_calculate_ext_draw_size(obj, LV_PART_MAIN); + *s = LV_MAX(*s, d); + } else if (code == LV_EVENT_DRAW_MAIN || code == LV_EVENT_DRAW_POST || + code == LV_EVENT_COVER_CHECK) { + lv_obj_draw(e); + } } /** * Set the state (fully overwrite) of an object. - * If specified in the styles, transition animations will be started from the previous state to the current. + * If specified in the styles, transition animations will be started from the + * previous state to the current. * @param obj pointer to an object * @param state the new state */ -static void lv_obj_set_state(lv_obj_t * obj, lv_state_t new_state) -{ - if(obj->state == new_state) return; +static void lv_obj_set_state(lv_obj_t *obj, lv_state_t new_state) { + if (obj->state == new_state) return; - LV_ASSERT_OBJ(obj, MY_CLASS); + LV_ASSERT_OBJ(obj, MY_CLASS); - lv_state_t prev_state = obj->state; - obj->state = new_state; + lv_state_t prev_state = obj->state; + obj->state = new_state; - _lv_style_state_cmp_t cmp_res = _lv_obj_style_state_compare(obj, prev_state, new_state); - /*If there is no difference in styles there is nothing else to do*/ - if(cmp_res == _LV_STYLE_STATE_CMP_SAME) return; + _lv_style_state_cmp_t cmp_res = + _lv_obj_style_state_compare(obj, prev_state, new_state); + /*If there is no difference in styles there is nothing else to do*/ + if (cmp_res == _LV_STYLE_STATE_CMP_SAME) return; - _lv_obj_style_transition_dsc_t * ts = lv_mem_buf_get(sizeof(_lv_obj_style_transition_dsc_t) * STYLE_TRANSITION_MAX); - lv_memset_00(ts, sizeof(_lv_obj_style_transition_dsc_t) * STYLE_TRANSITION_MAX); - uint32_t tsi = 0; - uint32_t i; - for(i = 0; i < obj->style_cnt && tsi < STYLE_TRANSITION_MAX; i++) { - _lv_obj_style_t * obj_style = &obj->styles[i]; - lv_state_t state_act = lv_obj_style_get_selector_state(obj->styles[i].selector); - lv_part_t part_act = lv_obj_style_get_selector_part(obj->styles[i].selector); - if(state_act & (~new_state)) continue; /*Skip unrelated styles*/ - if(obj_style->is_trans) continue; + _lv_obj_style_transition_dsc_t *ts = lv_mem_buf_get( + sizeof(_lv_obj_style_transition_dsc_t) * STYLE_TRANSITION_MAX); + lv_memset_00(ts, + sizeof(_lv_obj_style_transition_dsc_t) * STYLE_TRANSITION_MAX); + uint32_t tsi = 0; + uint32_t i; + for (i = 0; i < obj->style_cnt && tsi < STYLE_TRANSITION_MAX; i++) { + _lv_obj_style_t *obj_style = &obj->styles[i]; + lv_state_t state_act = + lv_obj_style_get_selector_state(obj->styles[i].selector); + lv_part_t part_act = + lv_obj_style_get_selector_part(obj->styles[i].selector); + if (state_act & (~new_state)) continue; /*Skip unrelated styles*/ + if (obj_style->is_trans) continue; - lv_style_value_t v; - if(lv_style_get_prop_inlined(obj_style->style, LV_STYLE_TRANSITION, &v) == false) continue; - const lv_style_transition_dsc_t * tr = v.ptr; + lv_style_value_t v; + if (lv_style_get_prop_inlined(obj_style->style, LV_STYLE_TRANSITION, &v) == + false) + continue; + const lv_style_transition_dsc_t *tr = v.ptr; - /*Add the props to the set if not added yet or added but with smaller weight*/ - uint32_t j; - for(j = 0; tr->props[j] != 0 && tsi < STYLE_TRANSITION_MAX; j++) { - uint32_t t; - for(t = 0; t < tsi; t++) { - lv_style_selector_t selector = ts[t].selector; - lv_state_t state_ts = lv_obj_style_get_selector_state(selector); - lv_part_t part_ts = lv_obj_style_get_selector_part(selector); - if(ts[t].prop == tr->props[j] && part_ts == part_act && state_ts >= state_act) break; - } + /*Add the props to the set if not added yet or added but with smaller + * weight*/ + uint32_t j; + for (j = 0; tr->props[j] != 0 && tsi < STYLE_TRANSITION_MAX; j++) { + uint32_t t; + for (t = 0; t < tsi; t++) { + lv_style_selector_t selector = ts[t].selector; + lv_state_t state_ts = lv_obj_style_get_selector_state(selector); + lv_part_t part_ts = lv_obj_style_get_selector_part(selector); + if (ts[t].prop == tr->props[j] && part_ts == part_act && + state_ts >= state_act) + break; + } - /*If not found add it*/ - if(t == tsi) { - ts[tsi].time = tr->time; - ts[tsi].delay = tr->delay; - ts[tsi].path_cb = tr->path_xcb; - ts[tsi].prop = tr->props[j]; + /*If not found add it*/ + if (t == tsi) { + ts[tsi].time = tr->time; + ts[tsi].delay = tr->delay; + ts[tsi].path_cb = tr->path_xcb; + ts[tsi].prop = tr->props[j]; #if LV_USE_USER_DATA - ts[tsi].user_data = tr->user_data; + ts[tsi].user_data = tr->user_data; #endif - ts[tsi].selector = obj_style->selector; - tsi++; - } - } + ts[tsi].selector = obj_style->selector; + tsi++; + } } + } - for(i = 0; i < tsi; i++) { - lv_part_t part_act = lv_obj_style_get_selector_part(ts[i].selector); - _lv_obj_style_create_transition(obj, part_act, prev_state, new_state, &ts[i]); - } + for (i = 0; i < tsi; i++) { + lv_part_t part_act = lv_obj_style_get_selector_part(ts[i].selector); + _lv_obj_style_create_transition(obj, part_act, prev_state, new_state, + &ts[i]); + } - lv_mem_buf_release(ts); + lv_mem_buf_release(ts); - if(cmp_res == _LV_STYLE_STATE_CMP_DIFF_REDRAW) { - lv_obj_invalidate(obj); - } - else if(cmp_res == _LV_STYLE_STATE_CMP_DIFF_LAYOUT) { - lv_obj_refresh_style(obj, LV_PART_ANY, LV_STYLE_PROP_ANY); - } - else if(cmp_res == _LV_STYLE_STATE_CMP_DIFF_DRAW_PAD) { - lv_obj_invalidate(obj); - lv_obj_refresh_ext_draw_size(obj); - } + if (cmp_res == _LV_STYLE_STATE_CMP_DIFF_REDRAW) { + lv_obj_invalidate(obj); + } else if (cmp_res == _LV_STYLE_STATE_CMP_DIFF_LAYOUT) { + lv_obj_refresh_style(obj, LV_PART_ANY, LV_STYLE_PROP_ANY); + } else if (cmp_res == _LV_STYLE_STATE_CMP_DIFF_DRAW_PAD) { + lv_obj_invalidate(obj); + lv_obj_refresh_ext_draw_size(obj); + } } -static bool obj_valid_child(const lv_obj_t * parent, const lv_obj_t * obj_to_find) -{ - /*Check all children of `parent`*/ - uint32_t child_cnt = 0; - if(parent->spec_attr) child_cnt = parent->spec_attr->child_cnt; - uint32_t i; - for(i = 0; i < child_cnt; i++) { - lv_obj_t * child = parent->spec_attr->children[i]; - if(child == obj_to_find) { - return true; - } - - /*Check the children*/ - bool found = obj_valid_child(child, obj_to_find); - if(found) { - return true; - } +static bool obj_valid_child(const lv_obj_t *parent, + const lv_obj_t *obj_to_find) { + /*Check all children of `parent`*/ + uint32_t child_cnt = 0; + if (parent->spec_attr) child_cnt = parent->spec_attr->child_cnt; + uint32_t i; + for (i = 0; i < child_cnt; i++) { + lv_obj_t *child = parent->spec_attr->children[i]; + if (child == obj_to_find) { + return true; } - return false; + + /*Check the children*/ + bool found = obj_valid_child(child, obj_to_find); + if (found) { + return true; + } + } + return false; } diff --git a/libraries/lvgl-8.2.0/src/core/lv_obj.h b/libraries/lvgl-8.2.0/src/core/lv_obj.h index 7bd89c8a..9ce66985 100644 --- a/libraries/lvgl-8.2.0/src/core/lv_obj.h +++ b/libraries/lvgl-8.2.0/src/core/lv_obj.h @@ -13,16 +13,17 @@ extern "C" { /********************* * INCLUDES *********************/ -#include "../lv_conf_internal.h" - -#include #include +#include + +#include "../hal/lv_esp3d_hal.h" +#include "../lv_conf_internal.h" +#include "../misc/lv_area.h" +#include "../misc/lv_assert.h" +#include "../misc/lv_color.h" #include "../misc/lv_style.h" #include "../misc/lv_types.h" -#include "../misc/lv_area.h" -#include "../misc/lv_color.h" -#include "../misc/lv_assert.h" -#include "../hal/lv_hal.h" + /********************* * DEFINES @@ -39,22 +40,23 @@ struct _lv_obj_t; * OR-ed values are possible */ enum { - LV_STATE_DEFAULT = 0x0000, - LV_STATE_CHECKED = 0x0001, - LV_STATE_FOCUSED = 0x0002, - LV_STATE_FOCUS_KEY = 0x0004, - LV_STATE_EDITED = 0x0008, - LV_STATE_HOVERED = 0x0010, - LV_STATE_PRESSED = 0x0020, - LV_STATE_SCROLLED = 0x0040, - LV_STATE_DISABLED = 0x0080, + LV_STATE_DEFAULT = 0x0000, + LV_STATE_CHECKED = 0x0001, + LV_STATE_FOCUSED = 0x0002, + LV_STATE_FOCUS_KEY = 0x0004, + LV_STATE_EDITED = 0x0008, + LV_STATE_HOVERED = 0x0010, + LV_STATE_PRESSED = 0x0020, + LV_STATE_SCROLLED = 0x0040, + LV_STATE_DISABLED = 0x0080, - LV_STATE_USER_1 = 0x1000, - LV_STATE_USER_2 = 0x2000, - LV_STATE_USER_3 = 0x4000, - LV_STATE_USER_4 = 0x8000, + LV_STATE_USER_1 = 0x1000, + LV_STATE_USER_2 = 0x2000, + LV_STATE_USER_3 = 0x4000, + LV_STATE_USER_4 = 0x8000, - LV_STATE_ANY = 0xFFFF, /**< Special value can be used in some functions to target all states*/ + LV_STATE_ANY = 0xFFFF, /**< Special value can be used in some functions to + target all states*/ }; typedef uint16_t lv_state_t; @@ -66,18 +68,23 @@ typedef uint16_t lv_state_t; * Note every part is used by every widget */ enum { - LV_PART_MAIN = 0x000000, /**< A background like rectangle*/ - LV_PART_SCROLLBAR = 0x010000, /**< The scrollbar(s)*/ - LV_PART_INDICATOR = 0x020000, /**< Indicator, e.g. for slider, bar, switch, or the tick box of the checkbox*/ - LV_PART_KNOB = 0x030000, /**< Like handle to grab to adjust the value*/ - LV_PART_SELECTED = 0x040000, /**< Indicate the currently selected option or section*/ - LV_PART_ITEMS = 0x050000, /**< Used if the widget has multiple similar elements (e.g. table cells)*/ - LV_PART_TICKS = 0x060000, /**< Ticks on scale e.g. for a chart or meter*/ - LV_PART_CURSOR = 0x070000, /**< Mark a specific place e.g. for text area's cursor or on a chart*/ + LV_PART_MAIN = 0x000000, /**< A background like rectangle*/ + LV_PART_SCROLLBAR = 0x010000, /**< The scrollbar(s)*/ + LV_PART_INDICATOR = 0x020000, /**< Indicator, e.g. for slider, bar, switch, or + the tick box of the checkbox*/ + LV_PART_KNOB = 0x030000, /**< Like handle to grab to adjust the value*/ + LV_PART_SELECTED = + 0x040000, /**< Indicate the currently selected option or section*/ + LV_PART_ITEMS = 0x050000, /**< Used if the widget has multiple similar + elements (e.g. table cells)*/ + LV_PART_TICKS = 0x060000, /**< Ticks on scale e.g. for a chart or meter*/ + LV_PART_CURSOR = 0x070000, /**< Mark a specific place e.g. for text area's + cursor or on a chart*/ - LV_PART_CUSTOM_FIRST = 0x080000, /**< Extension point for custom widgets*/ + LV_PART_CUSTOM_FIRST = 0x080000, /**< Extension point for custom widgets*/ - LV_PART_ANY = 0x0F0000, /**< Special value can be used in some functions to target all parts*/ + LV_PART_ANY = 0x0F0000, /**< Special value can be used in some functions to + target all parts*/ }; typedef uint32_t lv_part_t; @@ -87,41 +94,62 @@ typedef uint32_t lv_part_t; * OR-ed values are possible */ enum { - LV_OBJ_FLAG_HIDDEN = (1L << 0), /**< Make the object hidden. (Like it wasn't there at all)*/ - LV_OBJ_FLAG_CLICKABLE = (1L << 1), /**< Make the object clickable by the input devices*/ - LV_OBJ_FLAG_CLICK_FOCUSABLE = (1L << 2), /**< Add focused state to the object when clicked*/ - LV_OBJ_FLAG_CHECKABLE = (1L << 3), /**< Toggle checked state when the object is clicked*/ - LV_OBJ_FLAG_SCROLLABLE = (1L << 4), /**< Make the object scrollable*/ - LV_OBJ_FLAG_SCROLL_ELASTIC = (1L << 5), /**< Allow scrolling inside but with slower speed*/ - LV_OBJ_FLAG_SCROLL_MOMENTUM = (1L << 6), /**< Make the object scroll further when "thrown"*/ - LV_OBJ_FLAG_SCROLL_ONE = (1L << 7), /**< Allow scrolling only one snappable children*/ - LV_OBJ_FLAG_SCROLL_CHAIN_HOR = (1L << 8), /**< Allow propagating the horizontal scroll to a parent*/ - LV_OBJ_FLAG_SCROLL_CHAIN_VER = (1L << 9), /**< Allow propagating the vertical scroll to a parent*/ - LV_OBJ_FLAG_SCROLL_CHAIN = (LV_OBJ_FLAG_SCROLL_CHAIN_HOR | LV_OBJ_FLAG_SCROLL_CHAIN_VER), - LV_OBJ_FLAG_SCROLL_ON_FOCUS = (1L << 10), /**< Automatically scroll object to make it visible when focused*/ - LV_OBJ_FLAG_SCROLL_WITH_ARROW = (1L << 11), /**< Allow scrolling the focused object with arrow keys*/ - LV_OBJ_FLAG_SNAPPABLE = (1L << 12), /**< If scroll snap is enabled on the parent it can snap to this object*/ - LV_OBJ_FLAG_PRESS_LOCK = (1L << 13), /**< Keep the object pressed even if the press slid from the object*/ - LV_OBJ_FLAG_EVENT_BUBBLE = (1L << 14), /**< Propagate the events to the parent too*/ - LV_OBJ_FLAG_GESTURE_BUBBLE = (1L << 15), /**< Propagate the gestures to the parent*/ - LV_OBJ_FLAG_ADV_HITTEST = (1L << 16), /**< Allow performing more accurate hit (click) test. E.g. consider rounded corners.*/ - LV_OBJ_FLAG_IGNORE_LAYOUT = (1L << 17), /**< Make the object position-able by the layouts*/ - LV_OBJ_FLAG_FLOATING = (1L << 18), /**< Do not scroll the object when the parent scrolls and ignore layout*/ - LV_OBJ_FLAG_OVERFLOW_VISIBLE = (1L << 19), /**< Do not clip the children's content to the parent's boundary*/ + LV_OBJ_FLAG_HIDDEN = + (1L << 0), /**< Make the object hidden. (Like it wasn't there at all)*/ + LV_OBJ_FLAG_CLICKABLE = + (1L << 1), /**< Make the object clickable by the input devices*/ + LV_OBJ_FLAG_CLICK_FOCUSABLE = + (1L << 2), /**< Add focused state to the object when clicked*/ + LV_OBJ_FLAG_CHECKABLE = + (1L << 3), /**< Toggle checked state when the object is clicked*/ + LV_OBJ_FLAG_SCROLLABLE = (1L << 4), /**< Make the object scrollable*/ + LV_OBJ_FLAG_SCROLL_ELASTIC = + (1L << 5), /**< Allow scrolling inside but with slower speed*/ + LV_OBJ_FLAG_SCROLL_MOMENTUM = + (1L << 6), /**< Make the object scroll further when "thrown"*/ + LV_OBJ_FLAG_SCROLL_ONE = + (1L << 7), /**< Allow scrolling only one snappable children*/ + LV_OBJ_FLAG_SCROLL_CHAIN_HOR = + (1L << 8), /**< Allow propagating the horizontal scroll to a parent*/ + LV_OBJ_FLAG_SCROLL_CHAIN_VER = + (1L << 9), /**< Allow propagating the vertical scroll to a parent*/ + LV_OBJ_FLAG_SCROLL_CHAIN = + (LV_OBJ_FLAG_SCROLL_CHAIN_HOR | LV_OBJ_FLAG_SCROLL_CHAIN_VER), + LV_OBJ_FLAG_SCROLL_ON_FOCUS = (1L << 10), /**< Automatically scroll object to + make it visible when focused*/ + LV_OBJ_FLAG_SCROLL_WITH_ARROW = + (1L << 11), /**< Allow scrolling the focused object with arrow keys*/ + LV_OBJ_FLAG_SNAPPABLE = (1L << 12), /**< If scroll snap is enabled on the + parent it can snap to this object*/ + LV_OBJ_FLAG_PRESS_LOCK = (1L << 13), /**< Keep the object pressed even if the + press slid from the object*/ + LV_OBJ_FLAG_EVENT_BUBBLE = + (1L << 14), /**< Propagate the events to the parent too*/ + LV_OBJ_FLAG_GESTURE_BUBBLE = + (1L << 15), /**< Propagate the gestures to the parent*/ + LV_OBJ_FLAG_ADV_HITTEST = + (1L << 16), /**< Allow performing more accurate hit (click) test. E.g. + consider rounded corners.*/ + LV_OBJ_FLAG_IGNORE_LAYOUT = + (1L << 17), /**< Make the object position-able by the layouts*/ + LV_OBJ_FLAG_FLOATING = (1L << 18), /**< Do not scroll the object when the + parent scrolls and ignore layout*/ + LV_OBJ_FLAG_OVERFLOW_VISIBLE = + (1L << 19), /**< Do not clip the children's content to the parent's + boundary*/ - LV_OBJ_FLAG_LAYOUT_1 = (1L << 23), /**< Custom flag, free to use by layouts*/ - LV_OBJ_FLAG_LAYOUT_2 = (1L << 24), /**< Custom flag, free to use by layouts*/ + LV_OBJ_FLAG_LAYOUT_1 = (1L << 23), /**< Custom flag, free to use by layouts*/ + LV_OBJ_FLAG_LAYOUT_2 = (1L << 24), /**< Custom flag, free to use by layouts*/ - LV_OBJ_FLAG_WIDGET_1 = (1L << 25), /**< Custom flag, free to use by widget*/ - LV_OBJ_FLAG_WIDGET_2 = (1L << 26), /**< Custom flag, free to use by widget*/ - LV_OBJ_FLAG_USER_1 = (1L << 27), /**< Custom flag, free to use by user*/ - LV_OBJ_FLAG_USER_2 = (1L << 28), /**< Custom flag, free to use by user*/ - LV_OBJ_FLAG_USER_3 = (1L << 29), /**< Custom flag, free to use by user*/ - LV_OBJ_FLAG_USER_4 = (1L << 30), /**< Custom flag, free to use by user*/ + LV_OBJ_FLAG_WIDGET_1 = (1L << 25), /**< Custom flag, free to use by widget*/ + LV_OBJ_FLAG_WIDGET_2 = (1L << 26), /**< Custom flag, free to use by widget*/ + LV_OBJ_FLAG_USER_1 = (1L << 27), /**< Custom flag, free to use by user*/ + LV_OBJ_FLAG_USER_2 = (1L << 28), /**< Custom flag, free to use by user*/ + LV_OBJ_FLAG_USER_3 = (1L << 29), /**< Custom flag, free to use by user*/ + LV_OBJ_FLAG_USER_4 = (1L << 30), /**< Custom flag, free to use by user*/ }; - typedef uint32_t lv_obj_flag_t; /** @@ -129,19 +157,20 @@ typedef uint32_t lv_obj_flag_t; * Used in `LV_EVENT_DRAW_PART_BEGIN` and `LV_EVENT_DRAW_PART_END` */ typedef enum { - LV_OBJ_DRAW_PART_RECTANGLE, /**< The main rectangle*/ - LV_OBJ_DRAW_PART_BORDER_POST,/**< The border if style_border_post = true*/ - LV_OBJ_DRAW_PART_SCROLLBAR, /**< The scrollbar*/ + LV_OBJ_DRAW_PART_RECTANGLE, /**< The main rectangle*/ + LV_OBJ_DRAW_PART_BORDER_POST, /**< The border if style_border_post = true*/ + LV_OBJ_DRAW_PART_SCROLLBAR, /**< The scrollbar*/ } lv_obj_draw_part_type_t; -#include "lv_obj_tree.h" +#include "lv_event.h" +#include "lv_group.h" +#include "lv_obj_class.h" +#include "lv_obj_draw.h" #include "lv_obj_pos.h" #include "lv_obj_scroll.h" #include "lv_obj_style.h" -#include "lv_obj_draw.h" -#include "lv_obj_class.h" -#include "lv_event.h" -#include "lv_group.h" +#include "lv_obj_tree.h" + /** * Make the base object's class publicly available. @@ -153,43 +182,48 @@ extern const lv_obj_class_t lv_obj_class; * They are allocated automatically if any elements is set. */ typedef struct { - struct _lv_obj_t ** children; /**< Store the pointer of the children in an array.*/ - uint32_t child_cnt; /**< Number of children*/ - lv_group_t * group_p; + struct _lv_obj_t** + children; /**< Store the pointer of the children in an array.*/ + uint32_t child_cnt; /**< Number of children*/ + lv_group_t* group_p; - struct _lv_event_dsc_t * event_dsc; /**< Dynamically allocated event callback and user data array*/ - lv_point_t scroll; /**< The current X/Y scroll offset*/ + struct _lv_event_dsc_t* + event_dsc; /**< Dynamically allocated event callback and user data array*/ + lv_point_t scroll; /**< The current X/Y scroll offset*/ - lv_coord_t ext_click_pad; /**< Extra click padding in all direction*/ - lv_coord_t ext_draw_size; /**< EXTend the size in every direction for drawing.*/ + lv_coord_t ext_click_pad; /**< Extra click padding in all direction*/ + lv_coord_t + ext_draw_size; /**< EXTend the size in every direction for drawing.*/ - lv_scrollbar_mode_t scrollbar_mode : 2; /**< How to display scrollbars*/ - lv_scroll_snap_t scroll_snap_x : 2; /**< Where to align the snappable children horizontally*/ - lv_scroll_snap_t scroll_snap_y : 2; /**< Where to align the snappable children vertically*/ - lv_dir_t scroll_dir : 4; /**< The allowed scroll direction(s)*/ - uint8_t event_dsc_cnt; /**< Number of event callbacks stored in `event_dsc` array*/ + lv_scrollbar_mode_t scrollbar_mode : 2; /**< How to display scrollbars*/ + lv_scroll_snap_t scroll_snap_x : 2; /**< Where to align the snappable children + horizontally*/ + lv_scroll_snap_t + scroll_snap_y : 2; /**< Where to align the snappable children vertically*/ + lv_dir_t scroll_dir : 4; /**< The allowed scroll direction(s)*/ + uint8_t event_dsc_cnt; /**< Number of event callbacks stored in `event_dsc` + array*/ } _lv_obj_spec_attr_t; typedef struct _lv_obj_t { - const lv_obj_class_t * class_p; - struct _lv_obj_t * parent; - _lv_obj_spec_attr_t * spec_attr; - _lv_obj_style_t * styles; + const lv_obj_class_t* class_p; + struct _lv_obj_t* parent; + _lv_obj_spec_attr_t* spec_attr; + _lv_obj_style_t* styles; #if LV_USE_USER_DATA - void * user_data; + void* user_data; #endif - lv_area_t coords; - lv_obj_flag_t flags; - lv_state_t state; - uint16_t layout_inv : 1; - uint16_t scr_layout_inv : 1; - uint16_t skip_trans : 1; - uint16_t style_cnt : 6; - uint16_t h_layout : 1; - uint16_t w_layout : 1; + lv_area_t coords; + lv_obj_flag_t flags; + lv_state_t state; + uint16_t layout_inv : 1; + uint16_t scr_layout_inv : 1; + uint16_t skip_trans : 1; + uint16_t style_cnt : 6; + uint16_t h_layout : 1; + uint16_t w_layout : 1; } lv_obj_t; - /********************** * GLOBAL PROTOTYPES **********************/ @@ -204,7 +238,8 @@ void lv_init(void); /** * Deinit the 'lv' library - * Currently only implemented when not using custom allocators, or GC is enabled. + * Currently only implemented when not using custom allocators, or GC is + * enabled. */ void lv_deinit(void); @@ -217,11 +252,11 @@ bool lv_is_initialized(void); /** * Create a base object (a rectangle) - * @param parent pointer to a parent object. If NULL then a screen will be created. + * @param parent pointer to a parent object. If NULL then a screen will be + * created. * @return pointer to the new object */ -lv_obj_t * lv_obj_create(lv_obj_t * parent); - +lv_obj_t* lv_obj_create(lv_obj_t* parent); /*===================== * Setter functions @@ -232,31 +267,32 @@ lv_obj_t * lv_obj_create(lv_obj_t * parent); * @param obj pointer to an object * @param f R-ed values from `lv_obj_flag_t` to set. */ -void lv_obj_add_flag(lv_obj_t * obj, lv_obj_flag_t f); +void lv_obj_add_flag(lv_obj_t* obj, lv_obj_flag_t f); /** * Clear one or more flags * @param obj pointer to an object * @param f OR-ed values from `lv_obj_flag_t` to set. */ -void lv_obj_clear_flag(lv_obj_t * obj, lv_obj_flag_t f); - +void lv_obj_clear_flag(lv_obj_t* obj, lv_obj_flag_t f); /** - * Add one or more states to the object. The other state bits will remain unchanged. - * If specified in the styles, transition animation will be started from the previous state to the current. + * Add one or more states to the object. The other state bits will remain + * unchanged. If specified in the styles, transition animation will be started + * from the previous state to the current. * @param obj pointer to an object * @param state the states to add. E.g `LV_STATE_PRESSED | LV_STATE_FOCUSED` */ -void lv_obj_add_state(lv_obj_t * obj, lv_state_t state); +void lv_obj_add_state(lv_obj_t* obj, lv_state_t state); /** - * Remove one or more states to the object. The other state bits will remain unchanged. - * If specified in the styles, transition animation will be started from the previous state to the current. + * Remove one or more states to the object. The other state bits will remain + * unchanged. If specified in the styles, transition animation will be started + * from the previous state to the current. * @param obj pointer to an object * @param state the states to add. E.g `LV_STATE_PRESSED | LV_STATE_FOCUSED` */ -void lv_obj_clear_state(lv_obj_t * obj, lv_state_t state); +void lv_obj_clear_state(lv_obj_t* obj, lv_state_t state); /** * Set the user_data field of the object @@ -264,9 +300,8 @@ void lv_obj_clear_state(lv_obj_t * obj, lv_state_t state); * @param user_data pointer to the new user_data. */ #if LV_USE_USER_DATA -static inline void lv_obj_set_user_data(lv_obj_t * obj, void * user_data) -{ - obj->user_data = user_data; +static inline void lv_obj_set_user_data(lv_obj_t* obj, void* user_data) { + obj->user_data = user_data; } #endif @@ -280,22 +315,23 @@ static inline void lv_obj_set_user_data(lv_obj_t * obj, void * user_data) * @param f the flag(s) to check (OR-ed values can be used) * @return true: all flags are set; false: not all flags are set */ -bool lv_obj_has_flag(const lv_obj_t * obj, lv_obj_flag_t f); +bool lv_obj_has_flag(const lv_obj_t* obj, lv_obj_flag_t f); /** * Check if a given flag or any of the flags are set on an object. * @param obj pointer to an object * @param f the flag(s) to check (OR-ed values can be used) - * @return true: at lest one flag flag is set; false: none of the flags are set + * @return true: at lest one flag flag is set; false: none of the flags are + * set */ -bool lv_obj_has_flag_any(const lv_obj_t * obj, lv_obj_flag_t f); +bool lv_obj_has_flag_any(const lv_obj_t* obj, lv_obj_flag_t f); /** * Get the state of an object * @param obj pointer to an object * @return the state (OR-ed values from `lv_state_t`) */ -lv_state_t lv_obj_get_state(const lv_obj_t * obj); +lv_state_t lv_obj_get_state(const lv_obj_t* obj); /** * Check if the object is in a given state or not. @@ -303,14 +339,14 @@ lv_state_t lv_obj_get_state(const lv_obj_t * obj); * @param state a state or combination of states to check * @return true: `obj` is in `state`; false: `obj` is not in `state` */ -bool lv_obj_has_state(const lv_obj_t * obj, lv_state_t state); +bool lv_obj_has_state(const lv_obj_t* obj, lv_state_t state); /** * Get the group of the object * @param obj pointer to an object * @return the pointer to group of the object */ -void * lv_obj_get_group(const lv_obj_t * obj); +void* lv_obj_get_group(const lv_obj_t* obj); /** * Get the user_data field of the object @@ -318,9 +354,8 @@ void * lv_obj_get_group(const lv_obj_t * obj); * @return the pointer to the user_data of the object */ #if LV_USE_USER_DATA -static inline void * lv_obj_get_user_data(lv_obj_t * obj) -{ - return obj->user_data; +static inline void* lv_obj_get_user_data(lv_obj_t* obj) { + return obj->user_data; } #endif @@ -332,7 +367,7 @@ static inline void * lv_obj_get_user_data(lv_obj_t * obj) * Allocate special data for an object if not allocated yet. * @param obj pointer to an object */ -void lv_obj_allocate_spec_attr(lv_obj_t * obj); +void lv_obj_allocate_spec_attr(lv_obj_t* obj); /** * Check the type of obj. @@ -340,7 +375,7 @@ void lv_obj_allocate_spec_attr(lv_obj_t * obj); * @param class_p a class to check (e.g. `lv_slider_class`) * @return true: `class_p` is the `obj` class. */ -bool lv_obj_check_type(const lv_obj_t * obj, const lv_obj_class_t * class_p); +bool lv_obj_check_type(const lv_obj_t* obj, const lv_obj_class_t* class_p); /** * Check if any object has a given class (type). @@ -349,34 +384,33 @@ bool lv_obj_check_type(const lv_obj_t * obj, const lv_obj_class_t * class_p); * @param class_p a class to check (e.g. `lv_slider_class`) * @return true: `obj` has the given class */ -bool lv_obj_has_class(const lv_obj_t * obj, const lv_obj_class_t * class_p); +bool lv_obj_has_class(const lv_obj_t* obj, const lv_obj_class_t* class_p); /** * Get the class (type) of the object * @param obj pointer to an object * @return the class (type) of the object */ -const lv_obj_class_t * lv_obj_get_class(const lv_obj_t * obj); +const lv_obj_class_t* lv_obj_get_class(const lv_obj_t* obj); /** * Check if any object is still "alive". * @param obj pointer to an object * @return true: valid */ -bool lv_obj_is_valid(const lv_obj_t * obj); +bool lv_obj_is_valid(const lv_obj_t* obj); /** - * Scale the given number of pixels (a distance or size) relative to a 160 DPI display - * considering the DPI of the `obj`'s display. - * It ensures that e.g. `lv_dpx(100)` will have the same physical size regardless to the - * DPI of the display. + * Scale the given number of pixels (a distance or size) relative to a 160 DPI + * display considering the DPI of the `obj`'s display. It ensures that e.g. + * `lv_dpx(100)` will have the same physical size regardless to the DPI of the + * display. * @param obj an object whose display's dpi should be considered * @param n the number of pixels to scale * @return `n x current_dpi/160` */ -static inline lv_coord_t lv_obj_dpx(const lv_obj_t * obj, lv_coord_t n) -{ - return _LV_DPX_CALC(lv_disp_get_dpi(lv_obj_get_disp(obj)), n); +static inline lv_coord_t lv_obj_dpx(const lv_obj_t* obj, lv_coord_t n) { + return _LV_DPX_CALC(lv_disp_get_dpi(lv_obj_get_disp(obj)), n); } /********************** @@ -384,23 +418,26 @@ static inline lv_coord_t lv_obj_dpx(const lv_obj_t * obj, lv_coord_t n) **********************/ #if LV_USE_ASSERT_OBJ -# define LV_ASSERT_OBJ(obj_p, obj_class) \ - do { \ - LV_ASSERT_MSG(obj_p != NULL, "The object is NULL"); \ - LV_ASSERT_MSG(lv_obj_has_class(obj_p, obj_class) == true, "Incompatible object type."); \ - LV_ASSERT_MSG(lv_obj_is_valid(obj_p) == true, "The object is invalid, deleted or corrupted?"); \ - } while(0) -# else -# define LV_ASSERT_OBJ(obj_p, obj_class) do{}while(0) +#define LV_ASSERT_OBJ(obj_p, obj_class) \ + do { \ + LV_ASSERT_MSG(obj_p != NULL, "The object is NULL"); \ + LV_ASSERT_MSG(lv_obj_has_class(obj_p, obj_class) == true, \ + "Incompatible object type."); \ + LV_ASSERT_MSG(lv_obj_is_valid(obj_p) == true, \ + "The object is invalid, deleted or corrupted?"); \ + } while (0) +#else +#define LV_ASSERT_OBJ(obj_p, obj_class) \ + do { \ + } while (0) #endif #if LV_USE_LOG && LV_LOG_TRACE_OBJ_CREATE -# define LV_TRACE_OBJ_CREATE(...) LV_LOG_TRACE(__VA_ARGS__) +#define LV_TRACE_OBJ_CREATE(...) LV_LOG_TRACE(__VA_ARGS__) #else -# define LV_TRACE_OBJ_CREATE(...) +#define LV_TRACE_OBJ_CREATE(...) #endif - #ifdef __cplusplus } /*extern "C"*/ #endif diff --git a/libraries/lvgl-8.2.0/src/hal/lv_hal.h b/libraries/lvgl-8.2.0/src/hal/lv_hal.h index 167da1f4..a603680a 100644 --- a/libraries/lvgl-8.2.0/src/hal/lv_hal.h +++ b/libraries/lvgl-8.2.0/src/hal/lv_hal.h @@ -1,5 +1,5 @@ /** - * @file lv_hal.h + * @file lv_esp3d_hal.h * */ @@ -21,13 +21,14 @@ extern "C" { * DEFINES *********************/ /** - * Same as Android's DIP. (Different name is chosen to avoid mistype between LV_DPI and LV_DIP) - * 1 dip is 1 px on a 160 DPI screen - * 1 dip is 2 px on a 320 DPI screen + * Same as Android's DIP. (Different name is chosen to avoid mistype between + * LV_DPI and LV_DIP) 1 dip is 1 px on a 160 DPI screen 1 dip is 2 px on a 320 + * DPI screen * https://stackoverflow.com/questions/2025282/what-is-the-difference-between-px-dip-dp-and-sp */ -#define _LV_DPX_CALC(dpi, n) ((n) == 0 ? 0 :LV_MAX((( (dpi) * (n) + 80) / 160), 1)) /*+80 for rounding*/ -#define LV_DPX(n) _LV_DPX_CALC(lv_disp_get_dpi(NULL), n) +#define _LV_DPX_CALC(dpi, n) \ + ((n) == 0 ? 0 : LV_MAX((((dpi) * (n) + 80) / 160), 1)) /*+80 for rounding*/ +#define LV_DPX(n) _LV_DPX_CALC(lv_disp_get_dpi(NULL), n) /********************** * TYPEDEFS diff --git a/libraries/lvgl-8.2.0/src/hal/lv_hal_disp.c b/libraries/lvgl-8.2.0/src/hal/lv_hal_disp.c index 9a8e42d2..b3201d57 100644 --- a/libraries/lvgl-8.2.0/src/hal/lv_hal_disp.c +++ b/libraries/lvgl-8.2.0/src/hal/lv_hal_disp.c @@ -8,22 +8,23 @@ /********************* * INCLUDES *********************/ -#include #include -#include "lv_hal.h" -#include "../misc/lv_mem.h" -#include "../misc/lv_gc.h" -#include "../misc/lv_assert.h" +#include + #include "../core/lv_obj.h" #include "../core/lv_refr.h" #include "../core/lv_theme.h" #include "../draw/sdl/lv_draw_sdl.h" -#include "../draw/sw/lv_draw_sw.h" -#include "../draw/sdl/lv_draw_sdl.h" #include "../draw/stm32_dma2d/lv_gpu_stm32_dma2d.h" +#include "../draw/sw/lv_draw_sw.h" +#include "../misc/lv_assert.h" +#include "../misc/lv_gc.h" +#include "../misc/lv_mem.h" +#include "lv_esp3d_hal.h" + #if LV_USE_THEME_DEFAULT - #include "../extra/themes/default/lv_theme_default.h" +#include "../extra/themes/default/lv_theme_default.h" #endif /********************* @@ -37,30 +38,37 @@ /********************** * STATIC PROTOTYPES **********************/ -static lv_obj_tree_walk_res_t invalidate_layout_cb(lv_obj_t * obj, void * user_data); +static lv_obj_tree_walk_res_t invalidate_layout_cb(lv_obj_t* obj, + void* user_data); -static void set_px_true_color_alpha(lv_disp_drv_t * disp_drv, uint8_t * buf, lv_coord_t buf_w, lv_coord_t x, - lv_coord_t y, - lv_color_t color, lv_opa_t opa); +static void set_px_true_color_alpha(lv_disp_drv_t* disp_drv, uint8_t* buf, + lv_coord_t buf_w, lv_coord_t x, + lv_coord_t y, lv_color_t color, + lv_opa_t opa); -static void set_px_cb_alpha1(lv_disp_drv_t * disp_drv, uint8_t * buf, lv_coord_t buf_w, lv_coord_t x, lv_coord_t y, +static void set_px_cb_alpha1(lv_disp_drv_t* disp_drv, uint8_t* buf, + lv_coord_t buf_w, lv_coord_t x, lv_coord_t y, lv_color_t color, lv_opa_t opa); -static void set_px_cb_alpha2(lv_disp_drv_t * disp_drv, uint8_t * buf, lv_coord_t buf_w, lv_coord_t x, lv_coord_t y, +static void set_px_cb_alpha2(lv_disp_drv_t* disp_drv, uint8_t* buf, + lv_coord_t buf_w, lv_coord_t x, lv_coord_t y, lv_color_t color, lv_opa_t opa); -static void set_px_cb_alpha4(lv_disp_drv_t * disp_drv, uint8_t * buf, lv_coord_t buf_w, lv_coord_t x, lv_coord_t y, +static void set_px_cb_alpha4(lv_disp_drv_t* disp_drv, uint8_t* buf, + lv_coord_t buf_w, lv_coord_t x, lv_coord_t y, lv_color_t color, lv_opa_t opa); -static void set_px_cb_alpha8(lv_disp_drv_t * disp_drv, uint8_t * buf, lv_coord_t buf_w, lv_coord_t x, lv_coord_t y, +static void set_px_cb_alpha8(lv_disp_drv_t* disp_drv, uint8_t* buf, + lv_coord_t buf_w, lv_coord_t x, lv_coord_t y, lv_color_t color, lv_opa_t opa); -static void set_px_alpha_generic(lv_img_dsc_t * d, lv_coord_t x, lv_coord_t y, lv_color_t color, lv_opa_t opa); +static void set_px_alpha_generic(lv_img_dsc_t* d, lv_coord_t x, lv_coord_t y, + lv_color_t color, lv_opa_t opa); /********************** * STATIC VARIABLES **********************/ -static lv_disp_t * disp_def; +static lv_disp_t* disp_def; /********************** * MACROS @@ -76,44 +84,41 @@ static lv_disp_t * disp_def; * After it you can set the fields. * @param driver pointer to driver variable to initialize */ -void lv_disp_drv_init(lv_disp_drv_t * driver) -{ - lv_memset_00(driver, sizeof(lv_disp_drv_t)); - - driver->hor_res = 320; - driver->ver_res = 240; - driver->physical_hor_res = -1; - driver->physical_ver_res = -1; - driver->offset_x = 0; - driver->offset_y = 0; - driver->antialiasing = LV_COLOR_DEPTH > 8 ? 1 : 0; - driver->screen_transp = LV_COLOR_SCREEN_TRANSP; - driver->dpi = LV_DPI_DEF; - driver->color_chroma_key = LV_COLOR_CHROMA_KEY; +void lv_disp_drv_init(lv_disp_drv_t* driver) { + lv_memset_00(driver, sizeof(lv_disp_drv_t)); + driver->hor_res = 320; + driver->ver_res = 240; + driver->physical_hor_res = -1; + driver->physical_ver_res = -1; + driver->offset_x = 0; + driver->offset_y = 0; + driver->antialiasing = LV_COLOR_DEPTH > 8 ? 1 : 0; + driver->screen_transp = LV_COLOR_SCREEN_TRANSP; + driver->dpi = LV_DPI_DEF; + driver->color_chroma_key = LV_COLOR_CHROMA_KEY; #if LV_USE_GPU_STM32_DMA2D - driver->draw_ctx_init = lv_draw_stm32_dma2d_ctx_init; - driver->draw_ctx_deinit = lv_draw_stm32_dma2d_ctx_init; - driver->draw_ctx_size = sizeof(lv_draw_stm32_dma2d_ctx_t); + driver->draw_ctx_init = lv_draw_stm32_dma2d_ctx_init; + driver->draw_ctx_deinit = lv_draw_stm32_dma2d_ctx_init; + driver->draw_ctx_size = sizeof(lv_draw_stm32_dma2d_ctx_t); #elif LV_USE_GPU_NXP_PXP - driver->draw_ctx_init = lv_draw_nxp_pxp_init; - driver->draw_ctx_deinit = lv_draw_nxp_pxp_init; - driver->draw_ctx_size = sizeof(lv_draw_nxp_pxp_t); + driver->draw_ctx_init = lv_draw_nxp_pxp_init; + driver->draw_ctx_deinit = lv_draw_nxp_pxp_init; + driver->draw_ctx_size = sizeof(lv_draw_nxp_pxp_t); #elif LV_USE_GPU_NXP_VG_LITE - driver->draw_ctx_init = lv_draw_nxp_vglite_init; - driver->draw_ctx_deinit = lv_draw_nxp_vglite_init; - driver->draw_ctx_size = sizeof(lv_draw_nxp_vglite_t); + driver->draw_ctx_init = lv_draw_nxp_vglite_init; + driver->draw_ctx_deinit = lv_draw_nxp_vglite_init; + driver->draw_ctx_size = sizeof(lv_draw_nxp_vglite_t); #elif LV_USE_GPU_SDL - driver->draw_ctx_init = lv_draw_sdl_init_ctx; - driver->draw_ctx_deinit = lv_draw_sdl_deinit_ctx; - driver->draw_ctx_size = sizeof(lv_draw_sdl_ctx_t); + driver->draw_ctx_init = lv_draw_sdl_init_ctx; + driver->draw_ctx_deinit = lv_draw_sdl_deinit_ctx; + driver->draw_ctx_size = sizeof(lv_draw_sdl_ctx_t); #else - driver->draw_ctx_init = lv_draw_sw_init_ctx; - driver->draw_ctx_deinit = lv_draw_sw_init_ctx; - driver->draw_ctx_size = sizeof(lv_draw_sw_ctx_t); + driver->draw_ctx_init = lv_draw_sw_init_ctx; + driver->draw_ctx_deinit = lv_draw_sw_init_ctx; + driver->draw_ctx_size = sizeof(lv_draw_sw_ctx_t); #endif - } /** @@ -121,105 +126,108 @@ void lv_disp_drv_init(lv_disp_drv_t * driver) * @param draw_buf pointer `lv_disp_draw_buf_t` variable to initialize * @param buf1 A buffer to be used by LVGL to draw the image. * Always has to specified and can't be NULL. - * Can be an array allocated by the user. E.g. `static lv_color_t disp_buf1[1024 * 10]` - * Or a memory address e.g. in external SRAM - * @param buf2 Optionally specify a second buffer to make image rendering and image flushing - * (sending to the display) parallel. - * In the `disp_drv->flush` you should use DMA or similar hardware to send - * the image to the display in the background. - * It lets LVGL to render next frame into the other buffer while previous is being - * sent. Set to `NULL` if unused. + * Can be an array allocated by the user. E.g. `static lv_color_t + * disp_buf1[1024 * 10]` Or a memory address e.g. in external SRAM + * @param buf2 Optionally specify a second buffer to make image rendering and + * image flushing (sending to the display) parallel. In the `disp_drv->flush` + * you should use DMA or similar hardware to send the image to the display in + * the background. It lets LVGL to render next frame into the other buffer while + * previous is being sent. Set to `NULL` if unused. * @param size_in_px_cnt size of the `buf1` and `buf2` in pixel count. */ -void lv_disp_draw_buf_init(lv_disp_draw_buf_t * draw_buf, void * buf1, void * buf2, uint32_t size_in_px_cnt) -{ - lv_memset_00(draw_buf, sizeof(lv_disp_draw_buf_t)); +void lv_disp_draw_buf_init(lv_disp_draw_buf_t* draw_buf, void* buf1, void* buf2, + uint32_t size_in_px_cnt) { + lv_memset_00(draw_buf, sizeof(lv_disp_draw_buf_t)); - draw_buf->buf1 = buf1; - draw_buf->buf2 = buf2; - draw_buf->buf_act = draw_buf->buf1; - draw_buf->size = size_in_px_cnt; + draw_buf->buf1 = buf1; + draw_buf->buf2 = buf2; + draw_buf->buf_act = draw_buf->buf1; + draw_buf->size = size_in_px_cnt; } /** * Register an initialized display driver. * Automatically set the first display as active. - * @param driver pointer to an initialized 'lv_disp_drv_t' variable. Only its pointer is saved! + * @param driver pointer to an initialized 'lv_disp_drv_t' variable. Only its + * pointer is saved! * @return pointer to the new display or NULL on error */ -lv_disp_t * lv_disp_drv_register(lv_disp_drv_t * driver) -{ - lv_disp_t * disp = _lv_ll_ins_head(&LV_GC_ROOT(_lv_disp_ll)); - if(!disp) { - LV_ASSERT_MALLOC(disp); - return NULL; - } +lv_disp_t* lv_disp_drv_register(lv_disp_drv_t* driver) { + lv_disp_t* disp = _lv_ll_ins_head(&LV_GC_ROOT(_lv_disp_ll)); + if (!disp) { + LV_ASSERT_MALLOC(disp); + return NULL; + } - /*Create a draw context if not created yet*/ - if(driver->draw_ctx == NULL) { - lv_draw_ctx_t * draw_ctx = lv_mem_alloc(driver->draw_ctx_size); - LV_ASSERT_MALLOC(draw_ctx); - if(draw_ctx == NULL) return NULL; - driver->draw_ctx_init(driver, draw_ctx); - driver->draw_ctx = draw_ctx; - } + /*Create a draw context if not created yet*/ + if (driver->draw_ctx == NULL) { + lv_draw_ctx_t* draw_ctx = lv_mem_alloc(driver->draw_ctx_size); + LV_ASSERT_MALLOC(draw_ctx); + if (draw_ctx == NULL) return NULL; + driver->draw_ctx_init(driver, draw_ctx); + driver->draw_ctx = draw_ctx; + } - lv_memset_00(disp, sizeof(lv_disp_t)); + lv_memset_00(disp, sizeof(lv_disp_t)); - disp->driver = driver; + disp->driver = driver; - lv_disp_t * disp_def_tmp = disp_def; - disp_def = disp; /*Temporarily change the default screen to create the default screens on the - new display*/ - /*Create a refresh timer*/ - disp->refr_timer = lv_timer_create(_lv_disp_refr_timer, LV_DISP_DEF_REFR_PERIOD, disp); - LV_ASSERT_MALLOC(disp->refr_timer); - if(disp->refr_timer == NULL) { - lv_mem_free(disp); - return NULL; - } + lv_disp_t* disp_def_tmp = disp_def; + disp_def = disp; /*Temporarily change the default screen to create the default + screens on the new display*/ + /*Create a refresh timer*/ + disp->refr_timer = + lv_timer_create(_lv_disp_refr_timer, LV_DISP_DEF_REFR_PERIOD, disp); + LV_ASSERT_MALLOC(disp->refr_timer); + if (disp->refr_timer == NULL) { + lv_mem_free(disp); + return NULL; + } - if(driver->full_refresh && driver->draw_buf->size < (uint32_t)driver->hor_res * driver->ver_res) { - driver->full_refresh = 0; - LV_LOG_WARN("full_refresh requires at least screen sized draw buffer(s)"); - } + if (driver->full_refresh && + driver->draw_buf->size < (uint32_t)driver->hor_res * driver->ver_res) { + driver->full_refresh = 0; + LV_LOG_WARN("full_refresh requires at least screen sized draw buffer(s)"); + } - disp->bg_color = lv_color_white(); + disp->bg_color = lv_color_white(); #if LV_COLOR_SCREEN_TRANSP - disp->bg_opa = LV_OPA_TRANSP; + disp->bg_opa = LV_OPA_TRANSP; #else - disp->bg_opa = LV_OPA_COVER; + disp->bg_opa = LV_OPA_COVER; #endif #if LV_USE_THEME_DEFAULT - if(lv_theme_default_is_inited() == false) { - disp->theme = lv_theme_default_init(disp, lv_palette_main(LV_PALETTE_BLUE), lv_palette_main(LV_PALETTE_RED), - LV_THEME_DEFAULT_DARK, LV_FONT_DEFAULT); - } - else { - disp->theme = lv_theme_default_get(); - } + if (lv_theme_default_is_inited() == false) { + disp->theme = lv_theme_default_init(disp, lv_palette_main(LV_PALETTE_BLUE), + lv_palette_main(LV_PALETTE_RED), + LV_THEME_DEFAULT_DARK, LV_FONT_DEFAULT); + } else { + disp->theme = lv_theme_default_get(); + } #endif - disp->act_scr = lv_obj_create(NULL); /*Create a default screen on the display*/ - disp->top_layer = lv_obj_create(NULL); /*Create top layer on the display*/ - disp->sys_layer = lv_obj_create(NULL); /*Create sys layer on the display*/ - lv_obj_remove_style_all(disp->top_layer); - lv_obj_remove_style_all(disp->sys_layer); - lv_obj_clear_flag(disp->top_layer, LV_OBJ_FLAG_CLICKABLE); - lv_obj_clear_flag(disp->sys_layer, LV_OBJ_FLAG_CLICKABLE); + disp->act_scr = + lv_obj_create(NULL); /*Create a default screen on the display*/ + disp->top_layer = lv_obj_create(NULL); /*Create top layer on the display*/ + disp->sys_layer = lv_obj_create(NULL); /*Create sys layer on the display*/ + lv_obj_remove_style_all(disp->top_layer); + lv_obj_remove_style_all(disp->sys_layer); + lv_obj_clear_flag(disp->top_layer, LV_OBJ_FLAG_CLICKABLE); + lv_obj_clear_flag(disp->sys_layer, LV_OBJ_FLAG_CLICKABLE); - lv_obj_set_scrollbar_mode(disp->top_layer, LV_SCROLLBAR_MODE_OFF); - lv_obj_set_scrollbar_mode(disp->sys_layer, LV_SCROLLBAR_MODE_OFF); + lv_obj_set_scrollbar_mode(disp->top_layer, LV_SCROLLBAR_MODE_OFF); + lv_obj_set_scrollbar_mode(disp->sys_layer, LV_SCROLLBAR_MODE_OFF); - lv_obj_invalidate(disp->act_scr); + lv_obj_invalidate(disp->act_scr); - disp_def = disp_def_tmp; /*Revert the default display*/ - if(disp_def == NULL) disp_def = disp; /*Initialize the default display*/ + disp_def = disp_def_tmp; /*Revert the default display*/ + if (disp_def == NULL) disp_def = disp; /*Initialize the default display*/ - lv_timer_ready(disp->refr_timer); /*Be sure the screen will be refreshed immediately on start up*/ + lv_timer_ready(disp->refr_timer); /*Be sure the screen will be refreshed + immediately on start up*/ - return disp; + return disp; } /** @@ -227,122 +235,114 @@ lv_disp_t * lv_disp_drv_register(lv_disp_drv_t * driver) * @param disp pointer to a display. (return value of `lv_disp_drv_register`) * @param new_drv pointer to the new driver */ -void lv_disp_drv_update(lv_disp_t * disp, lv_disp_drv_t * new_drv) -{ - disp->driver = new_drv; +void lv_disp_drv_update(lv_disp_t* disp, lv_disp_drv_t* new_drv) { + disp->driver = new_drv; - if(disp->driver->full_refresh && - disp->driver->draw_buf->size < (uint32_t)disp->driver->hor_res * disp->driver->ver_res) { - disp->driver->full_refresh = 0; - LV_LOG_WARN("full_refresh requires at least screen sized draw buffer(s)"); - } + if (disp->driver->full_refresh && + disp->driver->draw_buf->size < + (uint32_t)disp->driver->hor_res * disp->driver->ver_res) { + disp->driver->full_refresh = 0; + LV_LOG_WARN("full_refresh requires at least screen sized draw buffer(s)"); + } - lv_coord_t w = lv_disp_get_hor_res(disp); - lv_coord_t h = lv_disp_get_ver_res(disp); - uint32_t i; - for(i = 0; i < disp->screen_cnt; i++) { - lv_area_t prev_coords; - lv_obj_get_coords(disp->screens[i], &prev_coords); - lv_area_set_width(&disp->screens[i]->coords, w); - lv_area_set_height(&disp->screens[i]->coords, h); - lv_event_send(disp->screens[i], LV_EVENT_SIZE_CHANGED, &prev_coords); - } + lv_coord_t w = lv_disp_get_hor_res(disp); + lv_coord_t h = lv_disp_get_ver_res(disp); + uint32_t i; + for (i = 0; i < disp->screen_cnt; i++) { + lv_area_t prev_coords; + lv_obj_get_coords(disp->screens[i], &prev_coords); + lv_area_set_width(&disp->screens[i]->coords, w); + lv_area_set_height(&disp->screens[i]->coords, h); + lv_event_send(disp->screens[i], LV_EVENT_SIZE_CHANGED, &prev_coords); + } - /* - * This method is usually called upon orientation change, thus the screen is now a - * different size. - * The object invalidated its previous area. That area is now out of the screen area - * so we reset all invalidated areas and invalidate the active screen's new area only. - */ - lv_memset_00(disp->inv_areas, sizeof(disp->inv_areas)); - lv_memset_00(disp->inv_area_joined, sizeof(disp->inv_area_joined)); - disp->inv_p = 0; - if(disp->act_scr != NULL) lv_obj_invalidate(disp->act_scr); + /* + * This method is usually called upon orientation change, thus the screen is + * now a different size. The object invalidated its previous area. That area + * is now out of the screen area so we reset all invalidated areas and + * invalidate the active screen's new area only. + */ + lv_memset_00(disp->inv_areas, sizeof(disp->inv_areas)); + lv_memset_00(disp->inv_area_joined, sizeof(disp->inv_area_joined)); + disp->inv_p = 0; + if (disp->act_scr != NULL) lv_obj_invalidate(disp->act_scr); - lv_obj_tree_walk(NULL, invalidate_layout_cb, NULL); + lv_obj_tree_walk(NULL, invalidate_layout_cb, NULL); - if(disp->driver->drv_update_cb) disp->driver->drv_update_cb(disp->driver); + if (disp->driver->drv_update_cb) disp->driver->drv_update_cb(disp->driver); } /** * Remove a display * @param disp pointer to display */ -void lv_disp_remove(lv_disp_t * disp) -{ - bool was_default = false; - if(disp == lv_disp_get_default()) was_default = true; +void lv_disp_remove(lv_disp_t* disp) { + bool was_default = false; + if (disp == lv_disp_get_default()) was_default = true; - /*Detach the input devices*/ - lv_indev_t * indev; - indev = lv_indev_get_next(NULL); - while(indev) { - if(indev->driver->disp == disp) { - indev->driver->disp = NULL; - } - indev = lv_indev_get_next(indev); + /*Detach the input devices*/ + lv_indev_t* indev; + indev = lv_indev_get_next(NULL); + while (indev) { + if (indev->driver->disp == disp) { + indev->driver->disp = NULL; } + indev = lv_indev_get_next(indev); + } - /** delete screen and other obj */ - if(disp->sys_layer) { - lv_obj_del(disp->sys_layer); - disp->sys_layer = NULL; - } - if(disp->top_layer) { - lv_obj_del(disp->top_layer); - disp->top_layer = NULL; - } - while(disp->screen_cnt != 0) { - /*Delete the screenst*/ - lv_obj_del(disp->screens[0]); - } + /** delete screen and other obj */ + if (disp->sys_layer) { + lv_obj_del(disp->sys_layer); + disp->sys_layer = NULL; + } + if (disp->top_layer) { + lv_obj_del(disp->top_layer); + disp->top_layer = NULL; + } + while (disp->screen_cnt != 0) { + /*Delete the screenst*/ + lv_obj_del(disp->screens[0]); + } - _lv_ll_remove(&LV_GC_ROOT(_lv_disp_ll), disp); - if(disp->refr_timer) lv_timer_del(disp->refr_timer); - lv_mem_free(disp); + _lv_ll_remove(&LV_GC_ROOT(_lv_disp_ll), disp); + if (disp->refr_timer) lv_timer_del(disp->refr_timer); + lv_mem_free(disp); - if(was_default) lv_disp_set_default(_lv_ll_get_head(&LV_GC_ROOT(_lv_disp_ll))); + if (was_default) + lv_disp_set_default(_lv_ll_get_head(&LV_GC_ROOT(_lv_disp_ll))); } /** * Set a default display. The new screens will be created on it by default. * @param disp pointer to a display */ -void lv_disp_set_default(lv_disp_t * disp) -{ - disp_def = disp; -} +void lv_disp_set_default(lv_disp_t* disp) { disp_def = disp; } /** * Get the default display * @return pointer to the default display */ -lv_disp_t * lv_disp_get_default(void) -{ - return disp_def; -} +lv_disp_t* lv_disp_get_default(void) { return disp_def; } /** * Get the horizontal resolution of a display * @param disp pointer to a display (NULL to use the default display) * @return the horizontal resolution of the display */ -lv_coord_t lv_disp_get_hor_res(lv_disp_t * disp) -{ - if(disp == NULL) disp = lv_disp_get_default(); +lv_coord_t lv_disp_get_hor_res(lv_disp_t* disp) { + if (disp == NULL) disp = lv_disp_get_default(); - if(disp == NULL) { - return 0; - } - else { - switch(disp->driver->rotated) { - case LV_DISP_ROT_90: - case LV_DISP_ROT_270: - return disp->driver->ver_res; - default: - return disp->driver->hor_res; - } + if (disp == NULL) { + return 0; + } else { + switch (disp->driver->rotated) { + case LV_DISP_ROT_90: + case LV_DISP_ROT_270: + return disp->driver->ver_res; + default: + return disp->driver->hor_res; } + } } /** @@ -350,22 +350,20 @@ lv_coord_t lv_disp_get_hor_res(lv_disp_t * disp) * @param disp pointer to a display (NULL to use the default display) * @return the vertical resolution of the display */ -lv_coord_t lv_disp_get_ver_res(lv_disp_t * disp) -{ - if(disp == NULL) disp = lv_disp_get_default(); +lv_coord_t lv_disp_get_ver_res(lv_disp_t* disp) { + if (disp == NULL) disp = lv_disp_get_default(); - if(disp == NULL) { - return 0; - } - else { - switch(disp->driver->rotated) { - case LV_DISP_ROT_90: - case LV_DISP_ROT_270: - return disp->driver->hor_res; - default: - return disp->driver->ver_res; - } + if (disp == NULL) { + return 0; + } else { + switch (disp->driver->rotated) { + case LV_DISP_ROT_90: + case LV_DISP_ROT_270: + return disp->driver->hor_res; + default: + return disp->driver->ver_res; } + } } /** @@ -373,22 +371,24 @@ lv_coord_t lv_disp_get_ver_res(lv_disp_t * disp) * @param disp pointer to a display (NULL to use the default display) * @return the full / physical horizontal resolution of the display */ -lv_coord_t lv_disp_get_physical_hor_res(lv_disp_t * disp) -{ - if(disp == NULL) disp = lv_disp_get_default(); +lv_coord_t lv_disp_get_physical_hor_res(lv_disp_t* disp) { + if (disp == NULL) disp = lv_disp_get_default(); - if(disp == NULL) { - return 0; - } - else { - switch(disp->driver->rotated) { - case LV_DISP_ROT_90: - case LV_DISP_ROT_270: - return disp->driver->physical_ver_res > 0 ? disp->driver->physical_ver_res : disp->driver->ver_res; - default: - return disp->driver->physical_hor_res > 0 ? disp->driver->physical_hor_res : disp->driver->hor_res; - } + if (disp == NULL) { + return 0; + } else { + switch (disp->driver->rotated) { + case LV_DISP_ROT_90: + case LV_DISP_ROT_270: + return disp->driver->physical_ver_res > 0 + ? disp->driver->physical_ver_res + : disp->driver->ver_res; + default: + return disp->driver->physical_hor_res > 0 + ? disp->driver->physical_hor_res + : disp->driver->hor_res; } + } } /** @@ -396,22 +396,24 @@ lv_coord_t lv_disp_get_physical_hor_res(lv_disp_t * disp) * @param disp pointer to a display (NULL to use the default display) * @return the full / physical vertical resolution of the display */ -lv_coord_t lv_disp_get_physical_ver_res(lv_disp_t * disp) -{ - if(disp == NULL) disp = lv_disp_get_default(); +lv_coord_t lv_disp_get_physical_ver_res(lv_disp_t* disp) { + if (disp == NULL) disp = lv_disp_get_default(); - if(disp == NULL) { - return 0; - } - else { - switch(disp->driver->rotated) { - case LV_DISP_ROT_90: - case LV_DISP_ROT_270: - return disp->driver->physical_hor_res > 0 ? disp->driver->physical_hor_res : disp->driver->hor_res; - default: - return disp->driver->physical_ver_res > 0 ? disp->driver->physical_ver_res : disp->driver->ver_res; - } + if (disp == NULL) { + return 0; + } else { + switch (disp->driver->rotated) { + case LV_DISP_ROT_90: + case LV_DISP_ROT_270: + return disp->driver->physical_hor_res > 0 + ? disp->driver->physical_hor_res + : disp->driver->hor_res; + default: + return disp->driver->physical_ver_res > 0 + ? disp->driver->physical_ver_res + : disp->driver->ver_res; } + } } /** @@ -419,25 +421,23 @@ lv_coord_t lv_disp_get_physical_ver_res(lv_disp_t * disp) * @param disp pointer to a display (NULL to use the default display) * @return the horizontal offset from the full / physical display */ -lv_coord_t lv_disp_get_offset_x(lv_disp_t * disp) -{ - if(disp == NULL) disp = lv_disp_get_default(); +lv_coord_t lv_disp_get_offset_x(lv_disp_t* disp) { + if (disp == NULL) disp = lv_disp_get_default(); - if(disp == NULL) { - return 0; - } - else { - switch(disp->driver->rotated) { - case LV_DISP_ROT_90: - return disp->driver->offset_y; - case LV_DISP_ROT_180: - return lv_disp_get_physical_hor_res(disp) - disp->driver->offset_x; - case LV_DISP_ROT_270: - return lv_disp_get_physical_hor_res(disp) - disp->driver->offset_y; - default: - return disp->driver->offset_x; - } + if (disp == NULL) { + return 0; + } else { + switch (disp->driver->rotated) { + case LV_DISP_ROT_90: + return disp->driver->offset_y; + case LV_DISP_ROT_180: + return lv_disp_get_physical_hor_res(disp) - disp->driver->offset_x; + case LV_DISP_ROT_270: + return lv_disp_get_physical_hor_res(disp) - disp->driver->offset_y; + default: + return disp->driver->offset_x; } + } } /** @@ -445,25 +445,23 @@ lv_coord_t lv_disp_get_offset_x(lv_disp_t * disp) * @param disp pointer to a display (NULL to use the default display) * @return the horizontal offset from the full / physical display */ -lv_coord_t lv_disp_get_offset_y(lv_disp_t * disp) -{ - if(disp == NULL) disp = lv_disp_get_default(); +lv_coord_t lv_disp_get_offset_y(lv_disp_t* disp) { + if (disp == NULL) disp = lv_disp_get_default(); - if(disp == NULL) { - return 0; - } - else { - switch(disp->driver->rotated) { - case LV_DISP_ROT_90: - return disp->driver->offset_x; - case LV_DISP_ROT_180: - return lv_disp_get_physical_ver_res(disp) - disp->driver->offset_y; - case LV_DISP_ROT_270: - return lv_disp_get_physical_ver_res(disp) - disp->driver->offset_x; - default: - return disp->driver->offset_y; - } + if (disp == NULL) { + return 0; + } else { + switch (disp->driver->rotated) { + case LV_DISP_ROT_90: + return disp->driver->offset_x; + case LV_DISP_ROT_180: + return lv_disp_get_physical_ver_res(disp) - disp->driver->offset_y; + case LV_DISP_ROT_270: + return lv_disp_get_physical_ver_res(disp) - disp->driver->offset_x; + default: + return disp->driver->offset_y; } + } } /** @@ -471,12 +469,11 @@ lv_coord_t lv_disp_get_offset_y(lv_disp_t * disp) * @param disp pointer to a display (NULL to use the default display) * @return true: anti-aliasing is enabled; false: disabled */ -bool lv_disp_get_antialiasing(lv_disp_t * disp) -{ - if(disp == NULL) disp = lv_disp_get_default(); - if(disp == NULL) return false; +bool lv_disp_get_antialiasing(lv_disp_t* disp) { + if (disp == NULL) disp = lv_disp_get_default(); + if (disp == NULL) return false; - return disp->driver->antialiasing ? true : false; + return disp->driver->antialiasing ? true : false; } /** @@ -484,57 +481,60 @@ bool lv_disp_get_antialiasing(lv_disp_t * disp) * @param disp pointer to a display (NULL to use the default display) * @return dpi of the display */ -lv_coord_t lv_disp_get_dpi(const lv_disp_t * disp) -{ - if(disp == NULL) disp = lv_disp_get_default(); - if(disp == NULL) return LV_DPI_DEF; /*Do not return 0 because it might be a divider*/ - return disp->driver->dpi; +lv_coord_t lv_disp_get_dpi(const lv_disp_t* disp) { + if (disp == NULL) disp = lv_disp_get_default(); + if (disp == NULL) + return LV_DPI_DEF; /*Do not return 0 because it might be a divider*/ + return disp->driver->dpi; } /** - * Call in the display driver's `flush_cb` function when the flushing is finished - * @param disp_drv pointer to display driver in `flush_cb` where this function is called + * Call in the display driver's `flush_cb` function when the flushing is + * finished + * @param disp_drv pointer to display driver in `flush_cb` where this function + * is called */ -LV_ATTRIBUTE_FLUSH_READY void lv_disp_flush_ready(lv_disp_drv_t * disp_drv) -{ - /*If the screen is transparent initialize it when the flushing is ready*/ +LV_ATTRIBUTE_FLUSH_READY void lv_disp_flush_ready(lv_disp_drv_t* disp_drv) { + /*If the screen is transparent initialize it when the flushing is ready*/ #if LV_COLOR_SCREEN_TRANSP - if(disp_drv->screen_transp) { - if(disp_drv->clear_cb) { - disp_drv->clear_cb(disp_drv, disp_drv->draw_buf->buf_act, disp_drv->draw_buf->size); - } - else { - lv_memset_00(disp_drv->draw_buf->buf_act, disp_drv->draw_buf->size * sizeof(lv_color32_t)); - } + if (disp_drv->screen_transp) { + if (disp_drv->clear_cb) { + disp_drv->clear_cb(disp_drv, disp_drv->draw_buf->buf_act, + disp_drv->draw_buf->size); + } else { + lv_memset_00(disp_drv->draw_buf->buf_act, + disp_drv->draw_buf->size * sizeof(lv_color32_t)); } + } #endif - disp_drv->draw_buf->flushing = 0; - disp_drv->draw_buf->flushing_last = 0; + disp_drv->draw_buf->flushing = 0; + disp_drv->draw_buf->flushing_last = 0; } /** * Tell if it's the last area of the refreshing process. - * Can be called from `flush_cb` to execute some special display refreshing if needed when all areas area flushed. + * Can be called from `flush_cb` to execute some special display refreshing if + * needed when all areas area flushed. * @param disp_drv pointer to display driver - * @return true: it's the last area to flush; false: there are other areas too which will be refreshed soon + * @return true: it's the last area to flush; false: there are other areas too + * which will be refreshed soon */ -LV_ATTRIBUTE_FLUSH_READY bool lv_disp_flush_is_last(lv_disp_drv_t * disp_drv) -{ - return disp_drv->draw_buf->flushing_last; +LV_ATTRIBUTE_FLUSH_READY bool lv_disp_flush_is_last(lv_disp_drv_t* disp_drv) { + return disp_drv->draw_buf->flushing_last; } /** * Get the next display. * @param disp pointer to the current display. NULL to initialize. - * @return the next display or NULL if no more. Give the first display when the parameter is NULL + * @return the next display or NULL if no more. Give the first display when the + * parameter is NULL */ -lv_disp_t * lv_disp_get_next(lv_disp_t * disp) -{ - if(disp == NULL) - return _lv_ll_get_head(&LV_GC_ROOT(_lv_disp_ll)); - else - return _lv_ll_get_next(&LV_GC_ROOT(_lv_disp_ll), disp); +lv_disp_t* lv_disp_get_next(lv_disp_t* disp) { + if (disp == NULL) + return _lv_ll_get_head(&LV_GC_ROOT(_lv_disp_ll)); + else + return _lv_ll_get_next(&LV_GC_ROOT(_lv_disp_ll), disp); } /** @@ -542,9 +542,8 @@ lv_disp_t * lv_disp_get_next(lv_disp_t * disp) * @param disp pointer to a display * @return pointer to the internal buffers */ -lv_disp_draw_buf_t * lv_disp_get_draw_buf(lv_disp_t * disp) -{ - return disp->driver->draw_buf; +lv_disp_draw_buf_t* lv_disp_get_draw_buf(lv_disp_t* disp) { + return disp->driver->draw_buf; } /** @@ -552,13 +551,12 @@ lv_disp_draw_buf_t * lv_disp_get_draw_buf(lv_disp_t * disp) * @param disp pointer to a display (NULL to use the default display) * @param rotation rotation angle */ -void lv_disp_set_rotation(lv_disp_t * disp, lv_disp_rot_t rotation) -{ - if(disp == NULL) disp = lv_disp_get_default(); - if(disp == NULL) return; +void lv_disp_set_rotation(lv_disp_t* disp, lv_disp_rot_t rotation) { + if (disp == NULL) disp = lv_disp_get_default(); + if (disp == NULL) return; - disp->driver->rotated = rotation; - lv_disp_drv_update(disp, disp->driver); + disp->driver->rotated = rotation; + lv_disp_drv_update(disp, disp->driver); } /** @@ -566,139 +564,139 @@ void lv_disp_set_rotation(lv_disp_t * disp, lv_disp_rot_t rotation) * @param disp pointer to a display (NULL to use the default display) * @return rotation angle */ -lv_disp_rot_t lv_disp_get_rotation(lv_disp_t * disp) -{ - if(disp == NULL) disp = lv_disp_get_default(); - if(disp == NULL) return LV_DISP_ROT_NONE; - return disp->driver->rotated; +lv_disp_rot_t lv_disp_get_rotation(lv_disp_t* disp) { + if (disp == NULL) disp = lv_disp_get_default(); + if (disp == NULL) return LV_DISP_ROT_NONE; + return disp->driver->rotated; } -void lv_disp_drv_use_generic_set_px_cb(lv_disp_drv_t * disp_drv, lv_img_cf_t cf) -{ - switch(cf) { - case LV_IMG_CF_TRUE_COLOR_ALPHA: - disp_drv->set_px_cb = set_px_true_color_alpha; - break; - case LV_IMG_CF_ALPHA_1BIT: - disp_drv->set_px_cb = set_px_cb_alpha1; - break; - case LV_IMG_CF_ALPHA_2BIT: - disp_drv->set_px_cb = set_px_cb_alpha2; - break; - case LV_IMG_CF_ALPHA_4BIT: - disp_drv->set_px_cb = set_px_cb_alpha4; - break; - case LV_IMG_CF_ALPHA_8BIT: - disp_drv->set_px_cb = set_px_cb_alpha8; - break; - default: - disp_drv->set_px_cb = NULL; - } +void lv_disp_drv_use_generic_set_px_cb(lv_disp_drv_t* disp_drv, + lv_img_cf_t cf) { + switch (cf) { + case LV_IMG_CF_TRUE_COLOR_ALPHA: + disp_drv->set_px_cb = set_px_true_color_alpha; + break; + case LV_IMG_CF_ALPHA_1BIT: + disp_drv->set_px_cb = set_px_cb_alpha1; + break; + case LV_IMG_CF_ALPHA_2BIT: + disp_drv->set_px_cb = set_px_cb_alpha2; + break; + case LV_IMG_CF_ALPHA_4BIT: + disp_drv->set_px_cb = set_px_cb_alpha4; + break; + case LV_IMG_CF_ALPHA_8BIT: + disp_drv->set_px_cb = set_px_cb_alpha8; + break; + default: + disp_drv->set_px_cb = NULL; + } } /********************** * STATIC FUNCTIONS **********************/ -static lv_obj_tree_walk_res_t invalidate_layout_cb(lv_obj_t * obj, void * user_data) -{ - LV_UNUSED(user_data); - lv_obj_mark_layout_as_dirty(obj); - return LV_OBJ_TREE_WALK_NEXT; +static lv_obj_tree_walk_res_t invalidate_layout_cb(lv_obj_t* obj, + void* user_data) { + LV_UNUSED(user_data); + lv_obj_mark_layout_as_dirty(obj); + return LV_OBJ_TREE_WALK_NEXT; } -static void set_px_cb_alpha1(lv_disp_drv_t * disp_drv, uint8_t * buf, lv_coord_t buf_w, lv_coord_t x, lv_coord_t y, - lv_color_t color, lv_opa_t opa) -{ - (void) disp_drv; /*Unused*/ +static void set_px_cb_alpha1(lv_disp_drv_t* disp_drv, uint8_t* buf, + lv_coord_t buf_w, lv_coord_t x, lv_coord_t y, + lv_color_t color, lv_opa_t opa) { + (void)disp_drv; /*Unused*/ - if(opa <= LV_OPA_MIN) return; - lv_img_dsc_t d; - d.data = buf; - d.header.w = buf_w; - d.header.cf = LV_IMG_CF_ALPHA_1BIT; + if (opa <= LV_OPA_MIN) return; + lv_img_dsc_t d; + d.data = buf; + d.header.w = buf_w; + d.header.cf = LV_IMG_CF_ALPHA_1BIT; - set_px_alpha_generic(&d, x, y, color, opa); + set_px_alpha_generic(&d, x, y, color, opa); } -static void set_px_cb_alpha2(lv_disp_drv_t * disp_drv, uint8_t * buf, lv_coord_t buf_w, lv_coord_t x, lv_coord_t y, - lv_color_t color, lv_opa_t opa) -{ - (void) disp_drv; /*Unused*/ +static void set_px_cb_alpha2(lv_disp_drv_t* disp_drv, uint8_t* buf, + lv_coord_t buf_w, lv_coord_t x, lv_coord_t y, + lv_color_t color, lv_opa_t opa) { + (void)disp_drv; /*Unused*/ - if(opa <= LV_OPA_MIN) return; - lv_img_dsc_t d; - d.data = buf; - d.header.w = buf_w; - d.header.cf = LV_IMG_CF_ALPHA_2BIT; + if (opa <= LV_OPA_MIN) return; + lv_img_dsc_t d; + d.data = buf; + d.header.w = buf_w; + d.header.cf = LV_IMG_CF_ALPHA_2BIT; - set_px_alpha_generic(&d, x, y, color, opa); + set_px_alpha_generic(&d, x, y, color, opa); } -static void set_px_cb_alpha4(lv_disp_drv_t * disp_drv, uint8_t * buf, lv_coord_t buf_w, lv_coord_t x, lv_coord_t y, - lv_color_t color, lv_opa_t opa) -{ - (void) disp_drv; /*Unused*/ +static void set_px_cb_alpha4(lv_disp_drv_t* disp_drv, uint8_t* buf, + lv_coord_t buf_w, lv_coord_t x, lv_coord_t y, + lv_color_t color, lv_opa_t opa) { + (void)disp_drv; /*Unused*/ - if(opa <= LV_OPA_MIN) return; - lv_img_dsc_t d; - d.data = buf; - d.header.w = buf_w; - d.header.cf = LV_IMG_CF_ALPHA_4BIT; + if (opa <= LV_OPA_MIN) return; + lv_img_dsc_t d; + d.data = buf; + d.header.w = buf_w; + d.header.cf = LV_IMG_CF_ALPHA_4BIT; - set_px_alpha_generic(&d, x, y, color, opa); + set_px_alpha_generic(&d, x, y, color, opa); } -static void set_px_cb_alpha8(lv_disp_drv_t * disp_drv, uint8_t * buf, lv_coord_t buf_w, lv_coord_t x, lv_coord_t y, - lv_color_t color, lv_opa_t opa) -{ - (void) disp_drv; /*Unused*/ +static void set_px_cb_alpha8(lv_disp_drv_t* disp_drv, uint8_t* buf, + lv_coord_t buf_w, lv_coord_t x, lv_coord_t y, + lv_color_t color, lv_opa_t opa) { + (void)disp_drv; /*Unused*/ - if(opa <= LV_OPA_MIN) return; - lv_img_dsc_t d; - d.data = buf; - d.header.w = buf_w; - d.header.cf = LV_IMG_CF_ALPHA_8BIT; + if (opa <= LV_OPA_MIN) return; + lv_img_dsc_t d; + d.data = buf; + d.header.w = buf_w; + d.header.cf = LV_IMG_CF_ALPHA_8BIT; - set_px_alpha_generic(&d, x, y, color, opa); + set_px_alpha_generic(&d, x, y, color, opa); } -static void set_px_alpha_generic(lv_img_dsc_t * d, lv_coord_t x, lv_coord_t y, lv_color_t color, lv_opa_t opa) -{ - d->header.always_zero = 0; - d->header.h = 1; /*Doesn't matter*/ +static void set_px_alpha_generic(lv_img_dsc_t* d, lv_coord_t x, lv_coord_t y, + lv_color_t color, lv_opa_t opa) { + d->header.always_zero = 0; + d->header.h = 1; /*Doesn't matter*/ - uint8_t br = lv_color_brightness(color); - if(opa < LV_OPA_MAX) { - uint8_t bg = lv_img_buf_get_px_alpha(d, x, y); - br = (uint16_t)((uint16_t)br * opa + (bg * (255 - opa))) >> 8; - } + uint8_t br = lv_color_brightness(color); + if (opa < LV_OPA_MAX) { + uint8_t bg = lv_img_buf_get_px_alpha(d, x, y); + br = (uint16_t)((uint16_t)br * opa + (bg * (255 - opa))) >> 8; + } - lv_img_buf_set_px_alpha(d, x, y, br); + lv_img_buf_set_px_alpha(d, x, y, br); } -static void set_px_true_color_alpha(lv_disp_drv_t * disp_drv, uint8_t * buf, lv_coord_t buf_w, lv_coord_t x, - lv_coord_t y, - lv_color_t color, lv_opa_t opa) -{ - (void) disp_drv; /*Unused*/ +static void set_px_true_color_alpha(lv_disp_drv_t* disp_drv, uint8_t* buf, + lv_coord_t buf_w, lv_coord_t x, + lv_coord_t y, lv_color_t color, + lv_opa_t opa) { + (void)disp_drv; /*Unused*/ - if(opa <= LV_OPA_MIN) return; - lv_img_dsc_t d; - d.data = buf; - d.header.always_zero = 0; - d.header.h = 1; /*Doesn't matter*/; - d.header.w = buf_w; - d.header.cf = LV_IMG_CF_TRUE_COLOR_ALPHA; + if (opa <= LV_OPA_MIN) return; + lv_img_dsc_t d; + d.data = buf; + d.header.always_zero = 0; + d.header.h = 1; /*Doesn't matter*/ + ; + d.header.w = buf_w; + d.header.cf = LV_IMG_CF_TRUE_COLOR_ALPHA; - lv_color_t bg_color = lv_img_buf_get_px_color(&d, x, y, lv_color_black()); - lv_opa_t bg_opa = lv_img_buf_get_px_alpha(&d, x, y); + lv_color_t bg_color = lv_img_buf_get_px_color(&d, x, y, lv_color_black()); + lv_opa_t bg_opa = lv_img_buf_get_px_alpha(&d, x, y); - lv_opa_t res_opa; - lv_color_t res_color; + lv_opa_t res_opa; + lv_color_t res_color; - lv_color_mix_with_alpha(bg_color, bg_opa, color, opa, &res_color, &res_opa); + lv_color_mix_with_alpha(bg_color, bg_opa, color, opa, &res_color, &res_opa); - lv_img_buf_set_px_alpha(&d, x, y, res_opa); - lv_img_buf_set_px_color(&d, x, y, res_color); + lv_img_buf_set_px_alpha(&d, x, y, res_opa); + lv_img_buf_set_px_color(&d, x, y, res_color); } diff --git a/libraries/lvgl-8.2.0/src/hal/lv_hal_disp.h b/libraries/lvgl-8.2.0/src/hal/lv_hal_disp.h index 6abbab1f..ab159f88 100644 --- a/libraries/lvgl-8.2.0/src/hal/lv_hal_disp.h +++ b/libraries/lvgl-8.2.0/src/hal/lv_hal_disp.h @@ -15,14 +15,16 @@ extern "C" { /********************* * INCLUDES *********************/ -#include #include -#include "lv_hal.h" +#include + #include "../draw/lv_draw.h" -#include "../misc/lv_color.h" #include "../misc/lv_area.h" +#include "../misc/lv_color.h" #include "../misc/lv_ll.h" #include "../misc/lv_timer.h" +#include "lv_esp3d_hal.h" + /********************* * DEFINES @@ -48,25 +50,28 @@ struct _lv_theme_t; * Structure for holding display buffer information. */ typedef struct _lv_disp_draw_buf_t { - void * buf1; /**< First display buffer.*/ - void * buf2; /**< Second display buffer.*/ + void* buf1; /**< First display buffer.*/ + void* buf2; /**< Second display buffer.*/ - /*Internal, used by the library*/ - void * buf_act; - uint32_t size; /*In pixel count*/ - /*1: flushing is in progress. (It can't be a bit field because when it's cleared from IRQ Read-Modify-Write issue might occur)*/ - volatile int flushing; - /*1: It was the last chunk to flush. (It can't be a bit field because when it's cleared from IRQ Read-Modify-Write issue might occur)*/ - volatile int flushing_last; - volatile uint32_t last_area : 1; /*1: the last area is being rendered*/ - volatile uint32_t last_part : 1; /*1: the last part of the current area is being rendered*/ + /*Internal, used by the library*/ + void* buf_act; + uint32_t size; /*In pixel count*/ + /*1: flushing is in progress. (It can't be a bit field because when it's + * cleared from IRQ Read-Modify-Write issue might occur)*/ + volatile int flushing; + /*1: It was the last chunk to flush. (It can't be a bit field because when + * it's cleared from IRQ Read-Modify-Write issue might occur)*/ + volatile int flushing_last; + volatile uint32_t last_area : 1; /*1: the last area is being rendered*/ + volatile uint32_t + last_part : 1; /*1: the last part of the current area is being rendered*/ } lv_disp_draw_buf_t; typedef enum { - LV_DISP_ROT_NONE = 0, - LV_DISP_ROT_90, - LV_DISP_ROT_180, - LV_DISP_ROT_270 + LV_DISP_ROT_NONE = 0, + LV_DISP_ROT_90, + LV_DISP_ROT_180, + LV_DISP_ROT_270 } lv_disp_rot_t; /** @@ -75,75 +80,86 @@ typedef enum { * `static lv_disp_drv_t my_drv` or allocated dynamically. */ typedef struct _lv_disp_drv_t { + lv_coord_t hor_res; /**< Horizontal resolution.*/ + lv_coord_t ver_res; /**< Vertical resolution.*/ - lv_coord_t hor_res; /**< Horizontal resolution.*/ - lv_coord_t ver_res; /**< Vertical resolution.*/ + lv_coord_t physical_hor_res; /**< Horizontal resolution of the full / physical + display. Set to -1 for fullscreen mode.*/ + lv_coord_t physical_ver_res; /**< Vertical resolution of the full / physical + display. Set to -1 for fullscreen mode.*/ + lv_coord_t offset_x; /**< Horizontal offset from the full / physical display. + Set to 0 for fullscreen mode.*/ + lv_coord_t offset_y; /**< Vertical offset from the full / physical display. + Set to 0 for fullscreen mode.*/ - lv_coord_t - physical_hor_res; /**< Horizontal resolution of the full / physical display. Set to -1 for fullscreen mode.*/ - lv_coord_t - physical_ver_res; /**< Vertical resolution of the full / physical display. Set to -1 for fullscreen mode.*/ - lv_coord_t - offset_x; /**< Horizontal offset from the full / physical display. Set to 0 for fullscreen mode.*/ - lv_coord_t offset_y; /**< Vertical offset from the full / physical display. Set to 0 for fullscreen mode.*/ + /** Pointer to a buffer initialized with `lv_disp_draw_buf_init()`. + * LVGL will use this buffer(s) to draw the screens contents*/ + lv_disp_draw_buf_t* draw_buf; - /** Pointer to a buffer initialized with `lv_disp_draw_buf_init()`. - * LVGL will use this buffer(s) to draw the screens contents*/ - lv_disp_draw_buf_t * draw_buf; + uint32_t direct_mode : 1; /**< 1: Use screen-sized buffers and draw to + absolute coordinates*/ + uint32_t full_refresh : 1; /**< 1: Always make the whole screen redrawn*/ + uint32_t sw_rotate : 1; /**< 1: use software rotation (slower)*/ + uint32_t antialiasing : 1; /**< 1: anti-aliasing is enabled on this display.*/ + uint32_t rotated : 2; /**< 1: turn the display by 90 degree. @warning Does not + update coordinates for you!*/ + uint32_t screen_transp : 1; /**Handle if the screen doesn't have a solid (opa + * == LV_OPA_COVER) background. Use only if + * required because it's slower.*/ - uint32_t direct_mode : 1; /**< 1: Use screen-sized buffers and draw to absolute coordinates*/ - uint32_t full_refresh : 1; /**< 1: Always make the whole screen redrawn*/ - uint32_t sw_rotate : 1; /**< 1: use software rotation (slower)*/ - uint32_t antialiasing : 1; /**< 1: anti-aliasing is enabled on this display.*/ - uint32_t rotated : 2; /**< 1: turn the display by 90 degree. @warning Does not update coordinates for you!*/ - uint32_t screen_transp : 1; /**Handle if the screen doesn't have a solid (opa == LV_OPA_COVER) background. - * Use only if required because it's slower.*/ + uint32_t dpi : 10; /** DPI (dot per inch) of the display. Default value is + `LV_DPI_DEF`.*/ - uint32_t dpi : 10; /** DPI (dot per inch) of the display. Default value is `LV_DPI_DEF`.*/ + /** MANDATORY: Write the internal buffer (draw_buf) to the display. + * 'lv_disp_flush_ready()' has to be called when finished*/ + void (*flush_cb)(struct _lv_disp_drv_t* disp_drv, const lv_area_t* area, + lv_color_t* color_p); - /** MANDATORY: Write the internal buffer (draw_buf) to the display. 'lv_disp_flush_ready()' has to be - * called when finished*/ - void (*flush_cb)(struct _lv_disp_drv_t * disp_drv, const lv_area_t * area, lv_color_t * color_p); + /** OPTIONAL: Extend the invalidated areas to match with the display drivers + * requirements E.g. round `y` to, 8, 16 ..) on a monochrome display*/ + void (*rounder_cb)(struct _lv_disp_drv_t* disp_drv, lv_area_t* area); - /** OPTIONAL: Extend the invalidated areas to match with the display drivers requirements - * E.g. round `y` to, 8, 16 ..) on a monochrome display*/ - void (*rounder_cb)(struct _lv_disp_drv_t * disp_drv, lv_area_t * area); + /** OPTIONAL: Set a pixel in a buffer according to the special requirements of + * the display Can be used for color format not supported in LittelvGL. E.g. 2 + * bit -> 4 gray scales + * @note Much slower then drawing with supported color formats.*/ + void (*set_px_cb)(struct _lv_disp_drv_t* disp_drv, uint8_t* buf, + lv_coord_t buf_w, lv_coord_t x, lv_coord_t y, + lv_color_t color, lv_opa_t opa); - /** OPTIONAL: Set a pixel in a buffer according to the special requirements of the display - * Can be used for color format not supported in LittelvGL. E.g. 2 bit -> 4 gray scales - * @note Much slower then drawing with supported color formats.*/ - void (*set_px_cb)(struct _lv_disp_drv_t * disp_drv, uint8_t * buf, lv_coord_t buf_w, lv_coord_t x, lv_coord_t y, - lv_color_t color, lv_opa_t opa); + void (*clear_cb)(struct _lv_disp_drv_t* disp_drv, uint8_t* buf, + uint32_t size); - void (*clear_cb)(struct _lv_disp_drv_t * disp_drv, uint8_t * buf, uint32_t size); + /** OPTIONAL: Called after every refresh cycle to tell the rendering and + * flushing time + the number of flushed pixels*/ + void (*monitor_cb)(struct _lv_disp_drv_t* disp_drv, uint32_t time, + uint32_t px); + /** OPTIONAL: Called periodically while lvgl waits for operation to be + * completed. For example flushing or GPU User can execute very simple tasks + * here or yield the task*/ + void (*wait_cb)(struct _lv_disp_drv_t* disp_drv); - /** OPTIONAL: Called after every refresh cycle to tell the rendering and flushing time + the - * number of flushed pixels*/ - void (*monitor_cb)(struct _lv_disp_drv_t * disp_drv, uint32_t time, uint32_t px); + /** OPTIONAL: Called when lvgl needs any CPU cache that affects rendering to + * be cleaned*/ + void (*clean_dcache_cb)(struct _lv_disp_drv_t* disp_drv); - /** OPTIONAL: Called periodically while lvgl waits for operation to be completed. - * For example flushing or GPU - * User can execute very simple tasks here or yield the task*/ - void (*wait_cb)(struct _lv_disp_drv_t * disp_drv); + /** OPTIONAL: called when driver parameters are updated */ + void (*drv_update_cb)(struct _lv_disp_drv_t* disp_drv); - /** OPTIONAL: Called when lvgl needs any CPU cache that affects rendering to be cleaned*/ - void (*clean_dcache_cb)(struct _lv_disp_drv_t * disp_drv); + /** On CHROMA_KEYED images this color will be transparent. + * `LV_COLOR_CHROMA_KEY` by default. (lv_conf.h)*/ + lv_color_t color_chroma_key; - /** OPTIONAL: called when driver parameters are updated */ - void (*drv_update_cb)(struct _lv_disp_drv_t * disp_drv); - - /** On CHROMA_KEYED images this color will be transparent. - * `LV_COLOR_CHROMA_KEY` by default. (lv_conf.h)*/ - lv_color_t color_chroma_key; - - lv_draw_ctx_t * draw_ctx; - void (*draw_ctx_init)(struct _lv_disp_drv_t * disp_drv, lv_draw_ctx_t * draw_ctx); - void (*draw_ctx_deinit)(struct _lv_disp_drv_t * disp_drv, lv_draw_ctx_t * draw_ctx); - size_t draw_ctx_size; + lv_draw_ctx_t* draw_ctx; + void (*draw_ctx_init)(struct _lv_disp_drv_t* disp_drv, + lv_draw_ctx_t* draw_ctx); + void (*draw_ctx_deinit)(struct _lv_disp_drv_t* disp_drv, + lv_draw_ctx_t* draw_ctx); + size_t draw_ctx_size; #if LV_USE_USER_DATA - void * user_data; /**< Custom display driver user data*/ + void* user_data; /**< Custom display driver user data*/ #endif } lv_disp_drv_t; @@ -153,37 +169,40 @@ typedef struct _lv_disp_drv_t { * @note `lv_disp_drv_t` should be the first member of the structure. */ typedef struct _lv_disp_t { - /**< Driver to the display*/ - struct _lv_disp_drv_t * driver; + /**< Driver to the display*/ + struct _lv_disp_drv_t* driver; - /**< A timer which periodically checks the dirty areas and refreshes them*/ - lv_timer_t * refr_timer; + /**< A timer which periodically checks the dirty areas and refreshes them*/ + lv_timer_t* refr_timer; - /**< The theme assigned to the screen*/ - struct _lv_theme_t * theme; + /**< The theme assigned to the screen*/ + struct _lv_theme_t* theme; - /** Screens of the display*/ - struct _lv_obj_t ** screens; /**< Array of screen objects.*/ - struct _lv_obj_t * act_scr; /**< Currently active screen on this display*/ - struct _lv_obj_t * prev_scr; /**< Previous screen. Used during screen animations*/ - struct _lv_obj_t * scr_to_load; /**< The screen prepared to load in lv_scr_load_anim*/ - struct _lv_obj_t * top_layer; /**< @see lv_disp_get_layer_top*/ - struct _lv_obj_t * sys_layer; /**< @see lv_disp_get_layer_sys*/ - uint32_t screen_cnt; -uint8_t del_prev : - 1; /**< 1: Automatically delete the previous screen when the screen load animation is ready*/ + /** Screens of the display*/ + struct _lv_obj_t** screens; /**< Array of screen objects.*/ + struct _lv_obj_t* act_scr; /**< Currently active screen on this display*/ + struct _lv_obj_t* + prev_scr; /**< Previous screen. Used during screen animations*/ + struct _lv_obj_t* + scr_to_load; /**< The screen prepared to load in lv_scr_load_anim*/ + struct _lv_obj_t* top_layer; /**< @see lv_disp_get_layer_top*/ + struct _lv_obj_t* sys_layer; /**< @see lv_disp_get_layer_sys*/ + uint32_t screen_cnt; + uint8_t del_prev : 1; /**< 1: Automatically delete the previous screen when + the screen load animation is ready*/ - lv_opa_t bg_opa; /**flush` you should use DMA or similar hardware to send - * the image to the display in the background. - * It lets LVGL to render next frame into the other buffer while previous is being - * sent. Set to `NULL` if unused. + * Can be an array allocated by the user. E.g. `static lv_color_t + * disp_buf1[1024 * 10]` Or a memory address e.g. in external SRAM + * @param buf2 Optionally specify a second buffer to make image rendering and + * image flushing (sending to the display) parallel. In the `disp_drv->flush` + * you should use DMA or similar hardware to send the image to the display in + * the background. It lets LVGL to render next frame into the other buffer while + * previous is being sent. Set to `NULL` if unused. * @param size_in_px_cnt size of the `buf1` and `buf2` in pixel count. */ -void lv_disp_draw_buf_init(lv_disp_draw_buf_t * draw_buf, void * buf1, void * buf2, uint32_t size_in_px_cnt); +void lv_disp_draw_buf_init(lv_disp_draw_buf_t* draw_buf, void* buf1, void* buf2, + uint32_t size_in_px_cnt); /** * Register an initialized display driver. * Automatically set the first display as active. - * @param driver pointer to an initialized 'lv_disp_drv_t' variable. Only its pointer is saved! + * @param driver pointer to an initialized 'lv_disp_drv_t' variable. Only its + * pointer is saved! * @return pointer to the new display or NULL on error */ -lv_disp_t * lv_disp_drv_register(lv_disp_drv_t * driver); +lv_disp_t* lv_disp_drv_register(lv_disp_drv_t* driver); /** * Update the driver in run time. * @param disp pointer to a display. (return value of `lv_disp_drv_register`) * @param new_drv pointer to the new driver */ -void lv_disp_drv_update(lv_disp_t * disp, lv_disp_drv_t * new_drv); +void lv_disp_drv_update(lv_disp_t* disp, lv_disp_drv_t* new_drv); /** * Remove a display * @param disp pointer to display */ -void lv_disp_remove(lv_disp_t * disp); +void lv_disp_remove(lv_disp_t* disp); /** * Set a default display. The new screens will be created on it by default. * @param disp pointer to a display */ -void lv_disp_set_default(lv_disp_t * disp); +void lv_disp_set_default(lv_disp_t* disp); /** * Get the default display * @return pointer to the default display */ -lv_disp_t * lv_disp_get_default(void); +lv_disp_t* lv_disp_get_default(void); /** * Get the horizontal resolution of a display * @param disp pointer to a display (NULL to use the default display) * @return the horizontal resolution of the display */ -lv_coord_t lv_disp_get_hor_res(lv_disp_t * disp); +lv_coord_t lv_disp_get_hor_res(lv_disp_t* disp); /** * Get the vertical resolution of a display * @param disp pointer to a display (NULL to use the default display) * @return the vertical resolution of the display */ -lv_coord_t lv_disp_get_ver_res(lv_disp_t * disp); +lv_coord_t lv_disp_get_ver_res(lv_disp_t* disp); /** * Get the full / physical horizontal resolution of a display * @param disp pointer to a display (NULL to use the default display) * @return the full / physical horizontal resolution of the display */ -lv_coord_t lv_disp_get_physical_hor_res(lv_disp_t * disp); +lv_coord_t lv_disp_get_physical_hor_res(lv_disp_t* disp); /** * Get the full / physical vertical resolution of a display * @param disp pointer to a display (NULL to use the default display) * @return the full / physical vertical resolution of the display */ -lv_coord_t lv_disp_get_physical_ver_res(lv_disp_t * disp); +lv_coord_t lv_disp_get_physical_ver_res(lv_disp_t* disp); /** * Get the horizontal offset from the full / physical display * @param disp pointer to a display (NULL to use the default display) * @return the horizontal offset from the full / physical display */ -lv_coord_t lv_disp_get_offset_x(lv_disp_t * disp); +lv_coord_t lv_disp_get_offset_x(lv_disp_t* disp); /** * Get the vertical offset from the full / physical display * @param disp pointer to a display (NULL to use the default display) * @return the horizontal offset from the full / physical display */ -lv_coord_t lv_disp_get_offset_y(lv_disp_t * disp); +lv_coord_t lv_disp_get_offset_y(lv_disp_t* disp); /** * Get if anti-aliasing is enabled for a display or not * @param disp pointer to a display (NULL to use the default display) * @return true: anti-aliasing is enabled; false: disabled */ -bool lv_disp_get_antialiasing(lv_disp_t * disp); +bool lv_disp_get_antialiasing(lv_disp_t* disp); /** * Get the DPI of the display * @param disp pointer to a display (NULL to use the default display) * @return dpi of the display */ -lv_coord_t lv_disp_get_dpi(const lv_disp_t * disp); - +lv_coord_t lv_disp_get_dpi(const lv_disp_t* disp); /** * Set the rotation of this display. * @param disp pointer to a display (NULL to use the default display) * @param rotation rotation angle */ -void lv_disp_set_rotation(lv_disp_t * disp, lv_disp_rot_t rotation); +void lv_disp_set_rotation(lv_disp_t* disp, lv_disp_rot_t rotation); /** * Get the current rotation of this display. * @param disp pointer to a display (NULL to use the default display) * @return rotation angle */ -lv_disp_rot_t lv_disp_get_rotation(lv_disp_t * disp); +lv_disp_rot_t lv_disp_get_rotation(lv_disp_t* disp); //! @cond Doxygen_Suppress /** - * Call in the display driver's `flush_cb` function when the flushing is finished - * @param disp_drv pointer to display driver in `flush_cb` where this function is called + * Call in the display driver's `flush_cb` function when the flushing is + * finished + * @param disp_drv pointer to display driver in `flush_cb` where this function + * is called */ -LV_ATTRIBUTE_FLUSH_READY void lv_disp_flush_ready(lv_disp_drv_t * disp_drv); +LV_ATTRIBUTE_FLUSH_READY void lv_disp_flush_ready(lv_disp_drv_t* disp_drv); /** * Tell if it's the last area of the refreshing process. - * Can be called from `flush_cb` to execute some special display refreshing if needed when all areas area flushed. + * Can be called from `flush_cb` to execute some special display refreshing if + * needed when all areas area flushed. * @param disp_drv pointer to display driver - * @return true: it's the last area to flush; false: there are other areas too which will be refreshed soon + * @return true: it's the last area to flush; false: there are other areas too + * which will be refreshed soon */ -LV_ATTRIBUTE_FLUSH_READY bool lv_disp_flush_is_last(lv_disp_drv_t * disp_drv); +LV_ATTRIBUTE_FLUSH_READY bool lv_disp_flush_is_last(lv_disp_drv_t* disp_drv); //! @endcond /** * Get the next display. * @param disp pointer to the current display. NULL to initialize. - * @return the next display or NULL if no more. Give the first display when the parameter is NULL + * @return the next display or NULL if no more. Give the first display when the + * parameter is NULL */ -lv_disp_t * lv_disp_get_next(lv_disp_t * disp); +lv_disp_t* lv_disp_get_next(lv_disp_t* disp); /** * Get the internal buffer of a display * @param disp pointer to a display * @return pointer to the internal buffers */ -lv_disp_draw_buf_t * lv_disp_get_draw_buf(lv_disp_t * disp); +lv_disp_draw_buf_t* lv_disp_get_draw_buf(lv_disp_t* disp); -void lv_disp_drv_use_generic_set_px_cb(lv_disp_drv_t * disp_drv, lv_img_cf_t cf); +void lv_disp_drv_use_generic_set_px_cb(lv_disp_drv_t* disp_drv, lv_img_cf_t cf); /********************** * MACROS diff --git a/libraries/lvgl-8.2.0/src/lv_conf_internal.h b/libraries/lvgl-8.2.0/src/lv_conf_internal.h index ebc10579..03268a24 100644 --- a/libraries/lvgl-8.2.0/src/lv_conf_internal.h +++ b/libraries/lvgl-8.2.0/src/lv_conf_internal.h @@ -2,7 +2,7 @@ * GENERATED FILE, DO NOT EDIT IT! * @file lv_conf_internal.h * Make sure all the defines of lv_conf.h have a default value -**/ + **/ #ifndef LV_CONF_INTERNAL_H #define LV_CONF_INTERNAL_H @@ -473,7 +473,7 @@ *LV_LOG_LEVEL_INFO Log important events *LV_LOG_LEVEL_WARN Log if something unwanted happened but didn't cause a problem *LV_LOG_LEVEL_ERROR Only critical issue, when the system may fail - *LV_LOG_LEVEL_USER Only logs added by the user + *LV_LOG_user Only logs added by the user *LV_LOG_LEVEL_NONE Do not log anything*/ #ifndef LV_LOG_LEVEL #ifdef CONFIG_LV_LOG_LEVEL diff --git a/libraries/lvgl-8.2.0/src/misc/lv_log.h b/libraries/lvgl-8.2.0/src/misc/lv_log.h index fa6f5ac6..30315410 100644 --- a/libraries/lvgl-8.2.0/src/misc/lv_log.h +++ b/libraries/lvgl-8.2.0/src/misc/lv_log.h @@ -13,30 +13,34 @@ extern "C" { /********************* * INCLUDES *********************/ -#include "../lv_conf_internal.h" #include +#include "../lv_conf_internal.h" #include "lv_types.h" + /********************* * DEFINES *********************/ -/*Possible log level. For compatibility declare it independently from `LV_USE_LOG`*/ +/*Possible log level. For compatibility declare it independently from + * `LV_USE_LOG`*/ #define LV_LOG_LEVEL_TRACE 0 /**< A lot of logs to give detailed information*/ -#define LV_LOG_LEVEL_INFO 1 /**< Log important events*/ -#define LV_LOG_LEVEL_WARN 2 /**< Log if something unwanted happened but didn't caused problem*/ -#define LV_LOG_LEVEL_ERROR 3 /**< Only critical issue, when the system may fail*/ -#define LV_LOG_LEVEL_USER 4 /**< Custom logs from the user*/ -#define LV_LOG_LEVEL_NONE 5 /**< Do not log anything*/ -#define _LV_LOG_LEVEL_NUM 6 /**< Number of log levels*/ +#define LV_LOG_LEVEL_INFO 1 /**< Log important events*/ +#define LV_LOG_LEVEL_WARN \ + 2 /**< Log if something unwanted happened but didn't caused problem*/ +#define LV_LOG_LEVEL_ERROR \ + 3 /**< Only critical issue, when the system may fail*/ +#define LV_LOG_user 4 /**< Custom logs from the user*/ +#define LV_LOG_LEVEL_NONE 5 /**< Do not log anything*/ +#define _LV_LOG_LEVEL_NUM 6 /**< Number of log levels*/ LV_EXPORT_CONST_INT(LV_LOG_LEVEL_TRACE); LV_EXPORT_CONST_INT(LV_LOG_LEVEL_INFO); LV_EXPORT_CONST_INT(LV_LOG_LEVEL_WARN); LV_EXPORT_CONST_INT(LV_LOG_LEVEL_ERROR); -LV_EXPORT_CONST_INT(LV_LOG_LEVEL_USER); +LV_EXPORT_CONST_INT(LV_LOG_user); LV_EXPORT_CONST_INT(LV_LOG_LEVEL_NONE); typedef int8_t lv_log_level_t; @@ -49,7 +53,7 @@ typedef int8_t lv_log_level_t; /** * Log print function. Receives a string buffer to print". */ -typedef void (*lv_log_print_g_cb_t)(const char * buf); +typedef void (*lv_log_print_g_cb_t)(const char* buf); /********************** * GLOBAL PROTOTYPES @@ -64,11 +68,12 @@ typedef void (*lv_log_print_g_cb_t)(const char * buf); void lv_log_register_print_cb(lv_log_print_g_cb_t print_cb); /** - * Print a log message via `printf` if enabled with `LV_LOG_PRINTF` in `lv_conf.h` - * and/or a print callback if registered with `lv_log_register_print_cb` + * Print a log message via `printf` if enabled with `LV_LOG_PRINTF` in + * `lv_conf.h` and/or a print callback if registered with + * `lv_log_register_print_cb` * @param buf a string message to print */ -void lv_log(const char * buf); +void lv_log(const char* buf); /** * Add a log @@ -79,61 +84,87 @@ void lv_log(const char * buf); * @param format printf-like format string * @param ... parameters for `format` */ -void _lv_log_add(lv_log_level_t level, const char * file, int line, - const char * func, const char * format, ...) LV_FORMAT_ATTRIBUTE(5, 6); +void _lv_log_add(lv_log_level_t level, const char* file, int line, + const char* func, const char* format, ...) + LV_FORMAT_ATTRIBUTE(5, 6); /********************** * MACROS **********************/ #ifndef LV_LOG_TRACE -# if LV_LOG_LEVEL <= LV_LOG_LEVEL_TRACE -# define LV_LOG_TRACE(...) _lv_log_add(LV_LOG_LEVEL_TRACE, __FILE__, __LINE__, __func__, __VA_ARGS__) -# else -# define LV_LOG_TRACE(...) do {}while(0) -# endif +#if LV_LOG_LEVEL <= LV_LOG_LEVEL_TRACE +#define LV_LOG_TRACE(...) \ + _lv_log_add(LV_LOG_LEVEL_TRACE, __FILE__, __LINE__, __func__, __VA_ARGS__) +#else +#define LV_LOG_TRACE(...) \ + do { \ + } while (0) +#endif #endif #ifndef LV_LOG_INFO -# if LV_LOG_LEVEL <= LV_LOG_LEVEL_INFO -# define LV_LOG_INFO(...) _lv_log_add(LV_LOG_LEVEL_INFO, __FILE__, __LINE__, __func__, __VA_ARGS__) -# else -# define LV_LOG_INFO(...) do {}while(0) -# endif +#if LV_LOG_LEVEL <= LV_LOG_LEVEL_INFO +#define LV_LOG_INFO(...) \ + _lv_log_add(LV_LOG_LEVEL_INFO, __FILE__, __LINE__, __func__, __VA_ARGS__) +#else +#define LV_LOG_INFO(...) \ + do { \ + } while (0) +#endif #endif #ifndef LV_LOG_WARN -# if LV_LOG_LEVEL <= LV_LOG_LEVEL_WARN -# define LV_LOG_WARN(...) _lv_log_add(LV_LOG_LEVEL_WARN, __FILE__, __LINE__, __func__, __VA_ARGS__) -# else -# define LV_LOG_WARN(...) do {}while(0) -# endif +#if LV_LOG_LEVEL <= LV_LOG_LEVEL_WARN +#define LV_LOG_WARN(...) \ + _lv_log_add(LV_LOG_LEVEL_WARN, __FILE__, __LINE__, __func__, __VA_ARGS__) +#else +#define LV_LOG_WARN(...) \ + do { \ + } while (0) +#endif #endif #ifndef LV_LOG_ERROR -# if LV_LOG_LEVEL <= LV_LOG_LEVEL_ERROR -# define LV_LOG_ERROR(...) _lv_log_add(LV_LOG_LEVEL_ERROR, __FILE__, __LINE__, __func__, __VA_ARGS__) -# else -# define LV_LOG_ERROR(...) do {}while(0) -# endif +#if LV_LOG_LEVEL <= LV_LOG_LEVEL_ERROR +#define LV_LOG_ERROR(...) \ + _lv_log_add(LV_LOG_LEVEL_ERROR, __FILE__, __LINE__, __func__, __VA_ARGS__) +#else +#define LV_LOG_ERROR(...) \ + do { \ + } while (0) +#endif #endif #ifndef LV_LOG_USER -# if LV_LOG_LEVEL <= LV_LOG_LEVEL_USER -# define LV_LOG_USER(...) _lv_log_add(LV_LOG_LEVEL_USER, __FILE__, __LINE__, __func__, __VA_ARGS__) -# else -# define LV_LOG_USER(...) do {}while(0) -# endif +#if LV_LOG_LEVEL <= LV_LOG_user +#define LV_LOG_USER(...) \ + _lv_log_add(LV_LOG_user, __FILE__, __LINE__, __func__, __VA_ARGS__) +#else +#define LV_LOG_USER(...) \ + do { \ + } while (0) +#endif #endif #else /*LV_USE_LOG*/ /*Do nothing if `LV_USE_LOG 0`*/ #define _lv_log_add(level, file, line, ...) -#define LV_LOG_TRACE(...) do {}while(0) -#define LV_LOG_INFO(...) do {}while(0) -#define LV_LOG_WARN(...) do {}while(0) -#define LV_LOG_ERROR(...) do {}while(0) -#define LV_LOG_USER(...) do {}while(0) +#define LV_LOG_TRACE(...) \ + do { \ + } while (0) +#define LV_LOG_INFO(...) \ + do { \ + } while (0) +#define LV_LOG_WARN(...) \ + do { \ + } while (0) +#define LV_LOG_ERROR(...) \ + do { \ + } while (0) +#define LV_LOG_USER(...) \ + do { \ + } while (0) #endif /*LV_USE_LOG*/ #ifdef __cplusplus