diff --git a/esp3d/configuration.h b/esp3d/configuration.h index 87de14b4..d9fd4ced 100644 --- a/esp3d/configuration.h +++ b/esp3d/configuration.h @@ -20,606 +20,611 @@ #ifndef _CONFIGURATION_H #define _CONFIGURATION_H /* Setup station as default, use AP mode first if not done -* Note: need both defined to enable it -* Uncomment and edit them to define -*/ -//#define STATION_WIFI_SSID "*********" -//#define STATION_WIFI_PASSWORD "*********" + * Note: need both defined to enable it + * Uncomment and edit them to define + */ +// #define STATION_WIFI_SSID "*********" +// #define STATION_WIFI_PASSWORD "*********" /* You can also use a different config file for SSID/password -* Just save it in same location as this configuration.h -* This file is ignored by github -*/ + * Just save it in same location as this configuration.h + * This file is ignored by github + */ #if defined __has_include -# if __has_include ("myconfig.h") -# include "myconfig.h" -# endif +#if __has_include("myconfig.h") +#include "myconfig.h" +#endif #endif /************************************ -* -* Serial Communications -* -* Settings and protocols -* -************************************/ + * + * Serial Communications + * + * Settings and protocols + * + ************************************/ /* Serial Communication protocol -* RAW_SERIAL // Basic serial protocol, without data change -* MKS_SERIAL // This is a MakerBase communication protocol, used with MKS printers and TFT, it encapsulated data in a custom protocol -*/ + * RAW_SERIAL // Basic serial protocol, without data change + * MKS_SERIAL // This is a MakerBase communication protocol, used with MKS + * printers and TFT, it encapsulated data in a custom protocol + */ #define COMMUNICATION_PROTOCOL RAW_SERIAL /* Main Serial port -* which serial ESP use to communicate to printer (ESP32 has 3 serials available, ESP8266 only 2) -* USE_SERIAL_0 //for ESP8266/32, also used by bootloader output, so consider to make it quiet -* USE_SERIAL_1 //for ESP8266/32 -* USE_SERIAL_2 //for ESP32 Only -*/ -//Main serial port + * which serial ESP use to communicate to printer (ESP32 has 3 serials + * available, ESP8266 only 2) USE_SERIAL_0 //for ESP8266/32, also used by + * bootloader output, so consider to make it quiet USE_SERIAL_1 //for ESP8266/32 + * USE_SERIAL_2 //for ESP32 Only + */ +// Main serial port #define ESP_SERIAL_OUTPUT USE_SERIAL_0 /* Bridge Serial port (deprecated on esp8266 as second serial is) -* which serial ESP use to bridge to another device (ESP32 has 3 serials available, ESP8266 only 2) -* USE_SERIAL_0 //for ESP8266/32, also used by bootloader output, so consider to make it quiet -* USE_SERIAL_1 //for ESP8266/32 -* USE_SERIAL_2 //for ESP32 Only\ -* Comment if not used -*/ -//#define ESP_SERIAL_BRIDGE_OUTPUT USE_SERIAL_1 + * which serial ESP use to bridge to another device (ESP32 has 3 serials + * available, ESP8266 only 2) USE_SERIAL_0 //for ESP8266/32, also used by + * bootloader output, so consider to make it quiet USE_SERIAL_1 //for ESP8266/32 + * USE_SERIAL_2 //for ESP32 Only\ + * Comment if not used + */ +// #define ESP_SERIAL_BRIDGE_OUTPUT USE_SERIAL_1 /* Serial buffer size -* Maximum size of the serial buffer -*/ + * Maximum size of the serial buffer + */ #define SERIAL_RX_BUFFER_SIZE 512 /************************************ -* -* Target firmware -* -* Targeted firmware that ESP3D will communicate with -* -************************************/ + * + * Target firmware + * + * Targeted firmware that ESP3D will communicate with + * + ************************************/ /* Target firmware (default UNKNOWN_FW can be changed later in settings) -* UNKNOWN_FW -* GRBL -* MARLIN -* SMOOTHIEWARE -* REPETIER -*/ + * UNKNOWN_FW + * GRBL + * MARLIN + * SMOOTHIEWARE + * REPETIER + */ #define DEFAULT_FW UNKNOWN_FW /************************************ -* -* Radio mode of ESP3D -* -* The radio mode ESP3D communicate with the network -* -************************************/ + * + * Radio mode of ESP3D + * + * The radio mode ESP3D communicate with the network + * + ************************************/ /* Use WiFi -* Enable wifi communications -*/ + * Enable wifi communications + */ #define WIFI_FEATURE /* Use Ethernet -* Enable ethernet communications -*/ -//#define ETH_FEATURE + * Enable ethernet communications + */ +// #define ETH_FEATURE -//Ethernet type (Check ETH.h eth_phy_type_t) -//TYPE_ETH_PHY_LAN8720 -//TYPE_ETH_PHY_TLK110 -//TYPE_ETH_PHY_RTL8201 -//TYPE_ETH_PHY_DP83848 -//TYPE_ETH_PHY_DM9051 -//TYPE_ETH_PHY_KSZ8041 -//TYPE_ETH_PHY_KSZ8081 +// Ethernet type (Check ETH.h eth_phy_type_t) +// TYPE_ETH_PHY_LAN8720 +// TYPE_ETH_PHY_TLK110 +// TYPE_ETH_PHY_RTL8201 +// TYPE_ETH_PHY_DP83848 +// TYPE_ETH_PHY_DM9051 +// TYPE_ETH_PHY_KSZ8041 +// TYPE_ETH_PHY_KSZ8081 #define ESP3D_ETH_PHY_TYPE TYPE_ETH_PHY_LAN8720 -//Ethernet board Clock mode -// MODE_ETH_CLOCK_GPIO0_IN -// MODE_ETH_CLOCK_GPIO0_OUT -// MODE_ETH_CLOCK_GPIO16_OUT -// MODE_ETH_CLOCK_GPIO17_OUT +// Ethernet board Clock mode +// MODE_ETH_CLOCK_GPIO0_IN +// MODE_ETH_CLOCK_GPIO0_OUT +// MODE_ETH_CLOCK_GPIO16_OUT +// MODE_ETH_CLOCK_GPIO17_OUT #define ESP3D_ETH_CLK_MODE MODE_ETH_CLOCK_GPIO17_OUT -//Pins of ethernet board +// Pins of ethernet board #define ESP3D_ETH_PHY_POWER_PIN 12 -//#define ESP3D_ETH_PHY_MDC_PIN 23 -//#define ESP3D_ETH_PHY_MDIO_PIN 18 - -//Address of ethernet board -//#define ESP3D_ETH_PHY_ADDR 0 +// #define ESP3D_ETH_PHY_MDC_PIN 23 +// #define ESP3D_ETH_PHY_MDIO_PIN 18 +// Address of ethernet board +// #define ESP3D_ETH_PHY_ADDR 0 /* Use Bluetooth -* Enable serial bluetooth communications -*/ -//#define BLUETOOTH_FEATURE + * Enable serial bluetooth communications + */ +// #define BLUETOOTH_FEATURE /************************************ -* -* Channels of ESP3D -* -* The way ESP3D communicate -* -************************************/ + * + * Channels of ESP3D + * + * The way ESP3D communicate + * + ************************************/ /* Use Web server -* Enable http server -*/ + * Enable http server + */ #define HTTP_FEATURE /* Use telnet server -* Enable telnet light (raw tcp) communications -*/ + * Enable telnet light (raw tcp) communications + */ #define TELNET_FEATURE /* Use Websocket server -* Enable websocket communications -*/ -//#define WS_DATA_FEATURE + * Enable websocket communications + */ +// #define WS_DATA_FEATURE // Enable notifications // Allows to send notifications to the user #define NOTIFICATION_FEATURE /* Notification message when online -* The message that will be sent when the ESP is online -*/ + * The message that will be sent when the ESP is online + */ #define NOTIFICATION_ESP_ONLINE "Hi, %ESP_NAME% is now online at %ESP_IP%" /* Notification title message -* The title of notification -*/ + * The title of notification + */ #define ESP_NOTIFICATION_TITLE "ESP3D Notification" /************************************ -* -* Discovery methods of ESP3D -* -* The discovery methods of ESP3D -* -************************************/ + * + * Discovery methods of ESP3D + * + * The discovery methods of ESP3D + * + ************************************/ /* Use captive portal -* Enable captive portal in AP mode -*/ + * Enable captive portal in AP mode + */ #define CAPTIVE_PORTAL_FEATURE /* Use mDNS discovery -* This method need `bonjour` protocol on windows, or `avahi` on linux -*/ + * This method need `bonjour` protocol on windows, or `avahi` on linux + */ #define MDNS_FEATURE /* Use Simple Service Discovery Protocol -* It is supported on Windows out of the box -*/ + * It is supported on Windows out of the box + */ #define SSDP_FEATURE /************************************ -* -* SSDP Customization settings -* -* Customize your ESP3D -* -************************************/ + * + * SSDP Customization settings + * + * Customize your ESP3D + * + ************************************/ /* Model name -* Modele name of device -*/ + * Modele name of device + */ #define ESP_MODEL_NAME "ESP Board" /* Model number -* Modele number of device -*/ + * Modele number of device + */ #define ESP_MODEL_NUMBER "ESP3D 3.0" /* Model url -* Modele url of device -*/ + * Modele url of device + */ #define ESP_MODEL_URL "https://www.espressif.com/en/products/devkits" /* Manufacturer name -* Manufacturer name of device -*/ + * Manufacturer name of device + */ #define ESP_MANUFACTURER_NAME "Espressif Systems" /* Manufacturer url -* Manufacturer url of device -*/ + * Manufacturer url of device + */ #define ESP_MANUFACTURER_URL "https://www.espressif.com" /************************************ -* -* Flash filesystem -* -* Filesystem on flash -* -************************************/ + * + * Flash filesystem + * + * Filesystem on flash + * + ************************************/ /* File system type used by ESP3D -* Type of file system used by ESP3D to store files -* ESP_SPIFFS_FILESYSTEM (Deprecated) -* ESP_FAT_FILESYSTEM (ESP32 only with large partitions) -* ESP_LITTLEFS_FILESYSTEM (Default) -*/ + * Type of file system used by ESP3D to store files + * ESP_SPIFFS_FILESYSTEM (Deprecated) + * ESP_FAT_FILESYSTEM (ESP32 only with large partitions) + * ESP_LITTLEFS_FILESYSTEM (Default) + */ #define FILESYSTEM_FEATURE ESP_LITTLEFS_FILESYSTEM /* Enable date/time on files -* Set date/time on files using SNTP or last webui connection -*/ -//#define FILESYSTEM_TIMESTAMP_FEATURE + * Set date/time on files using SNTP or last webui connection + */ +// #define FILESYSTEM_TIMESTAMP_FEATURE /************************************ -* -* SD filesystem -* -* Filesystem on SD card -* -************************************/ + * + * SD filesystem + * + * Filesystem on SD card + * + ************************************/ /* SD card connection -* ESP_NO_SD //(default) -* ESP_DIRECT_SD //Only your ESP board is connected to SDCard -* ESP_SHARED_SD //Printer SD Card is also connected to ESP3D -* Does your system has SD card and how it is connected to your ESP3D -*/ -//#define SD_DEVICE_CONNECTION ESP_DIRECT_SD + * ESP_NO_SD //(default) + * ESP_DIRECT_SD //Only your ESP board is connected to SDCard + * ESP_SHARED_SD //Printer SD Card is also connected to ESP3D + * Does your system has SD card and how it is connected to your ESP3D + */ +// #define SD_DEVICE_CONNECTION ESP_SHARED_SD /* SD card library -* ESP_SD_NATIVE //esp32 / esp8266 -* ESP_SDIO //esp32 only -* ESP_SDFAT2 //esp8266 / esp32 -*/ -//#define SD_DEVICE ESP_SDFAT2 + * ESP_SD_NATIVE //esp32 / esp8266 + * ESP_SDIO //esp32 only + * ESP_SDFAT2 //esp8266 / esp32 + */ +// #define SD_DEVICE ESP_SD_NATIVE + +// #define SD_CARD_TYPE ESP_FYSETC_WIFI_PRO_SDCARD /* Sdio bit mode -* Mode used by SDIO library 1 bit / 4bits -* SD_ONE_BIT_MODE -* SD_FOUR_BIT_MODE -*/ -//#define SDIO_BIT_MODE SD_ONE_BIT_MODE + * Mode used by SDIO library 1 bit / 4bits + * SD_ONE_BIT_MODE + * SD_FOUR_BIT_MODE + */ +// #define SDIO_BIT_MODE SD_ONE_BIT_MODE /* Enable date/time on files -* Set date/time on files using SNTP or last webui connection -*/ -//#define SD_TIMESTAMP_FEATURE + * Set date/time on files using SNTP or last webui connection + */ +// #define SD_TIMESTAMP_FEATURE /************************************ -* -* SD card pins -* -************************************/ + * + * SD card pins + * + ************************************/ /* SD card detect pin -* The pin used to detect SD card -*/ -//#define ESP_SD_DETECT_PIN 4 + * The pin used to detect SD card + */ +// #define ESP_SD_DETECT_PIN 4 /* SD card detect pin value -* State of SD card detect pin when card is present -*/ -//#define ESP_SD_DETECT_VALUE 0 + * State of SD card detect pin when card is present + */ +// #define ESP_SD_DETECT_VALUE 0 /* SD shared flag pin -* The pin used to enable SD card for ESP board -*/ -//#define ESP_FLAG_SHARED_SD_PIN -1 + * The pin used to enable SD card for ESP board + */ +// #define ESP_FLAG_SHARED_SD_PIN -1 /* SD shared flag pin value -* State of SD card shared pin for ESP board -*/ -//#define ESP_FLAG_SHARED_SD_VALUE 0 + * State of SD card shared pin for ESP board + */ +// #define ESP_FLAG_SHARED_SD_VALUE 0 /* SD card CS pin -* The pin used to select SD card in SPI mode -*/ -//#define ESP_SD_CS_PIN 5 + * The pin used to select SD card in SPI mode + */ +// #define ESP_SD_CS_PIN 5 /************************************ -* -* Remote access -* -* Remote filesystem access -* -************************************/ + * + * Remote access + * + * Remote filesystem access + * + ************************************/ /* Enable global filesystem -* Allows to access to all filesystems from same location -*/ -//#define GLOBAL_FILESYSTEM_FEATURE + * Allows to access to all filesystems from same location + */ +#define GLOBAL_FILESYSTEM_FEATURE /* WebDav access -* Use WebDav to access to your filesystem -* FS_ROOT //mount all FS, need GLOBAL_FILESYSTEM_FEATURE -* FS_FLASH //mount Flash FS -* FS_SD mount SD FS -*/ -//#define WEBDAV_FEATURE FS_ROOT + * Use WebDav to access to your filesystem + * FS_ROOT //mount all FS, need GLOBAL_FILESYSTEM_FEATURE + * FS_FLASH //mount Flash FS + * FS_SD mount SD FS + */ +#define WEBDAV_FEATURE FS_ROOT /* FTP access -* Use FTP to access to your filesystem (1 connection only) -* FS_ROOT //mount all FS, need GLOBAL_FILESYSTEM_FEATURE -* FS_FLASH //mount Flash FS -* FS_SD //mount SD FS -*/ -//#define FTP_FEATURE FS_ROOT + * Use FTP to access to your filesystem (1 connection only) + * FS_ROOT //mount all FS, need GLOBAL_FILESYSTEM_FEATURE + * FS_FLASH //mount Flash FS + * FS_SD //mount SD FS + */ +// #define FTP_FEATURE FS_ROOT /************************************ -* -* Reset ESP3D -* -* Reset ESP3D settings -* -************************************/ + * + * Reset ESP3D + * + * Reset ESP3D settings + * + ************************************/ /* Enable pin reset feature -* Use a pin to reset ESP3D settings -*/ -//#define PIN_RESET_FEATURE + * Use a pin to reset ESP3D settings + */ +// #define PIN_RESET_FEATURE /* Reset pin -* The pin used to reset ESP3D setting if set to low for more than 1 second at start -*/ + * The pin used to reset ESP3D setting if set to low for more than 1 second at + * start + */ #define ESP3D_RESET_PIN 0 /************************************ -* -* Update ESP3D -* -* Update ESP3D firmware -* -************************************/ + * + * Update ESP3D + * + * Update ESP3D firmware + * + ************************************/ /* Enable OTA -* Over The Air Update (OTA) -*/ -//#define OTA_FEATURE + * Over The Air Update (OTA) + */ +// #define OTA_FEATURE /* Enable Web Update -* Update firmware using WebUI, need 4MB of flash -*/ + * Update firmware using WebUI, need 4MB of flash + */ #define WEB_UPDATE_FEATURE /* Enable SD card Update -* Update firmware and settings using file on SDCard -*/ -//#define SD_UPDATE_FEATURE + * Update firmware and settings using file on SDCard + */ +// #define SD_UPDATE_FEATURE /************************************ -* -* Display settings -* -* Rendering screens -* -************************************/ + * + * Display settings + * + * Rendering screens + * + ************************************/ /* Printer screen -* If your printer has a display -*/ + * If your printer has a display + */ #define PRINTER_HAS_DISPLAY /* ESP3D screen -* Screen connected to ESP board -* OLED I2C SSD1306 128X64 -* OLED_I2C_SSDSH1106_132X64 -* TFT_SPI_ST7789_240X240 -* TFT_SPI_ST7789_135X240 -*/ -//#define DISPLAY_DEVICE OLED_I2C_SSD1306_128X64 + * Screen connected to ESP board + * OLED I2C SSD1306 128X64 + * OLED_I2C_SSDSH1106_132X64 + * TFT_SPI_ST7789_240X240 + * TFT_SPI_ST7789_135X240 + */ +// #define DISPLAY_DEVICE OLED_I2C_SSD1306_128X64 /* Flip screen -* Flip/rotate screen -*/ -//#define DISPLAY_FLIP_VERTICALY + * Flip/rotate screen + */ +// #define DISPLAY_FLIP_VERTICALY /* Display i2C address -* Wire address of display -*/ -//#define DISPLAY_I2C_ADDR 0x3c + * Wire address of display + */ +// #define DISPLAY_I2C_ADDR 0x3c /* Display reset pin -* The pin used to reset the screen (optional) -*/ -//#define DISPLAY_I2C_PIN_RST 22 + * The pin used to reset the screen (optional) + */ +// #define DISPLAY_I2C_PIN_RST 22 /* TFT led pin -* The pin used for the backlight -*/ -//#define DISPLAY_LED_PIN -1 + * The pin used for the backlight + */ +// #define DISPLAY_LED_PIN -1 /************************************ -* -* Audio settings -* -* Buzzer feature -* -************************************/ + * + * Audio settings + * + * Buzzer feature + * + ************************************/ /* Enable buzzer -* Your esp board has a passive buzzer -*/ -//#define BUZZER_DEVICE + * Your esp board has a passive buzzer + */ +// #define BUZZER_DEVICE /* Buzzer pin -* The pin used for the passive buzzer -*/ -//#define ESP3D_BUZZER_PIN 33 + * The pin used for the passive buzzer + */ +// #define ESP3D_BUZZER_PIN 33 /************************************ -* -* Sensor settings -* -* Sensor feature -* -************************************/ + * + * Sensor settings + * + * Sensor feature + * + ************************************/ /* Sensor pin -* The pin used for the sensor -*/ -//#define ESP3D_SENSOR_PIN 34 + * The pin used for the sensor + */ +// #define ESP3D_SENSOR_PIN 34 /* Sensor Unit -* Unit of the sensor result -*/ -//#define SENSOR__UNIT "C" + * Unit of the sensor result + */ +// #define SENSOR__UNIT "C" /************************************ -* -* Camera settings -* -* Connected camera -* -************************************/ + * + * Camera settings + * + * Connected camera + * + ************************************/ /* Camera type -* CAMERA_MODEL_CUSTOM //Edit the pins in include/pins.h -* CAMERA_MODEL_ESP_EYE -* CAMERA_MODEL_M5STACK_PSRAM -* CAMERA_MODEL_M5STACK_V2_PSRAM -* CAMERA_MODEL_M5STACK_WIDE -* CAMERA_MODEL_AI_THINKER //ESP32-CAM -* CAMERA_MODEL_WROVER_KIT -* CAMERA_MODEL_ESP32_CAM_BOARD -* CAMERA_MODEL_ESP32S2_CAM_BOARD -* CAMERA_MODEL_ESP32S3_CAM_LCD -* CAMERA_MODEL_ESP32S3_EYE -* Camera connected to ESP board, only ones with PSRAM are supported -*/ -//#define CAMERA_DEVICE CAMERA_MODEL_AI_THINKER + * CAMERA_MODEL_CUSTOM //Edit the pins in include/pins.h + * CAMERA_MODEL_ESP_EYE + * CAMERA_MODEL_M5STACK_PSRAM + * CAMERA_MODEL_M5STACK_V2_PSRAM + * CAMERA_MODEL_M5STACK_WIDE + * CAMERA_MODEL_AI_THINKER //ESP32-CAM + * CAMERA_MODEL_WROVER_KIT + * CAMERA_MODEL_ESP32_CAM_BOARD + * CAMERA_MODEL_ESP32S2_CAM_BOARD + * CAMERA_MODEL_ESP32S3_CAM_LCD + * CAMERA_MODEL_ESP32S3_EYE + * Camera connected to ESP board, only ones with PSRAM are supported + */ +// #define CAMERA_DEVICE CAMERA_MODEL_AI_THINKER /* Flip vertically -* Flip camera vertically -*/ -//#define CAMERA_DEVICE_FLIP_VERTICALY - + * Flip camera vertically + */ +// #define CAMERA_DEVICE_FLIP_VERTICALY /************************************ -* -* Levels of security -* -* How commands are allowed to be sent to ESP3D -* -************************************/ + * + * Levels of security + * + * How commands are allowed to be sent to ESP3D + * + ************************************/ /* Enable serial commands -* Allow commands to be sent to ESP3D via serial port -*/ + * Allow commands to be sent to ESP3D via serial port + */ #define SERIAL_COMMAND_FEATURE /* Allow remote access by enabling cross origin access -* check https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS -* this should be enabled only in specific cases -* like show the camera in web page different than device web server -* /if you do not know what is that then better left it commented -* Allow to show the camera in web page different than device web server -*/ -//#define ESP_ACCESS_CONTROL_ALLOW_ORIGIN + * check https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS + * this should be enabled only in specific cases + * like show the camera in web page different than device web server + * /if you do not know what is that then better left it commented + * Allow to show the camera in web page different than device web server + */ +// #define ESP_ACCESS_CONTROL_ALLOW_ORIGIN /* Enable authentication -* Force usage of authentication for commands -*/ -//#define AUTHENTICATION_FEATURE + * Force usage of authentication for commands + */ +// #define AUTHENTICATION_FEATURE /************************************ -* -* Additional features -* -* Extra settings -* -************************************/ + * + * Additional features + * + * Extra settings + * + ************************************/ /* Enable direct control pin -* Controls pins using [ESP201] -*/ + * Controls pins using [ESP201] + */ #define DIRECT_PIN_FEATURE /************************************ -* -* Scripting settings -* -* Scripting on ESP3D -* -************************************/ + * + * Scripting settings + * + * Scripting on ESP3D + * + ************************************/ /* Enable Autostart -* Commands to run on startup -* Separate commands with ';' or use file -*/ -//#define ESP_AUTOSTART_SCRIPT "M117 Mounting SD;M21" -//#define ESP_AUTOSTART_SCRIPT_FILE "autoscript.gco" + * Commands to run on startup + * Separate commands with ';' or use file + */ +// #define ESP_AUTOSTART_SCRIPT "M117 Mounting SD;M21" +// #define ESP_AUTOSTART_SCRIPT_FILE "autoscript.gco" /* Enable lua interpreter -* Allow to use lua interpreter on ESP3D -*/ -//#define ESP_LUA_INTERPRETER_FEATURE + * Allow to use lua interpreter on ESP3D + */ +// #define ESP_LUA_INTERPRETER_FEATURE /* Gcode Host Feature -* This feature allows to process Gcode files like macros. -*/ + * This feature allows to process Gcode files like macros. + */ #define GCODE_HOST_FEATURE /* Settings location -* SETTINGS_IN_EEPROM //ESP8266/ESP32 -* SETTINGS_IN_PREFERENCES //ESP32 only -* Location where ESP3D will save settings -*/ + * SETTINGS_IN_EEPROM //ESP8266/ESP32 + * SETTINGS_IN_PREFERENCES //ESP32 only + * Location where ESP3D will save settings + */ #define ESP_SAVE_SETTINGS SETTINGS_IN_EEPROM /* Add serial task -* ESP32 need to add a task to handle serial communication -*/ + * ESP32 need to add a task to handle serial communication + */ #define SERIAL_INDEPENDANT_TASK +/************************************ + * + * Development setting + * Do not modify them for production + ************************************/ +// Enable log mode +// Do not do this when connected to printer !!! +// be noted all upload may failed if enabled +// LOG_OUTPUT_SERIAL0 +// LOG_OUTPUT_SERIAL1 +// LOG_OUTPUT_SERIAL2 +// LOG_OUTPUT_TELNET +// LOG_OUTPUT_WEBSOCKET +// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 + +#define ESP3D_DEBUG_LEVEL LOG_LEVEL_ERROR + +// #define ESP_NO_SANITY_CHECK + +#ifdef ESP_LOG_FEATURE +#define LOG_ESP3D_BAUDRATE 115200 +#define LOG_ESP3D_OUTPUT_PORT 8000 +#endif // ESP_LOG_FEATURE + +// Enable benchmark report in dev console +// #define ESP_BENCHMARK_FEATURE + +// Disable sanity check at compilation +// #define ESP_NO_SANITY_CHECK /************************************ -* -* Development setting -* Do not modify them for production -************************************/ + * + * Sanity checks + * Do not modify + ************************************/ -//Enable debug mode -//Do not do this when connected to printer !!! -//be noted all upload may failed if enabled -//DEBUG_OUTPUT_SERIAL0 -//DEBUG_OUTPUT_SERIAL1 -//DEBUG_OUTPUT_SERIAL2 -//DEBUG_OUTPUT_TELNET -//DEBUG_OUTPUT_WEBSOCKET -//#define ESP_DEBUG_FEATURE DEBUG_OUTPUT_SERIAL0 - -#ifdef ESP_DEBUG_FEATURE -#define DEBUG_BAUDRATE 115200 -#define DEBUG_ESP3D_OUTPUT_PORT 8000 -#endif //ESP_DEBUG_FEATURE - -//Enable benchmark report in dev console -//#define ESP_BENCHMARK_FEATURE - -//Disable sanity check at compilation -//#define ESP_NO_SANITY_CHECK - - -/************************************ -* -* Sanity checks -* Do not modify -************************************/ - -#if defined (SD_TIMESTAMP_FEATURE) || defined (FILESYSTEM_TIMESTAMP_FEATURE) +#if defined(SD_TIMESTAMP_FEATURE) || defined(FILESYSTEM_TIMESTAMP_FEATURE) #define TIMESTAMP_FEATURE -#endif //SD_TIMESTAMP_FEATURE || FILESYSTEM_TIMESTAMP_FEATURE +#endif // SD_TIMESTAMP_FEATURE || FILESYSTEM_TIMESTAMP_FEATURE #if defined(PRINTER_HAS_DISPLAY) #define HAS_SERIAL_DISPLAY "" -#endif // PRINTER_HAS_DISPLAY +#endif // PRINTER_HAS_DISPLAY #if defined(CAMERA_DEVICE) -#if CAMERA_DEVICE==CAMERA_MODEL_ESP32_CAM_BOARD || CAMERA_DEVICE==CAMERA_MODEL_ESP32S2_CAM_BOARD +#if CAMERA_DEVICE == CAMERA_MODEL_ESP32_CAM_BOARD || \ + CAMERA_DEVICE == CAMERA_MODEL_ESP32S2_CAM_BOARD #define USE_BOARD_HEARDER 1 -#endif // CAMERA_DEVICE==CAMERA_MODEL_ESP32_CAM_BOARD || CAMERA_DEVICE==CAMERA_MODEL_ESP32S2_CAM_BOARD -#endif // CAMERA_DEVICE +#endif // CAMERA_DEVICE==CAMERA_MODEL_ESP32_CAM_BOARD || + // CAMERA_DEVICE==CAMERA_MODEL_ESP32S2_CAM_BOARD +#endif // CAMERA_DEVICE #if !defined(WIFI_FEATURE) && !defined(ETH_FEATURE) #undef HTTP_FEATURE @@ -633,4 +638,4 @@ #undef NOTIFICATION_FEATURE #endif -#endif //_CONFIGURATION_H +#endif //_CONFIGURATION_H diff --git a/esp3d/src/core/commands.cpp b/esp3d/src/core/commands.cpp index 36860609..5a9f89d0 100644 --- a/esp3d/src/core/commands.cpp +++ b/esp3d/src/core/commands.cpp @@ -17,774 +17,795 @@ 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_DEBUG_FEATURE DEBUG_OUTPUT_SERIAL0 +// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 +#include "commands.h" + #include "../include/esp3d_config.h" #include "esp3d.h" -#include "commands.h" #include "esp3doutput.h" #include "settings_esp3d.h" + #if COMMUNICATION_PROTOCOL == MKS_SERIAL #include "../modules/mks/mks_service.h" -#endif //COMMUNICATION_PROTOCOL == MKS_SERIAL +#endif // COMMUNICATION_PROTOCOL == MKS_SERIAL Commands esp3d_commands; -Commands::Commands() -{ -} +Commands::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(); - } +// 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 + 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()); + // 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); - } + 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 - } + 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; - } - } - } +// 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; -} - -//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("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()); + } + 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; } - -//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; +// 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); + } } -#endif //SERIAL_COMMAND_FEATURE - bool response = true; - level_authenticate_type auth_type = auth_level; - //log_esp3d("Authentication = %d", auth_type); -//override if parameters + } + 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 + // 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 + 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 + 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) + 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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 +#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) + 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 +#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) + 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 + // 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 + 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 + 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 + 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 + // Set HTTP state which can be ON, OFF //[ESP120]pwd= case 120: - response = ESP120(cmd_params, auth_type, output); - break; - //Set HTTP port + 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 + response = ESP121(cmd_params, auth_type, output); + break; +#endif // HTTP_FEATURE #ifdef TELNET_FEATURE - //Set TELNET state which can be ON, OFF + // Set TELNET state which can be ON, OFF //[ESP130]pwd= case 130: - response = ESP130(cmd_params, auth_type, output); - break; - //Set TELNET port + 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 + response = ESP131(cmd_params, auth_type, output); + break; +#endif // TELNET_FEATURE #ifdef TIMESTAMP_FEATURE - //Sync / Set / Get current time - //[ESP140] pwd= + // 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 + 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; + response = ESP150(cmd_params, auth_type, output); + break; #ifdef WS_DATA_FEATURE - //Set WebSocket state which can be ON, OFF + // Set WebSocket state which can be ON, OFF //[ESP160]pwd= case 160: - response = ESP160(cmd_params, auth_type, output); - break; - //Set WebSocket port + 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 + 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 + // 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 + // 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= + 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 + response = ESP171(cmd_params, auth_type, output); + break; +#endif // CAMERA_DEVICE #ifdef FTP_FEATURE - //Set Ftp state which can be ON, OFF + // Set Ftp state which can be ON, OFF //[ESP180]pwd= case 180: - response = ESP180(cmd_params, auth_type, output); - break; - //Set/get ftp ports + 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 + response = ESP181(cmd_params, auth_type, output); + break; +#endif // FTP_FEATURE #ifdef WEBDAV_FEATURE - //Set webdav state which can be ON, OFF + // Set webdav state which can be ON, OFF //[ESP190]pwd= case 190: - response = ESP190(cmd_params, auth_type, output); - break; - //Set/get webdav port + 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 + 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 + 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 + 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 + // 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 + response = ESP402(cmd_params, auth_type, output); + break; +#endif // #ifdef SD_UPDATE_FEATURE +#endif // SD_DEVICE #ifdef DIRECT_PIN_FEATURE - //Get/Set pin value + // 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 + response = ESP201(cmd_params, auth_type, output); + break; +#endif // DIRECT_PIN_FEATURE #ifdef SENSOR_DEVICE - //Get SENSOR Value / type/Set SENSOR type + // 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 + 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; + response = ESP214(cmd_params, auth_type, output); + break; #if defined(DISPLAY_TOUCH_DRIVER) - //Touch Calibration + // Touch Calibration //[ESP215][pwd=] case 215: - response = ESP215(cmd_params, auth_type, output); - break; -#endif //DISPLAY_TOUCH_DRIVER + response = ESP215(cmd_params, auth_type, output); + break; +#endif // DISPLAY_TOUCH_DRIVER #ifdef BUZZER_DEVICE - //Play sound + // Play sound //[ESP250]F= D= [pwd=] case 250: - response = ESP250(cmd_params, auth_type, output); - break; -#endif //BUZZER_DEVICE -#endif //DISPLAY_DEVICE - //Show pins + 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 + 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 + 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 + 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 + 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 + 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 + 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; + response = ESP444(cmd_params, auth_type, output); + break; #ifdef MDNS_FEATURE - //Get ESP3D list + // Get ESP3D list //[ESP450] pwd= case 450: - response = ESP450(cmd_params, auth_type, output); - break; -#endif //MDNS_FEATURE + response = ESP450(cmd_params, auth_type, output); + break; +#endif // MDNS_FEATURE #ifdef AUTHENTICATION_FEATURE - //Change admin password + // Change admin password //[ESP550]pwd= case 550: - response = ESP550(cmd_params, auth_type, output); - break; - //Change user password + 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 + response = ESP555(cmd_params, auth_type, output); + break; +#endif // AUTHENTICATION_FEATURE #if defined(NOTIFICATION_FEATURE) - //Send Notification + // 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 + 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 + 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 + response = ESP620(cmd_params, auth_type, output); + break; +#endif // NOTIFICATION_FEATURE #if defined(FILESYSTEM_FEATURE) - //Format ESP Filesystem + // Format ESP Filesystem //[ESP710]FORMAT pwd= case 710: - response = ESP710(cmd_params, auth_type, output); - break; - //List ESP Filesystem + 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 + 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 + response = ESP730(cmd_params, auth_type, output); + break; +#endif // FILESYSTEM_FEATURE #if defined(SD_DEVICE) - //Format ESP Filesystem + // Format ESP Filesystem //[ESP715]FORMATSD pwd= case 715: - response = ESP715(cmd_params, auth_type, output); - break; -#endif //SD_DEVICE + response = ESP715(cmd_params, auth_type, output); + break; +#endif // SD_DEVICE #if defined(GCODE_HOST_FEATURE) - //Open local file + // Open local file //[ESP700] case 700: - response = ESP700(cmd_params, auth_type, output); - break; - //Get Status and Control ESP700 stream + 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 + 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 + 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 + 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 + 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 + 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; + response = ESP800(cmd_params, auth_type, output); + break; #if COMMUNICATION_PROTOCOL != SOCKET_SERIAL - //Get state / Set Enable / Disable Serial Communication + // Get state / Set Enable / Disable Serial Communication //[ESP900] case 900: - response = ESP900(cmd_params, auth_type, output); - break; - //Get / Set Serial Baud Rate + 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 + response = ESP901(cmd_params, auth_type, output); + break; +#endif // COMMUNICATION_PROTOCOL != SOCKET_SERIAL #ifdef BUZZER_DEVICE - //Get state / Set Enable / Disable buzzer + // Get state / Set Enable / Disable buzzer //[ESP910] case 910: - response = ESP910(cmd_params, auth_type, output); - break; -#endif //BUZZER_DEVICE + 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; + // 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 + // 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 + 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) + 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 + // 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; + output->printERROR("Invalid Command"); + response = false; + } + return response; } diff --git a/esp3d/src/core/debug_esp3d.cpp b/esp3d/src/core/debug_esp3d.cpp deleted file mode 100644 index 2348c003..00000000 --- a/esp3d/src/core/debug_esp3d.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* - debug_esp3d.cpp - debug 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_DEBUG_FEATURE) - -#ifndef DEBUG_BAUDRATE -#define DEBUG_BAUDRATE 115200 -#endif //~DEBUG_BAUDRATE - -void initDebug() -{ -#if (ESP_DEBUG_FEATURE == DEBUG_OUTPUT_SERIAL0) || (ESP_DEBUG_FEATURE == DEBUG_OUTPUT_SERIAL1)||(ESP_DEBUG_FEATURE == DEBUG_OUTPUT_SERIAL2) -#ifdef ARDUINO_ARCH_ESP8266 - DEBUG_OUTPUT_SERIAL.begin(DEBUG_BAUDRATE, SERIAL_8N1, SERIAL_FULL, (ESP_DEBUG_TX_PIN == -1)?1:ESP_DEBUG_TX_PIN); -#if ESP_DEBUG_RX_PIN != -1 - DEBUG_OUTPUT_SERIAL.pins((ESP_DEBUG_TX_PIN == -1)?1:ESP_DEBUG_TX_PIN, ESP_DEBUG_RX_PIN) -#endif //ESP_DEBUG_RX_PIN != -1 -#endif //ARDUINO_ARCH_ESP8266 -#if defined(ARDUINO_ARCH_ESP32) - DEBUG_OUTPUT_SERIAL.begin (DEBUG_BAUDRATE, SERIAL_8N1, ESP_DEBUG_RX_PIN, ESP_DEBUG_TX_PIN); -#endif //ARDUINO_ARCH_ESP32 - -#endif // (ESP_DEBUG_FEATURE == DEBUG_OUTPUT_SERIAL0) || (ESP_DEBUG_FEATURE == DEBUG_OUTPUT_SERIAL1)||(ESP_DEBUG_FEATURE == DEBUG_OUTPUT_SERIAL2) -} - -//Telnet -#if ESP_DEBUG_FEATURE == DEBUG_OUTPUT_TELNET -Telnet_Server telnet_debug; -#endif // ESP_DEBUG_FEATURE == DEBUG_OUTPUT_TELNET - -//Websocket -#if ESP_DEBUG_FEATURE == DEBUG_OUTPUT_WEBSOCKET -WebSocket_Server websocket_debug("debug"); -#endif // ESP_DEBUG_FEATURE == DEBUG_OUTPUT_WEBSOCKET -#endif //ESP_DEBUG_FEATURE diff --git a/esp3d/src/core/debug_esp3d.h b/esp3d/src/core/debug_esp3d.h deleted file mode 100644 index 6a8b236c..00000000 --- a/esp3d/src/core/debug_esp3d.h +++ /dev/null @@ -1,93 +0,0 @@ -/* - debug_esp3d.h - esp3d debug 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 _DEBUG_ESP3D_H -#define _DEBUG_ESP3D_H - -#include "../include/esp3d_config.h" - -#define DEBUG_ESP3D_INIT -#define DEBUG_ESP3D_NETWORK_INIT -#define DEBUG_ESP3D_NETWORK_HANDLE -#define DEBUG_ESP3D_NETWORK_END - -#if defined(ESP_DEBUG_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 -//Serial -#if (ESP_DEBUG_FEATURE == DEBUG_OUTPUT_SERIAL0) || (ESP_DEBUG_FEATURE == DEBUG_OUTPUT_SERIAL1) || (ESP_DEBUG_FEATURE == DEBUG_OUTPUT_SERIAL2) - -extern void initDebug(); -#ifndef ESP3DLIB_ENV -#if ESP_DEBUG_FEATURE == DEBUG_OUTPUT_SERIAL0 -#define DEBUG_OUTPUT_SERIAL Serial -#endif //DEBUG_OUTPUT_SERIAL0 -#if ESP_DEBUG_FEATURE == DEBUG_OUTPUT_SERIAL1 -#define DEBUG_OUTPUT_SERIAL Serial1 -#endif //DEBUG_OUTPUT_SERIAL1 -#if ESP_DEBUG_FEATURE == DEBUG_OUTPUT_SERIAL2 -#define DEBUG_OUTPUT_SERIAL Serial2 -#endif //DEBUG_OUTPUT_SERIAL2 -#undef DEBUG_ESP3D_INIT -#define DEBUG_ESP3D_INIT initDebug(); -#else -#define DEBUG_OUTPUT_SERIAL MYSERIAL1 -#endif //ESP3DLIB_ENV -#define log_esp3d(format, ...) DEBUG_OUTPUT_SERIAL.printf("[ESP3D][%s:%u] %s(): " format "\r\n", pathToFileName(__FILE__), __LINE__, __FUNCTION__, ##__VA_ARGS__) -#define log_esp3ds(format, ...) DEBUG_OUTPUT_SERIAL.printf(format, ##__VA_ARGS__) -#endif //DEBUG_OUTPUT_SERIAL0 || DEBUG_OUTPUT_SERIAL1 || DEBUG_OUTPUT_SERIAL2 - -//Telnet -#if ESP_DEBUG_FEATURE == DEBUG_OUTPUT_TELNET -#include "../modules/telnet/telnet_server.h" -extern Telnet_Server telnet_debug; -#undef DEBUG_ESP3D_NETWORK_INIT -#undef DEBUG_ESP3D_NETWORK_END -#undef DEBUG_ESP3D_NETWORK_HANDLE -#define DEBUG_ESP3D_NETWORK_INIT telnet_debug.begin(DEBUG_ESP3D_OUTPUT_PORT, true); -#define DEBUG_ESP3D_NETWORK_HANDLE telnet_debug.handle(); -#define DEBUG_ESP3D_NETWORK_END telnet_debug.end(); -#define log_esp3d(format, ...) if(telnet_debug.isConnected())telnet_debug.printf("[ESP3D][%s:%u] %s(): " format "\r\n", pathToFileName(__FILE__), __LINE__, __FUNCTION__, ##__VA_ARGS__) -#define log_esp3ds(format, ...) if(telnet_debug.isConnected())telnet_debug.printf(format , ##__VA_ARGS__) -#endif // DEBUG_OUTPUT_TELNET - -//Telnet -#if ESP_DEBUG_FEATURE == DEBUG_OUTPUT_WEBSOCKET -#include "../modules/websocket/websocket_server.h" -extern WebSocket_Server websocket_debug; -#undef DEBUG_ESP3D_NETWORK_INIT -#undef DEBUG_ESP3D_NETWORK_END -#undef DEBUG_ESP3D_NETWORK_HANDLE -#define DEBUG_ESP3D_NETWORK_INIT websocket_debug.begin(DEBUG_ESP3D_OUTPUT_PORT, true); -#define DEBUG_ESP3D_NETWORK_HANDLE websocket_debug.handle(); -#define DEBUG_ESP3D_NETWORK_END websocket_debug.end(); -#define log_esp3d(format, ...) websocket_debug.printf("[ESP3D][%s:%u] %s(): " format "\r\n", pathToFileName(__FILE__), __LINE__, __FUNCTION__, ##__VA_ARGS__) -#define log_esp3ds(format, ...) websocket_debug.printf(format, ##__VA_ARGS__) -#endif // DEBUG_OUTPUT_WEBSOCKET -#else -#define log_esp3d(format, ...) -#define log_esp3ds(format, ...) -#endif //ESP_DEBUG_FEATURE - -#endif //_DEBUG_ESP3D_H diff --git a/esp3d/src/core/esp3d.cpp b/esp3d/src/core/esp3d.cpp index 9578d74e..86bdb324 100644 --- a/esp3d/src/core/esp3d.cpp +++ b/esp3d/src/core/esp3d.cpp @@ -1,21 +1,21 @@ /* This file is part of ESP3D Firmware for 3D printer. - ESP3D Firmware for 3D printer is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + ESP3D Firmware for 3D printer is free software: you can redistribute it + and/or modify it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - ESP3D Firmware for 3D printer is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of + ESP3D Firmware for 3D printer 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this Firmware. If not, see . - This firmware is using the standard arduino IDE with module to support ESP8266/ESP32: - https://github.com/esp8266/Arduino + This firmware is using the standard arduino IDE with module to support + ESP8266/ESP32: https://github.com/esp8266/Arduino https://github.com/espressif/arduino-esp32 Latest version of the code and documentation can be found here : @@ -25,243 +25,233 @@ */ #include "esp3d.h" + #include "../include/esp3d_config.h" #include "settings_esp3d.h" + #if COMMUNICATION_PROTOCOL != SOCKET_SERIAL || ESP_SERIAL_BRIDGE_OUTPUT #include "../modules/serial/serial_service.h" -#endif // COMMUNICATION_PROTOCOL != SOCKET_SERIAL -#if COMMUNICATION_PROTOCOL ==SOCKET_SERIAL +#endif // COMMUNICATION_PROTOCOL != SOCKET_SERIAL +#if COMMUNICATION_PROTOCOL == SOCKET_SERIAL #include "../modules/serial2socket/serial2socket.h" -#endif // COMMUNICATION_PROTOCOL ==SOCKET_SERIAL -#if defined (WIFI_FEATURE) || defined(ETH_FEATURE) +#endif // COMMUNICATION_PROTOCOL ==SOCKET_SERIAL +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) #include "../modules/network/netconfig.h" -#endif //WIFI_FEATURE || ETH FEATURE +#endif // WIFI_FEATURE || ETH FEATURE #if defined(FILESYSTEM_FEATURE) #include "../modules/filesystem/esp_filesystem.h" -#endif //FILESYSTEM_FEATURE +#endif // FILESYSTEM_FEATURE #ifdef CONNECTED_DEVICES_FEATURE #include "../modules/devices/devices_services.h" -#endif //CONNECTED_DEVICES_FEATURE +#endif // CONNECTED_DEVICES_FEATURE #ifdef DISPLAY_DEVICE #include "../modules/display/display.h" -#endif //DISPLAY_DEVICE +#endif // DISPLAY_DEVICE #ifdef GCODE_HOST_FEATURE #include "../modules/gcode_host/gcode_host.h" -#endif //GCODE_HOST_FEATURE +#endif // GCODE_HOST_FEATURE #ifdef ESP_LUA_INTERPRETER_FEATURE #include "../modules/lua_interpreter/lua_interpreter_service.h" -#endif //#ifdef -#ifdef SD_UPDATE_FEATURE +#endif // #ifdef +#ifdef SD_UPDATE_FEATURE #include "../modules/update/update_service.h" -#endif // SD_UPDATE_FEATURE -#include "esp3doutput.h" +#endif // SD_UPDATE_FEATURE #include "../modules/boot_delay/boot_delay.h" - +#include "esp3doutput.h" bool Esp3D::restart = false; -//Contructor -Esp3D::Esp3D() -{ - _started = false; -} +// Contructor +Esp3D::Esp3D() { _started = false; } -//Destructor -Esp3D::~Esp3D() -{ - end(); -} +// Destructor +Esp3D::~Esp3D() { end(); } -//Begin which setup everything -bool Esp3D::begin() -{ - BootDelay bd; - Hal::begin(); - DEBUG_ESP3D_INIT +// Begin which setup everything +bool Esp3D::begin() { + BootDelay bd; + Hal::begin(); + LOG_ESP3D_INIT #if COMMUNICATION_PROTOCOL == SOCKET_SERIAL - Serial2Socket.enable(); -#endif // COMMUNICATION_PROTOCOL == SOCKET_SERIAL - //init output - ESP3DOutput::isOutput(ESP_ALL_CLIENTS, true); - bool res = true; + Serial2Socket.enable(); +#endif // COMMUNICATION_PROTOCOL == SOCKET_SERIAL + // init output + ESP3DOutput::isOutput(ESP_ALL_CLIENTS, true); + bool res = true; #if defined(CONNECTED_DEVICES_FEATURE) - if (!DevicesServices::begin()) { - log_esp3d("Error setup connected devices"); - res = false; - } -#endif //CONNECTED_DEVICES_FEATURE - //delay to avoid to disturb printer - bd.begin(); -#ifdef SD_UPDATE_FEATURE - if (update_service.begin()) { - log_esp3d("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"); - reset(); - //Restart ESP3D - restart_now(); - } - //BT do not start automaticaly so should be OK + if (!DevicesServices::begin()) { + log_esp3d_e("Error setup connected devices"); + res = false; + } +#endif // CONNECTED_DEVICES_FEATURE + // delay to avoid to disturb printer + bd.begin(); +#ifdef SD_UPDATE_FEATURE + if (update_service.begin()) { + log_esp3d("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"); + reset(); + // Restart ESP3D + restart_now(); + } + // 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("Error with serial service"); - res = false; - } -#endif //COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - //Serial bridge + // Serial service + if (!serial_service.begin(ESP_SERIAL_OUTPUT)) { + log_esp3d_e("Error with serial service"); + res = false; + } +#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == + // MKS_SERIAL + // Serial bridge #if defined(ESP_SERIAL_BRIDGE_OUTPUT) - if (!serial_bridge_service.begin(ESP_SERIAL_BRIDGE_OUTPUT)) { - log_esp3d("Error with serial bridge service"); - res = false; - } -#endif //ESP_SERIAL_BRIDGE_OUTPUT - //Setup Filesystem + if (!serial_bridge_service.begin(ESP_SERIAL_BRIDGE_OUTPUT)) { + log_esp3d_e("Error with serial bridge service"); + res = false; + } +#endif // ESP_SERIAL_BRIDGE_OUTPUT + // Setup Filesystem #if defined(FILESYSTEM_FEATURE) - if (!ESP_FileSystem::begin()) { - log_esp3d("Error with filesystem service"); - res = false; - } -#endif //FILESYSTEM_FEATURE + if (!ESP_FileSystem::begin()) { + log_esp3d_e("Error with filesystem service"); + res = false; + } +#endif // FILESYSTEM_FEATURE #ifdef DISPLAY_DEVICE - esp3d_display.showScreenID(MAIN_SCREEN); - log_esp3d("Main screen"); -#endif //DISPLAY_DEVICE - //Setup Network + esp3d_display.showScreenID(MAIN_SCREEN); + log_esp3d("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) { - if (!NetConfig::begin()) { - log_esp3d("Error setup network"); - res = false; - } + if (Settings_ESP3D::read_byte(ESP_BOOT_RADIO_STATE) == 1) { + if (!NetConfig::begin()) { + log_esp3d_e("Error setup network"); + res = false; } + } -#endif //WIFI_FEATURE +#endif // WIFI_FEATURE #if defined(GCODE_HOST_FEATURE) #if defined(ESP_AUTOSTART_SCRIPT) - esp3d_gcode_host.processScript(ESP_AUTOSTART_SCRIPT); -#endif //ESP_AUTOSTART_FEATURE + esp3d_gcode_host.processScript(ESP_AUTOSTART_SCRIPT); +#endif // ESP_AUTOSTART_FEATURE #if defined(ESP_AUTOSTART_SCRIPT_FILE) - esp3d_gcode_host.processFile(ESP_AUTOSTART_SCRIPT_FILE); -#endif //ESP_AUTOSTART_FEATURE -#endif //GCODE_HOST_FEATURE - _started=true; - return res; + esp3d_gcode_host.processFile(ESP_AUTOSTART_SCRIPT_FILE); +#endif // ESP_AUTOSTART_FEATURE +#endif // GCODE_HOST_FEATURE + _started = true; + return res; } -//Process which handle all input -void Esp3D::handle() -{ - if(!_started) { - return; - } - //if need restart - if (restart) { - restart_now(); - } +// Process which handle all input +void Esp3D::handle() { + if (!_started) { + return; + } + // if need restart + if (restart) { + restart_now(); + } #if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - serial_service.handle(); -#endif //COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL + serial_service.handle(); +#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == + // MKS_SERIAL #if defined(ESP_SERIAL_BRIDGE_OUTPUT) - serial_bridge_service.handle(); -#endif //ESP_SERIAL_BRIDGE_OUTPUT -#if COMMUNICATION_PROTOCOL ==SOCKET_SERIAL - Serial2Socket.handle(); -#endif //COMMUNICATION_PROTOCOL == SOCKET_SERIAL + serial_bridge_service.handle(); +#endif // ESP_SERIAL_BRIDGE_OUTPUT +#if COMMUNICATION_PROTOCOL == SOCKET_SERIAL + Serial2Socket.handle(); +#endif // COMMUNICATION_PROTOCOL == SOCKET_SERIAL #if defined(WIFI_FEATURE) || defined(ETH_FEATURE) - NetConfig::handle(); -#endif //WIFI_FEATURE || ETH_FEATURE + NetConfig::handle(); +#endif // WIFI_FEATURE || ETH_FEATURE #if defined(CONNECTED_DEVICES_FEATURE) - DevicesServices::handle(); -#endif //CONNECTED_DEVICES_FEATURE + DevicesServices::handle(); +#endif // CONNECTED_DEVICES_FEATURE #if defined(GCODE_HOST_FEATURE) - esp3d_gcode_host.handle(); -#endif //GCODE_HOST_FEATURE + esp3d_gcode_host.handle(); +#endif // GCODE_HOST_FEATURE } -bool Esp3D::started() -{ - return _started; -} +bool Esp3D::started() { return _started; } -//End ESP3D -bool Esp3D::end() -{ - _started = false; +// End ESP3D +bool Esp3D::end() { + _started = false; #if defined(CONNECTED_DEVICES_FEATURE) - DevicesServices::end(); -#endif //CONNECTED_DEVICES_FEATURE + DevicesServices::end(); +#endif // CONNECTED_DEVICES_FEATURE #if defined(ESP_SERIAL_BRIDGE_OUTPUT) - serial_bridge_service.end(); -#endif //ESP_SERIAL_BRIDGE_OUTPUT + serial_bridge_service.end(); +#endif // ESP_SERIAL_BRIDGE_OUTPUT #if defined(WIFI_FEATURE) || defined(ETH_FEATURE) - NetConfig::end(); -#endif //WIFI_FEATURE || ETH_FEATURE + NetConfig::end(); +#endif // WIFI_FEATURE || ETH_FEATURE #if defined(FILESYSTEM_FEATURE) - ESP_FileSystem::end(); -#endif //FILESYSTEM_FEATURE + ESP_FileSystem::end(); +#endif // FILESYSTEM_FEATURE #if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - serial_service.end(); -#endif //COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - return true; + serial_service.end(); +#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == + // MKS_SERIAL + return true; } -//Reset ESP3D settings -bool Esp3D::reset() -{ - bool resetOk = true; +// Reset ESP3D settings +bool Esp3D::reset() { + bool resetOk = true; #if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - if (!serial_service.reset()) { - resetOk = false; - log_esp3d("Reset serial error"); - } -#endif //COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL + if (!serial_service.reset()) { + resetOk = false; + log_esp3d_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("Reset serial bridge error"); - } -#endif //ESP_SERIAL_BRIDGE_OUTPUT - if (!Settings_ESP3D::reset()) { - log_esp3d("Reset settings error"); - resetOk = false; - } - return resetOk; + if (!serial_bridge_service.reset()) { + resetOk = false; + log_esp3d_e("Reset serial bridge error"); + } +#endif // ESP_SERIAL_BRIDGE_OUTPUT + if (!Settings_ESP3D::reset()) { + log_esp3d_e("Reset settings error"); + resetOk = false; + } + return resetOk; } -//Set Restart flag -void Esp3D::restart_esp(bool need_restart) -{ - restart = need_restart; -} +// Set Restart flag +void Esp3D::restart_esp(bool need_restart) { restart = need_restart; } -void Esp3D::restart_now() -{ - //patch for https://github.com/espressif/arduino-esp32/issues/1912#issuecomment-426247971 +void Esp3D::restart_now() { + // patch for + // https://github.com/espressif/arduino-esp32/issues/1912#issuecomment-426247971 #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"); + digitalWrite(ESP3D_ETH_PHY_POWER_PIN, LOW); +#endif // ESP3D_ETH_PHY_POWER_PIN + log_esp3d("Restarting"); #if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - if (!serial_service.started()) { - serial_service.begin(ESP_SERIAL_OUTPUT); - } - serial_service.flush(); -#endif //COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL + if (!serial_service.started()) { + serial_service.begin(ESP_SERIAL_OUTPUT); + } + serial_service.flush(); +#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == + // MKS_SERIAL #if defined(FILESYSTEM_FEATURE) - ESP_FileSystem::end(); -#endif //FILESYSTEM_FEATURE + ESP_FileSystem::end(); +#endif // FILESYSTEM_FEATURE #if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - serial_service.swap(); -#endif //COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - ESP.restart(); - while (1) { - delay (1); - } + serial_service.swap(); +#endif // COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == + // MKS_SERIAL + ESP.restart(); + while (1) { + delay(1); + } } - diff --git a/esp3d/src/core/esp3d.h b/esp3d/src/core/esp3d.h index 2de53b56..ca14ffe3 100644 --- a/esp3d/src/core/esp3d.h +++ b/esp3d/src/core/esp3d.h @@ -20,25 +20,25 @@ #ifndef _ESP3D_H #define _ESP3D_H -//be sure correct IDE and settings are used for ESP8266 or ESP32 -#if !(defined( ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_ESP32)) +// be sure correct IDE and settings are used for ESP8266 or ESP32 +#if !(defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_ESP32)) #error Oops! Make sure you have 'ESP8266 or ESP32' compatible board selected from the 'Tools -> Boards' menu. -#endif // ARDUINO_ARCH_ESP8266 + ARDUINO_ARCH_ESP32 +#endif // ARDUINO_ARCH_ESP8266 + ARDUINO_ARCH_ESP32 #include -class Esp3D -{ -public: - Esp3D(); - ~Esp3D(); - bool begin(); - void handle(); - bool end(); - bool started(); - static bool reset(); - static void restart_esp(bool need_restart = true); -private: - static bool restart; - bool _started; - void restart_now(); +class Esp3D { + public: + Esp3D(); + ~Esp3D(); + bool begin(); + void handle(); + bool end(); + bool started(); + static bool reset(); + static void restart_esp(bool need_restart = true); + + private: + static bool restart; + bool _started; + void restart_now(); }; -#endif //_ESP3D_H +#endif //_ESP3D_H diff --git a/esp3d/src/core/esp3doutput.cpp b/esp3d/src/core/esp3doutput.cpp index ce6d5e0f..1205498a 100644 --- a/esp3d/src/core/esp3doutput.cpp +++ b/esp3d/src/core/esp3doutput.cpp @@ -17,808 +17,826 @@ 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_DEBUG_FEATURE DEBUG_OUTPUT_SERIAL0 -#include "../include/esp3d_config.h" +// #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 +#endif // COMMUNICATION_PROTOCOL != SOCKET_SERIAL #if COMMUNICATION_PROTOCOL == SOCKET_SERIAL #include "../modules/serial2socket/serial2socket.h" -#endif // COMMUNICATION_PROTOCOL == SOCKET_SERIAL +#endif // COMMUNICATION_PROTOCOL == SOCKET_SERIAL #include "settings_esp3d.h" -#if defined (HTTP_FEATURE) || defined(WS_DATA_FEATURE) +#if defined(HTTP_FEATURE) || defined(WS_DATA_FEATURE) #include "../modules/websocket/websocket_server.h" -#endif //HTTP_FEATURE || WS_DATA_FEATURE -#if defined (BLUETOOTH_FEATURE) +#endif // HTTP_FEATURE || WS_DATA_FEATURE +#if defined(BLUETOOTH_FEATURE) #include "../modules/bluetooth/BT_service.h" -#endif //BLUETOOTH_FEATURE -#if defined (TELNET_FEATURE) +#endif // BLUETOOTH_FEATURE +#if defined(TELNET_FEATURE) #include "../modules/telnet/telnet_server.h" -#endif //TELNET_FEATURE +#endif // TELNET_FEATURE #if COMMUNICATION_PROTOCOL == MKS_SERIAL #include "../modules/mks/mks_service.h" -#endif //COMMUNICATION_PROTOCOL == MKS_SERIAL +#endif // COMMUNICATION_PROTOCOL == MKS_SERIAL #if defined(GCODE_HOST_FEATURE) #include "../modules/gcode_host/gcode_host.h" -#endif //GCODE_HOST_FEATURE +#endif // GCODE_HOST_FEATURE -#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL || COMMUNICATION_PROTOCOL == SOCKET_SERIAL +#if COMMUNICATION_PROTOCOL == RAW_SERIAL || \ + COMMUNICATION_PROTOCOL == MKS_SERIAL || \ + COMMUNICATION_PROTOCOL == SOCKET_SERIAL uint8_t ESP3DOutput::_serialoutputflags = DEFAULT_SERIAL_OUTPUT_FLAG; -#endif //COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL || COMMUNICATION_PROTOCOL == SOCKET_SERIAL +#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 = DEFAULT_REMOTE_SCREEN_FLAG; -#endif //HAS_DISPLAY || HAS_SERIAL_DISPLAY -#if defined (WS_DATA_FEATURE) +#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) +#endif // WS_DATA_FEATURE +#if defined(TELNET_FEATURE) uint8_t ESP3DOutput::_telnetoutputflags = DEFAULT_TELNET_FLAG; -#endif //TELNET_FEATURE -#if defined (DISPLAY_DEVICE) +#endif // TELNET_FEATURE +#if defined(DISPLAY_DEVICE) uint8_t ESP3DOutput::_screenoutputflags = DEFAULT_SCREEN_FLAG; -#endif //DISPLAY_DEVICE -#if defined (BLUETOOTH_FEATURE) +#endif // DISPLAY_DEVICE +#if defined(BLUETOOTH_FEATURE) uint8_t ESP3DOutput::_BToutputflags = DEFAULT_BT_FLAG; -#endif //BLUETOOTH_FEATURE +#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) -#if defined (ARDUINO_ARCH_ESP32) +#endif // ESP_SERIAL_BRIDGE_OUTPUT +#if defined(HTTP_FEATURE) +#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 //HTTP_FEATURE -#if defined (DISPLAY_DEVICE) +#endif // ARDUINO_ARCH_ESP8266 +#endif // HTTP_FEATURE +#if defined(DISPLAY_DEVICE) #include "../modules/display/display.h" -#endif //DISPLAY_DEVICE +#endif // DISPLAY_DEVICE -const uint8_t activeClients [] = { -#if !(defined(HAS_DISPLAY) || defined(HAS_SERIAL_DISPLAY)) && (COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL) +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 +#endif // ESP_SERIAL_CLIENT #if defined(ESP_SERIAL_BRIDGE_OUTPUT) ESP_SERIAL_BRIDGE_CLIENT, -#endif //ESP_SERIAL_BRIDGE_OUTPUT -#if defined (TELNET_FEATURE) +#endif // ESP_SERIAL_BRIDGE_OUTPUT +#if defined(TELNET_FEATURE) ESP_TELNET_CLIENT, -#endif //TELNET_FEATURE -#if defined (HTTP_FEATURE) +#endif // TELNET_FEATURE +#if defined(HTTP_FEATURE) ESP_HTTP_CLIENT, -#endif //HTTP_FEATURE +#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) +#endif // defined(HAS_DISPLAY) || defined(HAS_SERIAL_DISPLAY) +#if defined(BLUETOOTH_FEATURE) ESP_BT_CLIENT, -#endif //BLUETOOTH_FEATURE -#if defined (DISPLAY_DEVICE) +#endif // BLUETOOTH_FEATURE +#if defined(DISPLAY_DEVICE) ESP_SCREEN_CLIENT, -#endif //DISPLAY_DEVICE -#if defined (WS_DATA_FEATURE) +#endif // DISPLAY_DEVICE +#if defined(WS_DATA_FEATURE) ESP_WEBSOCKET_CLIENT, -#endif //WS_DATA_FEATURE +#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 -}; +#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(); +// 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) { +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; + esp3d_display.updateIP(); +#endif // DISPLAY_DEVICE + break; case ESP_OUTPUT_STATUS: #ifdef DISPLAY_DEVICE - esp3d_display.setStatus(s); -#endif //DISPLAY_DEVICE - break; + 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; + esp3d_display.progress((uint8_t)atoi(s)); +#endif // DISPLAY_DEVICE + break; case ESP_OUTPUT_STATE: #ifdef DISPLAY_DEVICE - switch(atoi(s)) { + switch (atoi(s)) { case ESP_STATE_DISCONNECTED: - esp3d_display.setStatus("Disconnected"); - break; - default : - break; - } -#endif //DISPLAY_DEVICE - break; + esp3d_display.setStatus("Disconnected"); + break; + default: + break; + } +#endif // DISPLAY_DEVICE + break; default: - (void)s; - break; - } + (void)s; + break; + } } -//constructor -ESP3DOutput::ESP3DOutput(uint8_t client) -{ +// 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; - -#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; + } + return _client; } #ifdef HTTP_FEATURE -//constructor -ESP3DOutput::ESP3DOutput(WEBSERVER * webserver) -{ - _client = ESP_HTTP_CLIENT; - _code = 200; - _headerSent = false; - _footerSent = false; - _webserver = webserver; +// constructor +ESP3DOutput::ESP3DOutput(WEBSERVER *webserver) { + _client = ESP_HTTP_CLIENT; + _code = 200; + _headerSent = false; + _footerSent = false; + _webserver = webserver; } -#endif //HTTP_FEATURE +#endif // HTTP_FEATURE -//destructor -ESP3DOutput::~ESP3DOutput() -{ - flush(); -} +// 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 +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 + _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) { + _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; +#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; + 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; + 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; +#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; +#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; +#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; +#if defined(BLUETOOTH_FEATURE) + return _BToutputflags; +#endif // BLUETOOTH_FEATURE + return 0; default: - return true; - } + 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); +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 (!(_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 (!(_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); + 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 - } + 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 + } +#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_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); } - 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 // 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 //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 + } +#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); - } + 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 // 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 // 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; + } +#endif // WS_DATA_FEATURE + return len; } -//Flush -void ESP3DOutput::flush() -{ - if (!isOutput(_client)) { - return ; - } - switch (_client) { +// 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 + 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; - } + if (_webserver) { + if (_headerSent && !_footerSent) { + _webserver->sendContent(""); + _footerSent = true; } - break; -#endif //HTTP_FEATURE -#if defined (BLUETOOTH_FEATURE) + } + break; +#endif // HTTP_FEATURE +#if defined(BLUETOOTH_FEATURE) case ESP_BT_CLIENT: - bt_service.flush(); - break; -#endif //BLUETOOTH_FEATURE + 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) + 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 + 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; + // do nothing because there are side effects + break; default: - break; - } - return println(s); + break; + } } -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"); - _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"); -#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"); - 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"); - _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; - } +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"); + _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"); +#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"); + 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"); + _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/espcmd/ESP111.cpp b/esp3d/src/core/espcmd/ESP111.cpp index 2b1ba5dc..8a9f4903 100644 --- a/esp3d/src/core/espcmd/ESP111.cpp +++ b/esp3d/src/core/espcmd/ESP111.cpp @@ -17,49 +17,51 @@ 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_DEBUG_FEATURE DEBUG_OUTPUT_SERIAL0 +// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 #include "../../include/esp3d_config.h" -#if defined( WIFI_FEATURE) || defined (ETH_FEATURE) +#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" -#include "../../modules/network/netconfig.h" -#include "../../modules/authentication/authentication_service.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 { - output->printERROR(response.c_str(), 200); +#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"); } - return noError; + } + + 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 { + output->printERROR(response.c_str(), 200); + } + return noError; } -#endif //WIFI_FEATURE +#endif // WIFI_FEATURE diff --git a/esp3d/src/core/espcmd/ESP420.cpp b/esp3d/src/core/espcmd/ESP420.cpp index 728fc78b..81d34caf 100644 --- a/esp3d/src/core/espcmd/ESP420.cpp +++ b/esp3d/src/core/espcmd/ESP420.cpp @@ -18,1642 +18,1656 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../include/esp3d_config.h" +#include "../../modules/authentication/authentication_service.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" + #if COMMUNICATION_PROTOCOL != SOCKET_SERIAL || defined(ESP_SERIAL_BRIDGE_OUTPUT) #include "../../modules/serial/serial_service.h" -#endif // COMMUNICATION_PROTOCOL != SOCKET_SERIAL +#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) +#endif // FILESYSTEM_FEATURE +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BLUETOOTH_FEATURE) #include "../../modules/network/netconfig.h" -#if defined (WIFI_FEATURE) +#if defined(WIFI_FEATURE) #include "../../modules/wifi/wificonfig.h" -#endif //WIFI_FEATURE -#if defined (ETH_FEATURE) +#endif // WIFI_FEATURE +#if defined(ETH_FEATURE) #include "../../modules/ethernet/ethconfig.h" -#endif //ETH_FEATURE -#if defined (BLUETOOTH_FEATURE) +#endif // ETH_FEATURE +#if defined(BLUETOOTH_FEATURE) #include "../../modules/bluetooth/BT_service.h" -#endif //BLUETOOTH_FEATURE -#endif //WIFI_FEATURE || ETH_FEATURE || BLUETOOTH_FEATURE +#endif // BLUETOOTH_FEATURE +#endif // WIFI_FEATURE || ETH_FEATURE || BLUETOOTH_FEATURE #ifdef HTTP_FEATURE #include "../../modules/http/http_server.h" -#endif //HTTP_FEATURE +#endif // HTTP_FEATURE #ifdef TELNET_FEATURE #include "../../modules/telnet/telnet_server.h" -#endif //TELNET_FEATURE +#endif // TELNET_FEATURE #ifdef FTP_FEATURE #include "../../modules/ftp/FtpServer.h" -#endif //FTP_FEATURE +#endif // FTP_FEATURE #ifdef WS_DATA_FEATURE #include "../../modules/websocket/websocket_server.h" -#endif //WS_DATA_FEATURE +#endif // WS_DATA_FEATURE #ifdef WEBDAV_FEATURE #include "../../modules/webdav/webdav_server.h" -#endif //WEBDAV_FEATURE -#if defined (TIMESTAMP_FEATURE) +#endif // WEBDAV_FEATURE +#if defined(TIMESTAMP_FEATURE) #include "../../modules/time/time_server.h" -#endif //TIMESTAMP_FEATURE -#if defined (SENSOR_DEVICE) +#endif // TIMESTAMP_FEATURE +#if defined(SENSOR_DEVICE) #include "../../modules/sensor/sensor.h" -#endif //SENSOR_DEVICE +#endif // SENSOR_DEVICE #ifdef NOTIFICATION_FEATURE #include "../../modules/notifications/notifications_service.h" -#endif //NOTIFICATION_FEATURE +#endif // NOTIFICATION_FEATURE #ifdef BUZZER_DEVICE #include "../../modules/buzzer/buzzer.h" -#endif //BUZZER_DEVICE +#endif // BUZZER_DEVICE #ifdef CAMERA_DEVICE #include "../../modules/camera/camera.h" -#endif //CAMERA_DEVICE +#endif // CAMERA_DEVICE #ifdef SD_DEVICE #include "../../modules/filesystem/esp_sd.h" -#endif //SD_DEVICE -#if defined (DISPLAY_DEVICE) +#endif // SD_DEVICE +#if defined(DISPLAY_DEVICE) #include "../../modules/display/display.h" -#endif //DISPLAY_DEVICE -#define COMMANDID 420 +#endif // DISPLAY_DEVICE +#define COMMANDID 420 -//Get ESP current status -//output is JSON or plain text according parameter +// 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 +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; - } + 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 +=": "; - } + (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(); + line += ESP_FileSystem::formatBytes(ESP.getFreeHeap()).c_str(); #else - line+=ESP.getFreeHeap(); -#endif//FILESYSTEM_FEATURE + line += ESP.getFreeHeap(); +#endif // FILESYSTEM_FEATURE #ifdef ARDUINO_ARCH_ESP32 #ifdef BOARD_HAS_PSRAM - line+=" - PSRAM:"; - line+=ESP_FileSystem::formatBytes (ESP.getFreePsram()); + 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 +=": "; - } +#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()); + 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=""; + 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(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 + // 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 +=timeserver.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_DEBUG_FEATURE) - //debug - if (json) { - line +=",{\"id\":\""; - } - line +="debug"; - if (json) { - line +="\",\"value\":\""; - } else { - line +=": "; - } -#if ESP_DEBUG_FEATURE == DEBUG_OUTPUT_SERIAL0 - line +="Serial"; -#endif //DEBUG_OUTPUT_SERIAL0 -#if ESP_DEBUG_FEATURE == DEBUG_OUTPUT_SERIAL1 - line +="Serial1"; -#endif //DEBUG_OUTPUT_SERIAL1 -#if ESP_DEBUG_FEATURE == DEBUG_OUTPUT_SERIAL2 - line +="Serial2"; -#endif //DEBUG_OUTPUT_SERIAL2 -#if ESP_DEBUG_FEATURE == DEBUG_OUTPUT_TELNET - line+="Telnet("+String( DEBUG_ESP3D_OUTPUT_PORT) +")"; -#endif //DEBUG_OUTPUT_TELNET -#if ESP_DEBUG_FEATURE == DEBUG_OUTPUT_WEBSOCKET - line+="Websocket("+ String(DEBUG_ESP3D_OUTPUT_PORT)+")"; -#endif //DEBUG_OUTPUT_WEBSOCKET - if (json) { - line +="\"}"; - output->print (line.c_str()); - } else { - output->printMSGLine(line.c_str()); - } - line=""; -#endif //ESP_DEBUG_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 (noError) { + // 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) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); + 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 += timeserver.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 { - output->printERROR(response.c_str(), errorCode); + response = format_response(COMMANDID, json, false, + "This command doesn't take parameters"); + noError = false; } - return noError; + } + if (noError) { + if (json) { + output->printLN(response.c_str()); + } else { + output->printMSG(response.c_str()); + } + } else { + output->printERROR(response.c_str(), errorCode); + } + return noError; } diff --git a/esp3d/src/core/espcmd/ESP701.cpp b/esp3d/src/core/espcmd/ESP701.cpp index b4a77fd7..62f2821e 100644 --- a/esp3d/src/core/espcmd/ESP701.cpp +++ b/esp3d/src/core/espcmd/ESP701.cpp @@ -17,125 +17,139 @@ 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_DEBUG_FEATURE DEBUG_OUTPUT_SERIAL0 +// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 #include "../../include/esp3d_config.h" -#if defined(GCODE_HOST_FEATURE) +#if defined(GCODE_HOST_FEATURE) +#include "../../modules/authentication/authentication_service.h" +#include "../../modules/gcode_host/gcode_host.h" #include "../commands.h" #include "../esp3doutput.h" #include "../settings_esp3d.h" -#include "../../modules/authentication/authentication_service.h" -#include "../../modules/gcode_host/gcode_host.h" -#define COMMANDID 701 -//Query and Control ESP700 stream +#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 +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; - } + 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; - } + (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 (noError) { - if (json) { - output->printLN (response.c_str() ); - } else { - output->printMSG (response.c_str() ); - } } else { - output->printERROR(response.c_str(), errorCode); + 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; + } } - return noError; + } + if (noError) { + if (json) { + output->printLN(response.c_str()); + } else { + output->printMSG(response.c_str()); + } + } else { + output->printERROR(response.c_str(), errorCode); + } + return noError; } -#endif //GCODE_HOST_FEATURE +#endif // GCODE_HOST_FEATURE diff --git a/esp3d/src/core/hal.cpp b/esp3d/src/core/hal.cpp index c70d299e..d35c9734 100644 --- a/esp3d/src/core/hal.cpp +++ b/esp3d/src/core/hal.cpp @@ -22,228 +22,215 @@ #if defined(ARDUINO_ARCH_ESP8266) #include -#endif //ARDUINO_ARCH_ESP8266 +#endif // ARDUINO_ARCH_ESP8266 #if defined(ARDUINO_ARCH_ESP32) #include #if CONFIG_IDF_TARGET_ESP32 || CONFIG_IDF_TARGET_ESP32S2 -//FIXME : S3 not support it yet +// FIXME : S3 not support it yet #include -#endif //CONFIG_IDF_TARGET_ESP32 || CONFIG_IDF_TARGET_ESP32S2 -#include +#endif // CONFIG_IDF_TARGET_ESP32 || CONFIG_IDF_TARGET_ESP32S2 #include -#include #include +#include +#include + TaskHandle_t Hal::xHandle = nullptr; -#endif //ARDUINO_ARCH_ESP32 +#endif // ARDUINO_ARCH_ESP32 #include "esp3doutput.h" - uint32_t Hal::_analogRange = 255; uint32_t Hal::_analogWriteFreq = 1000; -void Hal::pinMode(uint8_t pin, uint8_t mode) -{ -#if defined (ARDUINO_ARCH_ESP8266) - if ((pin == 16) && (mode == INPUT_PULLUP)) { - ::pinMode(pin, INPUT_PULLDOWN_16); - return; - } +void Hal::pinMode(uint8_t pin, uint8_t mode) { +#if defined(ARDUINO_ARCH_ESP8266) + if ((pin == 16) && (mode == INPUT_PULLUP)) { + ::pinMode(pin, INPUT_PULLDOWN_16); + return; + } #endif - ::pinMode(pin, mode); + ::pinMode(pin, mode); } -int Hal::analogRead(uint8_t pin) -{ -#ifdef ARDUINO_ARCH_ESP8266 //only one ADC on ESP8266 A0 - (void)pin; - return ::analogRead (A0); +int Hal::analogRead(uint8_t pin) { +#ifdef ARDUINO_ARCH_ESP8266 // only one ADC on ESP8266 A0 + (void)pin; + return ::analogRead(A0); #else - return ::analogRead (pin); + return ::analogRead(pin); #endif } -bool Hal::analogWrite(uint8_t pin, uint value) -{ - if (value > (_analogRange-1)) { - return false; - } +bool Hal::analogWrite(uint8_t pin, uint value) { + if (value > (_analogRange - 1)) { + return false; + } #ifdef ARDUINO_ARCH_ESP8266 - ::analogWrite(pin, value); -#endif //ARDUINO_ARCH_ESP8266 + ::analogWrite(pin, value); +#endif // ARDUINO_ARCH_ESP8266 #ifdef ARDUINO_ARCH_ESP32 - ::analogWrite(pin, value); -#endif //ARDUINO_ARCH_ESP32 - return true; + ::analogWrite(pin, value); +#endif // ARDUINO_ARCH_ESP32 + return true; } -void Hal::analogWriteFreq(uint32_t freq) -{ - _analogWriteFreq = freq; +void Hal::analogWriteFreq(uint32_t freq) { + _analogWriteFreq = freq; #ifdef ARDUINO_ARCH_ESP8266 - ::analogWriteFreq(_analogWriteFreq); -#endif //ARDUINO_ARCH_ESP8266 + ::analogWriteFreq(_analogWriteFreq); +#endif // ARDUINO_ARCH_ESP8266 } -void Hal::analogRange(uint32_t range) -{ - _analogRange = range; - uint8_t resolution = 0; - switch(_analogRange) { +void Hal::analogRange(uint32_t range) { + _analogRange = range; + uint8_t resolution = 0; + switch (_analogRange) { case 8191: - resolution=13; - break; + resolution = 13; + break; case 1024: - resolution=10; - break; + resolution = 10; + break; case 2047: - resolution=11; - break; + resolution = 11; + break; case 4095: - resolution=12; - break; + resolution = 12; + break; default: - resolution=8; - _analogRange = 255; - break; - } + resolution = 8; + _analogRange = 255; + break; + } #if defined(ARDUINO_ARCH_ESP32) - analogReadResolution(resolution); -#endif //ARDUINO_ARCH_ESP32 + analogReadResolution(resolution); +#endif // ARDUINO_ARCH_ESP32 #ifdef ARDUINO_ARCH_ESP8266 - (void)resolution; - ::analogWriteRange(_analogRange); -#endif //ARDUINO_ARCH_ESP8266 + (void)resolution; + ::analogWriteRange(_analogRange); +#endif // ARDUINO_ARCH_ESP8266 } -//Setup -bool Hal::begin() -{ +// Setup +bool Hal::begin() { #if defined(ARDUINO_ARCH_ESP32) && defined(CAMERA_DEVICE) - log_esp3d("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 - WiFi.persistent(false); - WiFi.disconnect(true); - WiFi.enableSTA (false); - WiFi.enableAP (false); - WiFi.mode (WIFI_OFF); + log_esp3d("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 + WiFi.persistent(false); + WiFi.disconnect(true); + WiFi.enableSTA(false); + WiFi.enableAP(false); + WiFi.mode(WIFI_OFF); #if SD_DEVICE_CONNECTION == ESP_SHARED_SD #if defined(ESP_SD_DETECT_PIN) && ESP_SD_DETECT_PIN != -1 - pinMode (ESP_SD_DETECT_PIN, INPUT); + pinMode(ESP_SD_DETECT_PIN, INPUT); #endif #if defined(ESP_FLAG_SHARED_SD_PIN) && ESP_FLAG_SHARED_SD_PIN != -1 - pinMode (ESP_FLAG_SHARED_SD_PIN, OUTPUT); - digitalWrite(ESP_FLAG_SHARED_SD_PIN, !ESP_FLAG_SHARED_SD_VALUE); -#endif //ESP_FLAG_SHARED_SD_PIN -#endif //SD_DEVICE_CONNECTION == ESP_SHARED_SD - return true; + pinMode(ESP_FLAG_SHARED_SD_PIN, OUTPUT); + digitalWrite(ESP_FLAG_SHARED_SD_PIN, !ESP_FLAG_SHARED_SD_VALUE); +#endif // ESP_FLAG_SHARED_SD_PIN +#endif // SD_DEVICE_CONNECTION == ESP_SHARED_SD + return true; } -//End ESP3D -void Hal::end() -{ -} +// End ESP3D +void Hal::end() {} -//Watchdog feeder -void Hal::wdtFeed() -{ +// Watchdog feeder +void Hal::wdtFeed() { #ifdef ARDUINO_ARCH_ESP8266 - ESP.wdtFeed(); -#endif //ARDUINO_ARCH_ESP8266 + ESP.wdtFeed(); +#endif // ARDUINO_ARCH_ESP8266 #ifdef ARDUINO_ARCH_ESP32 - static uint64_t lastYield = 0; - uint64_t now = millis(); - if((now - lastYield) > 2000) { - lastYield = now; - vTaskDelay(5); //delay 1 RTOS tick - } + static uint64_t lastYield = 0; + uint64_t now = millis(); + if ((now - lastYield) > 2000) { + lastYield = now; + vTaskDelay(5); // delay 1 RTOS tick + } #if !defined(DISABLE_WDT_ESP3DLIB_TASK) && !defined(DISABLE_WDT_CORE_0) #if CONFIG_IDF_TARGET_ESP32 - //FIXME: not implemented - rtc_wdt_feed(); -#endif //CONFIG_IDF_TARGET_ESP32S2 -#endif//!defined(DISABLE_WDT_ESP3DLIB_TASK) && !defined(DISABLE_WDT_CORE_0) + // FIXME: not implemented + rtc_wdt_feed(); +#endif // CONFIG_IDF_TARGET_ESP32S2 +#endif //! defined(DISABLE_WDT_ESP3DLIB_TASK) && !defined(DISABLE_WDT_CORE_0) #ifndef DISABLE_WDT_ESP3DLIB_TASK - if (xHandle && esp_task_wdt_status(xHandle)==ESP_OK) { - if (esp_task_wdt_reset()!=ESP_OK) { - log_esp3d("WDT Reset failed"); - } + if (xHandle && esp_task_wdt_status(xHandle) == ESP_OK) { + if (esp_task_wdt_reset() != ESP_OK) { + log_esp3d_e("WDT Reset failed"); } -#endif //DISABLE_WDT_ESP3DLIB_TASK -#endif //ARDUINO_ARCH_ESP32 + } +#endif // DISABLE_WDT_ESP3DLIB_TASK +#endif // ARDUINO_ARCH_ESP32 } -//wait function -void Hal::wait (uint32_t milliseconds) -{ +// wait function +void Hal::wait(uint32_t milliseconds) { #if defined(ASYNCWEBSERVER) - uint32_t timeout = millis(); - while ( (millis() - timeout) < milliseconds) { - wdtFeed(); - } -#else // !(ASYNCWEBSERVER + uint32_t timeout = millis(); + while ((millis() - timeout) < milliseconds) { wdtFeed(); - //before 0 was acceptable, now it seems need to put 5 to have some effect if on esp32 core 0 - delay(milliseconds<5?5:milliseconds); -#endif // !ASYNCWEBSERVER + } +#else // !(ASYNCWEBSERVER + wdtFeed(); + // before 0 was acceptable, now it seems need to put 5 to have some effect if + // on esp32 core 0 + delay(milliseconds < 5 ? 5 : milliseconds); +#endif // !ASYNCWEBSERVER } -uint16_t Hal::getChipID() -{ +uint16_t Hal::getChipID() { #ifdef ARDUINO_ARCH_ESP8266 - return ESP.getChipId(); -#endif //ARDUINO_ARCH_ESP8266 + return ESP.getChipId(); +#endif // ARDUINO_ARCH_ESP8266 #ifdef ARDUINO_ARCH_ESP32 - return (uint16_t) (ESP.getEfuseMac() >> 32); -#endif //ARDUINO_ARCH_ESP32 + return (uint16_t)(ESP.getEfuseMac() >> 32); +#endif // ARDUINO_ARCH_ESP32 } -bool Hal::has_temperature_sensor() -{ +bool Hal::has_temperature_sensor() { #ifdef ARDUINO_ARCH_ESP8266 - return false; -#endif //ARDUINO_ARCH_ESP8266 + return false; +#endif // ARDUINO_ARCH_ESP8266 #ifdef ARDUINO_ARCH_ESP32 #if CONFIG_IDF_TARGET_ESP32S3 - //FIXME: not yet implemented - return false; + // FIXME: not yet implemented + return false; #else + return true; +#endif // CONFIG_IDF_TARGET_ESP32S3 +#endif // ARDUINO_ARCH_ESP32 +} + +float Hal::temperature() { +#ifdef ARDUINO_ARCH_ESP8266 + return 0.0; +#endif // ARDUINO_ARCH_ESP8266 + +#ifdef ARDUINO_ARCH_ESP32 +#if CONFIG_IDF_TARGET_ESP32S3 + // FIXME: not yet implemented + return 0.0; +#else + return temperatureRead(); +#endif // CONFIG_IDF_TARGET_ESP32S3 +#endif // ARDUINO_ARCH_ESP32 +} + +bool Hal::is_pin_usable(uint pin) { +#ifdef ARDUINO_ARCH_ESP8266 + if ((pin <= 5) || ((pin >= 12) && (pin <= 16))) { return true; -#endif //CONFIG_IDF_TARGET_ESP32S3 -#endif //ARDUINO_ARCH_ESP32 -} - -float Hal::temperature() -{ -#ifdef ARDUINO_ARCH_ESP8266 - return 0.0; -#endif //ARDUINO_ARCH_ESP8266 - + } else { + return false; + } +#endif // ARDUINO_ARCH_ESP8266 #ifdef ARDUINO_ARCH_ESP32 -#if CONFIG_IDF_TARGET_ESP32S3 - //FIXME: not yet implemented - return 0.0; -#else - return temperatureRead(); -#endif //CONFIG_IDF_TARGET_ESP32S3 -#endif //ARDUINO_ARCH_ESP32 -} - -bool Hal::is_pin_usable(uint pin) -{ -#ifdef ARDUINO_ARCH_ESP8266 - if ((pin <= 5) || ((pin >= 12) && (pin <= 16))) { - return true; - } else { - return false; - } -#endif //ARDUINO_ARCH_ESP8266 -#ifdef ARDUINO_ARCH_ESP32 - //TODO: Add support for ESP32 S2 S3 C2 C3 - if ((pin <= 5) || ((pin >= 12) && (pin <= 39))) { - return true; - } else { - return false; - } -#endif //ARDUINO_ARCH_ESP32 + // TODO: Add support for ESP32 S2 S3 C2 C3 + if ((pin <= 5) || ((pin >= 12) && (pin <= 39))) { + return true; + } else { + return false; + } +#endif // ARDUINO_ARCH_ESP32 } diff --git a/esp3d/src/core/log_esp3d.cpp b/esp3d/src/core/log_esp3d.cpp new file mode 100644 index 00000000..12a18b6a --- /dev/null +++ b/esp3d/src/core/log_esp3d.cpp @@ -0,0 +1,58 @@ +/* + 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 new file mode 100644 index 00000000..1de3cfce --- /dev/null +++ b/esp3d/src/core/log_esp3d.h @@ -0,0 +1,183 @@ +/* + 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/core/settings_esp3d.cpp b/esp3d/src/core/settings_esp3d.cpp index 64de36ea..3f628943 100644 --- a/esp3d/src/core/settings_esp3d.cpp +++ b/esp3d/src/core/settings_esp3d.cpp @@ -19,105 +19,102 @@ */ #include "../include/esp3d_config.h" -#if defined (ESP_SAVE_SETTINGS) -#include "settings_esp3d.h" +#if defined(ESP_SAVE_SETTINGS) #include "esp3doutput.h" +#include "settings_esp3d.h" #if ESP_SAVE_SETTINGS == SETTINGS_IN_EEPROM #include -//EEPROM SIZE (Up to 4096) -#define EEPROM_SIZE 2048 //max is 2048 -#endif //SETTINGS_IN_EEPROM +// EEPROM SIZE (Up to 4096) +#define EEPROM_SIZE 2048 // max is 2048 +#endif // SETTINGS_IN_EEPROM -#if defined (WIFI_FEATURE) || defined(ETH_FEATURE) +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) #include "../modules/network/netconfig.h" -#if defined (WIFI_FEATURE) +#if defined(WIFI_FEATURE) #include "../modules/wifi/wificonfig.h" -#endif //WIFI_FEATURE -#endif //WIFI_FEATURE || ETH_FEATURE - +#endif // WIFI_FEATURE +#endif // WIFI_FEATURE || ETH_FEATURE #if ESP_SAVE_SETTINGS == SETTINGS_IN_PREFERENCES #include #define NAMESPACE "ESP3D" -#endif // SETTINGS_IN_PREFERENCES +#endif // SETTINGS_IN_PREFERENCES -//Current Settings Version +// Current Settings Version #define CURRENT_SETTINGS_VERSION "ESP3D04" -//boundaries -#define MAX_SENSOR_INTERVAL 60000 -#define MIN_SENSOR_INTERVAL 0 -#define MAX_LOCAL_PASSWORD_LENGTH 20 -#define MIN_LOCAL_PASSWORD_LENGTH 1 -#define MAX_VERSION_LENGTH 7 //ESP3DXX -#define MAX_BOOT_DELAY 40000 -#define MIN_BOOT_DELAY 0 +// boundaries +#define MAX_SENSOR_INTERVAL 60000 +#define MIN_SENSOR_INTERVAL 0 +#define MAX_LOCAL_PASSWORD_LENGTH 20 +#define MIN_LOCAL_PASSWORD_LENGTH 1 +#define MAX_VERSION_LENGTH 7 // ESP3DXX +#define MAX_BOOT_DELAY 40000 +#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_SETTINGS_LENGTH 128 -#define MAX_SERVER_ADDRESS_LENGTH 128 -#define MIN_SERVER_ADDRESS_LENGTH 0 +#define MAX_SERVER_ADDRESS_LENGTH 128 +#define MIN_SERVER_ADDRESS_LENGTH 0 - -//default byte values +// default byte values #ifdef WIFI_FEATURE -#define DEFAULT_STA_FALLBACK_MODE ESP_AP_SETUP +#define DEFAULT_STA_FALLBACK_MODE ESP_AP_SETUP #if defined(STATION_WIFI_SSID) && defined(STATION_WIFI_PASSWORD) -#define DEFAULT_ESP_RADIO_MODE ESP_WIFI_STA +#define DEFAULT_ESP_RADIO_MODE ESP_WIFI_STA #else -#define DEFAULT_ESP_RADIO_MODE ESP_AP_SETUP -#endif //STATION_WIFI_SSID && STATION_WIFI_PASSWORD -#else //WIFI_FEATURE -#define DEFAULT_STA_FALLBACK_MODE ESP_NO_NETWORK +#define DEFAULT_ESP_RADIO_MODE ESP_AP_SETUP +#endif // STATION_WIFI_SSID && STATION_WIFI_PASSWORD +#else // WIFI_FEATURE +#define DEFAULT_STA_FALLBACK_MODE ESP_NO_NETWORK #ifdef BLUETOOTH_FEATURE -#define DEFAULT_ESP_RADIO_MODE ESP_BT -#else //BLUETOOTH_FEATURE +#define DEFAULT_ESP_RADIO_MODE ESP_BT +#else // BLUETOOTH_FEATURE #ifdef ETH_FEATURE -#define DEFAULT_ESP_RADIO_MODE ESP_ETH_STA -#else //BLUETOOTH_FEATURE -#define DEFAULT_ESP_RADIO_MODE ESP_NO_NETWORK -#endif //ETH_FEATURE -#endif //BLUETOOTH_FEATURE -#endif //WIFI_FEATURE +#define DEFAULT_ESP_RADIO_MODE ESP_ETH_STA +#else // BLUETOOTH_FEATURE +#define DEFAULT_ESP_RADIO_MODE ESP_NO_NETWORK +#endif // ETH_FEATURE +#endif // BLUETOOTH_FEATURE +#endif // WIFI_FEATURE #ifdef BUZZER_DEVICE #define DEFAULT_BUZZER_STATE 1 -#endif //BUZZER_DEVICE +#endif // BUZZER_DEVICE #ifdef TIMESTAMP_FEATURE -#define DEFAULT_INTERNET_TIME 0 -#endif //TIMESTAMP_FEATURE +#define DEFAULT_INTERNET_TIME 0 +#endif // TIMESTAMP_FEATURE +#define DEFAULT_SETUP 0 -#define DEFAULT_SETUP 0 - -#define DEFAULT_VERBOSE_BOOT 0 -#define DEFAULT_ESP_BYTE 0 +#define DEFAULT_VERBOSE_BOOT 0 +#define DEFAULT_ESP_BYTE 0 #define DEFAULT_ESP_STRING_SIZE 0 -#if defined (WIFI_FEATURE) || defined (ETH_FEATURE) -#define DEFAULT_STA_IP_MODE DHCP_MODE -#endif //WIFI_FEATURE || ETH_FEATURE -//#define DEFAULT_PHY_MODE WIFI_PHY_MODE_11G -//#define DEFAULT_SLEEP_MODE WIFI_MODEM_SLEEP -#define DEFAULT_AP_CHANNEL 11 -#define DEFAULT_AUTH_TYPE AUTH_WPA_PSK -#define DEFAULT_SSID_VISIBLE 1 -#define DEFAULT_OUTPUT_FLAG ESP_ALL_CLIENTS -#define DEFAULT_SDREADER_SPEED 4 +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) +#define DEFAULT_STA_IP_MODE DHCP_MODE +#endif // WIFI_FEATURE || ETH_FEATURE +// #define DEFAULT_PHY_MODE WIFI_PHY_MODE_11G +// #define DEFAULT_SLEEP_MODE WIFI_MODEM_SLEEP +#define DEFAULT_AP_CHANNEL 11 +#define DEFAULT_AUTH_TYPE AUTH_WPA_PSK +#define DEFAULT_SSID_VISIBLE 1 +#define DEFAULT_OUTPUT_FLAG ESP_ALL_CLIENTS +#define DEFAULT_SDREADER_SPEED 4 #ifndef DEFAULT_FW -#define DEFAULT_FW UNKNOWN_FW -#endif //DEFAULT_FW -#define DEFAULT_TIME_ZONE 0 -#define DEFAULT_TIME_DST 0 -#define DEFAULT_SD_MOUNT ESP_SD_ROOT +#define DEFAULT_FW UNKNOWN_FW +#endif // DEFAULT_FW +#define DEFAULT_TIME_ZONE 0 +#define DEFAULT_TIME_DST 0 +#define DEFAULT_SD_MOUNT ESP_SD_ROOT #define DEFAULT_SD_CHECK_UPDATE_AT_BOOT 1 -#define DEFAULT_SENSOR_TYPE NO_SENSOR_DEVICE -#define DEFAULT_HTTP_ON 1 -#define DEFAULT_FTP_ON 1 +#define DEFAULT_SENSOR_TYPE NO_SENSOR_DEVICE +#define DEFAULT_HTTP_ON 1 +#define DEFAULT_FTP_ON 1 #define DEFAULT_SERIAL_BRIDGE_ON 1 -#define DEFAULT_WEBDAV_ON 1 -#define DEFAULT_TELNET_ON 1 -#define DEFAULT_WEBSOCKET_ON 1 +#define DEFAULT_WEBDAV_ON 1 +#define DEFAULT_TELNET_ON 1 +#define DEFAULT_WEBSOCKET_ON 1 #define DEFAULT_NOTIFICATION_TYPE 0 #define DEFAULT_NOTIFICATION_TOKEN1 "" #define DEFAULT_NOTIFICATION_TOKEN2 "" @@ -126,1239 +123,1321 @@ #define DEFAULT_SECURE_SERIAL 1 #define DEFAULT_BOOT_RADIO_STATE 1 -//default int values -#define DEFAULT_ESP_INT 0L -#define DEFAULT_BAUD_RATE 115200L +// default int values +#define DEFAULT_ESP_INT 0L +#define DEFAULT_BAUD_RATE 115200L #define DEFAULT_SERIAL_BRIDGE_BAUD_RATE 115200L -#define DEFAULT_HTTP_PORT 80L -#define DEFAULT_FTP_CTRL_PORT 21L +#define DEFAULT_HTTP_PORT 80L +#define DEFAULT_FTP_CTRL_PORT 21L #define DEFAULT_FTP_ACTIVE_PORT 20L #define DEFAULT_FTP_PASSIVE_PORT 55600L -#define DEFAULT_WEBSOCKET_PORT 8282L -#define DEFAULT_WEBDAV_PORT 8181L -#define DEFAULT_TELNET_PORT 23L +#define DEFAULT_WEBSOCKET_PORT 8282L +#define DEFAULT_WEBDAV_PORT 8181L +#define DEFAULT_TELNET_PORT 23L #define DEFAULT_SENSOR_INTERVAL 30000L -#define DEFAULT_BOOT_DELAY 10000L +#define DEFAULT_BOOT_DELAY 10000L #define DEFAULT_CALIBRATION_VALUE 0 #define DEFAULT_CALIBRATION_DONE 0 #define DEFAULT_SESSION_TIMEOUT 3 #ifdef WIFI_FEATURE -//default string values -const char DEFAULT_AP_SSID [] = "ESP3D"; -const char DEFAULT_AP_PASSWORD [] = "12345678"; +// default string values +const char DEFAULT_AP_SSID[] = "ESP3D"; +const char DEFAULT_AP_PASSWORD[] = "12345678"; #if defined(STATION_WIFI_SSID) && defined(STATION_WIFI_PASSWORD) -const char DEFAULT_STA_SSID [] = STATION_WIFI_SSID; -const char DEFAULT_STA_PASSWORD [] = STATION_WIFI_PASSWORD; +const char DEFAULT_STA_SSID[] = STATION_WIFI_SSID; +const char DEFAULT_STA_PASSWORD[] = STATION_WIFI_PASSWORD; #else -const char DEFAULT_STA_SSID [] = "NETWORK_SSID"; -const char DEFAULT_STA_PASSWORD [] = "12345678"; -#endif //STATION_WIFI_SSID && STATION_WIFI_PASSWORD -#endif //WIFI_FEATURE -#if defined (BLUETOOTH_FEATURE) || defined (WIFI_FEATURE) ||defined (ETH_FEATURE) -const char DEFAULT_HOSTNAME [] = "esp3d"; -#endif //BLUETOOTH_FEATURE ||WIFI_FEATURE || ETH_FEATURE -const char DEFAULT_ESP_STRING [] = ""; +const char DEFAULT_STA_SSID[] = "NETWORK_SSID"; +const char DEFAULT_STA_PASSWORD[] = "12345678"; +#endif // STATION_WIFI_SSID && STATION_WIFI_PASSWORD +#endif // WIFI_FEATURE +#if defined(BLUETOOTH_FEATURE) || defined(WIFI_FEATURE) || defined(ETH_FEATURE) +const char DEFAULT_HOSTNAME[] = "esp3d"; +#endif // BLUETOOTH_FEATURE ||WIFI_FEATURE || ETH_FEATURE +const char DEFAULT_ESP_STRING[] = ""; #ifdef AUTHENTICATION_FEATURE -const char DEFAULT_ADMIN_PWD [] = "admin"; -const char DEFAULT_USER_PWD [] = "user"; -#endif //AUTHENTICATION_FEATURE +const char DEFAULT_ADMIN_PWD[] = "admin"; +const char DEFAULT_USER_PWD[] = "user"; +#endif // AUTHENTICATION_FEATURE #ifdef TIMESTAMP_FEATURE -const char DEFAULT_TIME_SERVER1 [] = "1.pool.ntp.org"; -const char DEFAULT_TIME_SERVER2 [] = "2.pool.ntp.org"; -const char DEFAULT_TIME_SERVER3 [] = "0.pool.ntp.org"; -#endif //TIMESTAMP_FEATURE -const char DEFAULT_SETTINGS_VERSION [] = "ESP3D"; +const char DEFAULT_TIME_SERVER1[] = "1.pool.ntp.org"; +const char DEFAULT_TIME_SERVER2[] = "2.pool.ntp.org"; +const char DEFAULT_TIME_SERVER3[] = "0.pool.ntp.org"; +#endif // TIMESTAMP_FEATURE +const char DEFAULT_SETTINGS_VERSION[] = "ESP3D"; -#if defined (WIFI_FEATURE) ||defined (ETH_FEATURE) -//default IP values -const uint8_t DEFAULT_IP_VALUE[] = {192, 168, 0, 1}; -const uint8_t DEFAULT_MASK_VALUE[] = {255, 255, 255, 0}; -#define DEFAULT_GATEWAY_VALUE DEFAULT_IP_VALUE -#define DEFAULT_DNS_VALUE DEFAULT_GATEWAY_VALUE -const uint8_t DEFAULT_ADDRESS_VALUE[] = {0, 0, 0, 0}; -#endif //WIFI_FEATURE || ETH_FEATURE +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) +// default IP values +const uint8_t DEFAULT_IP_VALUE[] = {192, 168, 0, 1}; +const uint8_t DEFAULT_MASK_VALUE[] = {255, 255, 255, 0}; +#define DEFAULT_GATEWAY_VALUE DEFAULT_IP_VALUE +#define DEFAULT_DNS_VALUE DEFAULT_GATEWAY_VALUE +const uint8_t DEFAULT_ADDRESS_VALUE[] = {0, 0, 0, 0}; +#endif // WIFI_FEATURE || ETH_FEATURE uint8_t Settings_ESP3D::_FirmwareTarget = DEFAULT_FW; bool Settings_ESP3D::_isverboseboot = DEFAULT_VERBOSE_BOOT; -bool Settings_ESP3D::begin() -{ - if(GetSettingsVersion() == -1) { - return false; - } - //get target FW - Settings_ESP3D::GetFirmwareTarget(true); - Settings_ESP3D::isVerboseBoot(true); - return true; +bool Settings_ESP3D::begin() { + if (GetSettingsVersion() == -1) { + return false; + } + // get target FW + Settings_ESP3D::GetFirmwareTarget(true); + Settings_ESP3D::isVerboseBoot(true); + return true; } -bool Settings_ESP3D::isVerboseBoot(bool fromsettings) -{ +bool Settings_ESP3D::isVerboseBoot(bool fromsettings) { #if COMMUNICATION_PROTOCOL != MKS_SERIAL - if(fromsettings) { - _isverboseboot = read_byte (ESP_VERBOSE_BOOT); - } + if (fromsettings) { + _isverboseboot = read_byte(ESP_VERBOSE_BOOT); + } #else - _isverboseboot = false; -#endif //#if COMMUNICATION_PROTOCOL == MKS_SERIAL - return _isverboseboot; + _isverboseboot = false; +#endif // #if COMMUNICATION_PROTOCOL == MKS_SERIAL + return _isverboseboot; } -uint8_t Settings_ESP3D::GetFirmwareTarget(bool fromsettings) -{ -#if defined( FIXED_FW_TARGET ) - (void)fromsettings; - _FirmwareTarget = FIXED_FW_TARGET; +uint8_t Settings_ESP3D::GetFirmwareTarget(bool fromsettings) { +#if defined(FIXED_FW_TARGET) + (void)fromsettings; + _FirmwareTarget = FIXED_FW_TARGET; #else - if(fromsettings) { - _FirmwareTarget = read_byte (ESP_TARGET_FW); - } -#endif //#if defined( FIXED_FW_TARGET ) - return _FirmwareTarget; - + if (fromsettings) { + _FirmwareTarget = read_byte(ESP_TARGET_FW); + } +#endif // #if defined( FIXED_FW_TARGET ) + return _FirmwareTarget; } -uint8_t Settings_ESP3D::GetSDDevice() -{ +uint8_t Settings_ESP3D::GetSDDevice() { #ifdef SD_DEVICE - return SD_DEVICE_CONNECTION; -#else // !SD_DEVICE - return ESP_NO_SD; -#endif //SD_DEVICE + return SD_DEVICE_CONNECTION; +#else // !SD_DEVICE + return ESP_NO_SD; +#endif // SD_DEVICE } -const char* Settings_ESP3D::GetFirmwareTargetShortName() -{ - static String response; +const char *Settings_ESP3D::GetFirmwareTargetShortName() { + static String response; - if ( _FirmwareTarget == REPETIER) { - response = F ("repetier"); - } else if ( _FirmwareTarget == MARLIN) { - response = F ("marlin"); - } else if ( _FirmwareTarget == MARLIN_EMBEDDED) { - response = F ("marlin"); - } else if ( _FirmwareTarget == SMOOTHIEWARE) { - response = F ("smoothieware"); - } else if ( _FirmwareTarget == GRBL) { - response = F ("grbl"); - } else { - response = F ("unknown"); - } - return response.c_str(); + if (_FirmwareTarget == REPETIER) { + response = F("repetier"); + } else if (_FirmwareTarget == MARLIN) { + response = F("marlin"); + } else if (_FirmwareTarget == MARLIN_EMBEDDED) { + response = F("marlin"); + } else if (_FirmwareTarget == SMOOTHIEWARE) { + response = F("smoothieware"); + } else if (_FirmwareTarget == GRBL) { + response = F("grbl"); + } else { + response = F("unknown"); + } + return response.c_str(); } -//Default value for a byte setting -uint8_t Settings_ESP3D::get_default_byte_value(int pos) -{ - uint8_t res; - switch(pos) { +// Default value for a byte setting +uint8_t Settings_ESP3D::get_default_byte_value(int pos) { + uint8_t res; + switch (pos) { case ESP_BOOT_RADIO_STATE: - res = DEFAULT_BOOT_RADIO_STATE; - break; + res = DEFAULT_BOOT_RADIO_STATE; + break; case ESP_STA_FALLBACK_MODE: - res = DEFAULT_STA_FALLBACK_MODE; - break; + res = DEFAULT_STA_FALLBACK_MODE; + break; #if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL case ESP_SECURE_SERIAL: - res = DEFAULT_SECURE_SERIAL; - break; -#endif //#if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL + res = DEFAULT_SECURE_SERIAL; + break; +#endif // #if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == + // MKS_SERIAL case ESP_RADIO_MODE: - res = DEFAULT_ESP_RADIO_MODE; - break; + res = DEFAULT_ESP_RADIO_MODE; + break; case ESP_VERBOSE_BOOT: - res = DEFAULT_VERBOSE_BOOT; - break; + res = DEFAULT_VERBOSE_BOOT; + break; case ESP_SETUP: - res = DEFAULT_SETUP; - break; + res = DEFAULT_SETUP; + break; #ifdef AUTHENTICATION_FEATURE case ESP_SESSION_TIMEOUT: - res = DEFAULT_SESSION_TIMEOUT; - break; -#endif //AUTHENTICATION_FEATURE + res = DEFAULT_SESSION_TIMEOUT; + break; +#endif // AUTHENTICATION_FEATURE #ifdef TIMESTAMP_FEATURE case ESP_INTERNET_TIME: - res = DEFAULT_INTERNET_TIME; - break; -#endif //TIMESTAMP_FEATURE + res = DEFAULT_INTERNET_TIME; + break; +#endif // TIMESTAMP_FEATURE #ifdef BUZZER_DEVICE case ESP_BUZZER: - res = DEFAULT_BUZZER_STATE; - break; -#endif //BUZZER_DEVICE + res = DEFAULT_BUZZER_STATE; + break; +#endif // BUZZER_DEVICE #ifdef NOTIFICATION_FEATURE case ESP_NOTIFICATION_TYPE: - res = DEFAULT_NOTIFICATION_TYPE; - break; + res = DEFAULT_NOTIFICATION_TYPE; + break; case ESP_AUTO_NOTIFICATION: - res = DEFAULT_AUTO_NOTIFICATION_STATE; - break; -#endif //NOTIFICATION_FEATURE -#if defined (WIFI_FEATURE) || defined (ETH_FEATURE) + res = DEFAULT_AUTO_NOTIFICATION_STATE; + break; +#endif // NOTIFICATION_FEATURE +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) case ESP_STA_IP_MODE: - res = DEFAULT_STA_IP_MODE; - break; -#endif //WIFI_FEATURE || ETH_FEATURE -#if defined (WIFI_FEATURE) + res = DEFAULT_STA_IP_MODE; + break; +#endif // WIFI_FEATURE || ETH_FEATURE +#if defined(WIFI_FEATURE) case ESP_AP_CHANNEL: - res = DEFAULT_AP_CHANNEL; - break; -#endif //WIFI_FEATURE + res = DEFAULT_AP_CHANNEL; + break; +#endif // WIFI_FEATURE case ESP_SERIAL_FLAG: - res = DEFAULT_SERIAL_OUTPUT_FLAG; - break; + res = DEFAULT_SERIAL_OUTPUT_FLAG; + break; case ESP_REMOTE_SCREEN_FLAG: - res = DEFAULT_REMOTE_SCREEN_FLAG; - break; + res = DEFAULT_REMOTE_SCREEN_FLAG; + break; case ESP_WEBSOCKET_FLAG: - res = DEFAULT_WEBSOCKET_FLAG; - break; + res = DEFAULT_WEBSOCKET_FLAG; + break; case ESP_TELNET_FLAG: - res = DEFAULT_TELNET_FLAG; - break; + res = DEFAULT_TELNET_FLAG; + break; case ESP_BT_FLAG: - res = DEFAULT_BT_FLAG; - break; + res = DEFAULT_BT_FLAG; + break; #if defined(ESP_SERIAL_BRIDGE_OUTPUT) case ESP_SERIAL_BRIDGE_FLAG: - res = DEFAULT_SERIAL_BRIDGE_FLAG; - break; + res = DEFAULT_SERIAL_BRIDGE_FLAG; + break; case ESP_SERIAL_BRIDGE_ON: - res = DEFAULT_SERIAL_BRIDGE_ON; - break; -#endif //defined() + res = DEFAULT_SERIAL_BRIDGE_ON; + break; +#endif // defined() case ESP_SCREEN_FLAG: - res = DEFAULT_SCREEN_FLAG; - break; + res = DEFAULT_SCREEN_FLAG; + break; #ifdef FTP_FEATURE case ESP_FTP_ON: - res = DEFAULT_FTP_ON; - break; -#endif //FTP_FEATURE + res = DEFAULT_FTP_ON; + break; +#endif // FTP_FEATURE #ifdef HTTP_FEATURE case ESP_HTTP_ON: - res = DEFAULT_HTTP_ON; - break; -#endif //HTTP_FEATURE + res = DEFAULT_HTTP_ON; + break; +#endif // HTTP_FEATURE #ifdef TELNET_FEATURE case ESP_TELNET_ON: - res = DEFAULT_TELNET_ON; - break; -#endif //TELNET_FEATURE + res = DEFAULT_TELNET_ON; + break; +#endif // TELNET_FEATURE #ifdef WS_DATA_FEATURE case ESP_WEBSOCKET_ON: - res = DEFAULT_WEBSOCKET_ON; - break; -#endif //WS_DATA_FEATURE + res = DEFAULT_WEBSOCKET_ON; + break; +#endif // WS_DATA_FEATURE #ifdef WEBDAV_FEATURE case ESP_WEBDAV_ON: - res = DEFAULT_WEBDAV_ON; - break; -#endif //WEBDAV_FEATURE + res = DEFAULT_WEBDAV_ON; + break; +#endif // WEBDAV_FEATURE #ifdef SD_DEVICE case ESP_SD_SPEED_DIV: - res = DEFAULT_SDREADER_SPEED; - break; + res = DEFAULT_SDREADER_SPEED; + break; case ESP_SD_MOUNT: - res = DEFAULT_SD_MOUNT; - break; + res = DEFAULT_SD_MOUNT; + break; case ESP_SD_CHECK_UPDATE_AT_BOOT: - res = DEFAULT_SD_CHECK_UPDATE_AT_BOOT; - break; -#endif //SD_DEVICE + res = DEFAULT_SD_CHECK_UPDATE_AT_BOOT; + break; +#endif // SD_DEVICE case ESP_TARGET_FW: - res = DEFAULT_FW; - break; + res = DEFAULT_FW; + break; #ifdef TIMESTAMP_FEATURE case ESP_TIMEZONE: - res = DEFAULT_TIME_ZONE; - break; + res = DEFAULT_TIME_ZONE; + break; case ESP_TIME_IS_DST: - res = DEFAULT_TIME_DST; - break; -#endif //TIMESTAMP_FEATURE + res = DEFAULT_TIME_DST; + break; +#endif // TIMESTAMP_FEATURE #if defined(SENSOR_DEVICE) case ESP_SENSOR_TYPE: - res = DEFAULT_SENSOR_TYPE; - break; -#endif //SENSOR_DEVICE + res = DEFAULT_SENSOR_TYPE; + break; +#endif // SENSOR_DEVICE #if defined(DISPLAY_DEVICE) && defined(DISPLAY_TOUCH_DRIVER) case ESP_CALIBRATION: - res = DEFAULT_CALIBRATION_DONE; - break; -#endif // DISPLAY_DEVICE && DISPLAY_TOUCH_DRIVER + res = DEFAULT_CALIBRATION_DONE; + break; +#endif // DISPLAY_DEVICE && DISPLAY_TOUCH_DRIVER default: - res = DEFAULT_ESP_BYTE; - } - return res; + res = DEFAULT_ESP_BYTE; + } + return res; } -//Default value for a int32 setting -uint32_t Settings_ESP3D::get_default_int32_value(int pos) -{ - uint32_t res; - switch(pos) { +// Default value for a int32 setting +uint32_t Settings_ESP3D::get_default_int32_value(int pos) { + uint32_t res; + switch (pos) { case ESP_BAUD_RATE: - res = DEFAULT_BAUD_RATE; - break; + res = DEFAULT_BAUD_RATE; + break; case ESP_SERIAL_BRIDGE_BAUD: #if defined(ESP_SERIAL_BRIDGE_OUTPUT) - res = DEFAULT_SERIAL_BRIDGE_BAUD_RATE; - break; -#endif //ESP_SERIAL_BRIDGE_OUT;UT + res = DEFAULT_SERIAL_BRIDGE_BAUD_RATE; + break; +#endif // ESP_SERIAL_BRIDGE_OUT;UT case ESP_BOOT_DELAY: - res = DEFAULT_BOOT_DELAY; - break; + res = DEFAULT_BOOT_DELAY; + break; #if defined(DISPLAY_DEVICE) && defined(DISPLAY_TOUCH_DRIVER) case ESP_CALIBRATION_1: case ESP_CALIBRATION_2: case ESP_CALIBRATION_3: case ESP_CALIBRATION_4: case ESP_CALIBRATION_5: - res = DEFAULT_CALIBRATION_VALUE; - break; -#endif // DISPLAY_DEVICE && DISPLAY_TOUCH_DRIVER -#if defined (WIFI_FEATURE) || defined (ETH_FEATURE) + res = DEFAULT_CALIBRATION_VALUE; + break; +#endif // DISPLAY_DEVICE && DISPLAY_TOUCH_DRIVER +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) case ESP_AP_IP_VALUE: case ESP_STA_IP_VALUE: - res = IPAddress(DEFAULT_IP_VALUE); - break; + res = IPAddress(DEFAULT_IP_VALUE); + break; case ESP_STA_MASK_VALUE: - res = IPAddress(DEFAULT_MASK_VALUE); - break; + res = IPAddress(DEFAULT_MASK_VALUE); + break; case ESP_STA_GATEWAY_VALUE: - res = IPAddress(DEFAULT_GATEWAY_VALUE); - break; + res = IPAddress(DEFAULT_GATEWAY_VALUE); + break; case ESP_STA_DNS_VALUE: - res = IPAddress(DEFAULT_DNS_VALUE); - break; -#endif //WIFI_FEATURE || ETH_FEATURE + res = IPAddress(DEFAULT_DNS_VALUE); + break; +#endif // WIFI_FEATURE || ETH_FEATURE #ifdef FTP_FEATURE case ESP_FTP_CTRL_PORT: - res = DEFAULT_FTP_CTRL_PORT; - break; + res = DEFAULT_FTP_CTRL_PORT; + break; case ESP_FTP_DATA_ACTIVE_PORT: - res = DEFAULT_FTP_ACTIVE_PORT; - break; + res = DEFAULT_FTP_ACTIVE_PORT; + break; case ESP_FTP_DATA_PASSIVE_PORT: - res = DEFAULT_FTP_PASSIVE_PORT; - break; -#endif //FTP_FEATURE + res = DEFAULT_FTP_PASSIVE_PORT; + break; +#endif // FTP_FEATURE #ifdef HTTP_FEATURE case ESP_HTTP_PORT: - res = DEFAULT_HTTP_PORT; - break; -#endif //HTTP_FEATURE + res = DEFAULT_HTTP_PORT; + break; +#endif // HTTP_FEATURE #ifdef TELNET_FEATURE case ESP_TELNET_PORT: - res = DEFAULT_TELNET_PORT; - break; -#endif //TELNET_FEATURE + res = DEFAULT_TELNET_PORT; + break; +#endif // TELNET_FEATURE #ifdef WS_DATA_FEATURE case ESP_WEBSOCKET_PORT: - res = DEFAULT_WEBSOCKET_PORT; - break; -#endif //WS_DATA_FEATURE + res = DEFAULT_WEBSOCKET_PORT; + break; +#endif // WS_DATA_FEATURE #ifdef WEBDAV_FEATURE case ESP_WEBDAV_PORT: - res = DEFAULT_WEBDAV_PORT; - break; -#endif //WEBDAV_FEATURE + res = DEFAULT_WEBDAV_PORT; + break; +#endif // WEBDAV_FEATURE #if defined(SENSOR_DEVICE) case ESP_SENSOR_INTERVAL: - res = DEFAULT_SENSOR_INTERVAL; - break; -#endif //SENSOR_DEVICE + res = DEFAULT_SENSOR_INTERVAL; + break; +#endif // SENSOR_DEVICE default: - res = DEFAULT_ESP_INT; - } - return res; + res = DEFAULT_ESP_INT; + } + return res; } -//Max value for a int32 setting -uint32_t Settings_ESP3D::get_max_int32_value(int pos) -{ - uint32_t res; - switch(pos) { +// Max value for a int32 setting +uint32_t Settings_ESP3D::get_max_int32_value(int pos) { + uint32_t res; + switch (pos) { case ESP_BOOT_DELAY: - res = MAX_BOOT_DELAY; - break; + res = MAX_BOOT_DELAY; + break; #ifdef FTP_FEATURE case ESP_FTP_CTRL_PORT: case ESP_FTP_DATA_ACTIVE_PORT: case ESP_FTP_DATA_PASSIVE_PORT: - res = MAX_FTP_PORT; - break; -#endif //FTP_FEATURE + res = MAX_FTP_PORT; + break; +#endif // FTP_FEATURE #ifdef HTTP_FEATURE case ESP_HTTP_PORT: - res = MAX_HTTP_PORT; - break; -#endif //HTTP_FEATURE + res = MAX_HTTP_PORT; + break; +#endif // HTTP_FEATURE #ifdef TELNET_FEATURE case ESP_TELNET_PORT: - res = MAX_TELNET_PORT; - break; -#endif //TELNET_FEATURE + res = MAX_TELNET_PORT; + break; +#endif // TELNET_FEATURE #ifdef WEBDAV_FEATURE case ESP_WEBDAV_PORT: - res = MAX_WEBDAV_PORT; - break; -#endif //WEBDAV_FEATURE + res = MAX_WEBDAV_PORT; + break; +#endif // WEBDAV_FEATURE #ifdef WS_DATA_FEATURE case ESP_WEBSOCKET_PORT: - res = MAX_WEBSOCKET_PORT; - break; -#endif //WS_DATA_FEATURE + res = MAX_WEBSOCKET_PORT; + break; +#endif // WS_DATA_FEATURE #if defined(SENSOR_DEVICE) case ESP_SENSOR_INTERVAL: - res = MAX_SENSOR_INTERVAL; - break; -#endif //SENSOR_DEVICE + res = MAX_SENSOR_INTERVAL; + break; +#endif // SENSOR_DEVICE default: - res = DEFAULT_ESP_INT; - } - return res; + res = DEFAULT_ESP_INT; + } + return res; } -//Min value for a int32 setting -uint32_t Settings_ESP3D::get_min_int32_value(int pos) -{ - uint32_t res; - switch(pos) { +// Min value for a int32 setting +uint32_t Settings_ESP3D::get_min_int32_value(int pos) { + uint32_t res; + switch (pos) { case ESP_BOOT_DELAY: - res = MIN_BOOT_DELAY; - break; + res = MIN_BOOT_DELAY; + break; #ifdef FTP_FEATURE case ESP_FTP_CTRL_PORT: case ESP_FTP_DATA_ACTIVE_PORT: case ESP_FTP_DATA_PASSIVE_PORT: - res =MIN_FTP_PORT; - break; -#endif //FTP_FEATURE + res = MIN_FTP_PORT; + break; +#endif // FTP_FEATURE #ifdef HTTP_FEATURE case ESP_HTTP_PORT: - res = MIN_HTTP_PORT; - break; -#endif //HTTP_FEATURE + res = MIN_HTTP_PORT; + break; +#endif // HTTP_FEATURE #ifdef TELNET_FEATURE case ESP_TELNET_PORT: - res = MIN_TELNET_PORT; - break; -#endif //TELNET_FEATURE + res = MIN_TELNET_PORT; + break; +#endif // TELNET_FEATURE #ifdef WS_DATA_FEATURE case ESP_WEBSOCKET_PORT: - res = MIN_WEBSOCKET_PORT; - break; -#endif //WS_DATA_FEATURE + res = MIN_WEBSOCKET_PORT; + break; +#endif // WS_DATA_FEATURE #ifdef WEBDAV_FEATURE case ESP_WEBDAV_PORT: - res = MIN_WEBDAV_PORT; - break; -#endif //WEBDAV_FEATURE + res = MIN_WEBDAV_PORT; + break; +#endif // WEBDAV_FEATURE #if defined(SENSOR_DEVICE) case ESP_SENSOR_INTERVAL: - res = MIN_SENSOR_INTERVAL; - break; -#endif //SENSOR_DEVICE + res = MIN_SENSOR_INTERVAL; + break; +#endif // SENSOR_DEVICE default: - res = DEFAULT_ESP_INT; - } - return res; + res = DEFAULT_ESP_INT; + } + return res; } -uint8_t Settings_ESP3D::get_max_byte(int pos) -{ - uint8_t res; - switch(pos) { -#if defined (WIFI_FEATURE) +uint8_t Settings_ESP3D::get_max_byte(int pos) { + uint8_t res; + switch (pos) { +#if defined(WIFI_FEATURE) case ESP_AP_CHANNEL: - res = MAX_CHANNEL; - break; -#endif //WIFI_FEATURE + res = MAX_CHANNEL; + break; +#endif // WIFI_FEATURE #ifdef TIMESTAMP_FEATURE case ESP_TIMEZONE: - res= 12; - break; -#endif //TIMESTAMP_FEATURE + res = 12; + break; +#endif // TIMESTAMP_FEATURE default: - res = 255; - } - return res; + res = 255; + } + return res; } -int8_t Settings_ESP3D::get_min_byte(int pos) -{ - uint8_t res; - switch(pos) { -#if defined (WIFI_FEATURE) +int8_t Settings_ESP3D::get_min_byte(int pos) { + uint8_t res; + switch (pos) { +#if defined(WIFI_FEATURE) case ESP_AP_CHANNEL: - res = MIN_CHANNEL; - break; -#endif //WIFI_FEATURE + res = MIN_CHANNEL; + break; +#endif // WIFI_FEATURE #ifdef TIMESTAMP_FEATURE case ESP_TIMEZONE: - res= -12; - break; -#endif //TIMESTAMP_FEATURE + res = -12; + break; +#endif // TIMESTAMP_FEATURE default: - res = 0; - } - return res; + res = 0; + } + return res; } -//Default value for a ip setting -uint32_t Settings_ESP3D::get_default_IP_value(int pos) -{ - return get_default_int32_value(pos); +// Default value for a ip setting +uint32_t Settings_ESP3D::get_default_IP_value(int pos) { + return get_default_int32_value(pos); } -//Default value for a byte setting -const String & Settings_ESP3D::get_default_string_value(int pos) -{ - static String res; - switch(pos) { -#if defined (WIFI_FEATURE) || defined (ETH_FEATURE) || defined (BLUETOOTH_FEATURE) +// Default value for a byte setting +const String &Settings_ESP3D::get_default_string_value(int pos) { + static String res; + switch (pos) { +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BLUETOOTH_FEATURE) case ESP_HOSTNAME: - res = DEFAULT_HOSTNAME; - break; -#endif //WIFI_FEATURE || ETH_FEATURE || defined (ETH_FEATURE) + res = DEFAULT_HOSTNAME; + break; +#endif // WIFI_FEATURE || ETH_FEATURE || defined (ETH_FEATURE) #ifdef TIMESTAMP_FEATURE case ESP_TIME_SERVER1: - res = DEFAULT_TIME_SERVER1; - break; + res = DEFAULT_TIME_SERVER1; + break; case ESP_TIME_SERVER2: - res = DEFAULT_TIME_SERVER2; - break; + res = DEFAULT_TIME_SERVER2; + break; case ESP_TIME_SERVER3: - res = DEFAULT_TIME_SERVER3; - break; -#endif //TIMESTAMP_FEATURE + res = DEFAULT_TIME_SERVER3; + break; +#endif // TIMESTAMP_FEATURE #ifdef NOTIFICATION_FEATURE case ESP_NOTIFICATION_TOKEN1: - res = DEFAULT_NOTIFICATION_TOKEN1; - break; + res = DEFAULT_NOTIFICATION_TOKEN1; + break; case ESP_NOTIFICATION_TOKEN2: - res = DEFAULT_NOTIFICATION_TOKEN2; - break; + res = DEFAULT_NOTIFICATION_TOKEN2; + break; case ESP_NOTIFICATION_SETTINGS: - res = DEFAULT_NOTIFICATION_SETTINGS; - break; -#endif //NOTIFICATION_FEATURE -#if defined (WIFI_FEATURE) + res = DEFAULT_NOTIFICATION_SETTINGS; + break; +#endif // NOTIFICATION_FEATURE +#if defined(WIFI_FEATURE) case ESP_STA_SSID: - res = DEFAULT_STA_SSID; - break; + res = DEFAULT_STA_SSID; + break; case ESP_AP_SSID: - res = DEFAULT_AP_SSID; - break; + res = DEFAULT_AP_SSID; + break; case ESP_STA_PASSWORD: - res = DEFAULT_STA_PASSWORD; - break; + res = DEFAULT_STA_PASSWORD; + break; case ESP_AP_PASSWORD: - res = DEFAULT_AP_PASSWORD; - break; -#endif //WIFI_FEATURE + res = DEFAULT_AP_PASSWORD; + break; +#endif // WIFI_FEATURE #ifdef AUTHENTICATION_FEATURE case ESP_ADMIN_PWD: - res = DEFAULT_ADMIN_PWD; - break; + res = DEFAULT_ADMIN_PWD; + break; case ESP_USER_PWD: - res = DEFAULT_USER_PWD; - break; -#endif //AUTHENTICATION_FEATURE + res = DEFAULT_USER_PWD; + break; +#endif // AUTHENTICATION_FEATURE case ESP_SETTINGS_VERSION: - res = DEFAULT_SETTINGS_VERSION; - break; + res = DEFAULT_SETTINGS_VERSION; + break; default: - res = DEFAULT_ESP_STRING; - } - return res; + res = DEFAULT_ESP_STRING; + } + return res; } -//Max size of for a string setting -uint8_t Settings_ESP3D::get_max_string_size(int pos) -{ - uint8_t res; - switch(pos) { -#if defined (WIFI_FEATURE) || defined (ETH_FEATURE) || defined (BLUETOOTH_FEATURE) +// Max size of for a string setting +uint8_t Settings_ESP3D::get_max_string_size(int pos) { + uint8_t res; + switch (pos) { +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BLUETOOTH_FEATURE) case ESP_HOSTNAME: - res = MAX_HOSTNAME_LENGTH; - break; -#endif //WIFI_FEATURE || ETH_FEATURE || BLUETOOTH_FEATURE + res = MAX_HOSTNAME_LENGTH; + break; +#endif // WIFI_FEATURE || ETH_FEATURE || BLUETOOTH_FEATURE #ifdef TIMESTAMP_FEATURE case ESP_TIME_SERVER1: case ESP_TIME_SERVER2: case ESP_TIME_SERVER3: - res = MAX_SERVER_ADDRESS_LENGTH; - break; -#endif //TIMESTAMP_FEATURE + res = MAX_SERVER_ADDRESS_LENGTH; + break; +#endif // TIMESTAMP_FEATURE #ifdef NOTIFICATION_FEATURE case ESP_NOTIFICATION_TOKEN1: case ESP_NOTIFICATION_TOKEN2: - res = MAX_NOTIFICATION_TOKEN_LENGTH; - break; + res = MAX_NOTIFICATION_TOKEN_LENGTH; + break; case ESP_NOTIFICATION_SETTINGS: - res = MAX_NOTIFICATION_SETTINGS_LENGTH; - break; -#endif //NOTIFICATION_FEATURE -#if defined (WIFI_FEATURE) + res = MAX_NOTIFICATION_SETTINGS_LENGTH; + break; +#endif // NOTIFICATION_FEATURE +#if defined(WIFI_FEATURE) case ESP_STA_SSID: case ESP_AP_SSID: - res = MAX_SSID_LENGTH; - break; + res = MAX_SSID_LENGTH; + break; case ESP_STA_PASSWORD: case ESP_AP_PASSWORD: - res = MAX_PASSWORD_LENGTH; - break; -#endif //WIFI_FEATURE + res = MAX_PASSWORD_LENGTH; + break; +#endif // WIFI_FEATURE #ifdef AUTHENTICATION_FEATURE case ESP_ADMIN_PWD: case ESP_USER_PWD: - res = MAX_LOCAL_PASSWORD_LENGTH; - break; -#endif //AUTHENTICATION_FEATURE + res = MAX_LOCAL_PASSWORD_LENGTH; + break; +#endif // AUTHENTICATION_FEATURE case ESP_SETTINGS_VERSION: - res = MAX_VERSION_LENGTH; - break; + res = MAX_VERSION_LENGTH; + break; default: - res = DEFAULT_ESP_STRING_SIZE; - } - return res; + res = DEFAULT_ESP_STRING_SIZE; + } + return res; } -//Min size of for a string setting -uint8_t Settings_ESP3D::get_min_string_size(int pos) -{ - uint8_t res; - switch(pos) { -#if defined (WIFI_FEATURE) || defined (ETH_FEATURE) || defined (BLUETOOTH_FEATURE) +// Min size of for a string setting +uint8_t Settings_ESP3D::get_min_string_size(int pos) { + uint8_t res; + switch (pos) { +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BLUETOOTH_FEATURE) case ESP_HOSTNAME: - res = MIN_HOSTNAME_LENGTH; - break; -#endif //WIFI_FEATURE || ETH_FEATURE || BLUETOOTH_FEATURE + res = MIN_HOSTNAME_LENGTH; + break; +#endif // WIFI_FEATURE || ETH_FEATURE || BLUETOOTH_FEATURE #ifdef NOTIFICATION_FEATURE case ESP_NOTIFICATION_TOKEN1: case ESP_NOTIFICATION_TOKEN2: - res = MIN_NOTIFICATION_TOKEN_LENGTH; - break; + res = MIN_NOTIFICATION_TOKEN_LENGTH; + break; case ESP_NOTIFICATION_SETTINGS: - res = MIN_NOTIFICATION_SETTINGS_LENGTH; - break; -#endif //NOTIFICATION_FEATURE + res = MIN_NOTIFICATION_SETTINGS_LENGTH; + break; +#endif // NOTIFICATION_FEATURE #ifdef TIMESTAMP_FEATURE case ESP_TIME_SERVER1: case ESP_TIME_SERVER2: case ESP_TIME_SERVER3: - res = MIN_SERVER_ADDRESS_LENGTH; - break; -#endif //TIMESTAMP_FEATURE -#if defined (WIFI_FEATURE) + res = MIN_SERVER_ADDRESS_LENGTH; + break; +#endif // TIMESTAMP_FEATURE +#if defined(WIFI_FEATURE) case ESP_STA_SSID: case ESP_AP_SSID: - res = MIN_SSID_LENGTH; - break; + res = MIN_SSID_LENGTH; + break; case ESP_STA_PASSWORD: case ESP_AP_PASSWORD: - res = MIN_PASSWORD_LENGTH; - break; -#endif //WIFI_FEATURE + res = MIN_PASSWORD_LENGTH; + break; +#endif // WIFI_FEATURE #ifdef AUTHENTICATION_FEATURE case ESP_ADMIN_PWD: case ESP_USER_PWD: - res = MIN_LOCAL_PASSWORD_LENGTH; - break; -#endif //AUTHENTICATION_FEATURE + res = MIN_LOCAL_PASSWORD_LENGTH; + break; +#endif // AUTHENTICATION_FEATURE default: - res = DEFAULT_ESP_STRING_SIZE; - } - return res; + res = DEFAULT_ESP_STRING_SIZE; + } + return res; } -uint8_t Settings_ESP3D::read_byte (int pos, bool * haserror) -{ - if(haserror) { - *haserror = true; - } - uint8_t value = get_default_byte_value(pos); +uint8_t Settings_ESP3D::read_byte(int pos, bool *haserror) { + if (haserror) { + *haserror = true; + } + uint8_t value = get_default_byte_value(pos); #if ESP_SAVE_SETTINGS == SETTINGS_IN_EEPROM -//check if parameters are acceptable - if ((pos + 1 > EEPROM_SIZE) ) { - log_esp3d("Error read byte %d", pos); - return value; - } -//read byte - EEPROM.begin (EEPROM_SIZE); - value = EEPROM.read (pos); - EEPROM.end(); -#endif //SETTINGS_IN_EEPROM -#if ESP_SAVE_SETTINGS == SETTINGS_IN_PREFERENCES - Preferences prefs; - if (!prefs.begin(NAMESPACE, true)) { - log_esp3d("Error opening %s", NAMESPACE); - return value; - } - String p = "P_" + String(pos); - if (prefs.isKey(p.c_str())) { - value = prefs.getChar(p.c_str(), get_default_byte_value(pos)); - } else { - value = get_default_byte_value(pos); - } - prefs.end(); -#endif //SETTINGS_IN_PREFERENCES - if(haserror) { - *haserror = false; - } + // check if parameters are acceptable + if ((pos + 1 > EEPROM_SIZE)) { + log_esp3d_e("Error read byte %d", pos); return value; -} - -//write a flag / byte -bool Settings_ESP3D::write_byte (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("Error read byte %d", pos); - return false; - } - EEPROM.begin (EEPROM_SIZE); - EEPROM.write (pos, value); - if (!EEPROM.commit()) { - log_esp3d("Error commit %d", pos); - return false; - } - EEPROM.end(); -#endif //SETTINGS_IN_EEPROM + } + // read byte + EEPROM.begin(EEPROM_SIZE); + value = EEPROM.read(pos); + EEPROM.end(); +#endif // SETTINGS_IN_EEPROM #if ESP_SAVE_SETTINGS == SETTINGS_IN_PREFERENCES - Preferences prefs; - if (!prefs.begin(NAMESPACE, false)) { - log_esp3d("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("Error commit %s", p.c_str()); - return false; - } -#endif //SETTINGS_IN_PREFERENCES - return true; + Preferences prefs; + if (!prefs.begin(NAMESPACE, true)) { + log_esp3d_e("Error opening %s", NAMESPACE); + return value; + } + String p = "P_" + String(pos); + if (prefs.isKey(p.c_str())) { + value = prefs.getChar(p.c_str(), get_default_byte_value(pos)); + } else { + value = get_default_byte_value(pos); + } + prefs.end(); +#endif // SETTINGS_IN_PREFERENCES + if (haserror) { + *haserror = false; + } + return value; } -bool Settings_ESP3D::is_string(const char * s, uint len) -{ - for (uint p = 0; p < len; p++) { - if (!isPrintable (char(s[p]))) { - return false; - } - } - return true; -} - -//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) -{ - uint8_t size_max = get_max_string_size(pos); - if (haserror) { - *haserror = true; - } - if (size_max == 0) { - log_esp3d("Error size string %d", pos); - return DEFAULT_ESP_STRING; - } +// write a flag / byte +bool Settings_ESP3D::write_byte(int pos, const uint8_t value) { #if ESP_SAVE_SETTINGS == SETTINGS_IN_EEPROM - static char * byte_buffer = NULL; - size_max++;//do not forget the 0x0 for the end - if (byte_buffer) { - free (byte_buffer); - byte_buffer = NULL; - } - //check if parameters are acceptable - if (pos + size_max + 1 > EEPROM_SIZE) { - log_esp3d("Error read string %d", pos); - return DEFAULT_ESP_STRING; - } - byte_buffer = (char *)malloc(size_max+1); - if (!byte_buffer) { - log_esp3d("Error mem read string %d", pos); - return DEFAULT_ESP_STRING; - } - EEPROM.begin (EEPROM_SIZE); - byte b = 1; // non zero for the while loop below - int i = 0; - - //read until max size is reached or \0 is found - while (i < size_max && b != 0) { - b = EEPROM.read (pos + i); - byte_buffer[i] = isPrintable (char(b))?b:0; - i++; - } - - // Be sure there is a 0 at the end. - if (b != 0) { - byte_buffer[i - 1] = 0x00; - } - EEPROM.end(); - - if (haserror) { - *haserror = false; - } - return byte_buffer; - -#endif //SETTINGS_IN_EEPROM + // check if parameters are acceptable + if (pos + 1 > EEPROM_SIZE) { + log_esp3d_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); + return false; + } + EEPROM.end(); +#endif // SETTINGS_IN_EEPROM #if ESP_SAVE_SETTINGS == SETTINGS_IN_PREFERENCES - Preferences prefs; - static String res; - - if (!prefs.begin(NAMESPACE, true)) { - log_esp3d("Error opening %s", NAMESPACE); - return ""; - } - String p = "P_" + String(pos); - if (prefs.isKey(p.c_str())) { - res = prefs.getString(p.c_str(), get_default_string_value(pos)); - } else { - res = get_default_string_value(pos); - } - prefs.end(); - - if (res.length() > size_max) { - log_esp3d("String too long %d vs %d", res.length(), size_max); - res = res.substring(0,size_max-1); - } - - if (haserror) { - *haserror = false; - } - return res.c_str(); - -#endif //SETTINGS_IN_PREFERENCES + Preferences prefs; + if (!prefs.begin(NAMESPACE, false)) { + log_esp3d_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()); + return false; + } +#endif // SETTINGS_IN_PREFERENCES + return true; } -//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); - uint8_t size_max = get_max_string_size(pos); - //check if parameters are acceptable - if (size_max == 0) { - log_esp3d("Error unknow entry %d", pos); - return false; +bool Settings_ESP3D::is_string(const char *s, uint len) { + for (uint p = 0; p < len; p++) { + if (!isPrintable(char(s[p]))) { + return false; } - if (size_max < size_buffer) { - log_esp3d("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("Error write string %d", pos); - return false; - } - //copy the value(s) - EEPROM.begin (EEPROM_SIZE); - for (int 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("Error commit %d", pos); - return false; - } - EEPROM.end(); -#endif //SETTINGS_IN_EEPROM -#if ESP_SAVE_SETTINGS == SETTINGS_IN_PREFERENCES - Preferences prefs; - if (!prefs.begin(NAMESPACE, false)) { - log_esp3d("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("Error commit %s", p.c_str()); - return false; - } -#endif //SETTINGS_IN_PREFERENCES - return true; + } + return true; } -//read a uint32 -uint32_t Settings_ESP3D::read_uint32(int pos, bool * haserror) -{ - if (haserror) { - *haserror = true; - } - uint32_t res = get_default_int32_value(pos); +// 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) { + uint8_t size_max = get_max_string_size(pos); + if (haserror) { + *haserror = true; + } + if (size_max == 0) { + log_esp3d_e("Error size string %d", pos); + return DEFAULT_ESP_STRING; + } #if ESP_SAVE_SETTINGS == SETTINGS_IN_EEPROM - //check if parameters are acceptable - uint8_t size_buffer = sizeof(uint32_t); - if ( pos + size_buffer > EEPROM_SIZE ) { - log_esp3d("Error read int %d", pos); - return res; - } - uint8_t i = 0; - EEPROM.begin (EEPROM_SIZE); - //read until max size is reached - while (i < size_buffer ) { - ((uint8_t *)(&res))[i] = EEPROM.read (pos + i); - i++; - } - EEPROM.end(); -#endif //SETTINGS_IN_EEPROM + static char *byte_buffer = NULL; + size_max++; // do not forget the 0x0 for the end + if (byte_buffer) { + free(byte_buffer); + byte_buffer = NULL; + } + // check if parameters are acceptable + if (pos + size_max + 1 > EEPROM_SIZE) { + log_esp3d_e("Error read string %d", pos); + return DEFAULT_ESP_STRING; + } + byte_buffer = (char *)malloc(size_max + 1); + if (!byte_buffer) { + log_esp3d_e("Error mem read string %d", pos); + return DEFAULT_ESP_STRING; + } + EEPROM.begin(EEPROM_SIZE); + byte b = 1; // non zero for the while loop below + int i = 0; + + // read until max size is reached or \0 is found + while (i < size_max && b != 0) { + b = EEPROM.read(pos + i); + byte_buffer[i] = isPrintable(char(b)) ? b : 0; + i++; + } + + // Be sure there is a 0 at the end. + if (b != 0) { + byte_buffer[i - 1] = 0x00; + } + EEPROM.end(); + + if (haserror) { + *haserror = false; + } + return byte_buffer; + +#endif // SETTINGS_IN_EEPROM #if ESP_SAVE_SETTINGS == SETTINGS_IN_PREFERENCES - Preferences prefs; - if (!prefs.begin(NAMESPACE, true)) { - log_esp3d("Error opening %s", NAMESPACE); - return res; - } - String p = "P_" + String(pos); - if (prefs.isKey(p.c_str())) { - res = prefs.getUInt(p.c_str(), res); - } else { - res = get_default_int32_value(pos); - } - prefs.end(); -#endif //SETTINGS_IN_PREFERENCES - if (haserror) { - *haserror = false; - } + Preferences prefs; + static String res; + + if (!prefs.begin(NAMESPACE, true)) { + log_esp3d_e("Error opening %s", NAMESPACE); + return ""; + } + String p = "P_" + String(pos); + if (prefs.isKey(p.c_str())) { + res = prefs.getString(p.c_str(), get_default_string_value(pos)); + } else { + res = get_default_string_value(pos); + } + prefs.end(); + + if (res.length() > size_max) { + log_esp3d_e("String too long %d vs %d", res.length(), size_max); + res = res.substring(0, size_max - 1); + } + + if (haserror) { + *haserror = false; + } + return res.c_str(); + +#endif // SETTINGS_IN_PREFERENCES +} + +// 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); + uint8_t size_max = get_max_string_size(pos); + // check if parameters are acceptable + if (size_max == 0) { + log_esp3d_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); + 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); + return false; + } + // copy the value(s) + EEPROM.begin(EEPROM_SIZE); + for (int 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); + return false; + } + EEPROM.end(); +#endif // SETTINGS_IN_EEPROM +#if ESP_SAVE_SETTINGS == SETTINGS_IN_PREFERENCES + Preferences prefs; + if (!prefs.begin(NAMESPACE, false)) { + log_esp3d_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()); + return false; + } +#endif // SETTINGS_IN_PREFERENCES + return true; +} + +// read a uint32 +uint32_t Settings_ESP3D::read_uint32(int pos, bool *haserror) { + if (haserror) { + *haserror = true; + } + uint32_t res = get_default_int32_value(pos); +#if ESP_SAVE_SETTINGS == SETTINGS_IN_EEPROM + // 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); return res; -} - -//read an IP -uint32_t Settings_ESP3D::read_IP(int pos, bool * haserror) -{ - return read_uint32(pos,haserror); -} - -//read an IP -String Settings_ESP3D::read_IP_String(int pos, bool * haserror) -{ - return IPtoString(read_uint32(pos,haserror)); -} - -//write a uint32 -bool Settings_ESP3D::write_uint32(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("Error invalid entry %d", pos); - return false; - } - EEPROM.begin (EEPROM_SIZE); - //copy the value(s) - for (int i = 0; i < size_buffer; i++) { - EEPROM.write (pos + i, ((uint8_t *)(&value))[i]); - } - if (!EEPROM.commit()) { - log_esp3d("Error commit %d", pos); - return false; - } - EEPROM.end(); -#endif //SETTINGS_IN_EEPROM + } + uint8_t i = 0; + EEPROM.begin(EEPROM_SIZE); + // read until max size is reached + while (i < size_buffer) { + ((uint8_t *)(&res))[i] = EEPROM.read(pos + i); + i++; + } + EEPROM.end(); +#endif // SETTINGS_IN_EEPROM #if ESP_SAVE_SETTINGS == SETTINGS_IN_PREFERENCES - Preferences prefs; - if (!prefs.begin(NAMESPACE, false)) { - log_esp3d("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("Error commit %s", p.c_str()); - return false; - } -#endif //SETTINGS_IN_PREFERENCES + Preferences prefs; + if (!prefs.begin(NAMESPACE, true)) { + log_esp3d_e("Error opening %s", NAMESPACE); + return res; + } + String p = "P_" + String(pos); + if (prefs.isKey(p.c_str())) { + res = prefs.getUInt(p.c_str(), res); + } else { + res = get_default_int32_value(pos); + } + prefs.end(); +#endif // SETTINGS_IN_PREFERENCES + if (haserror) { + *haserror = false; + } + return res; +} + +// read an IP +uint32_t Settings_ESP3D::read_IP(int pos, bool *haserror) { + return read_uint32(pos, haserror); +} + +// read an IP +String Settings_ESP3D::read_IP_String(int pos, bool *haserror) { + return IPtoString(read_uint32(pos, haserror)); +} + +// write a uint32 +bool Settings_ESP3D::write_uint32(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); + return false; + } + EEPROM.begin(EEPROM_SIZE); + // copy the value(s) + for (int i = 0; i < size_buffer; i++) { + EEPROM.write(pos + i, ((uint8_t *)(&value))[i]); + } + if (!EEPROM.commit()) { + log_esp3d_e("Error commit %d", pos); + return false; + } + EEPROM.end(); +#endif // SETTINGS_IN_EEPROM +#if ESP_SAVE_SETTINGS == SETTINGS_IN_PREFERENCES + Preferences prefs; + if (!prefs.begin(NAMESPACE, false)) { + log_esp3d_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()); + 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) { + // radio mode + Settings_ESP3D::write_byte( + ESP_RADIO_MODE, Settings_ESP3D::get_default_byte_value(ESP_RADIO_MODE)); + Settings_ESP3D::write_byte( + ESP_BOOT_RADIO_STATE, + Settings_ESP3D::get_default_byte_value(ESP_BOOT_RADIO_STATE)); + Settings_ESP3D::write_byte( + ESP_STA_FALLBACK_MODE, + Settings_ESP3D::get_default_byte_value(ESP_STA_FALLBACK_MODE)); +#if defined(WIFI_FEATURE) + // STA SSID + Settings_ESP3D::write_string( + ESP_STA_SSID, + Settings_ESP3D::get_default_string_value(ESP_STA_SSID).c_str()); + // STA pwd + Settings_ESP3D::write_string( + ESP_STA_PASSWORD, + Settings_ESP3D::get_default_string_value(ESP_STA_PASSWORD).c_str()); + // AP SSID + Settings_ESP3D::write_string( + ESP_AP_SSID, + Settings_ESP3D::get_default_string_value(ESP_AP_SSID).c_str()); + // AP password + Settings_ESP3D::write_string( + ESP_AP_PASSWORD, + Settings_ESP3D::get_default_string_value(ESP_AP_PASSWORD).c_str()); + // AP static IP + Settings_ESP3D::write_IP( + ESP_AP_IP_VALUE, Settings_ESP3D::get_default_IP_value(ESP_AP_IP_VALUE)); + // AP Channel + Settings_ESP3D::write_byte( + ESP_AP_CHANNEL, Settings_ESP3D::get_default_byte_value(ESP_AP_CHANNEL)); + +#endif // WIFI_FEATURE + +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) + // STA IP mode + Settings_ESP3D::write_byte( + ESP_STA_IP_MODE, Settings_ESP3D::get_default_byte_value(ESP_STA_IP_MODE)); + // STA static IP + Settings_ESP3D::write_IP( + ESP_STA_IP_VALUE, Settings_ESP3D::get_default_IP_value(ESP_STA_IP_VALUE)); + // STA static Gateway + Settings_ESP3D::write_IP( + ESP_STA_GATEWAY_VALUE, + Settings_ESP3D::get_default_IP_value(ESP_STA_GATEWAY_VALUE)); + // STA static Mask + Settings_ESP3D::write_IP( + ESP_STA_MASK_VALUE, + Settings_ESP3D::get_default_IP_value(ESP_STA_MASK_VALUE)); + // STA static DNS + Settings_ESP3D::write_IP( + ESP_STA_DNS_VALUE, + Settings_ESP3D::get_default_IP_value(ESP_STA_DNS_VALUE)); +#endif // WIFI_FEATURE || ETH_FEATURE + if (networkonly) { 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) -{ - //radio mode - Settings_ESP3D::write_byte(ESP_RADIO_MODE,Settings_ESP3D::get_default_byte_value(ESP_RADIO_MODE)); - Settings_ESP3D::write_byte(ESP_BOOT_RADIO_STATE,Settings_ESP3D::get_default_byte_value(ESP_BOOT_RADIO_STATE)); - Settings_ESP3D::write_byte(ESP_STA_FALLBACK_MODE,Settings_ESP3D::get_default_byte_value(ESP_STA_FALLBACK_MODE)); -#if defined (WIFI_FEATURE) - //STA SSID - Settings_ESP3D::write_string(ESP_STA_SSID,Settings_ESP3D::get_default_string_value(ESP_STA_SSID).c_str()); - //STA pwd - Settings_ESP3D::write_string(ESP_STA_PASSWORD,Settings_ESP3D::get_default_string_value(ESP_STA_PASSWORD).c_str()); - //AP SSID - Settings_ESP3D::write_string(ESP_AP_SSID,Settings_ESP3D::get_default_string_value(ESP_AP_SSID).c_str()); - //AP password - Settings_ESP3D::write_string(ESP_AP_PASSWORD,Settings_ESP3D::get_default_string_value(ESP_AP_PASSWORD).c_str()); - //AP static IP - Settings_ESP3D::write_IP(ESP_AP_IP_VALUE, Settings_ESP3D::get_default_IP_value(ESP_AP_IP_VALUE)); - //AP Channel - Settings_ESP3D::write_byte(ESP_AP_CHANNEL,Settings_ESP3D::get_default_byte_value(ESP_AP_CHANNEL)); - -#endif //WIFI_FEATURE - -#if defined (WIFI_FEATURE) || defined (ETH_FEATURE) - //STA IP mode - Settings_ESP3D::write_byte(ESP_STA_IP_MODE,Settings_ESP3D::get_default_byte_value(ESP_STA_IP_MODE)); - //STA static IP - Settings_ESP3D::write_IP(ESP_STA_IP_VALUE, Settings_ESP3D::get_default_IP_value(ESP_STA_IP_VALUE)); - //STA static Gateway - Settings_ESP3D::write_IP(ESP_STA_GATEWAY_VALUE, Settings_ESP3D::get_default_IP_value(ESP_STA_GATEWAY_VALUE)); - //STA static Mask - Settings_ESP3D::write_IP(ESP_STA_MASK_VALUE, Settings_ESP3D::get_default_IP_value(ESP_STA_MASK_VALUE)); - //STA static DNS - Settings_ESP3D::write_IP(ESP_STA_DNS_VALUE, Settings_ESP3D::get_default_IP_value(ESP_STA_DNS_VALUE)); -#endif //WIFI_FEATURE || ETH_FEATURE - if (networkonly) { - return true; - } - - bool res = true; - log_esp3d("Reset Settings"); + bool res = true; + log_esp3d("Reset Settings"); #if ESP_SAVE_SETTINGS == SETTINGS_IN_PREFERENCES - log_esp3d("clear preferences"); - Preferences prefs; - if (!prefs.begin(NAMESPACE, false)) { - return false; - } - res = prefs.clear(); - prefs.end(); -#endif //SETTINGS_IN_PREFERENCES + log_esp3d("clear preferences"); + Preferences prefs; + if (!prefs.begin(NAMESPACE, false)) { + return false; + } + res = prefs.clear(); + prefs.end(); +#endif // SETTINGS_IN_PREFERENCES -//for EEPROM need to overwrite all settings +// for EEPROM need to overwrite all settings #if ESP_SAVE_SETTINGS == SETTINGS_IN_EEPROM - log_esp3d("clear EEPROM"); + log_esp3d("clear EEPROM"); - //Setup done (internal only) - Settings_ESP3D::write_byte(ESP_SETUP,Settings_ESP3D::get_default_byte_value(ESP_SETUP)); - //Verbose boot - Settings_ESP3D::write_byte(ESP_VERBOSE_BOOT,Settings_ESP3D::get_default_byte_value(ESP_VERBOSE_BOOT)); - //Secure Serial + // Setup done (internal only) + Settings_ESP3D::write_byte(ESP_SETUP, + Settings_ESP3D::get_default_byte_value(ESP_SETUP)); + // Verbose boot + Settings_ESP3D::write_byte( + ESP_VERBOSE_BOOT, + Settings_ESP3D::get_default_byte_value(ESP_VERBOSE_BOOT)); + // Secure Serial #if COMMUNICATION_PROTOCOL == RAW_SERIAL || COMMUNICATION_PROTOCOL == MKS_SERIAL - Settings_ESP3D::write_byte(ESP_SECURE_SERIAL,Settings_ESP3D::get_default_byte_value(ESP_SECURE_SERIAL)); -#endif //COMMUNICATION PROTOCOL + Settings_ESP3D::write_byte( + ESP_SECURE_SERIAL, + Settings_ESP3D::get_default_byte_value(ESP_SECURE_SERIAL)); +#endif // COMMUNICATION PROTOCOL #if defined(DISPLAY_DEVICE) && defined(DISPLAY_TOUCH_DRIVER) - //Calibration done (internal only) - Settings_ESP3D::write_byte(ESP_CALIBRATION,Settings_ESP3D::get_default_byte_value(ESP_CALIBRATION)); - //Calibration data (internal only) - Settings_ESP3D::write_uint32 (ESP_CALIBRATION_1, Settings_ESP3D::get_default_int32_value(ESP_CALIBRATION_1)); - Settings_ESP3D::write_uint32 (ESP_CALIBRATION_2, Settings_ESP3D::get_default_int32_value(ESP_CALIBRATION_2)); - Settings_ESP3D::write_uint32 (ESP_CALIBRATION_3, Settings_ESP3D::get_default_int32_value(ESP_CALIBRATION_3)); - Settings_ESP3D::write_uint32 (ESP_CALIBRATION_4, Settings_ESP3D::get_default_int32_value(ESP_CALIBRATION_4)); - Settings_ESP3D::write_uint32 (ESP_CALIBRATION_5, Settings_ESP3D::get_default_int32_value(ESP_CALIBRATION_5)); -#endif // DISPLAY_DEVICE && DISPLAY_TOUCH_DRIVER + // Calibration done (internal only) + Settings_ESP3D::write_byte( + ESP_CALIBRATION, Settings_ESP3D::get_default_byte_value(ESP_CALIBRATION)); + // Calibration data (internal only) + Settings_ESP3D::write_uint32( + ESP_CALIBRATION_1, + Settings_ESP3D::get_default_int32_value(ESP_CALIBRATION_1)); + Settings_ESP3D::write_uint32( + ESP_CALIBRATION_2, + Settings_ESP3D::get_default_int32_value(ESP_CALIBRATION_2)); + Settings_ESP3D::write_uint32( + ESP_CALIBRATION_3, + Settings_ESP3D::get_default_int32_value(ESP_CALIBRATION_3)); + Settings_ESP3D::write_uint32( + ESP_CALIBRATION_4, + Settings_ESP3D::get_default_int32_value(ESP_CALIBRATION_4)); + Settings_ESP3D::write_uint32( + ESP_CALIBRATION_5, + Settings_ESP3D::get_default_int32_value(ESP_CALIBRATION_5)); +#endif // DISPLAY_DEVICE && DISPLAY_TOUCH_DRIVER #ifdef BUZZER_DEVICE - //Buzzer state - Settings_ESP3D::write_byte(ESP_BUZZER,Settings_ESP3D::get_default_byte_value(ESP_BUZZER)); -#endif //BUZZER_DEVICE -#if defined (WIFI_FEATURE) || defined (BLUETOOTH_FEATURE) || defined (ETH_FEATURE) - //Hostname - Settings_ESP3D::write_string(ESP_HOSTNAME,Settings_ESP3D::get_default_string_value(ESP_HOSTNAME).c_str()); -#endif //WIFI_FEATURE || BLUETOOTH_FEATURE || ETH_FEATURE + // Buzzer state + Settings_ESP3D::write_byte( + ESP_BUZZER, Settings_ESP3D::get_default_byte_value(ESP_BUZZER)); +#endif // BUZZER_DEVICE +#if defined(WIFI_FEATURE) || defined(BLUETOOTH_FEATURE) || defined(ETH_FEATURE) + // Hostname + Settings_ESP3D::write_string( + ESP_HOSTNAME, + Settings_ESP3D::get_default_string_value(ESP_HOSTNAME).c_str()); +#endif // WIFI_FEATURE || BLUETOOTH_FEATURE || ETH_FEATURE #ifdef NOTIFICATION_FEATURE - //Auto Notification - Settings_ESP3D::write_byte(ESP_AUTO_NOTIFICATION,Settings_ESP3D::get_default_byte_value(ESP_AUTO_NOTIFICATION)); - //Notification Type - Settings_ESP3D::write_byte(ESP_NOTIFICATION_TYPE,Settings_ESP3D::get_default_byte_value(ESP_NOTIFICATION_TYPE)); - //Notification Token1 - Settings_ESP3D::write_string(ESP_NOTIFICATION_TOKEN1,Settings_ESP3D::get_default_string_value(ESP_NOTIFICATION_TOKEN1).c_str()); - //Notification Token2 - Settings_ESP3D::write_string(ESP_NOTIFICATION_TOKEN2,Settings_ESP3D::get_default_string_value(ESP_NOTIFICATION_TOKEN2).c_str()); - //Notification Settings - Settings_ESP3D::write_string(ESP_NOTIFICATION_SETTINGS,Settings_ESP3D::get_default_string_value(ESP_NOTIFICATION_SETTINGS).c_str()); -#endif //NOTIFICATION_FEATURE - //radio mode - Settings_ESP3D::write_byte(ESP_RADIO_MODE,Settings_ESP3D::get_default_byte_value(ESP_RADIO_MODE)); + // Auto Notification + Settings_ESP3D::write_byte( + ESP_AUTO_NOTIFICATION, + Settings_ESP3D::get_default_byte_value(ESP_AUTO_NOTIFICATION)); + // Notification Type + Settings_ESP3D::write_byte( + ESP_NOTIFICATION_TYPE, + Settings_ESP3D::get_default_byte_value(ESP_NOTIFICATION_TYPE)); + // Notification Token1 + Settings_ESP3D::write_string( + ESP_NOTIFICATION_TOKEN1, + Settings_ESP3D::get_default_string_value(ESP_NOTIFICATION_TOKEN1) + .c_str()); + // Notification Token2 + Settings_ESP3D::write_string( + ESP_NOTIFICATION_TOKEN2, + Settings_ESP3D::get_default_string_value(ESP_NOTIFICATION_TOKEN2) + .c_str()); + // Notification Settings + Settings_ESP3D::write_string( + ESP_NOTIFICATION_SETTINGS, + Settings_ESP3D::get_default_string_value(ESP_NOTIFICATION_SETTINGS) + .c_str()); +#endif // NOTIFICATION_FEATURE + // radio mode + Settings_ESP3D::write_byte( + ESP_RADIO_MODE, Settings_ESP3D::get_default_byte_value(ESP_RADIO_MODE)); #ifdef FTP_FEATURE - //FTP On - Settings_ESP3D::write_byte(ESP_FTP_ON,Settings_ESP3D::get_default_byte_value(ESP_FTP_ON)); - //FTP Ctrl Port - Settings_ESP3D::write_uint32 (ESP_FTP_CTRL_PORT, Settings_ESP3D::get_default_int32_value(ESP_FTP_CTRL_PORT)); - //FTP Active data Port - Settings_ESP3D::write_uint32 (ESP_FTP_DATA_ACTIVE_PORT, Settings_ESP3D::get_default_int32_value(ESP_FTP_DATA_ACTIVE_PORT)); - //FTP Pasive data Port - Settings_ESP3D::write_uint32 (ESP_FTP_DATA_PASSIVE_PORT, Settings_ESP3D::get_default_int32_value(ESP_FTP_DATA_PASSIVE_PORT)); -#endif //FTP_FEATURE + // FTP On + Settings_ESP3D::write_byte( + ESP_FTP_ON, Settings_ESP3D::get_default_byte_value(ESP_FTP_ON)); + // FTP Ctrl Port + Settings_ESP3D::write_uint32( + ESP_FTP_CTRL_PORT, + Settings_ESP3D::get_default_int32_value(ESP_FTP_CTRL_PORT)); + // FTP Active data Port + Settings_ESP3D::write_uint32( + ESP_FTP_DATA_ACTIVE_PORT, + Settings_ESP3D::get_default_int32_value(ESP_FTP_DATA_ACTIVE_PORT)); + // FTP Pasive data Port + Settings_ESP3D::write_uint32( + ESP_FTP_DATA_PASSIVE_PORT, + Settings_ESP3D::get_default_int32_value(ESP_FTP_DATA_PASSIVE_PORT)); +#endif // FTP_FEATURE #ifdef HTTP_FEATURE - //HTTP On - Settings_ESP3D::write_byte(ESP_HTTP_ON,Settings_ESP3D::get_default_byte_value(ESP_HTTP_ON)); - //HTTP Port - Settings_ESP3D::write_uint32 (ESP_HTTP_PORT, Settings_ESP3D::get_default_int32_value(ESP_HTTP_PORT)); -#endif //HTTP_FEATURE + // HTTP On + Settings_ESP3D::write_byte( + ESP_HTTP_ON, Settings_ESP3D::get_default_byte_value(ESP_HTTP_ON)); + // HTTP Port + Settings_ESP3D::write_uint32( + ESP_HTTP_PORT, Settings_ESP3D::get_default_int32_value(ESP_HTTP_PORT)); +#endif // HTTP_FEATURE #ifdef TELNET_FEATURE - //TELNET On - Settings_ESP3D::write_byte(ESP_TELNET_ON,Settings_ESP3D::get_default_byte_value(ESP_TELNET_ON)); - //TELNET Port - Settings_ESP3D::write_uint32 (ESP_TELNET_PORT, Settings_ESP3D::get_default_int32_value(ESP_TELNET_PORT)); -#endif //TELNET + // TELNET On + Settings_ESP3D::write_byte( + ESP_TELNET_ON, Settings_ESP3D::get_default_byte_value(ESP_TELNET_ON)); + // TELNET Port + Settings_ESP3D::write_uint32( + ESP_TELNET_PORT, + Settings_ESP3D::get_default_int32_value(ESP_TELNET_PORT)); +#endif // TELNET #ifdef WS_DATA_FEATURE - //Websocket On - Settings_ESP3D::write_byte(ESP_WEBSOCKET_ON,Settings_ESP3D::get_default_byte_value(ESP_WEBSOCKET_ON)); - //Websocket Port - Settings_ESP3D::write_uint32 (ESP_WEBSOCKET_PORT, Settings_ESP3D::get_default_int32_value(ESP_WEBSOCKET_PORT)); -#endif //WS_DATA_FEATURE + // Websocket On + Settings_ESP3D::write_byte( + ESP_WEBSOCKET_ON, + Settings_ESP3D::get_default_byte_value(ESP_WEBSOCKET_ON)); + // Websocket Port + Settings_ESP3D::write_uint32( + ESP_WEBSOCKET_PORT, + Settings_ESP3D::get_default_int32_value(ESP_WEBSOCKET_PORT)); +#endif // WS_DATA_FEATURE #ifdef WEBDAV_FEATURE - //WebDav On - Settings_ESP3D::write_byte(ESP_WEBDAV_ON,Settings_ESP3D::get_default_byte_value(ESP_WEBDAV_ON)); - //WebDav Port - Settings_ESP3D::write_uint32 (ESP_WEBDAV_PORT, Settings_ESP3D::get_default_int32_value(ESP_WEBDAV_PORT)); -#endif //WEBDAV_FEATURE + // WebDav On + Settings_ESP3D::write_byte( + ESP_WEBDAV_ON, Settings_ESP3D::get_default_byte_value(ESP_WEBDAV_ON)); + // WebDav Port + Settings_ESP3D::write_uint32( + ESP_WEBDAV_PORT, + Settings_ESP3D::get_default_int32_value(ESP_WEBDAV_PORT)); +#endif // WEBDAV_FEATURE #ifdef AUTHENTICATION_FEATURE - //Admin password - Settings_ESP3D::write_string(ESP_ADMIN_PWD,Settings_ESP3D::get_default_string_value(ESP_ADMIN_PWD).c_str()); - //User password - Settings_ESP3D::write_string(ESP_USER_PWD,Settings_ESP3D::get_default_string_value(ESP_USER_PWD).c_str()); - //Session timeout - Settings_ESP3D::write_byte(ESP_SESSION_TIMEOUT,Settings_ESP3D::get_default_byte_value(ESP_SESSION_TIMEOUT)); -#endif //AUTHENTICATION_FEATURE - //Target FW - Settings_ESP3D::write_byte(ESP_TARGET_FW,Settings_ESP3D::get_default_byte_value(ESP_TARGET_FW)); - //Output flags - Settings_ESP3D::write_byte(ESP_SERIAL_FLAG,Settings_ESP3D::get_default_byte_value(ESP_SERIAL_FLAG)); - Settings_ESP3D::write_byte(ESP_SERIAL_BRIDGE_FLAG,Settings_ESP3D::get_default_byte_value(ESP_SERIAL_BRIDGE_FLAG)); - Settings_ESP3D::write_byte(ESP_REMOTE_SCREEN_FLAG,Settings_ESP3D::get_default_byte_value(ESP_REMOTE_SCREEN_FLAG)); - Settings_ESP3D::write_byte(ESP_WEBSOCKET_FLAG,Settings_ESP3D::get_default_byte_value(ESP_WEBSOCKET_FLAG)); - Settings_ESP3D::write_byte(ESP_TELNET_FLAG,Settings_ESP3D::get_default_byte_value(ESP_TELNET_FLAG)); - Settings_ESP3D::write_byte(ESP_BT_FLAG,Settings_ESP3D::get_default_byte_value(ESP_BT_FLAG)); - Settings_ESP3D::write_byte(ESP_SCREEN_FLAG,Settings_ESP3D::get_default_byte_value(ESP_SCREEN_FLAG)); + // Admin password + Settings_ESP3D::write_string( + ESP_ADMIN_PWD, + Settings_ESP3D::get_default_string_value(ESP_ADMIN_PWD).c_str()); + // User password + Settings_ESP3D::write_string( + ESP_USER_PWD, + Settings_ESP3D::get_default_string_value(ESP_USER_PWD).c_str()); + // Session timeout + Settings_ESP3D::write_byte( + ESP_SESSION_TIMEOUT, + Settings_ESP3D::get_default_byte_value(ESP_SESSION_TIMEOUT)); +#endif // AUTHENTICATION_FEATURE + // Target FW + Settings_ESP3D::write_byte( + ESP_TARGET_FW, Settings_ESP3D::get_default_byte_value(ESP_TARGET_FW)); + // Output flags + Settings_ESP3D::write_byte( + ESP_SERIAL_FLAG, Settings_ESP3D::get_default_byte_value(ESP_SERIAL_FLAG)); + Settings_ESP3D::write_byte( + ESP_SERIAL_BRIDGE_FLAG, + Settings_ESP3D::get_default_byte_value(ESP_SERIAL_BRIDGE_FLAG)); + Settings_ESP3D::write_byte( + ESP_REMOTE_SCREEN_FLAG, + Settings_ESP3D::get_default_byte_value(ESP_REMOTE_SCREEN_FLAG)); + Settings_ESP3D::write_byte( + ESP_WEBSOCKET_FLAG, + Settings_ESP3D::get_default_byte_value(ESP_WEBSOCKET_FLAG)); + Settings_ESP3D::write_byte( + ESP_TELNET_FLAG, Settings_ESP3D::get_default_byte_value(ESP_TELNET_FLAG)); + Settings_ESP3D::write_byte( + ESP_BT_FLAG, Settings_ESP3D::get_default_byte_value(ESP_BT_FLAG)); + Settings_ESP3D::write_byte( + ESP_SCREEN_FLAG, Settings_ESP3D::get_default_byte_value(ESP_SCREEN_FLAG)); #ifdef SD_DEVICE - //SPI SD Divider - Settings_ESP3D::write_byte(ESP_SD_SPEED_DIV,Settings_ESP3D::get_default_byte_value(ESP_SD_SPEED_DIV)); + // SPI SD Divider + Settings_ESP3D::write_byte( + ESP_SD_SPEED_DIV, + Settings_ESP3D::get_default_byte_value(ESP_SD_SPEED_DIV)); #ifdef SD_UPDATE_FEATURE - //SD Update feature - Settings_ESP3D::write_byte(ESP_SD_CHECK_UPDATE_AT_BOOT,Settings_ESP3D::get_default_byte_value(ESP_SD_CHECK_UPDATE_AT_BOOT)); -#endif //SD_UPDATE_FEATURE -#endif //SD_DEVICE + // SD Update feature + Settings_ESP3D::write_byte( + ESP_SD_CHECK_UPDATE_AT_BOOT, + Settings_ESP3D::get_default_byte_value(ESP_SD_CHECK_UPDATE_AT_BOOT)); +#endif // SD_UPDATE_FEATURE +#endif // SD_DEVICE #ifdef TIMESTAMP_FEATURE - //Internet time - Settings_ESP3D::write_byte(ESP_INTERNET_TIME,Settings_ESP3D::get_default_byte_value(ESP_INTERNET_TIME)); - //Time Zone - Settings_ESP3D::write_byte(ESP_TIMEZONE,Settings_ESP3D::get_default_byte_value(ESP_TIMEZONE)); - //Is DST Time Zone - Settings_ESP3D::write_byte(ESP_TIME_IS_DST,Settings_ESP3D::get_default_byte_value(ESP_TIME_IS_DST)); - //Time Server 1 address - Settings_ESP3D::write_string(ESP_TIME_SERVER1, Settings_ESP3D::get_default_string_value(ESP_TIME_SERVER1).c_str()); - //Time Server 2 address - Settings_ESP3D::write_string(ESP_TIME_SERVER2, Settings_ESP3D::get_default_string_value(ESP_TIME_SERVER2).c_str()); - //Time Server 3 address - Settings_ESP3D::write_string(ESP_TIME_SERVER3, Settings_ESP3D::get_default_string_value(ESP_TIME_SERVER3).c_str()); -#endif //TIMESTAMP_FEATURE + // Internet time + Settings_ESP3D::write_byte( + ESP_INTERNET_TIME, + Settings_ESP3D::get_default_byte_value(ESP_INTERNET_TIME)); + // Time Zone + Settings_ESP3D::write_byte( + ESP_TIMEZONE, Settings_ESP3D::get_default_byte_value(ESP_TIMEZONE)); + // Is DST Time Zone + Settings_ESP3D::write_byte( + ESP_TIME_IS_DST, Settings_ESP3D::get_default_byte_value(ESP_TIME_IS_DST)); + // Time Server 1 address + Settings_ESP3D::write_string( + ESP_TIME_SERVER1, + Settings_ESP3D::get_default_string_value(ESP_TIME_SERVER1).c_str()); + // Time Server 2 address + Settings_ESP3D::write_string( + ESP_TIME_SERVER2, + Settings_ESP3D::get_default_string_value(ESP_TIME_SERVER2).c_str()); + // Time Server 3 address + Settings_ESP3D::write_string( + ESP_TIME_SERVER3, + Settings_ESP3D::get_default_string_value(ESP_TIME_SERVER3).c_str()); +#endif // TIMESTAMP_FEATURE #ifdef SENSOR_DEVICE - //Sensor device - Settings_ESP3D::write_byte(ESP_SENSOR_TYPE,Settings_ESP3D::get_default_byte_value(ESP_SENSOR_TYPE)); - //Sensor query interval - Settings_ESP3D::write_uint32 (ESP_SENSOR_INTERVAL, Settings_ESP3D::get_default_int32_value(ESP_SENSOR_INTERVAL)); -#endif //SENSOR_DEVICE - //Start Delay - Settings_ESP3D::write_uint32 (ESP_BOOT_DELAY, Settings_ESP3D::get_default_int32_value(ESP_BOOT_DELAY)); -#endif //SETTINGS_IN_EEPROM - //set version in settings - if (res) { - log_esp3d("Reset Setting Version"); - //Settings version (internal only) - res = Settings_ESP3D::write_string(ESP_SETTINGS_VERSION, CURRENT_SETTINGS_VERSION); - } - return res; + // Sensor device + Settings_ESP3D::write_byte( + ESP_SENSOR_TYPE, Settings_ESP3D::get_default_byte_value(ESP_SENSOR_TYPE)); + // Sensor query interval + Settings_ESP3D::write_uint32( + ESP_SENSOR_INTERVAL, + Settings_ESP3D::get_default_int32_value(ESP_SENSOR_INTERVAL)); +#endif // SENSOR_DEVICE + // Start Delay + Settings_ESP3D::write_uint32( + ESP_BOOT_DELAY, Settings_ESP3D::get_default_int32_value(ESP_BOOT_DELAY)); +#endif // SETTINGS_IN_EEPROM + // set version in settings + if (res) { + log_esp3d("Reset Setting Version"); + // Settings version (internal only) + res = Settings_ESP3D::write_string(ESP_SETTINGS_VERSION, + CURRENT_SETTINGS_VERSION); + } + return res; } -//Get Settings Version -// * -1 means no version detected -// * 00 / 01 Not used -// * 03 and up is version -int8_t Settings_ESP3D::GetSettingsVersion() -{ - int8_t v = -1; - String version = Settings_ESP3D::read_string(ESP_SETTINGS_VERSION); - if ((version == "ESP3D") ||( version.length() != 7) || (version.indexOf("ESP3D")!=0)) { - log_esp3d("Invalid Settings Version %s",version.c_str()); - return v; - } - v = version.substring(5).toInt(); - log_esp3d("Settings Version %d", v); +// Get Settings Version +// * -1 means no version detected +// * 00 / 01 Not used +// * 03 and up is version +int8_t Settings_ESP3D::GetSettingsVersion() { + int8_t v = -1; + String version = Settings_ESP3D::read_string(ESP_SETTINGS_VERSION); + if ((version == "ESP3D") || (version.length() != 7) || + (version.indexOf("ESP3D") != 0)) { + log_esp3d_e("Invalid Settings Version %s", version.c_str()); return v; + } + v = version.substring(5).toInt(); + log_esp3d("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)); +// write a IP from string +bool Settings_ESP3D::write_IP_String(int pos, const char *value) { + return write_uint32(pos, StringtoIP(value)); } -//Helper to convert IP string to int -uint32_t Settings_ESP3D::StringtoIP(const char *s) -{ - uint32_t ip_int = 0; - IPAddress ipaddr; - if (ipaddr.fromString(s)) { - ip_int = ipaddr; - } - return ip_int; +// Helper to convert IP string to int +uint32_t Settings_ESP3D::StringtoIP(const char *s) { + uint32_t ip_int = 0; + IPAddress ipaddr; + if (ipaddr.fromString(s)) { + ip_int = ipaddr; + } + return ip_int; } // Helper to convert int to IP string -String Settings_ESP3D::IPtoString(uint32_t ip_int) -{ - static IPAddress ipaddr; - ipaddr = ip_int; - return ipaddr.toString(); +String Settings_ESP3D::IPtoString(uint32_t ip_int) { + static IPAddress ipaddr; + ipaddr = ip_int; + return ipaddr.toString(); } -const char * Settings_ESP3D::TargetBoard() -{ +const char *Settings_ESP3D::TargetBoard() { #ifdef ARDUINO_ARCH_ESP32 -# if CONFIG_IDF_TARGET_ESP32 -# define TYPE_BOARD "ESP32" -# elif CONFIG_IDF_TARGET_ESP32S2 -# define TYPE_BOARD "ESP32-S2" -# elif CONFIG_IDF_TARGET_ESP32S3 -# define TYPE_BOARD "ESP32-S3" -# elif CONFIG_IDF_TARGET_ESP32C3 -# define TYPE_BOARD "ESP32-C3" -# endif +#if CONFIG_IDF_TARGET_ESP32 +#define TYPE_BOARD "ESP32" +#elif CONFIG_IDF_TARGET_ESP32S2 +#define TYPE_BOARD "ESP32-S2" +#elif CONFIG_IDF_TARGET_ESP32S3 +#define TYPE_BOARD "ESP32-S3" +#elif CONFIG_IDF_TARGET_ESP32C3 +#define TYPE_BOARD "ESP32-C3" +#endif #ifdef BOARD_HAS_PSRAM #define IS_PSRAM " (PSRAM)" #else #define IS_PSRAM "" -#endif //BOARD_HAS_PSRAM - return TYPE_BOARD IS_PSRAM; -#endif //ARDUINO_ARCH_ESP32 +#endif // BOARD_HAS_PSRAM + return TYPE_BOARD IS_PSRAM; +#endif // ARDUINO_ARCH_ESP32 #ifdef ARDUINO_ARCH_ESP8266 - return "ESP82XX"; -#endif //ARDUINO_ARCH_ESP8266 + return "ESP82XX"; +#endif // ARDUINO_ARCH_ESP8266 } -bool Settings_ESP3D::isLocalPasswordValid (const char * password) -{ - char c; - //limited size - if ( (strlen (password) > MAX_LOCAL_PASSWORD_LENGTH) || (strlen (password) <= MIN_LOCAL_PASSWORD_LENGTH) ) { - return false; +bool Settings_ESP3D::isLocalPasswordValid(const char *password) { + char c; + // limited size + if ((strlen(password) > MAX_LOCAL_PASSWORD_LENGTH) || + (strlen(password) <= MIN_LOCAL_PASSWORD_LENGTH)) { + return false; + } + // no space allowed + for (uint8_t i = 0; i < strlen(password); i++) { + c = password[i]; + if (c == ' ') { + return false; } - //no space allowed - for (uint8_t i = 0; i < strlen (password); i++) { - c = password[i]; - if (c == ' ') { - return false; - } - } - return true; + } + return true; } -#endif //ESP_SAVE_SETTINGS +#endif // ESP_SAVE_SETTINGS diff --git a/esp3d/src/include/defines.h b/esp3d/src/include/defines.h index 12a0cc66..e8ee93a4 100644 --- a/esp3d/src/include/defines.h +++ b/esp3d/src/include/defines.h @@ -147,11 +147,16 @@ #define HIDDEN_PASSWORD "********" // Debug -#define DEBUG_OUTPUT_SERIAL0 1 -#define DEBUG_OUTPUT_SERIAL1 2 -#define DEBUG_OUTPUT_SERIAL2 3 -#define DEBUG_OUTPUT_TELNET 4 -#define DEBUG_OUTPUT_WEBSOCKET 5 +#define LOG_OUTPUT_SERIAL0 1 +#define LOG_OUTPUT_SERIAL1 2 +#define LOG_OUTPUT_SERIAL2 3 +#define LOG_OUTPUT_TELNET 4 +#define LOG_OUTPUT_WEBSOCKET 5 + +#define LOG_LEVEL_NONE 0 +#define LOG_LEVEL_ERROR 1 +#define LOG_LEVEL_DEBUG 2 +#define LOG_LEVEL_VERBOSE 3 // Serial #define USE_SERIAL_0 1 diff --git a/esp3d/src/include/esp3d_config.h b/esp3d/src/include/esp3d_config.h index 02486b93..7719f7e6 100644 --- a/esp3d/src/include/esp3d_config.h +++ b/esp3d/src/include/esp3d_config.h @@ -21,15 +21,17 @@ #ifndef _ESP3D_CONFIG_H #define _ESP3D_CONFIG_H #include + #include "../include/defines.h" + #if defined __has_include -# if __has_include ("../../configuration.h") +#if __has_include("../../configuration.h") #include "../../configuration.h" #define ESP3D_CODE_BASE "ESP3D" #else #undef DISABLED #undef _BV -# if __has_include ("../esp3dlib_config.h") +#if __has_include("../esp3dlib_config.h") #include "../esp3dlib_config.h" #define ESP3D_CODE_BASE "ESP3DLib" #else @@ -38,22 +40,23 @@ #endif #endif +#include "../core/hal.h" +#include "../core/log_esp3d.h" #include "../include/pins.h" #include "../include/sanity_esp3d.h" -#include "../core/hal.h" -#include "../core/debug_esp3d.h" #include "../include/version.h" + #if defined(ARDUINO_ARCH_ESP8266) /************************************ * * SSL Client * * **********************************/ -//Using BearSSL need to decrease size of packet to not be OOM on ESP8266 -#define BEARSSL_MFLN_SIZE 512 -#define BEARSSL_MFLN_SIZE_FALLBACK 4096 -#endif // ARDUINO_ARCH_ESP8266 +// Using BearSSL need to decrease size of packet to not be OOM on ESP8266 +#define BEARSSL_MFLN_SIZE 512 +#define BEARSSL_MFLN_SIZE_FALLBACK 4096 +#endif // ARDUINO_ARCH_ESP8266 /************************************ * @@ -61,13 +64,17 @@ * * **********************************/ -//Make Flag more generic -#if (defined(PIN_RESET_FEATURE) && defined(ESP3D_RESET_PIN) && ESP3D_RESET_PIN!=-1) || defined(SD_RECOVERY_FEATURE) +// Make Flag more generic +#if (defined(PIN_RESET_FEATURE) && defined(ESP3D_RESET_PIN) && \ + ESP3D_RESET_PIN != -1) || \ + defined(SD_RECOVERY_FEATURE) #define RECOVERY_FEATURE -#endif //PIN_RESET_FEATURE || SD_RECOVERY_FEATURE +#endif // PIN_RESET_FEATURE || SD_RECOVERY_FEATURE -#if defined(DISPLAY_DEVICE) || defined(SENSOR_DEVICE) || defined(RECOVERY_FEATURE) || defined(BUZZER_DEVICE) || defined(CAMERA_DEVICE) || defined(SD_DEVICE) +#if defined(DISPLAY_DEVICE) || defined(SENSOR_DEVICE) || \ + defined(RECOVERY_FEATURE) || defined(BUZZER_DEVICE) || \ + defined(CAMERA_DEVICE) || defined(SD_DEVICE) #define CONNECTED_DEVICES_FEATURE -#endif //DISPLAY_DEVICE || SENSOR_DEVICE , etc... +#endif // DISPLAY_DEVICE || SENSOR_DEVICE , etc... -#endif //_ESP3D_CONFIG_H +#endif //_ESP3D_CONFIG_H diff --git a/esp3d/src/include/pins.h b/esp3d/src/include/pins.h index 3907cd6d..c8bb8ac9 100644 --- a/esp3d/src/include/pins.h +++ b/esp3d/src/include/pins.h @@ -38,12 +38,12 @@ #endif // ESP_BRIDGE_TX_PIN #endif // ESP_SERIAL_BRIDGE_OUTPUT -#ifndef ESP_DEBUG_RX_PIN -#define ESP_DEBUG_RX_PIN -1 -#endif // ESP_DEBUG_RX_PIN -#ifndef ESP_DEBUG_TX_PIN -#define ESP_DEBUG_TX_PIN -1 -#endif // ESP_DEBUG_TX_PIN +#ifndef ESP_LOG_RX_PIN +#define ESP_LOG_RX_PIN -1 +#endif // ESP_LOG_RX_PIN +#ifndef ESP_LOG_TX_PIN +#define ESP_LOG_TX_PIN -1 +#endif // ESP_LOG_TX_PIN // I2C Pins #ifndef ESP_SDA_PIN diff --git a/esp3d/src/include/sanity_esp3d.h b/esp3d/src/include/sanity_esp3d.h index d6444687..7b12f530 100644 --- a/esp3d/src/include/sanity_esp3d.h +++ b/esp3d/src/include/sanity_esp3d.h @@ -37,14 +37,14 @@ * Debug * ***********************/ -#if defined(ESP_DEBUG_FEATURE) -#if ESP_DEBUG_FEATURE == ESP_SERIAL_OUTPUT -#warning You use same serial for output and debug -#endif // ESP_DEBUG_FEATURE == ESP_SERIAL_OUTPUT -#if (ESP_DEBUG_FEATURE == DEBUG_OUTPUT_SERIAL2) && defined(ARDUINO_ARCH_ESP8266) -#error Serial 2 is not available in ESP8266 for debug -#endif // ESP_DEBUG_FEATURE == DEBUG_OUTPUT_SERIAL2 ) && ARDUINO_ARCH_ESP8266 -#endif // ESP_DEBUG_FEATURE +#if defined(ESP_LOG_FEATURE) +#if ESP_LOG_FEATURE == ESP_SERIAL_OUTPUT +#warning You use same serial for output and log +#endif // ESP_LOG_FEATURE == ESP_SERIAL_OUTPUT +#if (ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL2) && defined(ARDUINO_ARCH_ESP8266) +#error Serial 2 is not available in ESP8266 for log +#endif // ESP_LOG_FEATURE == LOG_OUTPUT_SERIAL2 ) && ARDUINO_ARCH_ESP8266 +#endif // ESP_LOG_FEATURE /************************** * Serial diff --git a/esp3d/src/modules/camera/camera.cpp b/esp3d/src/modules/camera/camera.cpp index 8f939c53..85fc0216 100644 --- a/esp3d/src/modules/camera/camera.cpp +++ b/esp3d/src/modules/camera/camera.cpp @@ -20,379 +20,364 @@ #include "../../include/esp3d_config.h" #ifdef CAMERA_DEVICE -#include "camera.h" -#include "../../core/esp3doutput.h" -#include "../../core/esp3d.h" -#include -#include //not sure this one is needed -#include #include -#if defined (SD_DEVICE) -#include "../filesystem/esp_sd.h" -#endif //SD_DEVICE +#include +#include +#include //not sure this one is needed +#include "../../core/esp3d.h" +#include "../../core/esp3doutput.h" +#include "camera.h" + +#if defined(SD_DEVICE) +#include "../filesystem/esp_sd.h" +#endif // SD_DEVICE #define DEFAULT_FRAME_SIZE FRAMESIZE_SVGA #define JPEG_COMPRESSION 80 Camera esp3d_camera; -bool Camera::handle_snap(WebServer * webserver, const char *path, const char* filename) -{ - log_esp3d("Camera stream reached"); - if (!_initialised) { - log_esp3d("Camera not started"); - if (webserver) { - webserver->send (500, "text/plain", "Camera not started"); - } - return false; - } - sensor_t * s = esp_camera_sensor_get(); +bool Camera::handle_snap(WebServer *webserver, const char *path, + const char *filename) { + log_esp3d("Camera stream reached"); + if (!_initialised) { + log_esp3d_e("Camera not started"); if (webserver) { - if (webserver->hasArg ("framesize") ) { - if(s->status.framesize != webserver->arg ("framesize").toInt()) { - command("framesize", webserver->arg ("framesize").c_str()); - } - } - if (webserver->hasArg ("hmirror") ) { - command("hmirror", webserver->arg ("hmirror").c_str()); - } - if (webserver->hasArg ("vflip") ) { - command("vflip", webserver->arg ("vflip").c_str()); - } - if (webserver->hasArg ("wb_mode") ) { - command("wb_mode", webserver->arg ("wb_mode").c_str()); - } + webserver->send(500, "text/plain", "Camera not started"); + } + return false; + } + sensor_t *s = esp_camera_sensor_get(); + if (webserver) { + if (webserver->hasArg("framesize")) { + if (s->status.framesize != webserver->arg("framesize").toInt()) { + command("framesize", webserver->arg("framesize").c_str()); + } + } + if (webserver->hasArg("hmirror")) { + command("hmirror", webserver->arg("hmirror").c_str()); + } + if (webserver->hasArg("vflip")) { + command("vflip", webserver->arg("vflip").c_str()); + } + if (webserver->hasArg("wb_mode")) { + command("wb_mode", webserver->arg("wb_mode").c_str()); + } #ifdef ESP_ACCESS_CONTROL_ALLOW_ORIGIN - webserver->enableCrossOrigin(true); -#endif //ESP_ACCESS_CONTROL_ALLOw_ORIGIN - } - camera_fb_t * fb = NULL; - bool res_error = false; - size_t _jpg_buf_len = 0; - uint8_t * _jpg_buf = NULL; + webserver->enableCrossOrigin(true); +#endif // ESP_ACCESS_CONTROL_ALLOw_ORIGIN + } + camera_fb_t *fb = NULL; + bool res_error = false; + size_t _jpg_buf_len = 0; + uint8_t *_jpg_buf = NULL; + if (webserver) { + webserver->sendHeader(String(F("Content-Type")), String(F("image/jpeg")), + true); + webserver->sendHeader(String(F("Content-Disposition")), + String(F("inline; filename=capture.jpg")), true); + webserver->setContentLength(CONTENT_LENGTH_UNKNOWN); + webserver->send(200); + } + log_esp3d("Camera capture ongoing"); + fb = esp_camera_fb_get(); + if (!fb) { + log_esp3d_e("Camera capture failed"); if (webserver) { - webserver->sendHeader(String(F("Content-Type")), String(F("image/jpeg")),true); - webserver->sendHeader(String(F("Content-Disposition")), String(F("inline; filename=capture.jpg")),true); - webserver->setContentLength(CONTENT_LENGTH_UNKNOWN); - webserver->send(200); + webserver->send(500, "text/plain", "Capture failed"); } - log_esp3d("Camera capture ongoing"); - fb = esp_camera_fb_get(); - if (!fb) { - log_esp3d("Camera capture failed"); - if (webserver) { - webserver->send (500, "text/plain", "Capture failed"); - } - res_error=true; + res_error = true; + } else { + if (fb->format != PIXFORMAT_JPEG) { + bool jpeg_converted = + frame2jpg(fb, JPEG_COMPRESSION, &_jpg_buf, &_jpg_buf_len); + esp_camera_fb_return(fb); + fb = NULL; + if (!jpeg_converted) { + log_esp3d_e("JPEG compression failed"); + res_error = true; + } } else { - if(fb->format != PIXFORMAT_JPEG) { - bool jpeg_converted = frame2jpg(fb, JPEG_COMPRESSION, &_jpg_buf, &_jpg_buf_len); - esp_camera_fb_return(fb); - fb = NULL; - if(!jpeg_converted) { - log_esp3d("JPEG compression failed"); - res_error = true; - } - } else { - _jpg_buf_len = fb->len; - _jpg_buf = fb->buf; - } + _jpg_buf_len = fb->len; + _jpg_buf = fb->buf; } - if (!res_error) { - if(webserver) { - webserver->sendContent_P ((const char *)_jpg_buf, _jpg_buf_len); - } -#if defined (SD_DEVICE) - if (filename!=nullptr && path!=nullptr) { - if (!ESP_SD::accessFS()) { - res_error = true; - log_esp3d("SD not available"); + } + if (!res_error) { + if (webserver) { + webserver->sendContent_P((const char *)_jpg_buf, _jpg_buf_len); + } +#if defined(SD_DEVICE) + if (filename != nullptr && path != nullptr) { + if (!ESP_SD::accessFS()) { + res_error = true; + log_esp3d_e("SD not available"); + } else { + if (ESP_SD::getState(true) == ESP_SDCARD_NOT_PRESENT) { + res_error = true; + log_esp3d_e("No SD"); + } else { + ESP_SD::setState(ESP_SDCARD_BUSY); + String wpath = path[0] == '/' ? path : String("/") + path; + if (!ESP_SD::exists(wpath.c_str())) { + res_error = !ESP_SD::mkdir(wpath.c_str()); + } + if (!res_error) { + if (wpath[wpath.length() - 1] != '/') { + wpath += "/"; + } + wpath += filename; + ESP_SDFile f = ESP_SD::open(wpath.c_str(), ESP_FILE_WRITE); + if (f) { + f.write((const uint8_t *)_jpg_buf, _jpg_buf_len); + f.close(); + log_esp3d("Camera capture done"); } else { - if (ESP_SD::getState(true) == ESP_SDCARD_NOT_PRESENT) { - res_error = true; - log_esp3d("No SD"); - } else { - ESP_SD::setState(ESP_SDCARD_BUSY ); - String wpath = path[0]=='/' ? path : String("/")+path; - if (!ESP_SD::exists(wpath.c_str())) { - res_error = !ESP_SD::mkdir(wpath.c_str()); - } - if (!res_error) { - if (wpath[wpath.length()-1]!='/') { - wpath += "/"; - } - wpath +=filename ; - ESP_SDFile f = ESP_SD::open(wpath.c_str(), ESP_FILE_WRITE); - if (f) { - f.write((const uint8_t *)_jpg_buf, _jpg_buf_len); - f.close(); - log_esp3d("Camera capture done"); - } else { - res_error = true; - log_esp3d("Failed to open file for writing"); - } - } - } - ESP_SD::releaseFS(); + res_error = true; + log_esp3d_e("Failed to open file for writing"); } - - } -#endif //SD_DEVICE - if (!webserver && filename==nullptr && path==nullptr) { - log_esp3d("No output defined"); - res_error = true; + } } + ESP_SD::releaseFS(); + } } +#endif // SD_DEVICE + if (!webserver && filename == nullptr && path == nullptr) { + log_esp3d_e("No output defined"); + res_error = true; + } + } - if(fb) { - esp_camera_fb_return(fb); - fb = NULL; - _jpg_buf = NULL; - } else if(_jpg_buf) { - free(_jpg_buf); - _jpg_buf = NULL; - } - if(webserver) { - webserver->sendContent(""); - } - return !res_error; + if (fb) { + esp_camera_fb_return(fb); + fb = NULL; + _jpg_buf = NULL; + } else if (_jpg_buf) { + free(_jpg_buf); + _jpg_buf = NULL; + } + if (webserver) { + webserver->sendContent(""); + } + return !res_error; } -Camera::Camera() -{ - _started = false; - _initialised = false; +Camera::Camera() { + _started = false; + _initialised = false; } -Camera::~Camera() -{ - end(); -} +Camera::~Camera() { end(); } -int Camera::command(const char * param, const char * value) -{ - log_esp3d("Camera: %s=%s\n",param, value); - int res = 0; - int val = atoi(value); - sensor_t * s = esp_camera_sensor_get(); - if (s == nullptr) { - res = -1; - } +int Camera::command(const char *param, const char *value) { + log_esp3d("Camera: %s=%s\n", param, value); + int res = 0; + int val = atoi(value); + sensor_t *s = esp_camera_sensor_get(); + if (s == nullptr) { + res = -1; + } #if CAM_LED_PIN != -1 - if (!strcmp(param, "light")) { - digitalWrite(CAM_LED_PIN, val==1?HIGH:LOW); - } else -#endif //CAM_LED_PIN - if(!strcmp(param, "framesize")) { - if(s->pixformat == PIXFORMAT_JPEG) { - res = s->set_framesize(s, (framesize_t)val); - } - } else if(!strcmp(param, "quality")) { - res = s->set_quality(s, val); - } else if(!strcmp(param, "contrast")) { - res = s->set_contrast(s, val); - } else if(!strcmp(param, "brightness")) { - res = s->set_brightness(s, val); - } else if(!strcmp(param, "saturation")) { - res = s->set_saturation(s, val); - } else if(!strcmp(param, "gainceiling")) { - res = s->set_gainceiling(s, (gainceiling_t)val); - } else if(!strcmp(param, "colorbar")) { - res = s->set_colorbar(s, val); - } else if(!strcmp(param, "awb")) { - res = s->set_whitebal(s, val); - } else if(!strcmp(param, "agc")) { - res = s->set_gain_ctrl(s, val); - } else if(!strcmp(param, "aec")) { - res = s->set_exposure_ctrl(s, val); - } else if(!strcmp(param, "hmirror")) { - res = s->set_hmirror(s, val); - } else if(!strcmp(param, "vflip")) { - res = s->set_vflip(s, val); - } else if(!strcmp(param, "awb_gain")) { - res = s->set_awb_gain(s, val); - } else if(!strcmp(param, "agc_gain")) { - res = s->set_agc_gain(s, val); - } else if(!strcmp(param, "aec_value")) { - res = s->set_aec_value(s, val); - } else if(!strcmp(param, "aec2")) { - res = s->set_aec2(s, val); - } else if(!strcmp(param, "dcw")) { - res = s->set_dcw(s, val); - } else if(!strcmp(param, "bpc")) { - res = s->set_bpc(s, val); - } else if(!strcmp(param, "wpc")) { - res = s->set_wpc(s, val); - } else if(!strcmp(param, "raw_gma")) { - res = s->set_raw_gma(s, val); - } else if(!strcmp(param, "lenc")) { - res = s->set_lenc(s, val); - } else if(!strcmp(param, "special_effect")) { - res = s->set_special_effect(s, val); - } else if(!strcmp(param, "wb_mode")) { - res = s->set_wb_mode(s, val); - } else if(!strcmp(param, "ae_level")) { - res = s->set_ae_level(s, val); - } else { - res = -1; - } - return res; -} - -bool Camera::initHardware() -{ - _initialised = false; - log_esp3d("Disable brown out"); - WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //disable brownout detector - stopHardware(); - camera_config_t config; - config.ledc_channel = LEDC_CHANNEL_0; - config.ledc_timer = LEDC_TIMER_0; - config.pin_d0 = Y2_GPIO_NUM; - config.pin_d1 = Y3_GPIO_NUM; - config.pin_d2 = Y4_GPIO_NUM; - config.pin_d3 = Y5_GPIO_NUM; - config.pin_d4 = Y6_GPIO_NUM; - config.pin_d5 = Y7_GPIO_NUM; - config.pin_d6 = Y8_GPIO_NUM; - config.pin_d7 = Y9_GPIO_NUM; - config.pin_xclk = XCLK_GPIO_NUM; - config.pin_pclk = PCLK_GPIO_NUM; - config.pin_vsync = VSYNC_GPIO_NUM; - config.pin_href = HREF_GPIO_NUM; - config.pin_sccb_sda = SIOD_GPIO_NUM; - config.pin_sccb_scl = SIOC_GPIO_NUM; - config.pin_pwdn = PWDN_GPIO_NUM; - config.pin_reset = RESET_GPIO_NUM; - config.xclk_freq_hz = 20000000; - config.pixel_format = PIXFORMAT_JPEG; - config.jpeg_quality = 5; - config.fb_count = 1; - config.frame_size = DEFAULT_FRAME_SIZE; - config.fb_location = CAMERA_FB_IN_PSRAM; - config.grab_mode = CAMERA_GRAB_LATEST; - if(!psramFound()) { - _initialised = false; - log_esp3d("psram is not enabled"); - return false; - } - log_esp3d("Init camera"); -#if CAM_PULLUP1 != -1 - pinMode(CAM_PULLUP1, INPUT_PULLUP); -#endif //CAM_PULLUP1 -#if CAM_PULLUP2 != -1 - pinMode(CAM_PULLUP2, INPUT_PULLUP); -#endif //CAM_PULLUP2 -#if CAM_LED_PIN != -1 - pinMode(CAM_LED_PIN, OUTPUT); - digitalWrite(CAM_LED_PIN, LOW); -#endif //CAM_LED_PIN - //initialize the camera - -//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"); - gpio_config_t gpio_pwr_config; - gpio_pwr_config.pin_bit_mask = (1ULL << 32); - gpio_pwr_config.mode = GPIO_MODE_OUTPUT; - gpio_pwr_config.pull_down_en = GPIO_PULLDOWN_DISABLE; - gpio_pwr_config.pull_up_en = GPIO_PULLUP_DISABLE; - gpio_pwr_config.intr_type = GPIO_INTR_DISABLE; - gpio_config(&gpio_pwr_config); - gpio_set_level(GPIO_NUM_32,0); -#endif //CAMERA_DEVICE == CAMERA_MODEL_AI_THINKER - delay(500); - log_esp3d("Init camera config"); - esp_err_t err = esp_camera_init(&config); - if (err != ESP_OK) { - log_esp3d("Camera init failed with error 0x%x", err); + if (!strcmp(param, "light")) { + digitalWrite(CAM_LED_PIN, val == 1 ? HIGH : LOW); + } else +#endif // CAM_LED_PIN + if (!strcmp(param, "framesize")) { + if (s->pixformat == PIXFORMAT_JPEG) { + res = s->set_framesize(s, (framesize_t)val); + } + } else if (!strcmp(param, "quality")) { + res = s->set_quality(s, val); + } else if (!strcmp(param, "contrast")) { + res = s->set_contrast(s, val); + } else if (!strcmp(param, "brightness")) { + res = s->set_brightness(s, val); + } else if (!strcmp(param, "saturation")) { + res = s->set_saturation(s, val); + } else if (!strcmp(param, "gainceiling")) { + res = s->set_gainceiling(s, (gainceiling_t)val); + } else if (!strcmp(param, "colorbar")) { + res = s->set_colorbar(s, val); + } else if (!strcmp(param, "awb")) { + res = s->set_whitebal(s, val); + } else if (!strcmp(param, "agc")) { + res = s->set_gain_ctrl(s, val); + } else if (!strcmp(param, "aec")) { + res = s->set_exposure_ctrl(s, val); + } else if (!strcmp(param, "hmirror")) { + res = s->set_hmirror(s, val); + } else if (!strcmp(param, "vflip")) { + res = s->set_vflip(s, val); + } else if (!strcmp(param, "awb_gain")) { + res = s->set_awb_gain(s, val); + } else if (!strcmp(param, "agc_gain")) { + res = s->set_agc_gain(s, val); + } else if (!strcmp(param, "aec_value")) { + res = s->set_aec_value(s, val); + } else if (!strcmp(param, "aec2")) { + res = s->set_aec2(s, val); + } else if (!strcmp(param, "dcw")) { + res = s->set_dcw(s, val); + } else if (!strcmp(param, "bpc")) { + res = s->set_bpc(s, val); + } else if (!strcmp(param, "wpc")) { + res = s->set_wpc(s, val); + } else if (!strcmp(param, "raw_gma")) { + res = s->set_raw_gma(s, val); + } else if (!strcmp(param, "lenc")) { + res = s->set_lenc(s, val); + } else if (!strcmp(param, "special_effect")) { + res = s->set_special_effect(s, val); + } else if (!strcmp(param, "wb_mode")) { + res = s->set_wb_mode(s, val); + } else if (!strcmp(param, "ae_level")) { + res = s->set_ae_level(s, val); } else { - _initialised = true; + res = -1; } - return _initialised; + return res; } -bool Camera::stopHardware() -{ - return true; +bool Camera::initHardware() { + _initialised = false; + log_esp3d("Disable brown out"); + WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); // disable brownout detector + stopHardware(); + camera_config_t config; + config.ledc_channel = LEDC_CHANNEL_0; + config.ledc_timer = LEDC_TIMER_0; + config.pin_d0 = Y2_GPIO_NUM; + config.pin_d1 = Y3_GPIO_NUM; + config.pin_d2 = Y4_GPIO_NUM; + config.pin_d3 = Y5_GPIO_NUM; + config.pin_d4 = Y6_GPIO_NUM; + config.pin_d5 = Y7_GPIO_NUM; + config.pin_d6 = Y8_GPIO_NUM; + config.pin_d7 = Y9_GPIO_NUM; + config.pin_xclk = XCLK_GPIO_NUM; + config.pin_pclk = PCLK_GPIO_NUM; + config.pin_vsync = VSYNC_GPIO_NUM; + config.pin_href = HREF_GPIO_NUM; + config.pin_sccb_sda = SIOD_GPIO_NUM; + config.pin_sccb_scl = SIOC_GPIO_NUM; + config.pin_pwdn = PWDN_GPIO_NUM; + config.pin_reset = RESET_GPIO_NUM; + config.xclk_freq_hz = 20000000; + config.pixel_format = PIXFORMAT_JPEG; + config.jpeg_quality = 5; + config.fb_count = 1; + config.frame_size = DEFAULT_FRAME_SIZE; + config.fb_location = CAMERA_FB_IN_PSRAM; + config.grab_mode = CAMERA_GRAB_LATEST; + if (!psramFound()) { + _initialised = false; + log_esp3d_e("psram is not enabled"); + return false; + } + log_esp3d("Init camera"); +#if CAM_PULLUP1 != -1 + pinMode(CAM_PULLUP1, INPUT_PULLUP); +#endif // CAM_PULLUP1 +#if CAM_PULLUP2 != -1 + pinMode(CAM_PULLUP2, INPUT_PULLUP); +#endif // CAM_PULLUP2 +#if CAM_LED_PIN != -1 + pinMode(CAM_LED_PIN, OUTPUT); + digitalWrite(CAM_LED_PIN, LOW); +#endif // CAM_LED_PIN + // initialize the camera + +// 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"); + gpio_config_t gpio_pwr_config; + gpio_pwr_config.pin_bit_mask = (1ULL << 32); + gpio_pwr_config.mode = GPIO_MODE_OUTPUT; + gpio_pwr_config.pull_down_en = GPIO_PULLDOWN_DISABLE; + gpio_pwr_config.pull_up_en = GPIO_PULLUP_DISABLE; + gpio_pwr_config.intr_type = GPIO_INTR_DISABLE; + gpio_config(&gpio_pwr_config); + gpio_set_level(GPIO_NUM_32, 0); +#endif // CAMERA_DEVICE == CAMERA_MODEL_AI_THINKER + delay(500); + log_esp3d("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); + } else { + _initialised = true; + } + return _initialised; } -//need to be call by device and by network -bool Camera::begin() -{ - end(); - log_esp3d("Begin camera"); - if (!_initialised) { - log_esp3d("Init hardware not done"); - return false; - } - log_esp3d("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 - if (s->id.PID == OV3660_PID) { - s->set_brightness(s, 1);//up the blightness just a bit - s->set_saturation(s, -2);//lower the saturation - } +bool Camera::stopHardware() { return true; } - s->set_framesize(s, DEFAULT_FRAME_SIZE); +// need to be call by device and by network +bool Camera::begin() { + end(); + log_esp3d("Begin camera"); + if (!_initialised) { + log_esp3d("Init hardware not done"); + return false; + } + log_esp3d("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 + if (s->id.PID == OV3660_PID) { + s->set_brightness(s, 1); // up the blightness just a bit + s->set_saturation(s, -2); // lower the saturation + } + + s->set_framesize(s, DEFAULT_FRAME_SIZE); #if defined(CAMERA_DEVICE_FLIP_HORIZONTALY) - s->set_hmirror(s, 1); -#endif //CAMERA_DEVICE_FLIP_HORIZONTALY + s->set_hmirror(s, 1); +#endif // CAMERA_DEVICE_FLIP_HORIZONTALY #if defined(CAMERA_DEVICE_FLIP_VERTICALY) - s->set_vflip(s, 1); -#endif //CAMERA_DEVICE_FLIP_VERTICALY - } else { - log_esp3d("Cannot access camera sensor"); - } - _started = _initialised; - return _started; + s->set_vflip(s, 1); +#endif // CAMERA_DEVICE_FLIP_VERTICALY + } else { + log_esp3d("Cannot access camera sensor"); + } + _started = _initialised; + return _started; } -void Camera::end() -{ - _started = false; +void Camera::end() { _started = false; } + +void Camera::handle() { + // nothing to do } -void Camera::handle() -{ - //nothing to do -} +uint8_t Camera::GetModel() { return CAMERA_DEVICE; } -uint8_t Camera::GetModel() -{ - return CAMERA_DEVICE; -} - -const char *Camera::GetModelString() -{ +const char *Camera::GetModelString() { #if defined(CUSTOM_CAMERA_NAME) - return CUSTOM_CAMERA_NAME; + return CUSTOM_CAMERA_NAME; #else - switch(CAMERA_DEVICE) { + switch (CAMERA_DEVICE) { case CAMERA_MODEL_WROVER_KIT: - return "WROVER Kit"; - break; + return "WROVER Kit"; + break; case CAMERA_MODEL_ESP32S3_EYE: case CAMERA_MODEL_ESP_EYE: - return "ESP Eye"; - break; + return "ESP Eye"; + break; case CAMERA_MODEL_M5STACK_WIDE: case CAMERA_MODEL_M5STACK_V2_PSRAM: case CAMERA_MODEL_M5STACK_PSRAM: - return "M5Stack"; - break; + return "M5Stack"; + break; case CAMERA_MODEL_ESP32_CAM_BOARD: case CAMERA_MODEL_ESP32S2_CAM_BOARD: case CAMERA_MODEL_ESP32S3_CAM_LCD: case CAMERA_MODEL_AI_THINKER: - return "ESP32 Cam"; - break; + return "ESP32 Cam"; + break; default: - return "Unknow Camera"; - } -#endif //CUSTOM_CAMERA_NAME + return "Unknow Camera"; + } +#endif // CUSTOM_CAMERA_NAME } -#endif //CAMERA_DEVICE +#endif // CAMERA_DEVICE diff --git a/esp3d/src/modules/devices/devices_services.cpp b/esp3d/src/modules/devices/devices_services.cpp index 3332f75e..09d1a2e9 100644 --- a/esp3d/src/modules/devices/devices_services.cpp +++ b/esp3d/src/modules/devices/devices_services.cpp @@ -20,125 +20,122 @@ #include "../../include/esp3d_config.h" #ifdef CONNECTED_DEVICES_FEATURE -#include "devices_services.h" -#include "../../core/settings_esp3d.h" #include "../../core/esp3doutput.h" +#include "../../core/settings_esp3d.h" +#include "devices_services.h" #ifdef DISPLAY_DEVICE #include "../display/display.h" -#endif //DISPLAY_DEVICE +#endif // DISPLAY_DEVICE #ifdef SENSOR_DEVICE #include "../sensor/sensor.h" -#endif //SENSOR_DEVICE +#endif // SENSOR_DEVICE #ifdef BUZZER_DEVICE #include "../buzzer/buzzer.h" -#endif //BUZZER_DEVICE +#endif // BUZZER_DEVICE #ifdef RECOVERY_FEATURE #include "../recovery/recovery_service.h" -#endif //RECOVERY_FEATURE +#endif // RECOVERY_FEATURE #ifdef CAMERA_DEVICE #include "../camera/camera.h" -#endif //CAMERA_DEVICE +#endif // CAMERA_DEVICE #ifdef SD_DEVICE #include "../filesystem/esp_sd.h" -#endif //SD_DEVICE +#endif // SD_DEVICE bool DevicesServices::_started = false; -bool DevicesServices::begin() -{ - bool res = true; - _started = false; +bool DevicesServices::begin() { + bool res = true; + _started = false; #ifdef SD_DEVICE - if (!ESP_SD::begin()) { - log_esp3d("Error sd intialization failed"); - res = false; - } -#endif //SD_DEVICE + if (!ESP_SD::begin()) { + log_esp3d_e("Error sd intialization failed"); + res = false; + } +#endif // SD_DEVICE #ifdef DISPLAY_DEVICE - if (!esp3d_display.begin()) { - log_esp3d("Error starting display device"); - res = false; - } -#endif //DISPLAY_DEVICE + if (!esp3d_display.begin()) { + log_esp3d_e("Error starting display device"); + res = false; + } +#endif // DISPLAY_DEVICE #ifdef SENSOR_DEVICE - if (!esp3d_sensor.begin()) { - log_esp3d("Error starting sensor device"); - res = false; - } -#endif //SENSOR_DEVICE + if (!esp3d_sensor.begin()) { + log_esp3d_e("Error starting sensor device"); + res = false; + } +#endif // SENSOR_DEVICE #ifdef BUZZER_DEVICE - if (!esp3d_buzzer.begin()) { - log_esp3d("Error starting buzzer device"); - res = false; - } -#endif //BUZZER_DEVICE + if (!esp3d_buzzer.begin()) { + log_esp3d_e("Error starting buzzer device"); + res = false; + } +#endif // BUZZER_DEVICE #ifdef RECOVERY_FEATURE - if (!recovery_service.begin()) { - log_esp3d("Error starting recovery service"); - res = false; - } -#endif //RECOVERY_FEATURE + if (!recovery_service.begin()) { + log_esp3d_e("Error starting recovery service"); + res = false; + } +#endif // RECOVERY_FEATURE #ifdef CAMERA_DEVICE - if (!esp3d_camera.initHardware()) { - log_esp3d("Error camera intialization failed"); - res = false; - } -#endif //CAMERA_DEVICE - if (!res) { - end(); - } - _started = res; - return _started; + if (!esp3d_camera.initHardware()) { + log_esp3d_e("Error camera intialization failed"); + res = false; + } +#endif // CAMERA_DEVICE + if (!res) { + end(); + } + _started = res; + return _started; } -void DevicesServices::end() -{ - if(!_started) { - return; - } - _started = false; +void DevicesServices::end() { + if (!_started) { + return; + } + _started = false; #ifdef SD_DEVICE - ESP_SD::end(); -#endif //SD_DEVICE + ESP_SD::end(); +#endif // SD_DEVICE #ifdef CAMERA_DEVICE - esp3d_camera.stopHardware(); -#endif //CAMERA_DEVICE + esp3d_camera.stopHardware(); +#endif // CAMERA_DEVICE #ifdef RECOVERY_FEATURE - recovery_service.end(); -#endif //RECOVERY_FEATURE + recovery_service.end(); +#endif // RECOVERY_FEATURE #ifdef BUZZER_DEVICE - esp3d_buzzer.end(); -#endif //BUZZER_DEVICE + esp3d_buzzer.end(); +#endif // BUZZER_DEVICE #ifdef DISPLAY_DEVICE - esp3d_display.end(); -#endif //DISPLAY_DEVICE + esp3d_display.end(); +#endif // DISPLAY_DEVICE #ifdef SENSOR_DEVICE - esp3d_sensor.end(); -#endif //SENSOR_DEVICE + esp3d_sensor.end(); +#endif // SENSOR_DEVICE } -void DevicesServices::handle() -{ - if (_started) { +void DevicesServices::handle() { + if (_started) { #ifdef CAMERA_DEVICE - esp3d_camera.handle(); -#endif //CAMERA_DEVICE + esp3d_camera.handle(); +#endif // CAMERA_DEVICE #ifdef DISPLAY_DEVICE - esp3d_display.handle(); -#endif //DISPLAY_DEVICE + esp3d_display.handle(); +#endif // DISPLAY_DEVICE #ifdef SENSOR_DEVICE - esp3d_sensor.handle(); -#endif //SENSOR_DEVICE + esp3d_sensor.handle(); +#endif // SENSOR_DEVICE #ifdef BUZZER_DEVICE - esp3d_buzzer.handle(); -#endif //BUZZER_DEVICE + esp3d_buzzer.handle(); +#endif // BUZZER_DEVICE #ifdef RECOVERY_FEATURE - recovery_service.handle(); -#endif //RECOVERY_FEATURE + recovery_service.handle(); +#endif // RECOVERY_FEATURE #ifdef SD_DEVICE - ESP_SD::handle(); -#endif //SD_DEVICE - } + ESP_SD::handle(); +#endif // SD_DEVICE + } } -#endif //#CONNECTED_DEVICES_FEATURE +#endif // #CONNECTED_DEVICES_FEATURE diff --git a/esp3d/src/modules/ethernet/ethconfig.cpp b/esp3d/src/modules/ethernet/ethconfig.cpp index 6f22ff8b..b9c981bd 100644 --- a/esp3d/src/modules/ethernet/ethconfig.cpp +++ b/esp3d/src/modules/ethernet/ethconfig.cpp @@ -19,33 +19,33 @@ */ #include "../../include/esp3d_config.h" -#if defined (ETH_FEATURE) +#if defined(ETH_FEATURE) #ifdef ARDUINO_ARCH_ESP32 -#include "esp_eth.h" #include "dhcpserver/dhcpserver_options.h" -#endif //ARDUINO_ARCH_ESP32 +#include "esp_eth.h" + +#endif // ARDUINO_ARCH_ESP32 #ifdef ARDUINO_ARCH_ESP8266 -#endif //ARDUINO_ARCH_ESP8266 +#endif // ARDUINO_ARCH_ESP8266 #include "../../core/esp3doutput.h" #include "../../core/settings_esp3d.h" #include "../network/netconfig.h" #include "ethconfig.h" bool EthConfig::_started = false; bool EthConfig::_connected = false; -const uint8_t DEFAULT_AP_MASK_VALUE[] = {255, 255, 255, 0}; +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); - IPAddress ip(IP), mask(MK), gateway(GW), dns(DNS); - res = ETH.config(ip, gateway,mask,dns); - } - return res; +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); + IPAddress ip(IP), mask(MK), gateway(GW), dns(DNS); + res = ETH.config(ip, gateway, mask, dns); + } + return res; } /*bool EthConfig::StartSRV() { @@ -55,7 +55,7 @@ bool EthConfig::StartSTA() IPAddress ip(IP), mask(DEFAULT_AP_MASK_VALUE), gateway(IP); if (!ETH.config(ip, gateway,mask)) { res = false; - log_esp3d("Set static IP error"); + log_esp3d_e("Set static IP error"); } //start DHCP server if(res) { @@ -72,97 +72,86 @@ bool EthConfig::StartSTA() if (tcpip_adapter_dhcps_start(TCPIP_ADAPTER_IF_ETH) != ESP_OK){ res = false; - log_esp3d("Start DHCP server failed"); + log_esp3d_e("Start DHCP server failed"); } } return res; }*/ -bool EthConfig::linkUp() -{ -#if defined( ESP_IDF_VERSION_MAJOR ) - //patch for https://github.com/espressif/arduino-esp32/issues/6105 - return _connected; +bool EthConfig::linkUp() { +#if defined(ESP_IDF_VERSION_MAJOR) + // patch for https://github.com/espressif/arduino-esp32/issues/6105 + return _connected; #else - return ETH.linkUp(); + return ETH.linkUp(); #endif } /** * begin WiFi setup */ -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"); - } - res=true; +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"); + } + res = true; + } else { + output.printERROR("Failed Starting Ethernet"); + } + 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"); + } + espMode = Settings_ESP3D::read_byte(ESP_STA_FALLBACK_MODE); + res = true; } else { - output.printERROR("Failed Starting Ethernet"); - } - 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"); - } - espMode = Settings_ESP3D::read_byte(ESP_STA_FALLBACK_MODE); - res = true; - } else { - if (Settings_ESP3D::isVerboseBoot()) { - output.printMSG ("Client started"); - } - - } - - } else { - //if(!StartSRV()){ - // res = false; - // output.printMSG ("Failed Starting Server"); - //} else { - // output.printMSG ("Server started"); - //} + if (Settings_ESP3D::isVerboseBoot()) { + output.printMSG("Client started"); + } } + } 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 == ESP_ETH_SRV)){ - if ((Settings_ESP3D::read_byte(ESP_STA_IP_MODE) != DHCP_MODE)) { - //as no event to display static IP - output.printMSG (ETH.localIP().toString().c_str()); - } + // if ((Settings_ESP3D::read_byte(ESP_STA_IP_MODE) != DHCP_MODE) || (espMode + // == ESP_ETH_SRV)){ + if ((Settings_ESP3D::read_byte(ESP_STA_IP_MODE) != DHCP_MODE)) { + // as no event to display static IP + output.printMSG(ETH.localIP().toString().c_str()); + } - return res; + return res; } /** * End WiFi */ -void EthConfig::end() -{ - //esp_eth_disable(); - _started = false; +void EthConfig::end() { + // esp_eth_disable(); + _started = false; } -bool EthConfig::started() -{ - return _started; -} +bool EthConfig::started() { return _started; } /** * Handle not critical actions that must be done in sync environement */ -void EthConfig::handle() -{ -} - - -#endif // ETH_FEATURE +void EthConfig::handle() {} +#endif // ETH_FEATURE diff --git a/esp3d/src/modules/filesystem/esp_globalFS.cpp b/esp3d/src/modules/filesystem/esp_globalFS.cpp index 1cdeea1a..708ee5cf 100644 --- a/esp3d/src/modules/filesystem/esp_globalFS.cpp +++ b/esp3d/src/modules/filesystem/esp_globalFS.cpp @@ -17,791 +17,752 @@ 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_DEBUG_FEATURE DEBUG_OUTPUT_SERIAL0 +// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 #include "../../include/esp3d_config.h" #if defined(GLOBAL_FILESYSTEM_FEATURE) #include "esp_globalFS.h" -//to verify FS is accessible -bool ESP_GBFS::isavailable(uint8_t FS) -{ +// to verify FS is accessible +bool ESP_GBFS::isavailable(uint8_t FS) { #ifdef FILESYSTEM_FEATURE - if(FS == FS_FLASH) { - return ESP_FileSystem::started(); - } -#endif //FILESYSTEM_FEATURE + if (FS == FS_FLASH) { + return ESP_FileSystem::started(); + } +#endif // FILESYSTEM_FEATURE #ifdef SD_DEVICE - if(FS == FS_SD) { - return (ESP_SD::getState(true) == ESP_SDCARD_IDLE); - } -#endif //SD_DEVICE - return false; + if (FS == FS_SD) { + return (ESP_SD::getState(true) == ESP_SDCARD_IDLE); + } +#endif // SD_DEVICE + return false; } 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; +// 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) -{ +// depending FS +uint64_t ESP_GBFS::totalBytes(uint8_t FS) { #ifdef FILESYSTEM_FEATURE - if(FS == FS_FLASH) { - return ESP_FileSystem::totalBytes(); - } -#endif //FILESYSTEM_FEATURE + if (FS == FS_FLASH) { + return ESP_FileSystem::totalBytes(); + } +#endif // FILESYSTEM_FEATURE #ifdef SD_DEVICE - if(FS == FS_SD) { - return ESP_SD::totalBytes(); - } -#endif //SD_DEVICE - return 0; + if (FS == FS_SD) { + return ESP_SD::totalBytes(); + } +#endif // SD_DEVICE + return 0; } -uint64_t ESP_GBFS::usedBytes(uint8_t FS) -{ +uint64_t ESP_GBFS::usedBytes(uint8_t FS) { #ifdef FILESYSTEM_FEATURE - if(FS == FS_FLASH) { - return ESP_FileSystem::usedBytes(); - } -#endif //FILESYSTEM_FEATURE + if (FS == FS_FLASH) { + return ESP_FileSystem::usedBytes(); + } +#endif // FILESYSTEM_FEATURE #ifdef SD_DEVICE - if(FS == FS_SD) { - return ESP_SD::usedBytes(); - } -#endif //SD_DEVICE - return 0; + if (FS == FS_SD) { + return ESP_SD::usedBytes(); + } +#endif // SD_DEVICE + return 0; } -uint ESP_GBFS::maxPathLength() -{ - uint size = 255; +uint ESP_GBFS::maxPathLength() { + uint size = 255; #ifdef FILESYSTEM_FEATURE - if(size >32) { - size =32; - } -#endif //FILESYSTEM_FEATURE + if (size > 32) { + size = 32; + } +#endif // FILESYSTEM_FEATURE #ifdef SD_DEVICE - if(size >255) { - size =255; - } -#endif //SD_DEVICE - return size; + if (size > 255) { + size = 255; + } +#endif // SD_DEVICE + return size; } -bool ESP_GBFS::accessFS(uint8_t FS) -{ - if(FS == FS_ROOT) { - return true; - } +bool ESP_GBFS::accessFS(uint8_t FS) { + if (FS == FS_ROOT) { + return true; + } #ifdef FILESYSTEM_FEATURE - if(FS == FS_FLASH) { - return ESP_FileSystem::accessFS(); - } -#endif //FILESYSTEM_FEATURE + if (FS == FS_FLASH) { + return ESP_FileSystem::accessFS(); + } +#endif // FILESYSTEM_FEATURE #ifdef SD_DEVICE - if(FS == FS_SD) { - bool canAccess = ESP_SD::accessFS(); - if(canAccess) { - if (ESP_SD::getState(true) == ESP_SDCARD_NOT_PRESENT) { - canAccess = false; - ESP_SD::releaseFS(); - } else { - ESP_SD::setState(ESP_SDCARD_BUSY ); - canAccess = true; - } - - } - return canAccess; - } -#endif //SD_DEVICE - return false; -} -void ESP_GBFS::releaseFS(uint8_t FS) -{ -#ifdef FILESYSTEM_FEATURE - if(FS == FS_FLASH) { - ESP_FileSystem::releaseFS(); - } -#endif //FILESYSTEM_FEATURE -#ifdef SD_DEVICE - if(FS == FS_SD) { + if (FS == FS_SD) { + bool canAccess = ESP_SD::accessFS(); + if (canAccess) { + if (ESP_SD::getState(true) == ESP_SDCARD_NOT_PRESENT) { + canAccess = false; ESP_SD::releaseFS(); + } else { + ESP_SD::setState(ESP_SDCARD_BUSY); + canAccess = true; + } } -#endif //SD_DEVICE + return canAccess; + } +#endif // SD_DEVICE + return false; } - -uint64_t ESP_GBFS::freeBytes(uint8_t FS) -{ +void ESP_GBFS::releaseFS(uint8_t FS) { #ifdef FILESYSTEM_FEATURE - if(FS == FS_FLASH) { - return ESP_FileSystem::freeBytes(); - } -#endif //FILESYSTEM_FEATURE + if (FS == FS_FLASH) { + ESP_FileSystem::releaseFS(); + } +#endif // FILESYSTEM_FEATURE #ifdef SD_DEVICE - if(FS == FS_SD) { - return ESP_SD::freeBytes(); - } -#endif //SD_DEVICE - return 0; + if (FS == FS_SD) { + ESP_SD::releaseFS(); + } +#endif // SD_DEVICE } -//Format is not always available for all FS -bool format(uint8_t FS, ESP3DOutput * output = nullptr) -{ +uint64_t ESP_GBFS::freeBytes(uint8_t FS) { #ifdef FILESYSTEM_FEATURE - if(FS == FS_FLASH) { - return ESP_FileSystem::format(); - } -#endif //FILESYSTEM_FEATURE + if (FS == FS_FLASH) { + return ESP_FileSystem::freeBytes(); + } +#endif // FILESYSTEM_FEATURE #ifdef SD_DEVICE - if(FS == FS_SD) { - return ESP_SD::format(output); + if (FS == FS_SD) { + return ESP_SD::freeBytes(); + } +#endif // SD_DEVICE + return 0; +} + +// Format is not always available for all FS +bool format(uint8_t FS, ESP3DOutput *output = nullptr) { +#ifdef FILESYSTEM_FEATURE + if (FS == FS_FLASH) { + return ESP_FileSystem::format(); + } +#endif // FILESYSTEM_FEATURE +#ifdef SD_DEVICE + if (FS == FS_SD) { + return ESP_SD::format(output); + } +#endif // SD_DEVICE + output->printERROR("Not available"); + return false; +} + +// check type of FS according root dir +uint8_t ESP_GBFS::getFSType(const char *path) { + String p = path; + p.trim(); + if (p == "/") { + return FS_ROOT; + } +#if defined(FILESYSTEM_FEATURE) + if (p.startsWith(ESP_FLASH_FS_HEADER)) { + return FS_FLASH; + } +#endif // FILESYSTEM_FEATURE +#if defined(SD_DEVICE) + if (p.startsWith(ESP_SD_FS_HEADER)) { + return FS_SD; + } +#endif // SD_DEVICE + return FS_UNKNOWN; +} + +const char *ESP_GBFS::getRealPath(const char *path) { + static String p; + uint8_t t = getFSType(path); + p = ""; +#if defined(FILESYSTEM_FEATURE) + if (t == FS_FLASH) { + p = path; + // remove header + p.remove(0, strlen(ESP_FLASH_FS_HEADER)); + // if nothing it is root + if (p.length() == 0) { + p = "/"; } -#endif //SD_DEVICE - output->printERROR("Not available"); + } +#endif // FILESYSTEM_FEATURE +#if defined(SD_DEVICE) + if (t == FS_SD) { + p = path; + // remove header + p.remove(0, strlen(ESP_SD_FS_HEADER)); + // if nothing it is root + if (p.length() == 0) { + p = "/"; + } + } +#endif // SD_DEVICE + return p.c_str(); +} + +// path exists on / or SD or FS +bool ESP_GBFS::exists(const char *path) { +#if defined(FILESYSTEM_FEATURE) || defined(SD_DEVICE) + uint8_t t = getFSType(path); + if (t == FS_ROOT) { + return true; + } +#if defined(FILESYSTEM_FEATURE) + if (t == FS_FLASH) { + return ESP_FileSystem::exists(getRealPath(path)); + } +#endif // FILESYSTEM_FEATURE +#if defined(SD_DEVICE) + if (t == FS_SD) { + return ESP_SD::exists(getRealPath(path)); + } +#endif // SD_DEVICE +#endif // FILESYSTEM_FEATURE || SD_DEVICE + return false; +} + +bool ESP_GBFS::remove(const char *path) { +#if defined(FILESYSTEM_FEATURE) || defined(SD_DEVICE) + uint8_t t = getFSType(path); + if (t == FS_ROOT) { return false; + } +#if defined(FILESYSTEM_FEATURE) + if (t == FS_FLASH) { + return ESP_FileSystem::remove(getRealPath(path)); + } +#endif // FILESYSTEM_FEATURE +#if defined(SD_DEVICE) + if (t == FS_SD) { + return ESP_SD::remove(getRealPath(path)); + } +#endif // SD_DEVICE +#endif // FILESYSTEM_FEATURE || SD_DEVICE + return false; } -//check type of FS according root dir -uint8_t ESP_GBFS::getFSType(const char * path) -{ - String p = path; - p.trim(); - if (p == "/") { - return FS_ROOT; - } -#if defined (FILESYSTEM_FEATURE) - if (p.startsWith(ESP_FLASH_FS_HEADER)) { - return FS_FLASH; - } -#endif //FILESYSTEM_FEATURE -#if defined (SD_DEVICE) - if (p.startsWith(ESP_SD_FS_HEADER)) { - return FS_SD; - } -#endif //SD_DEVICE - return FS_UNKNOWN; -} - -const char * ESP_GBFS::getRealPath(const char * path) -{ - static String p; - uint8_t t = getFSType(path); - p = ""; -#if defined (FILESYSTEM_FEATURE) - if (t == FS_FLASH) { - p = path; - //remove header - p.remove(0,strlen(ESP_FLASH_FS_HEADER)); - //if nothing it is root - if (p.length() == 0) { - p = "/"; - } - } -#endif //FILESYSTEM_FEATURE -#if defined (SD_DEVICE) - if (t == FS_SD) { - p = path; - //remove header - p.remove(0,strlen(ESP_SD_FS_HEADER)); - //if nothing it is root - if (p.length() == 0) { - p = "/"; - } - } -#endif //SD_DEVICE - return p.c_str(); -} - -//path exists on / or SD or FS -bool ESP_GBFS::exists(const char* path) -{ -#if defined (FILESYSTEM_FEATURE) || defined(SD_DEVICE) - uint8_t t = getFSType(path); - if (t == FS_ROOT) { - return true; - } -#if defined (FILESYSTEM_FEATURE) - if (t == FS_FLASH) { - return ESP_FileSystem::exists(getRealPath(path)); - } -#endif //FILESYSTEM_FEATURE -#if defined (SD_DEVICE) - if (t == FS_SD) { - return ESP_SD::exists(getRealPath(path)); - } -#endif //SD_DEVICE -#endif // FILESYSTEM_FEATURE || SD_DEVICE +bool ESP_GBFS::rename(const char *oldpath, const char *newpath) { + log_esp3d("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"); 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()); + 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()); + 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"); + return false; } -bool ESP_GBFS::remove(const char *path) -{ -#if defined (FILESYSTEM_FEATURE) || defined(SD_DEVICE) - uint8_t t = getFSType(path); - if (t == FS_ROOT) { - return false; - } -#if defined (FILESYSTEM_FEATURE) - if (t == FS_FLASH) { - return ESP_FileSystem::remove(getRealPath(path)); - } -#endif //FILESYSTEM_FEATURE -#if defined (SD_DEVICE) - if (t == FS_SD) { - return ESP_SD::remove(getRealPath(path)); - } -#endif //SD_DEVICE -#endif // FILESYSTEM_FEATURE || SD_DEVICE +bool ESP_GBFS::mkdir(const char *path) { +#if defined(FILESYSTEM_FEATURE) || defined(SD_DEVICE) + uint8_t t = getFSType(path); + if (t == FS_ROOT) { return false; + } +#if defined(FILESYSTEM_FEATURE) + if (t == FS_FLASH) { + return ESP_FileSystem::mkdir(getRealPath(path)); + ; + } +#endif // FILESYSTEM_FEATURE +#if defined(SD_DEVICE) + if (t == FS_SD) { + return ESP_SD::mkdir(getRealPath(path)); + } +#endif // SD_DEVICE +#endif // FILESYSTEM_FEATURE || SD_DEVICE + return false; } -bool ESP_GBFS::rename(const char *oldpath, const char *newpath) -{ -#if defined (FILESYSTEM_FEATURE) || defined(SD_DEVICE) - uint8_t t = getFSType(oldpath); - if (t == FS_ROOT) { - return false; - } -#if defined (FILESYSTEM_FEATURE) - if (t == FS_FLASH) { - return ESP_FileSystem::rename(getRealPath(oldpath), getRealPath(newpath)); - } -#endif //FILESYSTEM_FEATURE -#if defined (SD_DEVICE) - if (t == FS_SD) { - return ESP_SD::rename(getRealPath(oldpath), getRealPath(newpath)); - } -#endif //SD_DEVICE -#endif // FILESYSTEM_FEATURE || SD_DEVICE +bool ESP_GBFS::rmdir(const char *path) { +#if defined(FILESYSTEM_FEATURE) || defined(SD_DEVICE) + uint8_t t = getFSType(path); + if (t == FS_ROOT) { return false; + } +#if defined(FILESYSTEM_FEATURE) + if (t == FS_FLASH) { + return ESP_FileSystem::rmdir(getRealPath(path)); + } +#endif // FILESYSTEM_FEATURE +#if defined(SD_DEVICE) + if (t == FS_SD) { + return ESP_SD::rmdir(getRealPath(path)); + ; + } +#endif // SD_DEVICE +#endif // FILESYSTEM_FEATURE || SD_DEVICE + return false; } -bool ESP_GBFS::mkdir(const char *path) -{ -#if defined (FILESYSTEM_FEATURE) || defined(SD_DEVICE) - uint8_t t = getFSType(path); - if (t == FS_ROOT) { - return false; - } -#if defined (FILESYSTEM_FEATURE) - if (t == FS_FLASH) { - return ESP_FileSystem::mkdir(getRealPath(path));; - } -#endif //FILESYSTEM_FEATURE -#if defined (SD_DEVICE) - if (t == FS_SD) { - return ESP_SD::mkdir(getRealPath(path)); - } -#endif //SD_DEVICE -#endif // FILESYSTEM_FEATURE || SD_DEVICE - return false; +void ESP_GBFS::closeAll() { + getNextFS(true); +#if defined(FILESYSTEM_FEATURE) + ESP_FileSystem::closeAll(); +#endif // FILESYSTEM_FEATURE +#if defined(SD_DEVICE) + ESP_SD::closeAll(); +#endif // SD_DEVICE } -bool ESP_GBFS::rmdir(const char *path) -{ -#if defined (FILESYSTEM_FEATURE) || defined(SD_DEVICE) - uint8_t t = getFSType(path); - if (t == FS_ROOT) { - return false; - } -#if defined (FILESYSTEM_FEATURE) - if (t == FS_FLASH) { - return ESP_FileSystem::rmdir(getRealPath(path)); - } -#endif //FILESYSTEM_FEATURE -#if defined (SD_DEVICE) - if (t == FS_SD) { - return ESP_SD::rmdir(getRealPath(path));; - } -#endif //SD_DEVICE -#endif // FILESYSTEM_FEATURE || SD_DEVICE - return false; -} - -void ESP_GBFS::closeAll() -{ +ESP_GBFile ESP_GBFS::open(const char *path, uint8_t mode) { + ESP_GBFile f; + log_esp3d("open %s", path); +#if defined(FILESYSTEM_FEATURE) || defined(SD_DEVICE) + uint8_t t = getFSType(path); + log_esp3d("type %d", t); + if ((t == FS_ROOT) && (mode == ESP_FILE_READ)) { + f = ESP_GBFile(FS_ROOT, "/"); + log_esp3d("root"); getNextFS(true); -#if defined (FILESYSTEM_FEATURE) - ESP_FileSystem::closeAll(); -#endif //FILESYSTEM_FEATURE -#if defined (SD_DEVICE) - ESP_SD::closeAll(); -#endif //SD_DEVICE + } +#if defined(FILESYSTEM_FEATURE) + if (t == FS_FLASH) { + log_esp3d("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)); + f = ESP_SD::open(getRealPath(path), mode); + } +#endif // SD_DEVICE +#endif // FILESYSTEM_FEATURE || SD_DEVICE + return f; } -ESP_GBFile ESP_GBFS::open(const char* path, uint8_t mode) -{ - ESP_GBFile f; - log_esp3d("open %s", path); -#if defined (FILESYSTEM_FEATURE) || defined(SD_DEVICE) - uint8_t t = getFSType(path); - log_esp3d("type %d", t); - if ((t == FS_ROOT) && (mode == ESP_FILE_READ)) { - f = ESP_GBFile(FS_ROOT,"/" ); - log_esp3d("root"); - getNextFS(true); - } -#if defined (FILESYSTEM_FEATURE) - if (t == FS_FLASH) { - log_esp3d("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)); - f = ESP_SD::open(getRealPath(path), mode); - } -#endif //SD_DEVICE -#endif // FILESYSTEM_FEATURE || SD_DEVICE - return f; +// Default File is no file +ESP_GBFile::ESP_GBFile() { _type = FS_UNKNOWN; } + +// File handle for the root +ESP_GBFile::ESP_GBFile(uint8_t FS, const char *name) { + _type = FS; + _name = name; } - -//Default File is no file -ESP_GBFile::ESP_GBFile() -{ - _type = FS_UNKNOWN; -} - -//File handle for the root -ESP_GBFile::ESP_GBFile(uint8_t FS, const char *name) -{ - _type = FS; - _name = name; -} - -//Handle for flash file +// Handle for flash file #ifdef FILESYSTEM_FEATURE -ESP_GBFile::ESP_GBFile(ESP_File & flashFile) -{ - _type = FS_FLASH; - _flashFile = flashFile; +ESP_GBFile::ESP_GBFile(ESP_File &flashFile) { + _type = FS_FLASH; + _flashFile = flashFile; #ifdef SD_DEVICE - _sdFile = ESP_SDFile(); -#endif //SD_DEVICE + _sdFile = ESP_SDFile(); +#endif // SD_DEVICE } -#endif //FILESYSTEM_FEATURE +#endif // FILESYSTEM_FEATURE -//Handle for SD file +// Handle for SD file #ifdef SD_DEVICE -ESP_GBFile::ESP_GBFile(ESP_SDFile & sdFile) -{ - _type = FS_SD; - _sdFile = sdFile; +ESP_GBFile::ESP_GBFile(ESP_SDFile &sdFile) { + _type = FS_SD; + _sdFile = sdFile; #ifdef FILESYSTEM_FEATURE - _flashFile = ESP_File(); -#endif //FILESYSTEM_FEATURE + _flashFile = ESP_File(); +#endif // FILESYSTEM_FEATURE } -#endif //SD_DEVICE +#endif // SD_DEVICE -//Destructor -ESP_GBFile::~ESP_GBFile() -{ -} +// Destructor +ESP_GBFile::~ESP_GBFile() {} -ESP_GBFile::operator bool() const -{ +ESP_GBFile::operator bool() const { #if defined(FILESYSTEM_FEATURE) || defined(SD_DEVICE) - if (_type == FS_ROOT) { - return true; - } -#endif //FILESYSTEM_FEATURE || SD_DEVICE + if (_type == FS_ROOT) { + return true; + } +#endif // FILESYSTEM_FEATURE || SD_DEVICE #ifdef FILESYSTEM_FEATURE - if (_type == FS_FLASH) { - return _flashFile; - } -#endif //FILESYSTEM_FEATURE + if (_type == FS_FLASH) { + return _flashFile; + } +#endif // FILESYSTEM_FEATURE #ifdef SD_DEVICE - if (_type == FS_SD) { - return _sdFile; - } -#endif //SD_DEVICE + if (_type == FS_SD) { + return _sdFile; + } +#endif // SD_DEVICE + return false; +} + +bool ESP_GBFile::seek(uint32_t pos, uint8_t mode) { +#if defined(FILESYSTEM_FEATURE) || defined(SD_DEVICE) + if (_type == FS_ROOT) { return false; + } +#endif // FILESYSTEM_FEATURE || SD_DEVICE +#ifdef FILESYSTEM_FEATURE + if (_type == FS_FLASH) { + _flashFile.seek(pos, mode); + } +#endif // FILESYSTEM_FEATURE +#ifdef SD_DEVICE + if (_type == FS_SD) { + return _sdFile.seek(pos, mode); + } +#endif // SD_DEVICE + return false; } -bool ESP_GBFile::seek(uint32_t pos, uint8_t mode) -{ +void ESP_GBFile::close() { #if defined(FILESYSTEM_FEATURE) || defined(SD_DEVICE) - if (_type == FS_ROOT) { - return false; - } -#endif //FILESYSTEM_FEATURE || SD_DEVICE + if (_type == FS_ROOT) { + // TBD + } +#endif // FILESYSTEM_FEATURE || SD_DEVICE #ifdef FILESYSTEM_FEATURE - if (_type == FS_FLASH) { - _flashFile.seek(pos,mode); - } -#endif //FILESYSTEM_FEATURE + if (_type == FS_FLASH) { + _flashFile.close(); + } +#endif // FILESYSTEM_FEATURE #ifdef SD_DEVICE - if (_type == FS_SD) { - return _sdFile.seek(pos,mode); - } -#endif //SD_DEVICE - return false; + if (_type == FS_SD) { + return _sdFile.close(); + } +#endif // SD_DEVICE } -void ESP_GBFile::close() -{ +bool ESP_GBFile::isOpen() { #if defined(FILESYSTEM_FEATURE) || defined(SD_DEVICE) - if (_type == FS_ROOT) { - //TBD - } -#endif //FILESYSTEM_FEATURE || SD_DEVICE + if (_type == FS_ROOT) { + return true; + } +#endif // FILESYSTEM_FEATURE || SD_DEVICE #ifdef FILESYSTEM_FEATURE - if (_type == FS_FLASH) { - _flashFile.close(); - } -#endif //FILESYSTEM_FEATURE + if (_type == FS_FLASH) { + return _flashFile.isOpen(); + } +#endif // FILESYSTEM_FEATURE #ifdef SD_DEVICE - if (_type == FS_SD) { - return _sdFile.close(); - } -#endif //SD_DEVICE + if (_type == FS_SD) { + return _sdFile.isOpen(); + } +#endif // SD_DEVICE + return false; } -bool ESP_GBFile::isOpen() -{ +const char *ESP_GBFile::name() const { + static String s; #if defined(FILESYSTEM_FEATURE) || defined(SD_DEVICE) - if (_type == FS_ROOT) { - return true; - } -#endif //FILESYSTEM_FEATURE || SD_DEVICE + if (_type == FS_ROOT) { + return _name.c_str(); + } +#endif // FILESYSTEM_FEATURE || SD_DEVICE #ifdef FILESYSTEM_FEATURE - if (_type == FS_FLASH) { - return _flashFile.isOpen(); + if (_type == FS_FLASH) { + if (strcmp(_flashFile.name(), "/") == 0) { + s = ESP_FLASH_FS_HEADER; + s.remove(0, 1); + return s.c_str(); } -#endif //FILESYSTEM_FEATURE + return _flashFile.name(); + } +#endif // FILESYSTEM_FEATURE #ifdef SD_DEVICE - if (_type == FS_SD) { - return _sdFile.isOpen(); + if (_type == FS_SD) { + if (strcmp(_sdFile.name(), "/") == 0) { + s = ESP_SD_FS_HEADER; + s.remove(0, 1); + return s.c_str(); } -#endif //SD_DEVICE - return false; + return _sdFile.name(); + } +#endif // SD_DEVICE + return ""; } -const char* ESP_GBFile::name() const -{ - static String s; +const char *ESP_GBFile::filename() const { #if defined(FILESYSTEM_FEATURE) || defined(SD_DEVICE) - if (_type == FS_ROOT) { - return _name.c_str(); - } -#endif //FILESYSTEM_FEATURE || SD_DEVICE + static String s; + if (_type == FS_ROOT) { + return "/"; + } +#endif // FILESYSTEM_FEATURE || SD_DEVICE #ifdef FILESYSTEM_FEATURE - if (_type == FS_FLASH) { - if (strcmp(_flashFile.name(), "/") == 0) { - s = ESP_FLASH_FS_HEADER; - s.remove(0,1); - return s.c_str(); - } - return _flashFile.name(); - } -#endif //FILESYSTEM_FEATURE + if (_type == FS_FLASH) { + s = ESP_FLASH_FS_HEADER; + s += _flashFile.filename(); + return s.c_str(); + } +#endif // FILESYSTEM_FEATURE #ifdef SD_DEVICE - if (_type == FS_SD) { - if (strcmp(_sdFile.name(), "/") == 0) { - s = ESP_SD_FS_HEADER; - s.remove(0,1); - return s.c_str(); - } - return _sdFile.name(); - } -#endif //SD_DEVICE - return ""; + if (_type == FS_SD) { + s = ESP_SD_FS_HEADER; + s += s += _sdFile.filename(); + return s.c_str(); + } +#endif // SD_DEVICE + return ""; } -const char* ESP_GBFile::filename() const -{ +bool ESP_GBFile::isDirectory() { #if defined(FILESYSTEM_FEATURE) || defined(SD_DEVICE) - static String s; - if (_type == FS_ROOT) { - return "/"; - } -#endif //FILESYSTEM_FEATURE || SD_DEVICE + if (_type == FS_ROOT) { + return true; + } +#endif // FILESYSTEM_FEATURE || SD_DEVICE #ifdef FILESYSTEM_FEATURE - if (_type == FS_FLASH) { - s = ESP_FLASH_FS_HEADER; - s += _flashFile.filename(); - return s.c_str(); - } -#endif //FILESYSTEM_FEATURE + if (_type == FS_FLASH) { + return _flashFile.isDirectory(); + } +#endif // FILESYSTEM_FEATURE #ifdef SD_DEVICE - if (_type == FS_SD) { - s = ESP_SD_FS_HEADER; - s += s += _sdFile.filename(); - return s.c_str(); - } -#endif //SD_DEVICE - return ""; + if (_type == FS_SD) { + return _sdFile.isDirectory(); + } +#endif // SD_DEVICE + return false; } -bool ESP_GBFile::isDirectory() -{ +size_t ESP_GBFile::size() { #if defined(FILESYSTEM_FEATURE) || defined(SD_DEVICE) - if (_type == FS_ROOT) { - return true; - } -#endif //FILESYSTEM_FEATURE || SD_DEVICE -#ifdef FILESYSTEM_FEATURE - if (_type == FS_FLASH) { - return _flashFile.isDirectory(); - } -#endif //FILESYSTEM_FEATURE -#ifdef SD_DEVICE - if (_type == FS_SD) { - return _sdFile.isDirectory(); - } -#endif //SD_DEVICE - return false; -} - -size_t ESP_GBFile::size() -{ -#if defined(FILESYSTEM_FEATURE) || defined(SD_DEVICE) - if (_type == FS_ROOT) { - return 0; - } -#endif //FILESYSTEM_FEATURE || SD_DEVICE -#ifdef FILESYSTEM_FEATURE - if (_type == FS_FLASH) { - return _flashFile.size(); - } -#endif //FILESYSTEM_FEATURE -#ifdef SD_DEVICE - if (_type == FS_SD) { - return _sdFile.size(); - } -#endif //SD_DEVICE + if (_type == FS_ROOT) { return 0; -} - -time_t ESP_GBFile::getLastWrite() -{ - if (_type == FS_FLASH) { - return _flashFile.getLastWrite(); - } -#ifdef SD_DEVICE - if (_type == FS_SD) { - return _sdFile.getLastWrite(); - } -#endif //SD_DEVICE - return 0; -} - -int ESP_GBFile::available() -{ -#if defined(FILESYSTEM_FEATURE) || defined(SD_DEVICE) - if (_type == FS_ROOT) { - return 0; - } -#endif //FILESYSTEM_FEATURE || SD_DEVICE + } +#endif // FILESYSTEM_FEATURE || SD_DEVICE #ifdef FILESYSTEM_FEATURE - if (_type == FS_FLASH) { - return _flashFile.available(); - } -#endif //FILESYSTEM_FEATURE + if (_type == FS_FLASH) { + return _flashFile.size(); + } +#endif // FILESYSTEM_FEATURE #ifdef SD_DEVICE - if (_type == FS_SD) { - return _sdFile.available(); - } -#endif //SD_DEVICE - return 0; + if (_type == FS_SD) { + return _sdFile.size(); + } +#endif // SD_DEVICE + return 0; } -size_t ESP_GBFile::write(uint8_t i) -{ -#if defined(FILESYSTEM_FEATURE) || defined(SD_DEVICE) - if (_type == FS_ROOT) { - return 0; - } -#endif //FILESYSTEM_FEATURE || SD_DEVICE -#ifdef FILESYSTEM_FEATURE - if (_type == FS_FLASH) { - return _flashFile.write(i); - } -#endif //FILESYSTEM_FEATURE +time_t ESP_GBFile::getLastWrite() { + if (_type == FS_FLASH) { + return _flashFile.getLastWrite(); + } #ifdef SD_DEVICE - if (_type == FS_SD) { - return _sdFile.write(i); - } -#endif //SD_DEVICE - return 0; + if (_type == FS_SD) { + return _sdFile.getLastWrite(); + } +#endif // SD_DEVICE + return 0; } -size_t ESP_GBFile::write(const uint8_t *buf, size_t size) -{ +int ESP_GBFile::available() { #if defined(FILESYSTEM_FEATURE) || defined(SD_DEVICE) - if (_type == FS_ROOT) { - return 0; - } -#endif //FILESYSTEM_FEATURE || SD_DEVICE -#ifdef FILESYSTEM_FEATURE - if (_type == FS_FLASH) { - return _flashFile.write(buf, size); - } -#endif //FILESYSTEM_FEATURE -#ifdef SD_DEVICE - if (_type == FS_SD) { - return _sdFile.write(buf, size); - } -#endif //SD_DEVICE + if (_type == FS_ROOT) { return 0; + } +#endif // FILESYSTEM_FEATURE || SD_DEVICE +#ifdef FILESYSTEM_FEATURE + if (_type == FS_FLASH) { + return _flashFile.available(); + } +#endif // FILESYSTEM_FEATURE +#ifdef SD_DEVICE + if (_type == FS_SD) { + return _sdFile.available(); + } +#endif // SD_DEVICE + return 0; } -int ESP_GBFile::read() -{ +size_t ESP_GBFile::write(uint8_t i) { #if defined(FILESYSTEM_FEATURE) || defined(SD_DEVICE) - if (_type == FS_ROOT) { - return -1; - } -#endif //FILESYSTEM_FEATURE || SD_DEVICE + if (_type == FS_ROOT) { + return 0; + } +#endif // FILESYSTEM_FEATURE || SD_DEVICE #ifdef FILESYSTEM_FEATURE - if (_type == FS_FLASH) { - return _flashFile.read(); - } -#endif //FILESYSTEM_FEATURE + if (_type == FS_FLASH) { + return _flashFile.write(i); + } +#endif // FILESYSTEM_FEATURE #ifdef SD_DEVICE - if (_type == FS_SD) { - return _sdFile.read(); - } -#endif //SD_DEVICE + if (_type == FS_SD) { + return _sdFile.write(i); + } +#endif // SD_DEVICE + return 0; +} + +size_t ESP_GBFile::write(const uint8_t *buf, size_t size) { +#if defined(FILESYSTEM_FEATURE) || defined(SD_DEVICE) + if (_type == FS_ROOT) { + return 0; + } +#endif // FILESYSTEM_FEATURE || SD_DEVICE +#ifdef FILESYSTEM_FEATURE + if (_type == FS_FLASH) { + return _flashFile.write(buf, size); + } +#endif // FILESYSTEM_FEATURE +#ifdef SD_DEVICE + if (_type == FS_SD) { + return _sdFile.write(buf, size); + } +#endif // SD_DEVICE + return 0; +} + +int ESP_GBFile::read() { +#if defined(FILESYSTEM_FEATURE) || defined(SD_DEVICE) + if (_type == FS_ROOT) { return -1; + } +#endif // FILESYSTEM_FEATURE || SD_DEVICE +#ifdef FILESYSTEM_FEATURE + if (_type == FS_FLASH) { + return _flashFile.read(); + } +#endif // FILESYSTEM_FEATURE +#ifdef SD_DEVICE + if (_type == FS_SD) { + return _sdFile.read(); + } +#endif // SD_DEVICE + return -1; } -size_t ESP_GBFile::read(uint8_t* buf, size_t size) -{ +size_t ESP_GBFile::read(uint8_t *buf, size_t size) { #if defined(FILESYSTEM_FEATURE) || defined(SD_DEVICE) - if (_type == FS_ROOT) { - return -1; - } -#endif //FILESYSTEM_FEATURE || SD_DEVICE -#ifdef FILESYSTEM_FEATURE - if (_type == FS_FLASH) { - return _flashFile.read(buf, size); - } -#endif //FILESYSTEM_FEATURE -#ifdef SD_DEVICE - if (_type == FS_SD) { - return _sdFile.read(buf, size); - } -#endif //SD_DEVICE + if (_type == FS_ROOT) { return -1; + } +#endif // FILESYSTEM_FEATURE || SD_DEVICE +#ifdef FILESYSTEM_FEATURE + if (_type == FS_FLASH) { + return _flashFile.read(buf, size); + } +#endif // FILESYSTEM_FEATURE +#ifdef SD_DEVICE + if (_type == FS_SD) { + return _sdFile.read(buf, size); + } +#endif // SD_DEVICE + return -1; } -void ESP_GBFile::flush() -{ +void ESP_GBFile::flush() { #ifdef FILESYSTEM_FEATURE - if (_type == FS_FLASH) { - return _flashFile.flush(); - } -#endif //FILESYSTEM_FEATURE + if (_type == FS_FLASH) { + return _flashFile.flush(); + } +#endif // FILESYSTEM_FEATURE #ifdef SD_DEVICE - if (_type == FS_SD) { - return _sdFile.flush(); - } -#endif //SD_DEVICE - return ; + if (_type == FS_SD) { + return _sdFile.flush(); + } +#endif // SD_DEVICE + return; } -ESP_GBFile& ESP_GBFile::operator=(const ESP_GBFile & other) -{ +ESP_GBFile &ESP_GBFile::operator=(const ESP_GBFile &other) { #ifdef FILESYSTEM_FEATURE - _flashFile = other._flashFile; -#endif //FILESYSTEM_FEATURE + _flashFile = other._flashFile; +#endif // FILESYSTEM_FEATURE #ifdef SD_DEVICE - _sdFile = other._sdFile; -#endif //SD_DEVICE - _type = other._type; - _name= other._name; - return *this; + _sdFile = other._sdFile; +#endif // SD_DEVICE + _type = other._type; + _name = other._name; + return *this; } #ifdef FILESYSTEM_FEATURE -ESP_GBFile & ESP_GBFile::operator=(const ESP_File & other) -{ - _flashFile = other; +ESP_GBFile &ESP_GBFile::operator=(const ESP_File &other) { + _flashFile = other; #ifdef SD_DEVICE - _sdFile = ESP_SDFile(); -#endif //SD_DEVICE - _type = FS_FLASH; - return *this; + _sdFile = ESP_SDFile(); +#endif // SD_DEVICE + _type = FS_FLASH; + return *this; } -#endif //FILESYSTEM_FEATURE +#endif // FILESYSTEM_FEATURE #ifdef SD_DEVICE -ESP_GBFile & ESP_GBFile::operator=(const ESP_SDFile & other) -{ +ESP_GBFile &ESP_GBFile::operator=(const ESP_SDFile &other) { #ifdef FILESYSTEM_FEATURE - _flashFile = ESP_File(); -#endif //FILESYSTEM_FEATURE - _sdFile = other; - _type = FS_SD; - return *this; + _flashFile = ESP_File(); +#endif // FILESYSTEM_FEATURE + _sdFile = other; + _type = FS_SD; + return *this; } -#endif //SD_DEVICE +#endif // SD_DEVICE -const char * ESP_GBFS::getNextFS(bool reset) -{ - static uint8_t index = 0; - if (reset) { - index = 0; - if(_nbFS == 0) { -#ifdef FILESYSTEM_FEATURE - _rootlist[_nbFS] = ESP_FLASH_FS_HEADER; - _nbFS++; -#endif //FILESYSTEM_FEATURE -#ifdef SD_DEVICE - _rootlist[_nbFS] = ESP_SD_FS_HEADER; - _nbFS++; -#endif //SD_DEVICE - } - return ""; - } - if (index < _nbFS) { - uint8_t i = index; - index++; - return _rootlist[i].c_str(); - } +const char *ESP_GBFS::getNextFS(bool reset) { + static uint8_t index = 0; + if (reset) { index = 0; - return ""; -} - -ESP_GBFile ESP_GBFile::openNextFile() -{ - ESP_GBFile f; - if (_type == FS_ROOT) { - String path = ESP_GBFS::getNextFS(); - if (path.length() > 0) { - f = ESP_GBFile(FS_ROOT, &path[1]); - } - } + if (_nbFS == 0) { #ifdef FILESYSTEM_FEATURE - if (_type == FS_FLASH) { - f = _flashFile.openNextFile(); - } -#endif //FILESYSTEM_FEATURE + _rootlist[_nbFS] = ESP_FLASH_FS_HEADER; + _nbFS++; +#endif // FILESYSTEM_FEATURE #ifdef SD_DEVICE - if (_type == FS_SD) { - f = _sdFile.openNextFile(); + _rootlist[_nbFS] = ESP_SD_FS_HEADER; + _nbFS++; +#endif // SD_DEVICE } -#endif //SD_DEVICE - return f; + return ""; + } + if (index < _nbFS) { + uint8_t i = index; + index++; + return _rootlist[i].c_str(); + } + index = 0; + return ""; } -#endif //GLOBAL_FILESYSTEM_FEATURE +ESP_GBFile ESP_GBFile::openNextFile() { + ESP_GBFile f; + if (_type == FS_ROOT) { + String path = ESP_GBFS::getNextFS(); + if (path.length() > 0) { + f = ESP_GBFile(FS_ROOT, &path[1]); + } + } +#ifdef FILESYSTEM_FEATURE + if (_type == FS_FLASH) { + f = _flashFile.openNextFile(); + } +#endif // FILESYSTEM_FEATURE +#ifdef SD_DEVICE + if (_type == FS_SD) { + f = _sdFile.openNextFile(); + } +#endif // SD_DEVICE + return f; +} + +#endif // GLOBAL_FILESYSTEM_FEATURE diff --git a/esp3d/src/modules/filesystem/esp_sd.cpp b/esp3d/src/modules/filesystem/esp_sd.cpp index 240177f4..2b477d85 100644 --- a/esp3d/src/modules/filesystem/esp_sd.cpp +++ b/esp3d/src/modules/filesystem/esp_sd.cpp @@ -17,7 +17,7 @@ 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_DEBUG_FEATURE DEBUG_OUTPUT_SERIAL0 +// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 #include "../../include/esp3d_config.h" #ifdef SD_DEVICE #include @@ -152,7 +152,7 @@ bool ESP_SD::accessFS(uint8_t FS) { log_esp3d("Access SD ok"); return true; } else { - log_esp3d("Enable shared SD failed"); + log_esp3d_e("Enable shared SD failed"); return false; } #else diff --git a/esp3d/src/modules/filesystem/flash/fat_esp32_filesystem.cpp b/esp3d/src/modules/filesystem/flash/fat_esp32_filesystem.cpp index 7ab4fd45..8284bcc2 100644 --- a/esp3d/src/modules/filesystem/flash/fat_esp32_filesystem.cpp +++ b/esp3d/src/modules/filesystem/flash/fat_esp32_filesystem.cpp @@ -17,283 +17,262 @@ fat_esp32_filesystem.cpp - ESP3D fat filesystem configuration class 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_DEBUG_FEATURE DEBUG_OUTPUT_SERIAL0 +// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 #include "../../../include/esp3d_config.h" #if (FILESYSTEM_FEATURE == ESP_FAT_FILESYSTEM) -#include "../esp_filesystem.h" -#include #include + +#include + +#include "../esp_filesystem.h" #include "FFat.h" extern File tFile_handle[ESP_MAX_OPENHANDLE]; -bool ESP_FileSystem::begin() -{ - _started = FFat.begin(); +bool ESP_FileSystem::begin() { + _started = FFat.begin(); + return _started; +} + +void ESP_FileSystem::end() { + FFat.end(); + _started = false; +} + +size_t ESP_FileSystem::freeBytes() { return FFat.freeBytes(); } + +size_t ESP_FileSystem::totalBytes() { return FFat.totalBytes(); } + +size_t ESP_FileSystem::usedBytes() { + return (FFat.totalBytes() - FFat.freeBytes()); +} + +uint ESP_FileSystem::maxPathLength() { return 32; } + +bool ESP_FileSystem::rename(const char *oldpath, const char *newpath) { + return FFat.rename(oldpath, newpath); +} + +const char *ESP_FileSystem::FilesystemName() { return "FAT"; } + +bool ESP_FileSystem::format() { + bool res = FFat.format(); + if (res) { + res = begin(); + } + return res; +} + +ESP_File ESP_FileSystem::open(const char *path, uint8_t mode) { + log_esp3d("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); + return ESP_File(); + } + // path must start by '/' + if (path[0] != '/') { + log_esp3d_e("%s is invalid path", path); + return ESP_File(); + } + File tmp = FFat.open(path, (mode == ESP_FILE_READ) ? FILE_READ + : (mode == ESP_FILE_WRITE) ? FILE_WRITE + : FILE_APPEND); + 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()); + return esptmp; + } else { + log_esp3d_e("open %s failed", path); + return ESP_File(); + } +} + +bool ESP_FileSystem::exists(const char *path) { + bool res = false; + // root should always be there if started + if (strcmp(path, "/") == 0) { return _started; -} - -void ESP_FileSystem::end() -{ - FFat.end(); - _started = false; -} - -size_t ESP_FileSystem::freeBytes() -{ - return FFat.freeBytes(); -} - -size_t ESP_FileSystem::totalBytes() -{ - return FFat.totalBytes(); -} - -size_t ESP_FileSystem::usedBytes() -{ - return (FFat.totalBytes() - FFat.freeBytes()); -} - -uint ESP_FileSystem::maxPathLength() -{ - return 32; -} - -bool ESP_FileSystem::rename(const char *oldpath, const char *newpath) -{ - return FFat.rename(oldpath,newpath); -} - -const char * ESP_FileSystem::FilesystemName() -{ - return "FAT"; -} - -bool ESP_FileSystem::format() -{ - bool res = FFat.format(); - if (res) { - res = begin(); + } + res = FFat.exists(path); + if (!res) { + ESP_File root = ESP_FileSystem::open(path, ESP_FILE_READ); + if (root) { + res = root.isDirectory(); } - return res; + root.close(); + } + return res; } -ESP_File ESP_FileSystem::open(const char* path, uint8_t mode) -{ - log_esp3d("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("reject %s", path); - return ESP_File(); - } - // path must start by '/' - if (path[0] != '/') { - log_esp3d("%s is invalid path", path); - return ESP_File(); - } - File tmp = FFat.open(path, (mode == ESP_FILE_READ)?FILE_READ:(mode == ESP_FILE_WRITE)?FILE_WRITE:FILE_APPEND); - 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()); - return esptmp; - } else { - log_esp3d("open %s failed", path); - return ESP_File(); +bool ESP_FileSystem::remove(const char *path) { return FFat.remove(path); } + +bool ESP_FileSystem::mkdir(const char *path) { + String p = path; + if (p[0] != '/') { + p = "/" + p; + } + if (p[p.length() - 1] == '/') { + if (p != "/") { + p.remove(p.length() - 1); } + } + return FFat.mkdir(p); } -bool ESP_FileSystem::exists(const char* path) -{ - bool res = false; - //root should always be there if started - if (strcmp(path, "/") == 0) { - return _started; +bool ESP_FileSystem::rmdir(const char *path) { + String p = path; + if (!p.startsWith("/")) { + p = '/' + p; + } + if (p != "/") { + if (p.endsWith("/")) { + p.remove(p.length() - 1); } - res = FFat.exists(path); - if (!res) { - ESP_File root = ESP_FileSystem::open(path, ESP_FILE_READ); - if (root) { - res = root.isDirectory(); + } + if (!exists(p.c_str())) { + return false; + } + bool res = true; + std::stack pathlist; + pathlist.push(p); + while (pathlist.size() > 0 && res) { + File dir = FFat.open(pathlist.top().c_str()); + File f = dir.openNextFile(); + bool candelete = true; + while (f && res) { + if (f.isDirectory()) { + candelete = false; + String newdir = pathlist.top() + '/'; + newdir += f.name(); + pathlist.push(newdir); + f.close(); + f = File(); + } else { + String filepath = pathlist.top() + '/'; + filepath += f.name(); + f.close(); + if (!FFat.remove(filepath.c_str())) { + res = false; } - root.close(); + f = dir.openNextFile(); + } } - return res; + if (candelete) { + if (pathlist.top() != "/") { + res = FFat.rmdir(pathlist.top().c_str()); + } + pathlist.pop(); + } + dir.close(); + } + p = String(); + log_esp3d("count %d", pathlist.size()); + return res; } -bool ESP_FileSystem::remove(const char *path) -{ - return FFat.remove(path); +void ESP_FileSystem::closeAll() { + for (uint8_t i = 0; i < ESP_MAX_OPENHANDLE; i++) { + tFile_handle[i].close(); + tFile_handle[i] = File(); + } } -bool ESP_FileSystem::mkdir(const char *path) -{ - String p = path; - if(p[0]!='/') { - p="/"+p; - } - if (p[p.length()-1] == '/') { - if (p!="/") { - p.remove(p.length()-1); +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; + 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].path(); + // name + if (_filename == "/") { + _name = "/"; + } else { + _name = tFile_handle[i].name(); + if (_name[0] == '/') { + _name.remove(0, 1); } + int pos = _name.lastIndexOf('/'); + if (pos != -1) { + _name.remove(0, pos + 1); + } + } + // 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()); + log_esp3d("path: %s", tFile_handle[i].path()); + set = true; } - return FFat.mkdir(p); + } + if (!set) { + log_esp3d("No handle available"); + } } -bool ESP_FileSystem::rmdir(const char *path) -{ - String p = path; - if (!p.startsWith("/")) { - p = '/'+p; - } - if (p!= "/") { - if (p.endsWith("/")) { - p.remove(p.length()-1); - } - } - if (!exists(p.c_str())) { - return false; - } - bool res = true; - std::stack pathlist; - pathlist.push(p); - while (pathlist.size() > 0 && res) { - File dir = FFat.open(pathlist.top().c_str()); - File f = dir.openNextFile(); - bool candelete = true; - while (f && res) { - if (f.isDirectory()) { - candelete = false; - String newdir = pathlist.top()+ '/'; - newdir+= f.name(); - pathlist.push(newdir); - f.close(); - f = File(); - } else { - String filepath = pathlist.top()+ '/'; - filepath+= f.name(); - f.close(); - if (!FFat.remove(filepath.c_str())) { - res = false; - } - f = dir.openNextFile(); - } - } - if (candelete) { - if (pathlist.top() !="/") { - res = FFat.rmdir(pathlist.top().c_str()); - } - pathlist.pop(); - } - dir.close(); - } - p = String(); - log_esp3d("count %d", pathlist.size()); - return res; +bool ESP_File::seek(uint32_t pos, uint8_t mode) { + return tFile_handle[_index].seek(pos, (SeekMode)mode); } -void ESP_FileSystem::closeAll() -{ - for (uint8_t i = 0; i < ESP_MAX_OPENHANDLE; i++) { - tFile_handle[i].close(); - tFile_handle[i] = File(); +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()); + tFile_handle[_index].close(); + // reopen if mode = write + // udate size + date + if (_iswritemode && !_isdir) { + log_esp3d("Updating %s size", _filename.c_str()); + File ftmp = FFat.open(_filename.c_str()); + if (ftmp) { + _size = ftmp.size(); + log_esp3d("Size is %d", _size); + _lastwrite = ftmp.getLastWrite(); + ftmp.close(); + } } -} - -ESP_File::ESP_File(void* handle, bool isdir, bool iswritemode, const char * path) -{ - _isdir = isdir; - _dirlist = ""; - _isfakedir = false; + tFile_handle[_index] = File(); _index = -1; - _filename = ""; - _name = ""; - _lastwrite = 0; - _iswritemode = iswritemode; - _size = 0; - if (!handle) { - log_esp3d("No handle"); - return ; - } - bool set =false; - 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].path(); - //name - if (_filename == "/") { - _name = "/"; - } else { - _name = tFile_handle[i].name(); - if (_name[0] == '/') { - _name.remove( 0, 1); - } - int pos = _name.lastIndexOf('/'); - if (pos != -1) { - _name.remove( 0, pos+1); - } - } - //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()); - log_esp3d("path: %s", tFile_handle[i].path()); - set = true; - } - } - if(!set) { - log_esp3d("No handle available"); - } + } } -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) { + log_esp3d("openNextFile %d failed", _index); + return ESP_File(); + } + File tmp = tFile_handle[_index].openNextFile(); + while (tmp) { + log_esp3d("tmp name :%s %s", tmp.name(), + (tmp.isDirectory()) ? "isDir" : "isFile"); + ESP_File esptmp(&tmp, tmp.isDirectory()); + esptmp.close(); + return esptmp; + } + return ESP_File(); } -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()); - tFile_handle[_index].close(); - //reopen if mode = write - //udate size + date - if (_iswritemode && !_isdir) { - log_esp3d("Updating %s size", _filename.c_str()); - File ftmp = FFat.open(_filename.c_str()); - if (ftmp) { - _size = ftmp.size(); - log_esp3d("Size is %d",_size); - _lastwrite = ftmp.getLastWrite(); - ftmp.close(); - } - } - tFile_handle[_index] = File(); - _index = -1; - } -} - -ESP_File ESP_File::openNextFile() -{ - if ((_index == -1) || !_isdir) { - log_esp3d("openNextFile %d failed", _index); - return ESP_File(); - } - File tmp = tFile_handle[_index].openNextFile(); - while (tmp) { - log_esp3d("tmp name :%s %s", tmp.name(), (tmp.isDirectory())?"isDir":"isFile"); - ESP_File esptmp(&tmp, tmp.isDirectory()); - esptmp.close(); - return esptmp; - } - return ESP_File(); -} - - -#endif //ESP_FAT_FILESYSTEM +#endif // ESP_FAT_FILESYSTEM diff --git a/esp3d/src/modules/filesystem/flash/littlefs_esp32_filesystem.cpp b/esp3d/src/modules/filesystem/flash/littlefs_esp32_filesystem.cpp index 50ef950a..7e849b67 100644 --- a/esp3d/src/modules/filesystem/flash/littlefs_esp32_filesystem.cpp +++ b/esp3d/src/modules/filesystem/flash/littlefs_esp32_filesystem.cpp @@ -17,296 +17,279 @@ littlefs_esp32_filesystem.cpp - ESP3D littlefs filesystem configuration class 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_DEBUG_FEATURE DEBUG_OUTPUT_SERIAL0 +// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 #include "../../../include/esp3d_config.h" -#if (FILESYSTEM_FEATURE == ESP_LITTLEFS_FILESYSTEM) && defined(ARDUINO_ARCH_ESP32) -#include "../esp_filesystem.h" -#include +#if (FILESYSTEM_FEATURE == ESP_LITTLEFS_FILESYSTEM) && \ + defined(ARDUINO_ARCH_ESP32) #include #include +#include + +#include "../esp_filesystem.h" + extern File tFile_handle[ESP_MAX_OPENHANDLE]; -bool ESP_FileSystem::begin() -{ - _started = LittleFS.begin(true); +bool ESP_FileSystem::begin() { + _started = LittleFS.begin(true); + return _started; +} + +void ESP_FileSystem::end() { + LittleFS.end(); + _started = false; +} + +size_t ESP_FileSystem::freeBytes() { + return (LittleFS.totalBytes() - LittleFS.usedBytes()); +} + +size_t ESP_FileSystem::totalBytes() { return LittleFS.totalBytes(); } + +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); + 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) { + log_esp3d("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); + return ESP_File(); + } + // path must start by '/' + if (path[0] != '/') { + log_esp3d("%s is invalid path", path); + return ESP_File(); + } + File tmp = LittleFS.open(path, (mode == ESP_FILE_READ) ? FILE_READ + : (mode == ESP_FILE_WRITE) ? FILE_WRITE + : FILE_APPEND); + 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"); + return esptmp; + } else { + log_esp3d("open %s failed", path); + return ESP_File(); + } +} + +bool ESP_FileSystem::exists(const char *path) { + bool res = false; + // root should always be there if started + if (strcmp(path, "/") == 0) { return _started; -} - -void ESP_FileSystem::end() -{ - LittleFS.end(); - _started = false; -} - -size_t ESP_FileSystem::freeBytes() -{ - return (LittleFS.totalBytes() - LittleFS.usedBytes()); -} - -size_t ESP_FileSystem::totalBytes() -{ - return LittleFS.totalBytes(); -} - -size_t ESP_FileSystem::usedBytes() -{ - return LittleFS.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 p = path; + if (p[0] != '/') { + p = "/" + p; + } + res = LittleFS.exists(p); + if (!res) { + ESP_File root = ESP_FileSystem::open(p.c_str(), ESP_FILE_READ); + if (root) { + res = root.isDirectory(); } - return res; + root.close(); + } + return res; } -ESP_File ESP_FileSystem::open(const char* path, uint8_t mode) -{ - log_esp3d("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); - return ESP_File(); +bool ESP_FileSystem::remove(const char *path) { + String p = path; + if (p[0] != '/') { + p = "/" + p; + } + return LittleFS.remove(p.c_str()); +} + +bool ESP_FileSystem::mkdir(const char *path) { + String p = path; + if (p[0] != '/') { + p = "/" + p; + } + if (p[p.length() - 1] == '/') { + if (p != "/") { + p.remove(p.length() - 1); } - // path must start by '/' - if (path[0] != '/') { - log_esp3d("%s is invalid path", path); - return ESP_File(); + } + return LittleFS.mkdir(p); +} + +bool ESP_FileSystem::rmdir(const char *path) { + String p = path; + if (!p.startsWith("/")) { + p = '/' + p; + } + if (p != "/") { + if (p.endsWith("/")) { + p.remove(p.length() - 1); } - File tmp = LittleFS.open(path, (mode == ESP_FILE_READ)?FILE_READ:(mode == ESP_FILE_WRITE)?FILE_WRITE:FILE_APPEND); - 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"); - return esptmp; + } + if (!exists(p.c_str())) { + return false; + } + bool res = true; + std::stack pathlist; + pathlist.push(p); + while (pathlist.size() > 0 && res) { + File dir = LittleFS.open(pathlist.top().c_str()); + File f = dir.openNextFile(); + bool candelete = true; + while (f && res) { + if (f.isDirectory()) { + candelete = false; + String newdir = pathlist.top() + '/'; + newdir += f.name(); + pathlist.push(newdir); + f.close(); + f = File(); + } else { + String filepath = pathlist.top() + '/'; + filepath += f.name(); + f.close(); + if (!LittleFS.remove(filepath.c_str())) { + res = false; + } + f = dir.openNextFile(); + } + } + if (candelete) { + if (pathlist.top() != "/") { + res = LittleFS.rmdir(pathlist.top().c_str()); + } + pathlist.pop(); + } + dir.close(); + } + p = String(); + log_esp3d("count %d", pathlist.size()); + return res; +} + +void ESP_FileSystem::closeAll() { + for (uint8_t i = 0; i < ESP_MAX_OPENHANDLE; i++) { + 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; + 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].path(); + // name + if (_filename == "/") { + _name = "/"; + } else { + _name = tFile_handle[i].name(); + if (_name[0] == '/') { + _name.remove(0, 1); + } + int pos = _name.lastIndexOf('/'); + if (pos != -1) { + _name.remove(0, pos + 1); + } + } + // 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()); + log_esp3d("path: %s", tFile_handle[i].path()); + set = true; } else { - log_esp3d("open %s failed", path); - return ESP_File(); + log_esp3d("File %d busy", i); + log_esp3d("%s", tFile_handle[i].name()); } -} - -bool ESP_FileSystem::exists(const char* path) -{ - bool res = false; - //root should always be there if started - if (strcmp(path, "/") == 0) { - return _started; + } + if (!set) { + log_esp3d("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()); } - String p = path; - if(p[0]!='/') { - p="/"+p; - } - res = LittleFS.exists(p); - if (!res) { - ESP_File root = ESP_FileSystem::open(p.c_str(), ESP_FILE_READ); - if (root) { - res = root.isDirectory(); - } - root.close(); - } - return res; -} - -bool ESP_FileSystem::remove(const char *path) -{ - String p = path; - if(p[0]!='/') { - p="/"+p; - } - return LittleFS.remove(p.c_str()); -} - -bool ESP_FileSystem::mkdir(const char *path) -{ - String p = path; - if(p[0]!='/') { - p="/"+p; - } - if (p[p.length()-1] == '/') { - if (p!="/") { - p.remove(p.length()-1); - } - } - return LittleFS.mkdir(p); -} - -bool ESP_FileSystem::rmdir(const char *path) -{ - String p = path; - if (!p.startsWith("/")) { - p = '/'+p; - } - if (p!= "/") { - if (p.endsWith("/")) { - p.remove(p.length()-1); - } - } - if (!exists(p.c_str())) { - return false; - } - bool res = true; - std::stack pathlist; - pathlist.push(p); - while (pathlist.size() > 0 && res) { - File dir = LittleFS.open(pathlist.top().c_str()); - File f = dir.openNextFile(); - bool candelete = true; - while (f && res) { - if (f.isDirectory()) { - candelete = false; - String newdir = pathlist.top()+ '/'; - newdir+= f.name(); - pathlist.push(newdir); - f.close(); - f = File(); - } else { - String filepath = pathlist.top()+ '/'; - filepath+= f.name(); - f.close(); - if (!LittleFS.remove(filepath.c_str())) { - res = false; - } - f = dir.openNextFile(); - } - } - if (candelete) { - if (pathlist.top() !="/") { - res = LittleFS.rmdir(pathlist.top().c_str()); - } - pathlist.pop(); - } - dir.close(); - } - p = String(); - log_esp3d("count %d", pathlist.size()); - return res; -} - -void ESP_FileSystem::closeAll() -{ - for (uint8_t i = 0; i < ESP_MAX_OPENHANDLE; i++) { - 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; - 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].path(); - //name - if (_filename == "/") { - _name = "/"; - } else { - _name = tFile_handle[i].name(); - if (_name[0] == '/') { - _name.remove( 0, 1); - } - int pos = _name.lastIndexOf('/'); - if (pos != -1) { - _name.remove( 0, pos+1); - } - } - //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()); - log_esp3d("path: %s", tFile_handle[i].path()); - set = true; - } else { - log_esp3d("File %d busy", i); - log_esp3d("%s", tFile_handle[i].name()); - } - } - if(!set) { - log_esp3d("No handle available"); -#if defined(ESP_DEBUG_FEATURE) - for (uint8_t i=0; (i < ESP_MAX_OPENHANDLE) ; i++) { - log_esp3d("%s", tFile_handle[i].name()); - } #endif - } + } } -void ESP_File::close() -{ - if (_index != -1) { - log_esp3d("Closing File at index %d", _index); - tFile_handle[_index].close(); - //reopen if mode = write - //udate size + date - if (_iswritemode && !_isdir) { - File ftmp = LittleFS.open(_filename.c_str()); - if (ftmp) { - _size = ftmp.size(); - _lastwrite = ftmp.getLastWrite(); - ftmp.close(); - } else { - log_esp3d("Error opening %s", _filename.c_str()); - } - } - tFile_handle[_index] = File(); - _index = -1; +void ESP_File::close() { + if (_index != -1) { + log_esp3d("Closing File at index %d", _index); + tFile_handle[_index].close(); + // reopen if mode = write + // udate size + date + if (_iswritemode && !_isdir) { + File ftmp = LittleFS.open(_filename.c_str()); + if (ftmp) { + _size = ftmp.size(); + _lastwrite = ftmp.getLastWrite(); + ftmp.close(); + } else { + log_esp3d("Error opening %s", _filename.c_str()); + } } + tFile_handle[_index] = File(); + _index = -1; + } } -bool ESP_File::seek(uint32_t pos, uint8_t mode) -{ - return tFile_handle[_index].seek(pos, (SeekMode)mode); +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) { - log_esp3d("openNextFile %d failed", _index); - return ESP_File(); - } - File tmp = tFile_handle[_index].openNextFile(); - while (tmp) { - log_esp3d("tmp name :%s %s", tmp.name(), (tmp.isDirectory())?"isDir":"isFile"); - ESP_File esptmp(&tmp, tmp.isDirectory()); - esptmp.close(); - return esptmp; - } - return ESP_File(); +ESP_File ESP_File::openNextFile() { + if ((_index == -1) || !_isdir) { + log_esp3d("openNextFile %d failed", _index); + return ESP_File(); + } + File tmp = tFile_handle[_index].openNextFile(); + while (tmp) { + log_esp3d("tmp name :%s %s", tmp.name(), + (tmp.isDirectory()) ? "isDir" : "isFile"); + ESP_File esptmp(&tmp, tmp.isDirectory()); + esptmp.close(); + 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 15a8bfb6..d9859cb0 100644 --- a/esp3d/src/modules/filesystem/flash/spiffs_esp32_filesystem.cpp +++ b/esp3d/src/modules/filesystem/flash/spiffs_esp32_filesystem.cpp @@ -17,331 +17,319 @@ 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_DEBUG_FEATURE DEBUG_OUTPUT_SERIAL0 +// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 #include "../../../include/esp3d_config.h" #if (FILESYSTEM_FEATURE == ESP_SPIFFS_FILESYSTEM) && defined(ARDUINO_ARCH_ESP32) -#include "../esp_filesystem.h" -#include #include #include + +#include + +#include "../esp_filesystem.h" + extern File tFile_handle[ESP_MAX_OPENHANDLE]; -bool ESP_FileSystem::begin() -{ - _started = SPIFFS.begin(true); +bool ESP_FileSystem::begin() { + _started = SPIFFS.begin(true); + return _started; +} +void ESP_FileSystem::end() { + _started = false; + SPIFFS.end(); +} + +size_t ESP_FileSystem::freeBytes() { return totalBytes() - usedBytes(); } + +size_t ESP_FileSystem::totalBytes() { return SPIFFS.totalBytes(); } + +size_t ESP_FileSystem::usedBytes() { return SPIFFS.usedBytes(); } + +uint ESP_FileSystem::maxPathLength() { return 32; } + +bool ESP_FileSystem::rename(const char *oldpath, const char *newpath) { + return SPIFFS.rename(oldpath, newpath); +} + +const char *ESP_FileSystem::FilesystemName() { return "SPIFFS"; } + +bool ESP_FileSystem::format() { + bool res = SPIFFS.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(); + } + // TODO add support if path = /DIR1/ <- with last / + File tmp = SPIFFS.open(path, (mode == ESP_FILE_READ) ? FILE_READ + : (mode == ESP_FILE_WRITE) ? FILE_WRITE + : FILE_APPEND); + 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"); + return esptmp; + } else { + log_esp3d("open %s failed", path); + return ESP_File(); + } +} + +bool ESP_FileSystem::exists(const char *path) { + bool res = false; + // root should always be there if started + if (strcmp(path, "/") == 0) { return _started; -} -void ESP_FileSystem::end() -{ - _started = false; - SPIFFS.end(); -} - -size_t ESP_FileSystem::freeBytes() -{ - return totalBytes() - usedBytes(); -} - -size_t ESP_FileSystem::totalBytes() -{ - return SPIFFS.totalBytes(); -} - -size_t ESP_FileSystem::usedBytes() -{ - return SPIFFS.usedBytes(); -} - -uint ESP_FileSystem::maxPathLength() -{ - return 32; -} - -bool ESP_FileSystem::rename(const char *oldpath, const char *newpath) -{ - return SPIFFS.rename(oldpath,newpath); -} - -const char * ESP_FileSystem::FilesystemName() -{ - return "SPIFFS"; -} - -bool ESP_FileSystem::format() -{ - bool res = SPIFFS.format(); - if (res) { - res = begin(); + } + String spath = path; + spath.trim(); + if (spath[spath.length() - 1] == '/') { + if (spath != "/") { + spath.remove(spath.length() - 1); } - 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(); + } + res = SPIFFS.exists(spath.c_str()); + if (!res) { + String newpath = spath; + if (newpath[newpath.length() - 1] != '/') { + newpath += "/"; } - // path must start by '/' - if (path[0] != '/') { - return ESP_File(); - } - //TODO add support if path = /DIR1/ <- with last / - File tmp = SPIFFS.open(path, (mode == ESP_FILE_READ)?FILE_READ:(mode == ESP_FILE_WRITE)?FILE_WRITE:FILE_APPEND); - 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"); - return esptmp; - } else { - log_esp3d("open %s failed", path); - return ESP_File(); - } -} - -bool ESP_FileSystem::exists(const char* path) -{ - bool res = false; - //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); - } - } - res = SPIFFS.exists(spath.c_str()); + newpath += "."; + log_esp3d("Check %s", newpath.c_str()); + res = SPIFFS.exists(newpath); if (!res) { - String newpath = spath; - if (newpath[newpath.length()-1] != '/') { - newpath+="/"; + ESP_File f = ESP_FileSystem::open(path, ESP_FILE_READ); + if (f) { + // Check directories + ESP_File sub = f.openNextFile(); + if (sub) { + sub.close(); + res = true; } - newpath+="."; - log_esp3d("Check %s", newpath.c_str()); - res = SPIFFS.exists(newpath); - if (!res) { - ESP_File f = ESP_FileSystem::open(path, ESP_FILE_READ); - if (f) { - //Check directories - ESP_File sub = f.openNextFile(); - if (sub) { - sub.close(); - res = true; - } - f.close(); - } - } - } - return res; -} - -bool ESP_FileSystem::remove(const char *path) -{ - String p = path; - if(p[0]!='/') { - p="/"+p; - } - return SPIFFS.remove(p); -} - -bool ESP_FileSystem::mkdir(const char *path) -{ - //Use file named . to simulate directory - String p = path; - if (p[p.length()-1] != '/') { - p+="/"; - } - p+="."; - log_esp3d("Dir create : %s", p.c_str()); - ESP_File f = open(p.c_str(), ESP_FILE_WRITE); - if (f) { f.close(); - return true; - } else { - return false; + } } + } + return res; } -bool ESP_FileSystem::rmdir(const char *path) -{ - String spath = path; - spath.trim(); - if (!spath.startsWith("/")) { - spath = '/'+spath; +bool ESP_FileSystem::remove(const char *path) { + String p = path; + if (p[0] != '/') { + p = "/" + p; + } + return SPIFFS.remove(p); +} + +bool ESP_FileSystem::mkdir(const char *path) { + // Use file named . to simulate directory + String p = path; + if (p[p.length() - 1] != '/') { + p += "/"; + } + p += "."; + log_esp3d("Dir create : %s", p.c_str()); + ESP_File f = open(p.c_str(), ESP_FILE_WRITE); + if (f) { + f.close(); + return true; + } else { + return false; + } +} + +bool ESP_FileSystem::rmdir(const char *path) { + String spath = path; + spath.trim(); + if (!spath.startsWith("/")) { + spath = '/' + spath; + } + if (spath != "/") { + if (spath.endsWith("/")) { + spath.remove(spath.length() - 1); } - if (spath!= "/") { - if (spath.endsWith("/")) { - spath.remove(spath.length()-1); - } + } + log_esp3d("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()); + if (!SPIFFS.remove(pfile.path())) { + pfile.close(); + return false; + } + pfile.close(); + pfile = ftmp.openNextFile(); } - log_esp3d("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()); - if (!SPIFFS.remove(pfile.path())) { - pfile.close(); - return false; - } - pfile.close(); - pfile = ftmp.openNextFile(); + ftmp.close(); + return true; + } else { + return false; + } +} + +void ESP_FileSystem::closeAll() { + for (uint8_t i = 0; i < ESP_MAX_OPENHANDLE; i++) { + 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; + 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].path(); + + // if root + if (_filename == "/") { + _filename = "/."; + } + if (_isdir) { + if (_filename[_filename.length() - 1] != '.') { + if (_filename[_filename.length() - 2] != '/') { + _filename += "/"; + } + _filename += "."; } + } + // name + if (_filename == "/.") { + _name = "/"; + } else { + _name = tFile_handle[i].name(); + if (_name.endsWith("/.")) { + _name.remove(_name.length() - 2, 2); + _isfakedir = true; + _isdir = true; + } + if (_name[0] == '/') { + _name.remove(0, 1); + } + int pos = _name.lastIndexOf('/'); + if (pos != -1) { + _name.remove(0, pos + 1); + } + } + // 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; + } + } +} + +bool ESP_File::seek(uint32_t pos, uint8_t mode) { + return tFile_handle[_index].seek(pos, (SeekMode)mode); +} + +void ESP_File::close() { + if (_index != -1) { + log_esp3d("Closing File at index %d", _index); + tFile_handle[_index].close(); + // reopen if mode = write + // udate size + date + if (_iswritemode && !_isdir) { + File ftmp = SPIFFS.open(_filename.c_str()); + if (ftmp) { + _size = ftmp.size(); + _lastwrite = ftmp.getLastWrite(); ftmp.close(); - return true; - } else { - return false; + } } -} - -void ESP_FileSystem::closeAll() -{ - for (uint8_t i = 0; i < ESP_MAX_OPENHANDLE; i++) { - 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; + tFile_handle[_index] = File(); _index = -1; - _filename = ""; - _name = ""; - _lastwrite = 0; - _iswritemode = iswritemode; - _size = 0; - if (!handle) { - log_esp3d("No handle"); - return ; - } - bool set =false; - 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].path(); + } +} - //if root - if (_filename == "/") { - _filename = "/."; - } - if (_isdir) { - if (_filename[_filename.length()-1] != '.') { - if (_filename[_filename.length()-2] != '/') { - _filename+="/"; - } - _filename+="."; - } - } - //name - if (_filename == "/.") { - _name = "/"; - } else { - _name = tFile_handle[i].name(); - if (_name.endsWith("/.")) { - _name.remove( _name.length() - 2,2); - _isfakedir = true; - _isdir = true; - } - if (_name[0] == '/') { - _name.remove( 0, 1); - } - int pos = _name.lastIndexOf('/'); - if (pos != -1) { - _name.remove( 0, pos+1); - } - } - //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; +ESP_File ESP_File::openNextFile() { + if ((_index == -1) || !_isdir) { + log_esp3d("openNextFile failed"); + return ESP_File(); + } + File tmp = tFile_handle[_index].openNextFile(); + while (tmp) { + log_esp3d("tmp name :%s %s", tmp.name(), + (tmp.isDirectory()) ? "isDir" : "isFile"); + ESP_File esptmp(&tmp, tmp.isDirectory()); + esptmp.close(); + String sub = esptmp.filename(); + sub.remove(0, _filename.length() - 1); + int pos = sub.indexOf("/"); + if (pos != -1) { + // is subdir + sub = sub.substring(0, pos); + log_esp3d("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 + "*"; + // test if already in directory list + if (_dirlist.indexOf(tag) == + -1) { // not in list so add it and return the info + _dirlist += tag; + String fname = + _filename.substring(0, _filename.length() - 1) + sub + "/."; + log_esp3d("Found dir # name: %s filename:%s", sub.c_str(), + fname.c_str()); + if (sub == ".") { + log_esp3d("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()); + tmp = tFile_handle[_index].openNextFile(); + } + } else { // is file + log_esp3d("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"); + tmp = tFile_handle[_index].openNextFile(); + } else { + log_esp3d("Found file # name: %s filename:%s", esptmp.filename(), + esptmp.name()); + return esptmp; + } } + } + return ESP_File(); } -bool ESP_File::seek(uint32_t pos, uint8_t mode) -{ - return tFile_handle[_index].seek(pos, (SeekMode)mode); -} - -void ESP_File::close() -{ - if (_index != -1) { - log_esp3d("Closing File at index %d", _index); - tFile_handle[_index].close(); - //reopen if mode = write - //udate size + date - if (_iswritemode && !_isdir) { - File ftmp = SPIFFS.open(_filename.c_str()); - if (ftmp) { - _size = ftmp.size(); - _lastwrite = ftmp.getLastWrite(); - ftmp.close(); - } - } - tFile_handle[_index] = File(); - _index = -1; - } -} - -ESP_File ESP_File::openNextFile() -{ - if ((_index == -1) || !_isdir) { - log_esp3d("openNextFile failed"); - return ESP_File(); - } - File tmp = tFile_handle[_index].openNextFile(); - while (tmp) { - log_esp3d("tmp name :%s %s", tmp.name(), (tmp.isDirectory())?"isDir":"isFile"); - ESP_File esptmp(&tmp, tmp.isDirectory()); - esptmp.close(); - String sub = esptmp.filename(); - sub.remove(0,_filename.length()-1); - int pos = sub.indexOf("/"); - if (pos!=-1) { - //is subdir - sub = sub.substring(0,pos); - log_esp3d("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 + "*"; - //test if already in directory list - if (_dirlist.indexOf(tag) == -1) {//not in list so add it and return the info - _dirlist+= tag; - String fname = _filename.substring(0,_filename.length()-1) + sub + "/."; - log_esp3d("Found dir # name: %s filename:%s", sub.c_str(), fname.c_str()); - if (sub == ".") { - log_esp3d("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()); - tmp = tFile_handle[_index].openNextFile(); - } - } else { //is file - log_esp3d("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"); - tmp = tFile_handle[_index].openNextFile(); - } else { - log_esp3d("Found file # name: %s filename:%s", esptmp.filename(), esptmp.name()); - return esptmp; - } - } - } - return ESP_File(); -} - - -#endif //ESP_SPIFFS_FILESYSTEM +#endif // ESP_SPIFFS_FILESYSTEM diff --git a/esp3d/src/modules/filesystem/sd/sd_native_esp32.cpp b/esp3d/src/modules/filesystem/sd/sd_native_esp32.cpp index 198c7ef2..83c95a22 100644 --- a/esp3d/src/modules/filesystem/sd/sd_native_esp32.cpp +++ b/esp3d/src/modules/filesystem/sd/sd_native_esp32.cpp @@ -150,6 +150,7 @@ 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); return SD.rename(oldpath, newpath); } @@ -177,7 +178,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); + log_esp3d_e("Error opening: %s", path); return ESP_SDFile(); } } diff --git a/esp3d/src/modules/filesystem/sd/sd_native_esp8266.cpp b/esp3d/src/modules/filesystem/sd/sd_native_esp8266.cpp index 85262a2a..07dfb91a 100644 --- a/esp3d/src/modules/filesystem/sd/sd_native_esp8266.cpp +++ b/esp3d/src/modules/filesystem/sd/sd_native_esp8266.cpp @@ -18,408 +18,391 @@ sd_native_esp8266.cpp - ESP3D sd support class Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../../include/esp3d_config.h" -#if defined (ARDUINO_ARCH_ESP8266) && defined(SD_DEVICE) +#if defined(ARDUINO_ARCH_ESP8266) && defined(SD_DEVICE) #if (SD_DEVICE == ESP_SD_NATIVE) #define FS_NO_GLOBALS -#include "../esp_sd.h" -#include -#include "../../../core/settings_esp3d.h" #include #include + +#include + +#include "../../../core/settings_esp3d.h" +#include "../esp_sd.h" + extern File tSDFile_handle[ESP_MAX_SD_OPENHANDLE]; -void dateTime (uint16_t* date, uint16_t* dtime) -{ - struct tm tmstruct; - time_t now; - time (&now); - localtime_r (&now, &tmstruct); - *date = FAT_DATE ( (tmstruct.tm_year) + 1900, ( tmstruct.tm_mon) + 1, tmstruct.tm_mday); - *dtime = FAT_TIME (tmstruct.tm_hour, tmstruct.tm_min, tmstruct.tm_sec); +void dateTime(uint16_t* date, uint16_t* dtime) { + struct tm tmstruct; + time_t now; + time(&now); + localtime_r(&now, &tmstruct); + *date = FAT_DATE((tmstruct.tm_year) + 1900, (tmstruct.tm_mon) + 1, + tmstruct.tm_mday); + *dtime = FAT_TIME(tmstruct.tm_hour, tmstruct.tm_min, tmstruct.tm_sec); } -time_t getDateTimeFile(File & filehandle) -{ - static time_t dt = 0; +time_t getDateTimeFile(File& filehandle) { + static time_t dt = 0; #ifdef SD_TIMESTAMP_FEATURE - struct tm timefile; - dir_t d; - if(filehandle) { - if (filehandle.dirEntry(&d)) { - timefile.tm_year = FAT_YEAR(d.lastWriteDate) - 1900; - timefile.tm_mon = FAT_MONTH(d.lastWriteDate) - 1; - timefile.tm_mday = FAT_DAY(d.lastWriteDate); - timefile.tm_hour = FAT_HOUR(d.lastWriteTime); - timefile.tm_min = FAT_MINUTE(d.lastWriteTime); - timefile.tm_sec = FAT_SECOND(d.lastWriteTime); - timefile.tm_isdst = -1; - dt = mktime(&timefile); - if (dt == -1) { - log_esp3d("mktime failed"); - } - } else { - log_esp3d("stat file failed"); - } + struct tm timefile; + dir_t d; + if (filehandle) { + if (filehandle.dirEntry(&d)) { + timefile.tm_year = FAT_YEAR(d.lastWriteDate) - 1900; + timefile.tm_mon = FAT_MONTH(d.lastWriteDate) - 1; + timefile.tm_mday = FAT_DAY(d.lastWriteDate); + timefile.tm_hour = FAT_HOUR(d.lastWriteTime); + timefile.tm_min = FAT_MINUTE(d.lastWriteTime); + timefile.tm_sec = FAT_SECOND(d.lastWriteTime); + timefile.tm_isdst = -1; + dt = mktime(&timefile); + if (dt == -1) { + log_esp3d_e("mktime failed"); + } } else { - log_esp3d("check file for stat failed"); + log_esp3d_e("stat file failed"); } -#endif //SD_TIMESTAMP_FEATURE - return dt; + } else { + log_esp3d("check file for stat failed"); + } +#endif // SD_TIMESTAMP_FEATURE + return dt; } -uint8_t ESP_SD::getState(bool refresh) -{ +uint8_t ESP_SD::getState(bool refresh) { #if defined(ESP_SD_DETECT_PIN) && ESP_SD_DETECT_PIN != -1 - //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), ESP_SD_DETECT_VALUE); - _state = ESP_SDCARD_NOT_PRESENT; - return _state; - } else { - log_esp3d("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"); - return _state; - } - if (!refresh) { - log_esp3d("SD State cache is %d", _state); - return _state; //to avoid refresh=true + busy to reset SD and waste time - } else { - _sizechanged = true; - } - //SD is idle or not detected, let see if still the case + // 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), + ESP_SD_DETECT_VALUE); _state = ESP_SDCARD_NOT_PRESENT; - //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"); - if (SD.size64() > 0 ) { - log_esp3d("SD available"); - _state = ESP_SDCARD_IDLE; - } else { - log_esp3d("Cannot get card size"); - } - } else { - log_esp3d("Init SD State failed"); - } - log_esp3d("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); - //sanity check - if (_spi_speed_divider <= 0) { - _spi_speed_divider = 1; - } -#ifdef SD_TIMESTAMP_FEATURE - //set callback to get time on files on SD - SdFile::dateTimeCallback (dateTime); -#endif //SD_TIMESTAMP_FEATURE - //Setup pins -#if defined(ESP_SD_DETECT_PIN) && ESP_SD_DETECT_PIN != -1 - pinMode (ESP_SD_DETECT_PIN, INPUT); -#endif //ESP_SD_DETECT_PIN -#if SD_DEVICE_CONNECTION == ESP_SHARED_SD -#if defined(ESP_FLAG_SHARED_SD_PIN) && ESP_FLAG_SHARED_SD_PIN != -1 - pinMode (ESP_FLAG_SHARED_SD_PIN, OUTPUT); - digitalWrite(ESP_FLAG_SHARED_SD_PIN, !ESP_FLAG_SHARED_SD_VALUE); -#endif //ESP_FLAG_SHARED_SD_PIN -#endif //SD_DEVICE_CONNECTION == ESP_SHARED_SD - return _started; -} - -void ESP_SD::end() -{ - _state = ESP_SDCARD_NOT_PRESENT; - _started = false; -} - -void ESP_SD::refreshStats(bool force) -{ - if (force || _sizechanged) { - freeBytes(true); - } - _sizechanged = false; -} - -uint64_t ESP_SD::totalBytes(bool refresh) -{ - static uint64_t _totalBytes = 0; - if (refresh || _totalBytes==0) { - _totalBytes = SD.size64();; - } - return _totalBytes; -} - -uint64_t ESP_SD::usedBytes(bool refresh) -{ - FSInfo64 info; - static uint64_t _usedBytes = 0; - if (refresh) { - if (!SDFS.info64(info)) { - return 0; - } - _usedBytes = info.usedBytes; - } - return _usedBytes; -} - -uint64_t ESP_SD::freeBytes(bool refresh) -{ - return (totalBytes(refresh) - usedBytes(refresh)); -} - -uint ESP_SD::maxPathLength() -{ - return 255; -} - -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!"); - } - 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); - return ESP_SDFile(); - } - } - File tmp = SD.open(path, (mode == ESP_FILE_READ)?FILE_READ:(mode == ESP_FILE_WRITE)?FILE_WRITE:FILE_WRITE); - ESP_SDFile esptmp(&tmp, tmp.isDirectory(),(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) { - res = root.isDirectory(); - } - } - log_esp3d("Seems %s", res?"yes":"no"); - return res; -} - -bool ESP_SD::remove(const char *path) -{ + } else { + log_esp3d("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"); + return _state; + } + if (!refresh) { + log_esp3d("SD State cache is %d", _state); + return _state; // to avoid refresh=true + busy to reset SD and waste time + } else { _sizechanged = true; - return SD.remove(path); + } + // SD is idle or not detected, let see if still the case + _state = ESP_SDCARD_NOT_PRESENT; + // 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"); + if (SD.size64() > 0) { + log_esp3d("SD available"); + _state = ESP_SDCARD_IDLE; + } else { + log_esp3d_e("Cannot get card size"); + } + } else { + log_esp3d_e("Init SD State failed"); + } + log_esp3d("SD State is %d", _state); + return _state; } -bool ESP_SD::mkdir(const char *path) -{ - return SD.mkdir(path); +bool ESP_SD::begin() { + _started = true; + _state = ESP_SDCARD_NOT_PRESENT; + _spi_speed_divider = Settings_ESP3D::read_byte(ESP_SD_SPEED_DIV); + // sanity check + if (_spi_speed_divider <= 0) { + _spi_speed_divider = 1; + } +#ifdef SD_TIMESTAMP_FEATURE + // set callback to get time on files on SD + SdFile::dateTimeCallback(dateTime); +#endif // SD_TIMESTAMP_FEATURE + // Setup pins +#if defined(ESP_SD_DETECT_PIN) && ESP_SD_DETECT_PIN != -1 + pinMode(ESP_SD_DETECT_PIN, INPUT); +#endif // ESP_SD_DETECT_PIN +#if SD_DEVICE_CONNECTION == ESP_SHARED_SD +#if defined(ESP_FLAG_SHARED_SD_PIN) && ESP_FLAG_SHARED_SD_PIN != -1 + pinMode(ESP_FLAG_SHARED_SD_PIN, OUTPUT); + digitalWrite(ESP_FLAG_SHARED_SD_PIN, !ESP_FLAG_SHARED_SD_VALUE); +#endif // ESP_FLAG_SHARED_SD_PIN +#endif // SD_DEVICE_CONNECTION == ESP_SHARED_SD + return _started; } -bool ESP_SD::rmdir(const char *path) -{ +void ESP_SD::end() { + _state = ESP_SDCARD_NOT_PRESENT; + _started = false; +} + +void ESP_SD::refreshStats(bool force) { + if (force || _sizechanged) { + freeBytes(true); + } + _sizechanged = false; +} + +uint64_t ESP_SD::totalBytes(bool refresh) { + static uint64_t _totalBytes = 0; + if (refresh || _totalBytes == 0) { + _totalBytes = SD.size64(); + ; + } + return _totalBytes; +} + +uint64_t ESP_SD::usedBytes(bool refresh) { + FSInfo64 info; + static uint64_t _usedBytes = 0; + if (refresh) { + if (!SDFS.info64(info)) { + return 0; + } + _usedBytes = info.usedBytes; + } + return _usedBytes; +} + +uint64_t ESP_SD::freeBytes(bool refresh) { + return (totalBytes(refresh) - usedBytes(refresh)); +} + +uint ESP_SD::maxPathLength() { return 255; } + +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!"); + } + 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; - if (!p.endsWith("/")) { - p+= '/'; - } - if (!p.startsWith("/")) { - p = '/'+p; - } + p.remove(p.lastIndexOf('/') + 1); if (!exists(p.c_str())) { - return false; + log_esp3d("Error opening: %s", path); + return ESP_SDFile(); } - 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.isDirectory()) { - candelete = false; - String newdir = pathlist.top() + f.name(); - newdir+="/"; - pathlist.push(newdir); - f.close(); - f = File(); - } else { - _sizechanged = true; - String filepath = pathlist.top() + f.name(); - f.close(); - if (!SD.remove(filepath.c_str())) { - res= false; - } - f = dir.openNextFile(); - } + } + File tmp = SD.open(path, (mode == ESP_FILE_READ) ? FILE_READ + : (mode == ESP_FILE_WRITE) ? FILE_WRITE + : FILE_WRITE); + ESP_SDFile esptmp(&tmp, tmp.isDirectory(), + (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) { + res = root.isDirectory(); + } + } + log_esp3d("Seems %s", res ? "yes" : "no"); + return res; +} + +bool ESP_SD::remove(const char* 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) { + File dir = SD.open(pathlist.top().c_str()); + dir.rewindDirectory(); + File f = dir.openNextFile(); + bool candelete = true; + while (f && res) { + if (f.isDirectory()) { + candelete = false; + String newdir = pathlist.top() + f.name(); + newdir += "/"; + pathlist.push(newdir); + f.close(); + f = File(); + } else { + _sizechanged = true; + String filepath = pathlist.top() + f.name(); + f.close(); + if (!SD.remove(filepath.c_str())) { + res = false; } - if (candelete) { - if (pathlist.top() !="/") { - res = SD.rmdir(pathlist.top().c_str()); - } - pathlist.pop(); - } - dir.close(); + f = dir.openNextFile(); + } } - p = String(); - log_esp3d("count %d", pathlist.size()); - return res; -} - -bool ESP_SDFile::seek(uint32_t pos, uint8_t mode) -{ - return tSDFile_handle[_index].seek(pos, (SeekMode)mode); -} - -void ESP_SD::closeAll() -{ - for (uint8_t i = 0; i < ESP_MAX_SD_OPENHANDLE; i++) { - tSDFile_handle[i].close(); - tSDFile_handle[i] = File(); + 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; } -ESP_SDFile::ESP_SDFile(void* handle, bool isdir, bool iswritemode, const char * path) -{ - _isdir = isdir; - _dirlist = ""; +bool ESP_SDFile::seek(uint32_t pos, uint8_t mode) { + return tSDFile_handle[_index].seek(pos, (SeekMode)mode); +} + +void ESP_SD::closeAll() { + for (uint8_t i = 0; i < ESP_MAX_SD_OPENHANDLE; i++) { + tSDFile_handle[i].close(); + tSDFile_handle[i] = 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]) { + tSDFile_handle[i] = *((File*)handle); + // filename + _filename = path; + // name + _name = tSDFile_handle[i].name(); + 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) { + _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; + } + } +} +// todo need also to add short filename +const char* ESP_SDFile::shortname() const { + // not supported in native so return name + 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) { + 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; - _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] = *((File*)handle); - //filename - _filename = path; - //name - _name = tSDFile_handle[i].name(); - 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) { - _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; - } - } -} -//todo need also to add short filename -const char* ESP_SDFile::shortname() const -{ - //not supported in native so return name - 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) { - 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; +ESP_SDFile ESP_SDFile::openNextFile() { + if ((_index == -1) || !_isdir) { + log_esp3d_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(), + (tmp.isDirectory()) ? "isDir" : "isFile"); + String s = _filename; + if (s != "/") { + s += "/"; } + s += name; + ESP_SDFile esptmp(&tmp, tmp.isDirectory(), false, s.c_str()); + esptmp.close(); + return esptmp; + } + return ESP_SDFile(); } -ESP_SDFile ESP_SDFile::openNextFile() -{ - if ((_index == -1) || !_isdir) { - log_esp3d("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(), (tmp.isDirectory())?"isDir":"isFile"); - String s = _filename ; - if (s!="/") { - s+="/"; - } - s += name; - ESP_SDFile esptmp(&tmp, tmp.isDirectory(),false, s.c_str()); - esptmp.close(); - return esptmp; - } - return ESP_SDFile(); -} +const char* ESP_SD::FilesystemName() { return "SD native"; } -const char * ESP_SD::FilesystemName() -{ - return "SD native"; -} - -#endif //SD_DEVICE == ESP_SD_NATIVE -#endif //ARCH_ESP8266 && SD_DEVICE +#endif // SD_DEVICE == ESP_SD_NATIVE +#endif // ARCH_ESP8266 && SD_DEVICE diff --git a/esp3d/src/modules/filesystem/sd/sd_sdfat2_esp32.cpp b/esp3d/src/modules/filesystem/sd/sd_sdfat2_esp32.cpp index 521a648b..83d7c3c0 100644 --- a/esp3d/src/modules/filesystem/sd/sd_sdfat2_esp32.cpp +++ b/esp3d/src/modules/filesystem/sd/sd_sdfat2_esp32.cpp @@ -89,13 +89,13 @@ time_t getDateTimeFile(File& filehandle) { timefile.tm_isdst = -1; dt = mktime(&timefile); if (dt == -1) { - log_esp3d("mktime failed"); + log_esp3d_e("mktime failed"); } } else { - log_esp3d("stat file failed"); + log_esp3d_e("stat file failed"); } } else { - log_esp3d("check file for stat failed"); + log_esp3d_e("check file for stat failed"); } #endif // SD_TIMESTAMP_FEATURE return dt; @@ -319,12 +319,12 @@ ESP_SDFile ESP_SD::open(const char* path, uint8_t mode) { ((mode == ESP_FILE_WRITE) || (mode == ESP_FILE_APPEND))) || (strlen(path) == 0)) { _sizechanged = true; - log_esp3d("reject %s", path); + log_esp3d_e("reject %s", path); return ESP_SDFile(); } // path must start by '/' if (path[0] != '/') { - log_esp3d("%s is invalid path", path); + log_esp3d_e("%s is invalid path", path); return ESP_SDFile(); } if (mode != ESP_FILE_READ) { @@ -332,7 +332,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); + log_esp3d_e("Error opening: %s", path); return ESP_SDFile(); } } @@ -345,7 +345,7 @@ ESP_SDFile ESP_SD::open(const char* path, uint8_t mode) { log_esp3d("%s is a %s", path, tmp.isDir() ? "Dir" : "File"); return esptmp; } else { - log_esp3d("open %s failed", path); + log_esp3d_e("open %s failed", path); 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 0301be7f..c74422b1 100644 --- a/esp3d/src/modules/filesystem/sd/sd_sdfat2_esp8266.cpp +++ b/esp3d/src/modules/filesystem/sd/sd_sdfat2_esp8266.cpp @@ -17,14 +17,16 @@ sd_sdfat2_esp8266.cpp - ESP3D sd support class 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_DEBUG_FEATURE DEBUG_OUTPUT_SERIAL0 +// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 #include "../../../include/esp3d_config.h" -#if defined (ARDUINO_ARCH_ESP8266) && defined(SD_DEVICE) +#if defined(ARDUINO_ARCH_ESP8266) && defined(SD_DEVICE) #if (SD_DEVICE == ESP_SDFAT2) #define FS_NO_GLOBALS -#include "../esp_sd.h" #include + #include "../../../core/settings_esp3d.h" +#include "../esp_sd.h" + #define NO_GLOBAL_SD #include #include @@ -33,509 +35,491 @@ sd_sdfat2_esp8266.cpp - ESP3D sd support class #if HAS_SDIO_CLASS #define SD_CONFIG SdioConfig(FIFO_SDIO) #elif ENABLE_DEDICATED_SPI -#define SD_CONFIG SdSpiConfig((ESP_SD_CS_PIN == -1)?SS:ESP_SD_CS_PIN, DEDICATED_SPI) +#define SD_CONFIG \ + SdSpiConfig((ESP_SD_CS_PIN == -1) ? SS : ESP_SD_CS_PIN, DEDICATED_SPI) #else // HAS_SDIO_CLASS -#define SD_CONFIG SdSpiConfig((ESP_SD_CS_PIN == -1)?SS:ESP_SD_CS_PIN, SHARED_SPI) +#define SD_CONFIG \ + SdSpiConfig((ESP_SD_CS_PIN == -1) ? SS : ESP_SD_CS_PIN, SHARED_SPI) #endif // HAS_SDIO_CLASS extern sdfat::File tSDFile_handle[ESP_MAX_SD_OPENHANDLE]; using namespace sdfat; SdFat SD; -void dateTime (uint16_t* date, uint16_t* dtime) -{ - struct tm tmstruct; - time_t now; - time (&now); - localtime_r (&now, &tmstruct); - *date = FAT_DATE ( (tmstruct.tm_year) + 1900, ( tmstruct.tm_mon) + 1, tmstruct.tm_mday); - *dtime = FAT_TIME (tmstruct.tm_hour, tmstruct.tm_min, tmstruct.tm_sec); +void dateTime(uint16_t* date, uint16_t* dtime) { + struct tm tmstruct; + time_t now; + time(&now); + localtime_r(&now, &tmstruct); + *date = FAT_DATE((tmstruct.tm_year) + 1900, (tmstruct.tm_mon) + 1, + tmstruct.tm_mday); + *dtime = FAT_TIME(tmstruct.tm_hour, tmstruct.tm_min, tmstruct.tm_sec); } -time_t getDateTimeFile(sdfat::File & filehandle) -{ - static time_t dt = 0; +time_t getDateTimeFile(sdfat::File& filehandle) { + static time_t dt = 0; #ifdef SD_TIMESTAMP_FEATURE - struct tm timefile; - uint16_t date; - uint16_t time; - if(filehandle) { - if (filehandle.getModifyDateTime(&date, &time)) { - timefile.tm_year = FS_YEAR(date) - 1900; - timefile.tm_mon = FS_MONTH(date) - 1; - timefile.tm_mday = FS_DAY(date); - timefile.tm_hour = FS_HOUR(time); - timefile.tm_min = FS_MINUTE(time); - timefile.tm_sec = FS_SECOND(time); - timefile.tm_isdst = -1; - dt = mktime(&timefile); - if (dt == -1) { - log_esp3d("mktime failed"); - } - } else { - log_esp3d("stat file failed"); - } + struct tm timefile; + uint16_t date; + uint16_t time; + if (filehandle) { + if (filehandle.getModifyDateTime(&date, &time)) { + timefile.tm_year = FS_YEAR(date) - 1900; + timefile.tm_mon = FS_MONTH(date) - 1; + timefile.tm_mday = FS_DAY(date); + timefile.tm_hour = FS_HOUR(time); + timefile.tm_min = FS_MINUTE(time); + timefile.tm_sec = FS_SECOND(time); + timefile.tm_isdst = -1; + dt = mktime(&timefile); + if (dt == -1) { + log_esp3d_e("mktime failed"); + } } else { - log_esp3d("check file for stat failed"); + log_esp3d_e("stat file failed"); } -#endif //SD_TIMESTAMP_FEATURE - return dt; + } else { + log_esp3d_e("check file for stat failed"); + } +#endif // SD_TIMESTAMP_FEATURE + return dt; } -uint8_t ESP_SD::getState(bool refresh) -{ +uint8_t ESP_SD::getState(bool refresh) { #if defined(ESP_SD_DETECT_PIN) && ESP_SD_DETECT_PIN != -1 - //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), ESP_SD_DETECT_VALUE); - _state = ESP_SDCARD_NOT_PRESENT; - return _state; - } else { - log_esp3d("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"); - return _state; - } - if (!refresh) { - log_esp3d("SD State cache is %d", _state); - return _state; //to avoid refresh=true + busy to reset SD and waste time - } else { - _sizechanged = true; - } - //SD is idle or not detected, let see if still the case + // 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), + ESP_SD_DETECT_VALUE); _state = ESP_SDCARD_NOT_PRESENT; - //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"); - csd_t m_csd; - if (SD.card()->readCSD(&m_csd) && sdCardCapacity(&m_csd) > 0 ) { - _state = ESP_SDCARD_IDLE; - } else { - log_esp3d("Cannot get card size"); - } - } else { - log_esp3d("Init SD State failed"); - } - log_esp3d("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); - //sanity check - if (_spi_speed_divider <= 0) { - _spi_speed_divider = 1; - } -#ifdef SD_TIMESTAMP_FEATURE - //set callback to get time on files on SD - SdFile::dateTimeCallback (dateTime); -#endif //SD_TIMESTAMP_FEATURE - //Setup pins -#if defined(ESP_SD_DETECT_PIN) && ESP_SD_DETECT_PIN != -1 - pinMode (ESP_SD_DETECT_PIN, INPUT); -#endif //ESP_SD_DETECT_PIN -#if SD_DEVICE_CONNECTION == ESP_SHARED_SD -#if defined(ESP_FLAG_SHARED_SD_PIN) && ESP_FLAG_SHARED_SD_PIN != -1 - pinMode (ESP_FLAG_SHARED_SD_PIN, OUTPUT); - digitalWrite(ESP_FLAG_SHARED_SD_PIN, !ESP_FLAG_SHARED_SD_VALUE); -#endif //ESP_FLAG_SHARED_SD_PIN -#endif //SD_DEVICE_CONNECTION == ESP_SHARED_SD - return _started; -} - -void ESP_SD::end() -{ - _state = ESP_SDCARD_NOT_PRESENT; - _started = false; -} - -void ESP_SD::refreshStats(bool force) -{ - if (force || _sizechanged) { - usedBytes(true); - } - _sizechanged = false; -} - -uint64_t ESP_SD::totalBytes(bool refresh) -{ - static uint64_t _totalBytes = 0; - if (!SD.volumeBegin()) { - return 0; - } - if (refresh || _totalBytes==0) { - _totalBytes = SD.clusterCount(); - uint8_t sectors = SD.sectorsPerCluster(); - _totalBytes = _totalBytes * sectors * 512; - } - return _totalBytes; -} - -uint64_t ESP_SD::usedBytes(bool refresh) -{ - return totalBytes(refresh) - freeBytes(refresh); -} - -uint64_t ESP_SD::freeBytes(bool refresh) -{ - static uint64_t _freeBytes = 0; - if (!SD.volumeBegin()) { - return 0; - } - if (refresh || _freeBytes==0) { - - _freeBytes = SD.freeClusterCount(); - uint8_t sectors = SD.sectorsPerCluster(); - _freeBytes = _freeBytes * sectors * 512; - } - return _freeBytes; -} - -uint ESP_SD::maxPathLength() -{ - return 255; -} - -bool ESP_SD::rename(const char *oldpath, const char *newpath) -{ - return SD.rename(oldpath,newpath); -} - -bool ESP_SD::format(ESP3DOutput * output) -{ - 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."); - } - return false; - } - - cardSectorCount = m_card->sectorCount(); - if (!cardSectorCount) { - if (output) { - output->printMSG("Get sector count failed."); - } - return false; - } - - if (output) { - String s = "Capacity detected :" + String(cardSectorCount*5.12e-7) + "GB"; - output->printMSG(s.c_str()); - } - - 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"); - } - return false; - } - - return true; - } - if (output) { - output->printMSG("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); - 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; -} - -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) { - res = root.isDirectory(); - } - } - log_esp3d("Seems %s", res?"yes":"no"); - return res; -} - -bool ESP_SD::remove(const char *path) -{ + } else { + log_esp3d("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"); + return _state; + } + if (!refresh) { + log_esp3d("SD State cache is %d", _state); + return _state; // to avoid refresh=true + busy to reset SD and waste time + } else { _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) { - 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 = sdfat::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", 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); -} - -void ESP_SD::closeAll() -{ - 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]) { - tSDFile_handle[i] = *((sdfat::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) { - _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; - } - } -} -//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; + } + // SD is idle or not detected, let see if still the case + _state = ESP_SDCARD_NOT_PRESENT; + // 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"); + csd_t m_csd; + if (SD.card()->readCSD(&m_csd) && sdCardCapacity(&m_csd) > 0) { + _state = ESP_SDCARD_IDLE; } else { - return _name.c_str(); + log_esp3d_e("Cannot get card size"); } + } else { + log_esp3d_e("Init SD State failed"); + } + log_esp3d("SD State is %d", _state); + return _state; } -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) { - sdfat::File ftmp = SD.open(_filename.c_str()); - if (ftmp) { - _size = ftmp.size(); - _lastwrite = getDateTimeFile(ftmp); - ftmp.close(); - } +bool ESP_SD::begin() { + _started = true; + _state = ESP_SDCARD_NOT_PRESENT; + _spi_speed_divider = Settings_ESP3D::read_byte(ESP_SD_SPEED_DIV); + // sanity check + if (_spi_speed_divider <= 0) { + _spi_speed_divider = 1; + } +#ifdef SD_TIMESTAMP_FEATURE + // set callback to get time on files on SD + SdFile::dateTimeCallback(dateTime); +#endif // SD_TIMESTAMP_FEATURE + // Setup pins +#if defined(ESP_SD_DETECT_PIN) && ESP_SD_DETECT_PIN != -1 + pinMode(ESP_SD_DETECT_PIN, INPUT); +#endif // ESP_SD_DETECT_PIN +#if SD_DEVICE_CONNECTION == ESP_SHARED_SD +#if defined(ESP_FLAG_SHARED_SD_PIN) && ESP_FLAG_SHARED_SD_PIN != -1 + pinMode(ESP_FLAG_SHARED_SD_PIN, OUTPUT); + digitalWrite(ESP_FLAG_SHARED_SD_PIN, !ESP_FLAG_SHARED_SD_VALUE); +#endif // ESP_FLAG_SHARED_SD_PIN +#endif // SD_DEVICE_CONNECTION == ESP_SHARED_SD + return _started; +} + +void ESP_SD::end() { + _state = ESP_SDCARD_NOT_PRESENT; + _started = false; +} + +void ESP_SD::refreshStats(bool force) { + if (force || _sizechanged) { + usedBytes(true); + } + _sizechanged = false; +} + +uint64_t ESP_SD::totalBytes(bool refresh) { + static uint64_t _totalBytes = 0; + if (!SD.volumeBegin()) { + return 0; + } + if (refresh || _totalBytes == 0) { + _totalBytes = SD.clusterCount(); + uint8_t sectors = SD.sectorsPerCluster(); + _totalBytes = _totalBytes * sectors * 512; + } + return _totalBytes; +} + +uint64_t ESP_SD::usedBytes(bool refresh) { + return totalBytes(refresh) - freeBytes(refresh); +} + +uint64_t ESP_SD::freeBytes(bool refresh) { + static uint64_t _freeBytes = 0; + if (!SD.volumeBegin()) { + return 0; + } + if (refresh || _freeBytes == 0) { + _freeBytes = SD.freeClusterCount(); + uint8_t sectors = SD.sectorsPerCluster(); + _freeBytes = _freeBytes * sectors * 512; + } + return _freeBytes; +} + +uint ESP_SD::maxPathLength() { return 255; } + +bool ESP_SD::rename(const char* oldpath, const char* newpath) { + return SD.rename(oldpath, newpath); +} + +bool ESP_SD::format(ESP3DOutput* output) { + 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."); + } + return false; + } + + cardSectorCount = m_card->sectorCount(); + if (!cardSectorCount) { + if (output) { + output->printMSG("Get sector count failed."); + } + return false; + } + + if (output) { + String s = + "Capacity detected :" + String(cardSectorCount * 5.12e-7) + "GB"; + output->printMSG(s.c_str()); + } + + 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"); } - tSDFile_handle[_index] = sdfat::File(); - //log_esp3d("Closing File at index %d",_index); - _index = -1; + 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"); + } + return false; + } + + return true; + } + if (output) { + output->printMSG("cannot erase"); + } + return false; } -ESP_SDFile ESP_SDFile::openNextFile() -{ - if ((_index == -1) || !_isdir) { - log_esp3d("openNextFile failed"); - return ESP_SDFile(); +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); + 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!="/") { - s+="/"; + } + 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) { + res = root.isDirectory(); + } + } + log_esp3d("Seems %s", res ? "yes" : "no"); + return res; +} + +bool ESP_SD::remove(const char* 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) { + 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 = sdfat::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; } - s += tmps; - ESP_SDFile esptmp(&tmp, tmp.isDir(),false, s.c_str()); - esptmp.close(); - return esptmp; + f = dir.openNextFile(); + } } - return ESP_SDFile(); + 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; } -const char * ESP_SD::FilesystemName() -{ - return "SDFat - " SD_FAT_VERSION_STR ; +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); } -#endif //SD_DEVICE == ESP_SDFAT2 -#endif //ARCH_ESP8266 && SD_DEVICE +void ESP_SD::closeAll() { + 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]) { + tSDFile_handle[i] = *((sdfat::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) { + _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; + } + } +} +// 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(); + } +} + +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) { + 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; + } +} + +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 != "/") { + s += "/"; + } + 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; } + +#endif // SD_DEVICE == ESP_SDFAT2 +#endif // ARCH_ESP8266 && SD_DEVICE diff --git a/esp3d/src/modules/filesystem/sd/sdio_esp32.cpp b/esp3d/src/modules/filesystem/sd/sdio_esp32.cpp index 7bcbe68e..79a29f66 100644 --- a/esp3d/src/modules/filesystem/sd/sdio_esp32.cpp +++ b/esp3d/src/modules/filesystem/sd/sdio_esp32.cpp @@ -18,376 +18,358 @@ sdio_esp32.cpp - ESP3D sd support class Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../../../include/esp3d_config.h" -#if defined (ARDUINO_ARCH_ESP32) && defined(SD_DEVICE) +#if defined(ARDUINO_ARCH_ESP32) && defined(SD_DEVICE) #if (SD_DEVICE == ESP_SDIO) -#include "../esp_sd.h" #include + #include "../../../core/settings_esp3d.h" +#include "../esp_sd.h" #include "FS.h" #include "SD_MMC.h" - extern File tSDFile_handle[ESP_MAX_SD_OPENHANDLE]; #define SDMMC_FORCE_BEGIN #ifndef SDIO_BIT_MODE #define SDIO_BIT_MODE SD_FOUR_BIT_MODE -#endif //SDIO_BIT_MODE +#endif // SDIO_BIT_MODE -uint8_t ESP_SD::getState(bool refresh) -{ - static bool lastinitok = false; +uint8_t ESP_SD::getState(bool refresh) { + static bool lastinitok = false; #ifdef SDMMC_FORCE_BEGIN - lastinitok = false; -#endif //SDMMC_LIGHT_CHECK + lastinitok = false; +#endif // SDMMC_LIGHT_CHECK #if defined(ESP_SD_DETECT_PIN) && ESP_SD_DETECT_PIN != -1 - //no need to go further if SD detect is not correct - if (!((digitalRead (ESP_SD_DETECT_PIN) == ESP_SD_DETECT_VALUE) ? true : false)) { - _state = ESP_SDCARD_NOT_PRESENT; - return _state; - } -#endif //ESP_SD_DETECT_PIN - //if busy doing something return state - if (!((_state == ESP_SDCARD_NOT_PRESENT) || _state == ESP_SDCARD_IDLE)) { - return _state; - } - if (!refresh) { - return _state; //to avoid refresh=true + busy to reset SD and waste time - } -//SD is idle or not detected, let see if still the case + // no need to go further if SD detect is not correct + if (!((digitalRead(ESP_SD_DETECT_PIN) == ESP_SD_DETECT_VALUE) ? true + : false)) { _state = ESP_SDCARD_NOT_PRESENT; -//refresh content if card was removed - if (!lastinitok) { - log_esp3d("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"); - if (SD_MMC.cardType() != CARD_NONE ) { - _state = ESP_SDCARD_IDLE; - lastinitok = true; - log_esp3d("sd_mmc card type succeed"); - } else { - log_esp3d("sd_mmc card type failed"); - } - } else { - log_esp3d("sd_mmc begin failed"); - } - } else { - log_esp3d("last init was ok try card type"); - if(SD_MMC.cardType() != CARD_NONE) { - log_esp3d("checking sd_mmc card type succeed"); - _state = ESP_SDCARD_IDLE; - } else { - lastinitok = false; - log_esp3d("Soft sd check failed"); - SD_MMC.end(); - if (SD_MMC.begin("/sdcard", SDIO_BIT_MODE)) { - log_esp3d("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"); - } else { - log_esp3d("new sd_mmc card type failed"); - } - } else { - log_esp3d("new sd_mmc begin failed"); - } - } - } return _state; -} - -bool ESP_SD::begin() -{ -#if (ESP_SDIO_CLK_PIN != -1) || (ESP_SDIO_CMD_PIN != -1) || (ESP_SDIO_D0_PIN != -1) || (ESP_SDIO_D1_PIN != -1) || (ESP_SDIO_D2_PIN != -1) || (ESP_SDIO_D3_PIN != -1) - 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"); - _started = true; -#ifdef SDMMC_FORCE_BEGIN - _state = ESP_SDCARD_NOT_PRESENT; -#else - _state = getState(true); -#endif //SDMMC_FORCE_BEGIN - - return _started; -} - -void ESP_SD::end() -{ + } +#endif // ESP_SD_DETECT_PIN + // if busy doing something return state + if (!((_state == ESP_SDCARD_NOT_PRESENT) || _state == ESP_SDCARD_IDLE)) { + return _state; + } + if (!refresh) { + return _state; // to avoid refresh=true + busy to reset SD and waste time + } + // SD is idle or not detected, let see if still the case + _state = ESP_SDCARD_NOT_PRESENT; + // refresh content if card was removed + if (!lastinitok) { + log_esp3d("last init was failed try sd_mmc begin"); SD_MMC.end(); - _state = ESP_SDCARD_NOT_PRESENT; - _started = false; -} - -void ESP_SD::refreshStats(bool force) -{ - if (force || _sizechanged) { - freeBytes(true); + if (SD_MMC.begin("/sdcard", SDIO_BIT_MODE)) { + log_esp3d("sd_mmc begin succeed"); + if (SD_MMC.cardType() != CARD_NONE) { + _state = ESP_SDCARD_IDLE; + lastinitok = true; + log_esp3d("sd_mmc card type succeed"); + } else { + log_esp3d_e("sd_mmc card type failed"); + } + } else { + log_esp3d_e("sd_mmc begin failed"); } - _sizechanged = false; -} - -uint64_t ESP_SD::totalBytes(bool refresh) -{ - static uint64_t _totalBytes = 0; - if (refresh || _totalBytes==0) { - _totalBytes = SD_MMC.totalBytes();; + } else { + log_esp3d("last init was ok try card type"); + if (SD_MMC.cardType() != CARD_NONE) { + log_esp3d("checking sd_mmc card type succeed"); + _state = ESP_SDCARD_IDLE; + } else { + lastinitok = false; + log_esp3d_e("Soft sd check failed"); + SD_MMC.end(); + if (SD_MMC.begin("/sdcard", SDIO_BIT_MODE)) { + log_esp3d("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"); + } else { + log_esp3d_e("new sd_mmc card type failed"); + } + } else { + log_esp3d("new sd_mmc begin failed"); + } } - return _totalBytes; + } + return _state; } -uint64_t ESP_SD::usedBytes(bool refresh) -{ - static uint64_t _usedBytes = 0; - if (refresh || _usedBytes==0) { - _usedBytes = SD_MMC.usedBytes(); +bool ESP_SD::begin() { +#if (ESP_SDIO_CLK_PIN != -1) || (ESP_SDIO_CMD_PIN != -1) || \ + (ESP_SDIO_D0_PIN != -1) || (ESP_SDIO_D1_PIN != -1) || \ + (ESP_SDIO_D2_PIN != -1) || (ESP_SDIO_D3_PIN != -1) + 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"); + _started = true; +#ifdef SDMMC_FORCE_BEGIN + _state = ESP_SDCARD_NOT_PRESENT; +#else + _state = getState(true); +#endif // SDMMC_FORCE_BEGIN + + return _started; +} + +void ESP_SD::end() { + SD_MMC.end(); + _state = ESP_SDCARD_NOT_PRESENT; + _started = false; +} + +void ESP_SD::refreshStats(bool force) { + if (force || _sizechanged) { + freeBytes(true); + } + _sizechanged = false; +} + +uint64_t ESP_SD::totalBytes(bool refresh) { + static uint64_t _totalBytes = 0; + if (refresh || _totalBytes == 0) { + _totalBytes = SD_MMC.totalBytes(); + ; + } + return _totalBytes; +} + +uint64_t ESP_SD::usedBytes(bool refresh) { + static uint64_t _usedBytes = 0; + if (refresh || _usedBytes == 0) { + _usedBytes = SD_MMC.usedBytes(); + } + return _usedBytes; +} + +uint64_t ESP_SD::freeBytes(bool refresh) { + return (totalBytes(refresh) - usedBytes(refresh)); +} + +uint ESP_SD::maxPathLength() { return 255; } + +bool ESP_SD::rename(const char *oldpath, const char *newpath) { + return SD_MMC.rename(oldpath, newpath); +} + +bool ESP_SD::format(ESP3DOutput *output) { + // not available yet + if (output) { + output->printERROR("Not implemented!"); + } + 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)) { + log_esp3d_e("File open check : failed"); + return ESP_SDFile(); + } + // path must start by '/' + if (path[0] != '/') { + log_esp3d_e("File open path is invalid"); + 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, %s does not exists", path, p.c_str()); + return ESP_SDFile(); } - return _usedBytes; + } + File tmp = SD_MMC.open(path, (mode == ESP_FILE_READ) ? FILE_READ + : (mode == ESP_FILE_WRITE) ? FILE_WRITE + : FILE_APPEND); + ESP_SDFile esptmp(&tmp, tmp.isDirectory(), + (mode == ESP_FILE_READ) ? false : true, path); + return esptmp; } -uint64_t ESP_SD::freeBytes(bool refresh) -{ - return (totalBytes(refresh) - usedBytes(refresh)); -} +bool ESP_SD::exists(const char *path) { + bool res = false; + String p = path; + // root should always be there if started + if (p == "/") { + return _started; + } -uint ESP_SD::maxPathLength() -{ - return 255; -} - -bool ESP_SD::rename(const char *oldpath, const char *newpath) -{ - return SD_MMC.rename(oldpath,newpath); -} - -bool ESP_SD::format(ESP3DOutput * output) -{ - //not available yet - if (output) { - output->printERROR ("Not implemented!"); + if (p.endsWith("/")) { + p.remove(p.length() - 1, 1); + } + res = SD_MMC.exists(p); + if (!res) { + ESP_SDFile root = ESP_SD::open(p.c_str(), ESP_FILE_READ); + if (root) { + res = root.isDirectory(); } + } + return res; +} + +bool ESP_SD::remove(const char *path) { return SD_MMC.remove(path); } + +bool ESP_SD::mkdir(const char *path) { + String p = path; + if (p.endsWith("/")) { + p.remove(p.length() - 1, 1); + } + return SD_MMC.mkdir(p.c_str()); +} + +bool ESP_SD::rmdir(const char *path) { + if (!exists(path)) { 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)) { - log_esp3d("File open check : failed"); - return ESP_SDFile(); - } - // path must start by '/' - if (path[0] != '/') { - log_esp3d("File open path is invalid"); - 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, %s does not exists", path,p.c_str()); - return ESP_SDFile(); + } + bool res = true; + std::stack pathlist; + String p = path; + if (p.endsWith("/")) { + p.remove(p.length() - 1, 1); + } + pathlist.push(p); + while (pathlist.size() > 0 && res) { + File dir = SD_MMC.open(pathlist.top().c_str()); + File f = dir.openNextFile(); + bool candelete = true; + while (f && res) { + if (f.isDirectory()) { + candelete = false; + String newdir = pathlist.top() + '/'; + newdir += f.name(); + pathlist.push(newdir); + f.close(); + f = File(); + } else { + String filepath = pathlist.top() + '/'; + filepath += f.name(); + f.close(); + if (!SD_MMC.remove(filepath.c_str())) { + res = false; } + f = dir.openNextFile(); + } } - File tmp = SD_MMC.open(path, (mode == ESP_FILE_READ)?FILE_READ:(mode == ESP_FILE_WRITE)?FILE_WRITE:FILE_APPEND); - ESP_SDFile esptmp(&tmp, tmp.isDirectory(),(mode == ESP_FILE_READ)?false:true, path); - return esptmp; + if (candelete) { + if (pathlist.top() != "/") { + res = SD_MMC.rmdir(pathlist.top().c_str()); + } + pathlist.pop(); + } + dir.close(); + } + p = String(); + log_esp3d("count %d", pathlist.size()); + return res; } -bool ESP_SD::exists(const char* path) -{ - bool res = false; - String p = path; - //root should always be there if started - if (p == "/") { - return _started; - } - - if (p.endsWith("/")) { - p.remove( p.length() - 1,1); - } - res = SD_MMC.exists(p); - if (!res) { - ESP_SDFile root = ESP_SD::open(p.c_str(), ESP_FILE_READ); - if (root) { - res = root.isDirectory(); - } - } - 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(); + } } -bool ESP_SD::remove(const char *path) -{ - return SD_MMC.remove(path); +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]) { + tSDFile_handle[i] = *((File *)handle); + // filename + _name = tSDFile_handle[i].name(); + _filename = path; + 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 + _lastwrite = tSDFile_handle[i].getLastWrite(); + _index = i; + // log_esp3d("Opening File at index %d",_index); + set = true; + } + } } -bool ESP_SD::mkdir(const char *path) -{ - String p = path; - if (p.endsWith("/")) { - p.remove( p.length() - 1,1); - } - return SD_MMC.mkdir(p.c_str()); +bool ESP_SDFile::seek(uint32_t pos, uint8_t mode) { + return tSDFile_handle[_index].seek(pos, (SeekMode)mode); } -bool ESP_SD::rmdir(const char *path) -{ - if (!exists(path)) { - return false; +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_MMC.open(_filename.c_str()); + if (ftmp) { + _size = ftmp.size(); + _lastwrite = ftmp.getLastWrite(); + ftmp.close(); + } } - bool res = true; - std::stack pathlist; - String p = path; - if (p.endsWith("/")) { - p.remove( p.length() - 1,1); - } - pathlist.push(p); - while (pathlist.size() > 0 && res) { - File dir = SD_MMC.open(pathlist.top().c_str()); - File f = dir.openNextFile(); - bool candelete = true; - while (f && res) { - if (f.isDirectory()) { - candelete = false; - String newdir = pathlist.top()+ '/'; - newdir+= f.name(); - pathlist.push(newdir); - f.close(); - f = File(); - } else { - String filepath = pathlist.top()+ '/'; - filepath+= f.name(); - f.close(); - if (!SD_MMC.remove(filepath.c_str())) { - res = false; - } - f = dir.openNextFile(); - } - } - if (candelete) { - if (pathlist.top() !="/") { - res = SD_MMC.rmdir(pathlist.top().c_str()); - } - pathlist.pop(); - } - dir.close(); - } - p = String(); - log_esp3d("count %d", pathlist.size()); - 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(); - } -} - -ESP_SDFile::ESP_SDFile(void* handle, bool isdir, bool iswritemode, const char * path) -{ - _isdir = isdir; - _dirlist = ""; + tSDFile_handle[_index] = File(); + // log_esp3d("Closing File at index %d",_index); _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] = *((File*)handle); - //filename - _name = tSDFile_handle[i].name(); - _filename = path; - 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 - _lastwrite = tSDFile_handle[i].getLastWrite(); - _index = i; - //log_esp3d("Opening File at index %d",_index); - set = true; - } - } + } } -bool ESP_SDFile::seek(uint32_t pos, uint8_t mode) -{ - return tSDFile_handle[_index].seek(pos, (SeekMode)mode); +ESP_SDFile ESP_SDFile::openNextFile() { + if ((_index == -1) || !_isdir) { + log_esp3d("openNextFile failed"); + return ESP_SDFile(); + } + File tmp = tSDFile_handle[_index].openNextFile(); + if (tmp) { + log_esp3d("tmp name :%s %s %s", tmp.name(), + (tmp.isDirectory()) ? "isDir" : "isFile", _filename.c_str()); + String s = tmp.name(); + // if (s!="/")s+="/"; + // s += tmp.name(); + ESP_SDFile esptmp(&tmp, tmp.isDirectory(), false, s.c_str()); + esptmp.close(); + return esptmp; + } + return ESP_SDFile(); } -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_MMC.open(_filename.c_str()); - if (ftmp) { - _size = ftmp.size(); - _lastwrite = ftmp.getLastWrite(); - ftmp.close(); - } - } - tSDFile_handle[_index] = File(); - //log_esp3d("Closing File at index %d",_index); - _index = -1; - } -} +// TODO need to find reliable way +const char *ESP_SDFile::shortname() const { return _name.c_str(); } -ESP_SDFile ESP_SDFile::openNextFile() -{ - if ((_index == -1) || !_isdir) { - log_esp3d("openNextFile failed"); - return ESP_SDFile(); - } - File tmp = tSDFile_handle[_index].openNextFile(); - if (tmp) { - log_esp3d("tmp name :%s %s %s", tmp.name(), (tmp.isDirectory())?"isDir":"isFile", _filename.c_str()); - String s = tmp.name() ; - //if (s!="/")s+="/"; - //s += tmp.name(); - ESP_SDFile esptmp(&tmp, tmp.isDirectory(),false, s.c_str()); - esptmp.close(); - return esptmp; - } - return ESP_SDFile(); -} - -//TODO need to find reliable way -const char* ESP_SDFile::shortname() const -{ - return _name.c_str(); -} - -const char * ESP_SD::FilesystemName() -{ - return "SDIO"; -} -#endif //SD_DEVICE == ESP_SDIO -#endif //ARCH_ESP32 && SD_DEVICE +const char *ESP_SD::FilesystemName() { return "SDIO"; } +#endif // SD_DEVICE == ESP_SDIO +#endif // ARCH_ESP32 && SD_DEVICE diff --git a/esp3d/src/modules/ftp/FtpServer.cpp b/esp3d/src/modules/ftp/FtpServer.cpp index def14277..7313b5f1 100644 --- a/esp3d/src/modules/ftp/FtpServer.cpp +++ b/esp3d/src/modules/ftp/FtpServer.cpp @@ -65,1112 +65,1161 @@ * 2019-10-27 Modified version for ESP3D by Luc LEBOSSE @luc-github * support for ESP8266 and ESP32 in ESP3D project */ -//#define ESP_DEBUG_FEATURE DEBUG_OUTPUT_SERIAL0 +// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 #include "../../include/esp3d_config.h" -#if defined (FTP_FEATURE) -#include +#if defined(FTP_FEATURE) #include -#include "FtpServer.h" -#include "ExtStreaming.h" -#include "../network/netconfig.h" -#include "../authentication/authentication_service.h" -#include "../../core/settings_esp3d.h" +#include + #include "../../core/esp3doutput.h" +#include "../../core/settings_esp3d.h" +#include "../authentication/authentication_service.h" +#include "../network/netconfig.h" +#include "ExtStreaming.h" +#include "FtpServer.h" + #if FTP_FEATURE == FS_ROOT #include "../filesystem/esp_globalFS.h" -typedef ESP_GBFile FTPFile; -typedef ESP_GBFS FTPFS; -#endif //FTP_FEATURE == FS_ROOT +typedef ESP_GBFile FTPFile; +typedef ESP_GBFS FTPFS; +#endif // FTP_FEATURE == FS_ROOT #if FTP_FEATURE == FS_FLASH #include "../filesystem/esp_filesystem.h" -typedef ESP_File FTPFile; -typedef ESP_FileSystem FTPFS; -#endif //FTP_FEATURE == FS_FLASH +typedef ESP_File FTPFile; +typedef ESP_FileSystem FTPFS; +#endif // FTP_FEATURE == FS_FLASH #if FTP_FEATURE == FS_SD #include "../filesystem/esp_sd.h" -typedef ESP_SDFile FTPFile; -typedef ESP_SD FTPFS; -#endif //FTP_FEATURE == FS_SD +typedef ESP_SDFile FTPFile; +typedef ESP_SD FTPFS; +#endif // FTP_FEATURE == FS_SD // Uncomment to print additional info for log_esp3d -//#define FTP_DEBUG +// #define FTP_DEBUG -//width in char of file size output in listing +// width in char of file size output in listing #define SIZELISTPADING 15 -FTPFile dir; -FTPFile file; +FTPFile dir; +FTPFile file; FtpServer ftp_server; -bool legalChar( char c ) -{ - if( c == '"' || c == '*' || c == '?' || c == ':' || - c == '<' || c == '>' || c == '|' ) { - return false; - } - return 0x1f < c && c < 0x7f; +bool legalChar(char c) { + if (c == '"' || c == '*' || c == '?' || c == ':' || c == '<' || c == '>' || + c == '|') { + return false; + } + return 0x1f < c && c < 0x7f; } +void FtpServer::closeClient() { client.stop(); } -void FtpServer::closeClient() -{ - client.stop(); +bool FtpServer::isConnected() { return client.connected(); } + +FtpServer::FtpServer() { + ftpServer = nullptr; + dataServer = nullptr; + ctrlPort = 0; + activePort = 0; + passivePort = 0; + _root = FS_ROOT; } -bool FtpServer::isConnected() -{ - return client.connected(); -} +FtpServer::~FtpServer() { end(); } -FtpServer::FtpServer() -{ +void FtpServer::end() { + if (ftpServer) { + delete (ftpServer); ftpServer = nullptr; + } + if (dataServer) { + delete (dataServer); dataServer = nullptr; - ctrlPort = 0; - activePort = 0; - passivePort = 0; - _root = FS_ROOT; + } + ctrlPort = 0; + activePort = 0; + passivePort = 0; + _started = false; + _root = FS_ROOT; } -FtpServer::~FtpServer() -{ - end(); +const char* FtpServer::clientIPAddress() { + static String res; + res = "0.0.0.0"; + if (client && client.connected()) { + res = client.remoteIP().toString(); + } + return res.c_str(); } -void FtpServer::end() -{ - if(ftpServer) { - delete(ftpServer); - ftpServer = nullptr; - } - if(dataServer) { - delete(dataServer); - dataServer = nullptr; - } - ctrlPort = 0; - activePort = 0; - passivePort = 0; - _started = false; - _root = FS_ROOT; -} +bool FtpServer::started() { return _started; } -const char* FtpServer::clientIPAddress() -{ - static String res; - res = "0.0.0.0"; - if (client && client.connected()) { - res = client.remoteIP().toString(); - } - return res.c_str(); -} - -bool FtpServer::started() -{ - return _started; -} - -bool FtpServer::begin() -{ - end(); - if (Settings_ESP3D::read_byte(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); - ftpServer = new WiFiServer(ctrlPort); - if (!ftpServer) { - return false; - } - dataServer = new WiFiServer(passivePort); - if (!dataServer) { - return false; - } - // Tells the ftp server to begin listening for incoming connection - ftpServer->begin(); - ftpServer->setNoDelay( true ); - dataServer->begin(); - millisDelay = 0; - cmdStage = FTP_Stop; - iniVariables(); - _started = true; - _fsType = FS_UNKNOWN; - return _started; -} - -bool FtpServer::accessFS(const char* path) -{ - if (_fsType != FS_UNKNOWN) { - log_esp3d("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("FTP: accessFS:No SD card"); - _fsType = FS_UNKNOWN; - FTPFS::releaseFS(); - return false; - } else { - FTPFS::setState(ESP_SDCARD_BUSY ); - log_esp3d("FTP: accessFS: Accessed granted"); - } -#endif //FTP_FEATURE == FS_SD - return true; - } - log_esp3d("FTP: accessFS: Access denied"); - return false; -} -void FtpServer::releaseFS() -{ - if (_fsType != FS_UNKNOWN) { - FTPFS::releaseFS(_fsType); - log_esp3d("FTP: accessFS: Access revoked"); - _fsType = FS_UNKNOWN; - } -} - -void FtpServer::iniVariables() -{ - // Default for data port - dataPort = activePort; - - // Default Data connection is Active - dataConn = FTP_NoConn; - - // Set the root directory - strcpy( cwdName, "/" ); - - rnfrCmd = false; - transferStage = FTP_Close; -} - - -void FtpServer::handle() -{ - if (!_started) { - return; - } -#ifdef FTP_DEBUG - int8_t data0 = data.status(); - ftpTransfer transferStage0 = transferStage; - ftpCmd cmdStage0 = cmdStage; -#endif - - if((int32_t) ( millisDelay - millis() ) > 0 ) { - return; - } - - if( cmdStage == FTP_Stop ) { - log_esp3d("FTP_STOP"); - releaseFS(); - if( client.connected()) { - disconnectClient(); - } - cmdStage = FTP_Init; - } else if( cmdStage == FTP_Init ) { // Ftp server waiting for connection - abortTransfer(); - iniVariables(); - log_esp3d(" Ftp server waiting for connection on port %d", ctrlPort); - cmdStage = FTP_Client; - } else if( cmdStage == FTP_Client ) { // Ftp server idle - if( ftpServer->hasClient()) { - client.stop(); - client = ftpServer->available(); - } - if( client.connected()) { // A client connected - clientConnected(); - millisEndConnection = millis() + 1000L * FTP_AUTH_TIME_OUT; // wait client id for 10 s. - cmdStage = FTP_User; - } - } else if( readChar() > 0 ) { // got response - processCommand(); - if( cmdStage == FTP_Stop ) { - millisEndConnection = millis() + 1000L * FTP_AUTH_TIME_OUT; // wait authentication for 10 s. - } else if( cmdStage < FTP_Cmd ) { - millisDelay = millis() + 200; // delay of 100 ms - } else { - millisEndConnection = millis() + 1000L * FTP_TIME_OUT; - } - } else if( ! client.connected() ) { - cmdStage = FTP_Init; - } - - if( transferStage == FTP_Retrieve ) { // Retrieve data - if( ! doRetrieve()) { - transferStage = FTP_Close; - } else { - releaseFS(); - } - } else if( transferStage == FTP_Store ) { // Store data - if( ! doStore()) { - transferStage = FTP_Close; - } else { - releaseFS(); - } - } else if( transferStage == FTP_List || - transferStage == FTP_Nlst) { // LIST or NLST - if( ! doList()) { - transferStage = FTP_Close; - } else { - releaseFS(); - } - } else if( transferStage == FTP_Mlsd ) { // MLSD listing - if( ! doMlsd()) { - transferStage = FTP_Close; - } else { - releaseFS(); - } - } else if( cmdStage > FTP_Client && - ! ((int32_t) ( millisEndConnection - millis() ) > 0 )) { - client << F("530 Timeout") << eol; - millisDelay = millis() + 200; // delay of 200 ms - cmdStage = FTP_Stop; - } - -#ifdef FTP_DEBUG - uint8_t dstat = data.status(); - if( cmdStage != cmdStage0 || transferStage != transferStage0 || - dstat != data0 ) { - log_esp3d (" Command: %d Transfer: %d Data: %d", cmdStage, transferStage, _HEX( dstat )); - } -#endif -} - -void FtpServer::clientConnected() -{ - log_esp3d(" 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"); - _currentUser = ""; -#ifdef AUTHENTICATION_FEATURE - if ((user != nullptr) && ((strcmp(user, DEFAULT_ADMIN_LOGIN) == 0) || (strcmp(user, DEFAULT_USER_LOGIN) == 0))) { - _currentUser = user; - return true; - } - return false; -#endif //AUTHENTICATION_FEATURE - (void)user; - _currentUser = DEFAULT_ADMIN_LOGIN; - log_esp3d("User is %s",_currentUser.c_str()); +bool FtpServer::begin() { + end(); + if (Settings_ESP3D::read_byte(ESP_FTP_ON) != 1) { return true; - -} -bool FtpServer::isPassword(const char * password) -{ - log_esp3d("Check Password"); -#ifdef AUTHENTICATION_FEATURE - if(((_currentUser == DEFAULT_ADMIN_LOGIN) && AuthenticationService::isadmin(password)) || - ((_currentUser == DEFAULT_USER_LOGIN) && AuthenticationService::isuser(password))) { - log_esp3d("Password ok"); - 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); + ftpServer = new WiFiServer(ctrlPort); + if (!ftpServer) { return false; -#endif //AUTHENTICATION_FEATURE - (void)password; + } + dataServer = new WiFiServer(passivePort); + if (!dataServer) { + return false; + } + // Tells the ftp server to begin listening for incoming connection + ftpServer->begin(); + ftpServer->setNoDelay(true); + dataServer->begin(); + millisDelay = 0; + cmdStage = FTP_Stop; + iniVariables(); + _started = true; + _fsType = FS_UNKNOWN; + return _started; +} + +bool FtpServer::accessFS(const char* path) { + if (_fsType != FS_UNKNOWN) { + log_esp3d_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"); + _fsType = FS_UNKNOWN; + FTPFS::releaseFS(); + return false; + } else { + FTPFS::setState(ESP_SDCARD_BUSY); + log_esp3d("FTP: accessFS: Accessed granted"); + } +#endif // FTP_FEATURE == FS_SD + return true; + } + log_esp3d_e("FTP: accessFS: Access denied"); + return false; +} +void FtpServer::releaseFS() { + if (_fsType != FS_UNKNOWN) { + FTPFS::releaseFS(_fsType); + log_esp3d("FTP: accessFS: Access revoked"); + _fsType = FS_UNKNOWN; + } +} + +void FtpServer::iniVariables() { + // Default for data port + dataPort = activePort; + + // Default Data connection is Active + dataConn = FTP_NoConn; + + // Set the root directory + strcpy(cwdName, "/"); + + rnfrCmd = false; + transferStage = FTP_Close; +} + +void FtpServer::handle() { + if (!_started) { + return; + } +#ifdef FTP_DEBUG + int8_t data0 = data.status(); + ftpTransfer transferStage0 = transferStage; + ftpCmd cmdStage0 = cmdStage; +#endif + + if ((int32_t)(millisDelay - millis()) > 0) { + return; + } + + if (cmdStage == FTP_Stop) { + log_esp3d("FTP_STOP"); + releaseFS(); + if (client.connected()) { + disconnectClient(); + } + cmdStage = FTP_Init; + } else if (cmdStage == FTP_Init) { // Ftp server waiting for connection + abortTransfer(); + iniVariables(); + log_esp3d(" Ftp server waiting for connection on port %d", ctrlPort); + cmdStage = FTP_Client; + } else if (cmdStage == FTP_Client) { // Ftp server idle + if (ftpServer->hasClient()) { + client.stop(); + client = ftpServer->available(); + } + if (client.connected()) { // A client connected + clientConnected(); + millisEndConnection = + millis() + 1000L * FTP_AUTH_TIME_OUT; // wait client id for 10 s. + cmdStage = FTP_User; + } + } else if (readChar() > 0) { // got response + processCommand(); + if (cmdStage == FTP_Stop) { + millisEndConnection = + millis() + + 1000L * FTP_AUTH_TIME_OUT; // wait authentication for 10 s. + } else if (cmdStage < FTP_Cmd) { + millisDelay = millis() + 200; // delay of 100 ms + } else { + millisEndConnection = millis() + 1000L * FTP_TIME_OUT; + } + } else if (!client.connected()) { + cmdStage = FTP_Init; + } + + if (transferStage == FTP_Retrieve) { // Retrieve data + if (!doRetrieve()) { + transferStage = FTP_Close; + log_esp3d("Release FS"); + releaseFS(); + } + } else if (transferStage == FTP_Store) { // Store data + if (!doStore()) { + transferStage = FTP_Close; + log_esp3d("Release FS"); + releaseFS(); + } + } else if (transferStage == FTP_List || + transferStage == FTP_Nlst) { // LIST or NLST + if (!doList()) { + transferStage = FTP_Close; + log_esp3d("Release FS"); + releaseFS(); + } + } else if (transferStage == FTP_Mlsd) { // MLSD listing + if (!doMlsd()) { + transferStage = FTP_Close; + log_esp3d("Release FS"); + releaseFS(); + } + } else if (cmdStage > FTP_Client && + !((int32_t)(millisEndConnection - millis()) > 0)) { + client << F("530 Timeout") << eol; + millisDelay = millis() + 200; // delay of 200 ms + cmdStage = FTP_Stop; + releaseFS(); + } + +#ifdef FTP_DEBUG + uint8_t dstat = data.status(); + if (cmdStage != cmdStage0 || transferStage != transferStage0 || + dstat != data0) { + log_esp3d(" Command: %d Transfer: %d Data: %d", cmdStage, transferStage, + _HEX(dstat)); + } +#endif +} + +void FtpServer::clientConnected() { + log_esp3d(" 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"); + _currentUser = ""; +#ifdef AUTHENTICATION_FEATURE + if ((user != nullptr) && ((strcmp(user, DEFAULT_ADMIN_LOGIN) == 0) || + (strcmp(user, DEFAULT_USER_LOGIN) == 0))) { + _currentUser = user; + return true; + } + return false; +#endif // AUTHENTICATION_FEATURE + (void)user; + _currentUser = DEFAULT_ADMIN_LOGIN; + log_esp3d("User is %s", _currentUser.c_str()); + return true; +} +bool FtpServer::isPassword(const char* password) { + log_esp3d("Check Password"); +#ifdef AUTHENTICATION_FEATURE + if (((_currentUser == DEFAULT_ADMIN_LOGIN) && + AuthenticationService::isadmin(password)) || + ((_currentUser == DEFAULT_USER_LOGIN) && + AuthenticationService::isuser(password))) { log_esp3d("Password ok"); return true; + } + return false; +#endif // AUTHENTICATION_FEATURE + (void)password; + log_esp3d("Password ok"); + return true; } -void FtpServer::disconnectClient() -{ - log_esp3d(" Disconnecting client"); - abortTransfer(); +void FtpServer::disconnectClient() { + log_esp3d(" Disconnecting client"); + abortTransfer(); + client << F("221 Goodbye") << eol; + client.stop(); + _currentUser = ""; +} + +bool FtpServer::processCommand() { + log_esp3d("Process Command"); + /////////////////////////////////////// + // // + // AUTHENTICATION COMMANDS // + // // + /////////////////////////////////////// + + // + // USER - User Identity + // + if (CommandIs("USER")) { + log_esp3d("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"); + client << F("530 ") << eol; + cmdStage = FTP_Stop; + } + } + // + // PASS - Password + // + else if (CommandIs("PASS")) { + log_esp3d("PASS : Command: %s Param: %s", command, + (parameter == nullptr) ? "" : parameter); + if (cmdStage != FTP_Pass) { + log_esp3d_e("Error PASS"); + client << F("503 ") << eol; + cmdStage = FTP_Stop; + } + if (isPassword(parameter)) { + log_esp3d(" Authentication Ok. Waiting for commands."); + client << F("230 Ok") << eol; + cmdStage = FTP_Cmd; + } else { + log_esp3d_e("Wrong PASS"); + client << F("530 ") << eol; + cmdStage = FTP_Stop; + } + } + // + // FEAT - New Features + // + else if (CommandIs("FEAT")) { + client << F("211-Extensions suported:") << eol; + client << F(" MLST type*;modify*;size*;") << eol; + client << F(" MLSD") << eol; + client << F(" MDTM") << eol; + client << F(" MFMT") << eol; + client << F(" SIZE") << eol; + client << F(" SITE FREE") << eol; + client << F("211 End.") << eol; + } + // + // AUTH - Not implemented + // + else if (CommandIs("AUTH")) { + client << F("502 ") << eol; + } + // + // OPTS / SYST - Not implemented + // + else if ((cmdStage < FTP_Cmd) && + (CommandIs("OPTS") || CommandIs("SYST") || CommandIs("TYPE"))) { + log_esp3d_e("Unsupported Command: %s Param: %s stage %d", command, + (parameter == nullptr) ? "" : parameter, cmdStage); + client << F("500 ") << eol; + cmdStage = FTP_User; + } + // + // Unrecognized commands at stage of authentication + // + else if (cmdStage < FTP_Cmd) { + log_esp3d_e("Unknow Command: %s Param: %s stage %d", command, + (parameter == nullptr) ? "" : parameter, cmdStage); + client << F("200 ") << eol; + cmdStage = FTP_Stop; + } + + /////////////////////////////////////// + // // + // ACCESS CONTROL COMMANDS // + // // + /////////////////////////////////////// + + // + // PWD - Print Directory + // + else if (CommandIs("PWD") || (CommandIs("CWD") && ParameterIs("."))) { + client << F("257 \"") << cwdName << F("\"") + << F(" is your current directory") << eol; + } + // + // CDUP - Change to Parent Directory + // + else if (CommandIs("CDUP") || (CommandIs("CWD") && ParameterIs(".."))) { + bool ok = false; + + if (strlen(cwdName) > 1) { // do nothing if cwdName is root + // if cwdName ends with '/', remove it (must not append) + if (cwdName[strlen(cwdName) - 1] == '/') { + cwdName[strlen(cwdName) - 1] = 0; + } + // search last '/' + char* pSep = strrchr(cwdName, '/'); + ok = pSep > cwdName; + // if found, ends the string on its position + if (ok) { + *pSep = 0; + log_esp3d("FTP: check accessFS"); + if (accessFS(cwdName)) { + ok = FTPFS::exists(cwdName); + log_esp3d("FTP: releaseFS"); + releaseFS(); + } else { + ok = false; + log_esp3d_e("FTP: access is denied"); + } + } + } + // if an error appends, move to root + if (!ok) { + strcpy(cwdName, "/"); + } + client << F("250 Ok. Current directory is ") << cwdName << eol; + } + // + // CWD - Change Working Directory + // + else if (CommandIs("CWD")) { + char path[FTP_CWD_SIZE]; + if (haveParameter() && makeExistsPath(path)) { + strcpy(cwdName, path); + client << F("250 Directory changed to ") << cwdName << eol; + } + } + // + // QUIT + // + else if (CommandIs("QUIT")) { + log_esp3d("QUIT"); client << F("221 Goodbye") << eol; - client.stop(); - _currentUser = ""; -} + log_esp3d("FTP: releaseFS"); + releaseFS(); + disconnectClient(); + cmdStage = FTP_Stop; + } -bool FtpServer::processCommand() -{ - log_esp3d("Process Command"); - /////////////////////////////////////// - // // - // AUTHENTICATION COMMANDS // - // // - /////////////////////////////////////// + /////////////////////////////////////// + // // + // TRANSFER PARAMETER COMMANDS // + // // + /////////////////////////////////////// - // - // USER - User Identity - // - if( CommandIs( "USER" )) { - log_esp3d("USER : Command: %s Param: %s", command, (parameter == nullptr)?"":parameter); - if( isUser(parameter)) { - client << F("331 Ok. Password required") << eol; - strcpy( cwdName, "/" ); - cmdStage = FTP_Pass; + // + // MODE - Transfer Mode + // + else if (CommandIs("MODE")) { + if (ParameterIs("S")) { + client << F("200 S Ok") << eol; + } else { + client << F("504 Only S(tream) is suported") << eol; + } + } + // + // PASV - Passive Connection management + // + else if (CommandIs("PASV")) { + data.stop(); + dataServer->begin(); + dataIp.fromString(NetConfig::localIP()); + dataPort = passivePort; + log_esp3d(" Connection management set to passive"); + log_esp3d(" 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; + dataConn = FTP_Pasive; + } + // + // PORT - Data Port + // + else if (CommandIs("PORT")) { + data.stop(); + // get IP of data client + dataIp[0] = atoi(parameter); + char* p = strchr(parameter, ','); + for (uint8_t i = 1; i < 4; i++) { + dataIp[i] = atoi(++p); + p = strchr(p, ','); + } + // get port of data client + dataPort = 256 * atoi(++p); + p = strchr(p, ','); + dataPort += atoi(++p); + 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); + client << F("200 PORT command successful") << eol; + dataConn = FTP_Active; + } + } + // + // STRU - File Structure + // + else if (CommandIs("STRU")) { + if (ParameterIs("F")) { + client << F("200 F Ok") << eol; + } + // else if( ParameterIs( "R" )) + // client << F("200 B Ok") << eol; + else { + log_esp3d_e("504 Only F(ile) is suported"); + client << F("504 Only F(ile) is suported") << eol; + } + } + // + // TYPE - Data Type + // + else if (CommandIs("TYPE")) { + if (ParameterIs("A")) { + client << F("200 TYPE is now ASCII") << eol; + } else if (ParameterIs("I")) { + client << F("200 TYPE is now 8-bit binary") << eol; + } else { + client << F("504 Unknow TYPE") << eol; + } + } + + /////////////////////////////////////// + // // + // FTP SERVICE COMMANDS // + // // + /////////////////////////////////////// + + // + // ABOR - Abort + // + else if (CommandIs("ABOR")) { + abortTransfer(); + client << F("226 Data connection closed") << eol; + } + // + // DELE - Delete a File + // + else if (CommandIs("DELE")) { + char path[FTP_CWD_SIZE]; + if (haveParameter() && makeExistsPath(path)) { + log_esp3d("FTP: check accessFS"); + if (accessFS(path)) { + if (FTPFS::remove(path)) { + client << F("250 Deleted ") << parameter << eol; } else { - log_esp3d("Error USER"); - client << F("530 ") << eol; - cmdStage = FTP_Stop; + client << F("450 Can't delete ") << parameter << eol; + log_esp3d_e("FTP: Can't delete %s", parameter); } - } - // - // PASS - Password - // - else if( CommandIs( "PASS" )) { - log_esp3d("PASS : Command: %s Param: %s", command, (parameter == nullptr)?"":parameter); - if( cmdStage != FTP_Pass ) { - log_esp3d("Error PASS"); - client << F("503 ") << eol; - cmdStage = FTP_Stop; - } - if( isPassword(parameter)) { - log_esp3d(" Authentication Ok. Waiting for commands."); - client << F("230 Ok") << eol; - cmdStage = FTP_Cmd; - } else { - log_esp3d("Wrong PASS"); - client << F("530 ") << eol; - cmdStage = FTP_Stop; - } - } - // - // FEAT - New Features - // - else if( CommandIs( "FEAT" )) { - client << F("211-Extensions suported:") << eol; - client << F(" MLST type*;modify*;size*;") << eol; - client << F(" MLSD") << eol; - client << F(" MDTM") << eol; - client << F(" MFMT") << eol; - client << F(" SIZE") << eol; - client << F(" SITE FREE") << eol; - client << F("211 End.") << eol; - } - // - // AUTH - Not implemented - // - else if( CommandIs( "AUTH" )) { - client << F("502 ") << eol; - } - // - // OPTS / SYST - Not implemented - // - else if((cmdStage < FTP_Cmd) && ( CommandIs( "OPTS" ) || CommandIs( "SYST" ) || CommandIs( "TYPE" ))) { - log_esp3d("Unsupported Command: %s Param: %s stage %d", command, (parameter == nullptr)?"":parameter, cmdStage); - client << F("500 ") << eol; - cmdStage = FTP_User; - } - // - // Unrecognized commands at stage of authentication - // - else if(cmdStage < FTP_Cmd) { - log_esp3d("Unknow Command: %s Param: %s stage %d", command, (parameter == nullptr)?"":parameter, cmdStage); - client << F("200 ") << eol; - cmdStage = FTP_Stop; - } - - /////////////////////////////////////// - // // - // ACCESS CONTROL COMMANDS // - // // - /////////////////////////////////////// - - // - // PWD - Print Directory - // - else if( CommandIs( "PWD" ) || - ( CommandIs( "CWD" ) && ParameterIs( "." ))) { - client << F("257 \"") << cwdName << F("\"") << F(" is your current directory") << eol; - } - // - // CDUP - Change to Parent Directory - // - else if( CommandIs( "CDUP" ) || - ( CommandIs( "CWD" ) && ParameterIs( ".." ))) { - bool ok = false; - - if( strlen( cwdName ) > 1 ) { // do nothing if cwdName is root - // if cwdName ends with '/', remove it (must not append) - if( cwdName[ strlen( cwdName ) - 1 ] == '/' ) { - cwdName[ strlen( cwdName ) - 1 ] = 0; - } - // search last '/' - char * pSep = strrchr( cwdName, '/' ); - ok = pSep > cwdName; - // if found, ends the string on its position - if( ok ) { - * pSep = 0; - log_esp3d("FTP: check accessFS"); - if (accessFS(cwdName)) { - ok = FTPFS::exists( cwdName ); - log_esp3d("FTP: releaseFS"); - releaseFS(); - } else { - ok = false; - } - } - } - // if an error appends, move to root - if( ! ok ) { - strcpy( cwdName, "/" ); - } - client << F("250 Ok. Current directory is ") << cwdName << eol; - } - // - // CWD - Change Working Directory - // - else if( CommandIs( "CWD" )) { - char path[ FTP_CWD_SIZE ]; - if( haveParameter() && makeExistsPath( path )) { - strcpy( cwdName, path ); - client << F("250 Directory changed to ") << cwdName << eol; - } - } - // - // QUIT - // - else if( CommandIs( "QUIT" )) { - log_esp3d("QUIT"); - client << F("221 Goodbye") << eol; log_esp3d("FTP: releaseFS"); releaseFS(); - disconnectClient(); - cmdStage = FTP_Stop; + } else { + client << F("550 Can't access ") << parameter << eol; + log_esp3d_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); } - - /////////////////////////////////////// - // // - // TRANSFER PARAMETER COMMANDS // - // // - /////////////////////////////////////// - - // - // MODE - Transfer Mode - // - else if( CommandIs( "MODE" )) { - if( ParameterIs( "S" )) { - client << F("200 S Ok") << eol; + } + // + // LIST - List + // NLST - Name List + // MLSD - Listing for Machine Processing (see RFC 3659) + // + else if (CommandIs("LIST") || CommandIs("NLST") || CommandIs("MLSD")) { + bool access = false; + if (dataConnect()) { + log_esp3d("FTP: check accessFS"); + access = accessFS(cwdName); + if (access) { + dir = FTPFS::open(cwdName); + log_esp3d("Open %s", cwdName); + } + } + if (dir) { + log_esp3d("Dir open"); + nbMatch = 0; + if (CommandIs("LIST")) { + log_esp3d("FTP: LIST"); + transferStage = FTP_List; + } else if (CommandIs("NLST")) { + log_esp3d("FTP: NLST"); + transferStage = FTP_Nlst; + } else { + log_esp3d("FTP: MLSD"); + transferStage = FTP_Mlsd; + } + } else { + log_esp3d("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"); + releaseFS(); + } + client << F("550 Can't open directory ") << cwdName << eol; + log_esp3d_e("FTP: Can't open directory %s", cwdName); + data.stop(); + } + } + // + // MLST - Listing for Machine Processing (see RFC 3659) + // + else if (CommandIs("MLST")) { + char path[FTP_CWD_SIZE]; + time_t t = 0; + char dtStr[15]; + bool isdir = false; + if (haveParameter() && makeExistsPath(path)) { + log_esp3d("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); } else { - client << F("504 Only S(tream) is suported") << eol; + if (file = FTPFS::open(path)) { + isdir = file.isDirectory(); + t = file.getLastWrite(); + file.close(); + } + client << F("250-Begin") << eol << F(" Type=") + << (isdir ? F("dir") : F("file")) << F(";Modify=") + << makeDateTimeStr(dtStr, t); + if (!isdir) { + client << F(";Size=") << file.size(); + } + client << F("; ") << path << eol << F("250 End.") << eol; } + log_esp3d("FTP: releaseFS"); + releaseFS(); + } else { + client << F("550 Can't access ") << parameter << eol; + log_esp3d_e("FTP: Can't access %s", parameter); + } } - // - // PASV - Passive Connection management - // - else if( CommandIs( "PASV" )) { - data.stop(); - dataServer->begin(); - dataIp.fromString(NetConfig::localIP()); - dataPort = passivePort; - log_esp3d(" Connection management set to passive"); - log_esp3d(" 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; - dataConn = FTP_Pasive; - } - // - // PORT - Data Port - // - else if( CommandIs( "PORT" )) { - data.stop(); - // get IP of data client - dataIp[ 0 ] = atoi( parameter ); - char * p = strchr( parameter, ',' ); - for( uint8_t i = 1; i < 4; i ++ ) { - dataIp[ i ] = atoi( ++ p ); - p = strchr( p, ',' ); + } + // + // NOOP + // + else if (CommandIs("NOOP")) { + client << F("200 Zzz...") << eol; + } + // + // RETR - Retrieve + // + else if (CommandIs("RETR")) { + char path[FTP_CWD_SIZE]; + if (haveParameter() && makeExistsPath(path)) { + log_esp3d("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"); + releaseFS(); + } else if (dataConnect(false)) { + log_esp3d(" Sending %s", parameter); + client << F("150-Connected to port ") << dataPort << eol; + client << F("150 ") << file.size() << F(" bytes to download") << eol; + millisBeginTrans = millis(); + bytesTransfered = 0; + transferStage = FTP_Retrieve; } - // get port of data client - dataPort = 256 * atoi( ++ p ); - p = strchr( p, ',' ); - dataPort += atoi( ++ p ); - if( p == NULL ) { - client << F("501 Can't interpret parameters") << eol; + } else { + client << F("550 Can't access ") << parameter << eol; + log_esp3d_e("FTP: Can't access %s", parameter); + } + } + } + // + // STOR - Store + // APPE - Append + // + else if (CommandIs("STOR") || CommandIs("APPE")) { + char path[FTP_CWD_SIZE]; + if (haveParameter() && makePath(path)) { + log_esp3d("FTP: check accessFS"); + if (accessFS(path)) { + if (FTPFS::exists(path)) { + file = FTPFS::open( + path, ESP_FILE_WRITE | + (CommandIs("APPE") ? ESP_FILE_APPEND : ESP_FILE_WRITE)); } else { - log_esp3d(" Data IP set to %s", dataIp.toString().c_str()); - log_esp3d(" Data port set to %d", dataPort); - client << F("200 PORT command successful") << eol; - dataConn = FTP_Active; + file = FTPFS::open(path, ESP_FILE_WRITE); } - } - // - // STRU - File Structure - // - else if( CommandIs( "STRU" )) { - if( ParameterIs( "F" )) { - client << F("200 F Ok") << eol; - } - // else if( ParameterIs( "R" )) - // client << F("200 B Ok") << eol; - else { - client << F("504 Only F(ile) is suported") << eol; - } - } - // - // TYPE - Data Type - // - else if( CommandIs( "TYPE" )) { - if( ParameterIs( "A" )) { - client << F("200 TYPE is now ASCII") << eol; - } else if( ParameterIs( "I" )) { - client << F("200 TYPE is now 8-bit binary") << eol; + 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"); + releaseFS(); + } else if (!dataConnect()) { + file.close(); + log_esp3d("FTP: releaseFS"); + releaseFS(); } else { - client << F("504 Unknow TYPE") << eol; + log_esp3d(" 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); + } } - - /////////////////////////////////////// - // // - // FTP SERVICE COMMANDS // - // // - /////////////////////////////////////// - - // - // ABOR - Abort - // - else if( CommandIs( "ABOR" )) { - abortTransfer(); - client << F("226 Data connection closed") << eol; + } + // + // MKD - Make Directory + // + else if (CommandIs("MKD") || CommandIs("XMKD")) { + char path[FTP_CWD_SIZE]; + if (haveParameter() && makePath(path)) { + log_esp3d("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); + 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); + } + } + log_esp3d("FTP: releaseFS"); + releaseFS(); + } else { + client << F("550 Can't access ") << parameter << eol; + log_esp3d_e("FTP: Can't access %s", parameter); + } } - // - // DELE - Delete a File - // - else if( CommandIs( "DELE" )) { - char path[ FTP_CWD_SIZE ]; - if(haveParameter() && makeExistsPath( path )) { - log_esp3d("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("FTP: releaseFS"); - releaseFS(); + } + // + // RMD - Remove a Directory + // + else if (CommandIs("RMD") || CommandIs("XRMD")) { + char path[FTP_CWD_SIZE]; + if (haveParameter() && makeExistsPath(path)) { + log_esp3d("FTP: check accessFS"); + if (accessFS(path)) { + if (FTPFS::rmdir(path)) { + log_esp3d(" 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); + } + log_esp3d("FTP: releaseFS"); + releaseFS(); + } else { + client << F("550 Can't access ") << parameter << eol; + log_esp3d_e("FTP: Can't access %s", parameter); + } + } + } + // + // RNFR - Rename From + // + else if (CommandIs("RNFR")) { + rnfrName[0] = 0; + if (haveParameter() && makeExistsPath(rnfrName)) { + log_esp3d(" Ready for renaming %s", rnfrName); + client << F("350 RNFR accepted - file exists, ready for destination") + << eol; + rnfrCmd = true; + } + } + // + // RNTO - Rename To + // + else if (CommandIs("RNTO")) { + char path[FTP_CWD_SIZE]; + char dirp[FTP_FIL_SIZE]; + if (strlen(rnfrName) == 0 || !rnfrCmd) { + client << F("503 Need RNFR before RNTO") << eol; + } else if (haveParameter() && makePath(path)) { + log_esp3d("FTP: check accessFS"); + if (accessFS(path)) { + if (FTPFS::exists(path)) { + client << F("553 ") << parameter << F(" already exists") << eol; + } else { + strcpy(dirp, path); + char* psep = strrchr(dirp, '/'); + bool fail = psep == NULL; + if (!fail) { + if (psep == dirp) { + psep++; + } + *psep = 0; + FTPFile f = FTPFS::open(dirp); + f.close(); + fail = !f.isDirectory(); + if (fail) { + client << F("550 \"") << dirp << F("\" is not directory") << eol; } else { - client << F("550 Can't access ") << parameter << eol; + log_esp3d(" Renaming %s to %s", rnfrName, path); + if (FTPFS::rename(rnfrName, path)) { + client << F("250 File successfully renamed or moved") << eol; + } else { + fail = true; + } } - } else { - client << F("550 Can't access ") << parameter << eol; + } + if (fail) { + client << F("451 Rename/move failure") << eol; + log_esp3d_e("FTP: Rename/move failure"); + } } + log_esp3d("FTP: releaseFS"); + releaseFS(); + } else { + client << F("550 Can't access ") << parameter << eol; + log_esp3d_e("FTP: Can't access %s", parameter); + } } -// -// LIST - List -// NLST - Name List -// MLSD - Listing for Machine Processing (see RFC 3659) -// - else if( CommandIs( "LIST" ) || CommandIs( "NLST" ) || CommandIs( "MLSD" )) { - bool access = false; - if( dataConnect()) { - log_esp3d("FTP: check accessFS"); - access = accessFS(cwdName); - if (access) { - dir = FTPFS::open(cwdName); - } - } - if (dir) { - nbMatch = 0; - if( CommandIs( "LIST" )) { - transferStage = FTP_List; - } else if( CommandIs( "NLST" )) { - transferStage = FTP_Nlst; + rnfrCmd = false; + } + + // + // SYST - System + // + else if (CommandIs("SYST")) { + client << F("215 ESP3D") << eol; + } + + /////////////////////////////////////// + // // + // EXTENSIONS COMMANDS (RFC 3659) // + // // + /////////////////////////////////////// + + // + // MDTM && MFMT - File Modification Time (see RFC 3659) + // + else if (CommandIs("MDTM") || CommandIs("MFMT")) { + if (haveParameter()) { + char path[FTP_CWD_SIZE]; + char* fname = parameter; + uint16_t year; + uint8_t month, day, hour, minute, second, setTime; + char dt[15]; + bool mdtm = CommandIs("MDTM"); + + setTime = getDateTime(dt, &year, &month, &day, &hour, &minute, &second); + // fname point to file name + fname += setTime; + if (strlen(fname) <= 0) { + client << "501 No file name" << eol; + } else if (makeExistsPath(path, fname)) { + if (setTime) { // set file modification time + if (timeStamp(path, year, month, day, hour, minute, second)) { + client << "213 " << dt << eol; + } else { + client << "550 Unable to modify time" << eol; + log_esp3d_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"); + if (accessFS(path)) { + if (getFileModTime(path, t)) { + client << "213 " << makeDateTimeStr(dtStr, t) << eol; } else { - transferStage = FTP_Mlsd; - } - } else { - //we got access but file opening failed, so let's release the FS - if (access) { - log_esp3d("FTP: releaseFS"); - releaseFS(); - } - client << F("550 Can't open directory ") << cwdName << eol; - data.stop(); - } - } -// -// MLST - Listing for Machine Processing (see RFC 3659) -// - else if( CommandIs( "MLST" )) { - char path[ FTP_CWD_SIZE ]; - time_t t = 0; - char dtStr[ 15 ]; - bool isdir = false; - if( haveParameter() && makeExistsPath( path )) { - log_esp3d("FTP: check accessFS"); - if (accessFS(path)) { - if( ! getFileModTime( path, t )) { - client << F("550 Unable to retrieve time for ") << parameter << eol; - } else { - if( file = FTPFS::open(path)) { - isdir = file.isDirectory(); - t = file.getLastWrite(); - file.close(); - } - client << F("250-Begin") << eol - << F(" Type=") << ( isdir ? F("dir") : F("file")) - << F(";Modify=") << makeDateTimeStr( dtStr, t ); - if( ! isdir ) { - client << F(";Size=") << file.size(); - } - client << F("; ") << path << eol - << F("250 End.") << eol; - } - log_esp3d("FTP: releaseFS"); - releaseFS(); - } - } - } -// -// NOOP -// - else if( CommandIs( "NOOP" )) { - client << F("200 Zzz...") << eol; - } -// -// RETR - Retrieve -// - else if( CommandIs( "RETR" )) { - char path[ FTP_CWD_SIZE ]; - if( haveParameter() && makeExistsPath( path )) { - log_esp3d("FTP: check accessFS"); - if( accessFS(path)) { - file = FTPFS::open(path); - if( ! file.isOpen()) { - client << F("450 Can't open ") << parameter << eol; - log_esp3d("FTP: releaseFS"); - releaseFS(); - } else if( dataConnect( false )) { - log_esp3d(" Sending %s", parameter); - client << F("150-Connected to port ") << dataPort << eol; - client << F("150 ") << file.size() << F(" bytes to download") << eol; - millisBeginTrans = millis(); - bytesTransfered = 0; - transferStage = FTP_Retrieve; - } - } - } - } -// -// STOR - Store -// APPE - Append -// - else if( CommandIs( "STOR" ) || CommandIs( "APPE" )) { - char path[ FTP_CWD_SIZE ]; - if( haveParameter() && makePath( path )) { - log_esp3d("FTP: check accessFS"); - if(accessFS(path)) { - if( FTPFS::exists( path )) { - file = FTPFS::open( path, ESP_FILE_WRITE | ( CommandIs( "APPE" ) ? ESP_FILE_APPEND : ESP_FILE_WRITE )); - } else { - file = FTPFS::open( path, ESP_FILE_WRITE ); - } - if( ! file.isOpen() ) { - client << F("451 Can't open/create ") << parameter << eol; - log_esp3d("FTP: releaseFS"); - releaseFS(); - } else if( ! dataConnect()) { - file.close(); - log_esp3d("FTP: releaseFS"); - releaseFS(); - } else { - log_esp3d(" Receiving %s", parameter); - millisBeginTrans = millis(); - bytesTransfered = 0; - transferStage = FTP_Store; - } - } - } - } -// -// MKD - Make Directory -// - else if( CommandIs( "MKD" ) || CommandIs( "XMKD" )) { - char path[ FTP_CWD_SIZE ]; - if( haveParameter() && makePath( path )) { - log_esp3d("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); - if( FTPFS::mkdir( path )) { - client << F("257 \"") << parameter << F("\"") << F(" created") << eol; - } else { - client << F("550 Can't create \"") << parameter << F("\"") << eol; - } - } - log_esp3d("FTP: releaseFS"); - releaseFS(); - } - } - } -// -// RMD - Remove a Directory -// - else if( CommandIs( "RMD" ) || CommandIs( "XRMD" )) { - char path[ FTP_CWD_SIZE ]; - if( haveParameter() && makeExistsPath( path )) { - log_esp3d("FTP: check accessFS"); - if (accessFS(path)) { - if( FTPFS::rmdir( path )) { - log_esp3d(" 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("FTP: releaseFS"); - releaseFS(); - } - } - } -// -// RNFR - Rename From -// - else if( CommandIs( "RNFR" )) { - rnfrName[ 0 ] = 0; - if( haveParameter() && makeExistsPath( rnfrName )) { - log_esp3d(" Ready for renaming %s", rnfrName); - client << F("350 RNFR accepted - file exists, ready for destination") << eol; - rnfrCmd = true; - } - } -// -// RNTO - Rename To -// - else if( CommandIs( "RNTO" )) { - char path[ FTP_CWD_SIZE ]; - char dirp[ FTP_FIL_SIZE ]; - if( strlen( rnfrName ) == 0 || ! rnfrCmd ) { - client << F("503 Need RNFR before RNTO") << eol; - } else if( haveParameter() && makePath( path )) { - log_esp3d("FTP: check accessFS"); - if (accessFS(path)) { - if( FTPFS::exists( path )) { - client << F("553 ") << parameter << F(" already exists") << eol; - } else { - strcpy( dirp, path ); - char * psep = strrchr( dirp, '/' ); - bool fail = psep == NULL; - if( ! fail ) { - if( psep == dirp ) { - psep ++; - } - * psep = 0; - FTPFile f = FTPFS::open( dirp ); - f.close(); - fail = ! f.isDirectory(); - if( fail ) { - client << F("550 \"") << dirp << F("\" is not directory") << eol; - } else { - log_esp3d(" Renaming %s to %s", rnfrName, path); - if( FTPFS::rename( rnfrName, path )) { - client << F("250 File successfully renamed or moved") << eol; - } else { - fail = true; - } - } - } - if( fail ) { - client << F("451 Rename/move failure") << eol; - } - } - log_esp3d("FTP: releaseFS"); - releaseFS(); - } - } - rnfrCmd = false; - } - -// -// SYST - System -// - else if( CommandIs( "SYST" )) { - client << F("215 ESP3D") << eol; - } - - -/////////////////////////////////////// -// // -// EXTENSIONS COMMANDS (RFC 3659) // -// // -/////////////////////////////////////// - -// -// MDTM && MFMT - File Modification Time (see RFC 3659) -// - else if( CommandIs( "MDTM" ) || CommandIs( "MFMT" )) { - if( haveParameter()) { - char path[ FTP_CWD_SIZE ]; - char * fname = parameter; - uint16_t year; - uint8_t month, day, hour, minute, second, setTime; - char dt[ 15 ]; - bool mdtm = CommandIs( "MDTM" ); - - setTime = getDateTime( dt, & year, & month, & day, & hour, & minute, & second ); - // fname point to file name - fname += setTime; - if( strlen( fname ) <= 0 ) { - client << "501 No file name" << eol; - } else if( makeExistsPath( path, fname )) { - if( setTime ) { // set file modification time - if( timeStamp( path, year, month, day, hour, minute, second )) { - client << "213 " << dt << eol; - } else { - client << "550 Unable to modify time" << eol; - } - } else if( mdtm ) { // get file modification time - time_t t = 0; - char dtStr[ 15 ]; - log_esp3d("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("FTP: releaseFS"); - releaseFS(); - } else { - client << "550 Unable to retrieve time" << eol; - } - } - } - } - } -// -// SIZE - Size of the file -// - else if( CommandIs( "SIZE" )) { - char path[ FTP_CWD_SIZE ]; - if( haveParameter() && makeExistsPath( path )) { - log_esp3d("FTP: check accessFS"); - if (accessFS(path)) { - file = FTPFS::open( path ); - } - if( ! file.isOpen()) { - client << F("450 Can't open ") << parameter << eol; - } else { - client << F("213 ") << file.size() << eol; - file.close(); + client << "550 Unable to retrieve time" << eol; + log_esp3d_e("FTP: Unable to retrieve time"); } log_esp3d("FTP: releaseFS"); releaseFS(); + } else { + client << "550 Unable to retrieve time" << eol; + log_esp3d_e("FTP: Unable to retrieve time for %s", path); + } } + } } -// -// SITE - System command -// - else if( CommandIs( "SITE" )) { - if( ParameterIs( "FREE" )) { - log_esp3d("FTP: check accessFS"); - if (accessFS(cwdName)) { + } + // + // SIZE - Size of the file + // + else if (CommandIs("SIZE")) { + char path[FTP_CWD_SIZE]; + if (haveParameter() && makeExistsPath(path)) { + log_esp3d("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); + } else { + client << F("213 ") << file.size() << eol; + file.close(); + } + log_esp3d("FTP: releaseFS"); + releaseFS(); + } else { + client << F("550 Can't access ") << parameter << eol; + log_esp3d_e("FTP: Can't access %s", parameter); + } + } else { + log_esp3d_e("FTP:no parameter"); + } + } + // + // SITE - System command + // + else if (CommandIs("SITE")) { + if (ParameterIs("FREE")) { + log_esp3d("FTP: check accessFS"); + if (accessFS(cwdName)) { #if FTP_FEATURE == FS_ROOT - uint8_t fs = FTPFS::getFSType(cwdName); - uint64_t capacity = FTPFS::totalBytes(fs); - uint64_t free = FTPFS::freeBytes(fs); + uint8_t fs = FTPFS::getFSType(cwdName); + uint64_t capacity = FTPFS::totalBytes(fs); + uint64_t free = FTPFS::freeBytes(fs); #else #if FTP_FEATURE == FS_FLASH - size_t capacity; - size_t free; + size_t capacity; + size_t free; #endif #if FTP_FEATURE == FS_SD - uint64_t capacity; - uint64_t free; + uint64_t capacity; + uint64_t free; #endif - capacity = FTPFS::totalBytes(); - free = FTPFS::freeBytes(); + 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"); - releaseFS(); - } - } else { - client << F("500 Unknow SITE command ") << parameter << eol; - } - } -// -// Unrecognized commands ... -// - else { - client << F("500 Unknow command") << eol; - } - return true; -} - -int FtpServer::dataConnect( bool out150 ) -{ - if( ! data.connected()) { - if( dataConn == FTP_Pasive ) { - uint16_t count = 1000; // wait up to a second - while( ! data.connected() && count -- > 0 ) { - if( dataServer->hasClient()) { - data.stop(); - data = dataServer->available(); - } - delay( 1 ); - } - } else if( dataConn == FTP_Active ) { - data.connect( dataIp, dataPort ); - } - } - if( ! data.connected()) { - client << F("425 No data connection") << eol; - } else if( out150 ) { - client << F("150 Accepted data connection to port ") << dataPort << eol; - } - - return data.connected(); -} - -bool FtpServer::dataConnected() -{ - if( data.connected()) { - return true; - } - data.stop(); - client << F("426 Data connection closed. Transfer aborted") << eol; - transferStage = FTP_Close; - return false; -} - -bool FtpServer::doRetrieve() -{ - if( ! dataConnected()) { - file.close(); - return false; - } - int16_t nb = file.read( buf, FTP_BUF_SIZE ); - if( nb > 0 ) { - data.write( buf, nb ); - bytesTransfered += nb; - return true; - } - closeTransfer(); - return false; -} - -bool FtpServer::doStore() -{ - int16_t na = data.available(); - if( na == 0 ) { - if( data.connected()) { - return true; - } else { - closeTransfer(); - return false; - } - } - if( na > FTP_BUF_SIZE ) { - na = FTP_BUF_SIZE; - } - int16_t nb = data.read((uint8_t *) buf, na ); - int16_t rc = 0; - if( nb > 0 ) { - rc = file.write( buf, nb ); - bytesTransfered += nb; - } - if( nb < 0 || rc == nb ) { - return true; - } - client << F("552 Probably insufficient storage space") << eol; - file.close(); - data.stop(); - return false; -} - -bool FtpServer::doList() -{ - if( ! dataConnected()) { - dir.close(); - return false; - } - if (dir) { - if (file) { - file.close(); - } - file = dir.openNextFile(); - if (file) { - time_t t = file.getLastWrite(); - char dtStr[ 15 ]; - data << (file.isDirectory()?"d":"-") << "rwxrwxrwx 1 " << _currentUser.c_str() << " " << _currentUser.c_str(); - String s = String(file.size()); - for(uint i = 0; i < SIZELISTPADING - s.length(); i++) { - data << " "; - } - data << file.size() << " " << makeDateTimeString(dtStr,t) << " " << file.name() << eol; - nbMatch ++; - file.close(); - return true; - } - } - client << F("226 ") << nbMatch << F(" matches total") << eol; - dir.close(); - data.stop(); - return false; -} - -bool FtpServer::doMlsd() -{ - if( ! dataConnected()) { - dir.close(); - return false; - } - if (dir) { - if(file) { - file.close(); - } - file = dir.openNextFile(); - if (file) { - char dtStr[ 15 ]; - time_t t = file.getLastWrite(); - 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(), makeDateTimeStr( dtStr, t), file.name()); - file.close(); - nbMatch ++; - return true; - } - } - client << F("226-options: -a -l") << eol; - client << F("226 ") << nbMatch << F(" matches total") << eol; - dir.close(); - data.stop(); - return false; -} - -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, 1.0*bytesTransfered / deltaT); - client << F("226-File successfully transferred") << eol; - client << F("226 ") << deltaT << F(" ms, ") - << bytesTransfered / deltaT << F(" kbytes/s") << eol; + client << F("200 ") << FTPFS::formatBytes(free) << F(" free of ") + << FTPFS::formatBytes(capacity) << F(" capacity") << eol; + log_esp3d("FTP: releaseFS"); + releaseFS(); + } else { + client << F("550 Can't access ") << cwdName << eol; + log_esp3d_e("FTP: Can't access %s", cwdName); + } } else { - client << F("226 File successfully transferred") << eol; + client << F("500 Unknow SITE command ") << parameter << eol; + log_esp3d_e("FTP: Unknow SITE command %s", parameter); } - - file.close(); - data.stop(); + } + // + // Unrecognized commands ... + // + else { + client << F("500 Unknow command") << eol; + log_esp3d_e("FTP: Unknow command %s", command); + } + return true; } -void FtpServer::abortTransfer() -{ - if( transferStage != FTP_Close ) { - file.close(); - dir.close(); - client << F("426 Transfer aborted") << eol; - log_esp3d(" Transfer aborted!"); - transferStage = FTP_Close; +int FtpServer::dataConnect(bool out150) { + if (!data.connected()) { + if (dataConn == FTP_Pasive) { + uint16_t count = 1000; // wait up to a second + while (!data.connected() && count-- > 0) { + if (dataServer->hasClient()) { + data.stop(); + data = dataServer->available(); + } + delay(1); + } + } else if (dataConn == FTP_Active) { + data.connect(dataIp, dataPort); } -// if( data.connected()) - data.stop(); + } + if (!data.connected()) { + client << F("425 No data connection") << eol; + } else if (out150) { + client << F("150 Accepted data connection to port ") << dataPort << eol; + } + + return data.connected(); +} + +bool FtpServer::dataConnected() { + if (data.connected()) { + return true; + } + data.stop(); + client << F("426 Data connection closed. Transfer aborted") << eol; + transferStage = FTP_Close; + return false; +} + +bool FtpServer::doRetrieve() { + if (!dataConnected()) { + file.close(); + return false; + } + int16_t nb = file.read(buf, FTP_BUF_SIZE); + if (nb > 0) { + data.write(buf, nb); + bytesTransfered += nb; + return true; + } + closeTransfer(); + return false; +} + +bool FtpServer::doStore() { + int16_t na = data.available(); + if (na == 0) { + if (data.connected()) { + return true; + } else { + closeTransfer(); + return false; + } + } + if (na > FTP_BUF_SIZE) { + na = FTP_BUF_SIZE; + } + int16_t nb = data.read((uint8_t*)buf, na); + int16_t rc = 0; + if (nb > 0) { + rc = file.write(buf, nb); + bytesTransfered += nb; + } + if (nb < 0 || rc == nb) { + return true; + } + client << F("552 Probably insufficient storage space") << eol; + log_esp3d_e("FTP: Probably insufficient storage space"); + file.close(); + data.stop(); + return false; +} + +bool FtpServer::doList() { + if (!dataConnected()) { + log_esp3d_e("FTP: data not connected"); + dir.close(); + return false; + } + if (dir) { + if (file) { + file.close(); + } + file = dir.openNextFile(); + if (file) { + time_t t = file.getLastWrite(); + char dtStr[15]; + data << (file.isDirectory() ? "d" : "-") << "rwxrwxrwx 1 " + << _currentUser.c_str() << " " << _currentUser.c_str(); + String s = String(file.size()); + for (uint i = 0; i < SIZELISTPADING - s.length(); i++) { + data << " "; + } + data << file.size() << " " << makeDateTimeString(dtStr, t) << " " + << file.name() << eol; + nbMatch++; + file.close(); + return true; + } else { + log_esp3d("FTP: no more file"); + } + } else { + log_esp3d_e("FTP: dir not open"); + } + client << F("226 ") << nbMatch << F(" matches total") << eol; + dir.close(); + data.stop(); + return false; +} + +bool FtpServer::doMlsd() { + if (!dataConnected()) { + log_esp3d_e("FTP: data not connected"); + dir.close(); + return false; + } + if (dir) { + log_esp3d("FTP: dir open"); + if (file) { + file.close(); + } + file = dir.openNextFile(); + if (file) { + char dtStr[15]; + time_t t = file.getLastWrite(); + 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(), + makeDateTimeStr(dtStr, t), file.name()); + file.close(); + nbMatch++; + return true; + } else { + log_esp3d("FTP: no more file"); + } + } else { + log_esp3d_e("FTP: dir not open"); + } + client << F("226-options: -a -l") << eol; + client << F("226 ") << nbMatch << F(" matches total") << eol; + dir.close(); + data.stop(); + return false; +} + +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, + 1.0 * bytesTransfered / deltaT); + client << F("226-File successfully transferred") << eol; + client << F("226 ") << deltaT << F(" ms, ") << bytesTransfered / deltaT + << F(" kbytes/s") << eol; + } else { + client << F("226 File successfully transferred") << eol; + } + + file.close(); + data.stop(); +} + +void FtpServer::abortTransfer() { + if (transferStage != FTP_Close) { + file.close(); + dir.close(); + client << F("426 Transfer aborted") << eol; + log_esp3d_e(" Transfer aborted!"); + transferStage = FTP_Close; + } + // if( data.connected()) + data.stop(); } // Read a char from client connected to ftp server @@ -1183,76 +1232,77 @@ void FtpServer::abortTransfer() // 0 if empty line received // length of cmdLine (positive) if no empty line received -int8_t FtpServer::readChar() -{ - int8_t rc = -1; +int8_t FtpServer::readChar() { + int8_t rc = -1; - if( client.available()) { - char c = client.read(); - log_esp3d("read %c", c); - if( c == '\\' ) { - c = '/'; - } - if( c != '\r' ) { - if( c != '\n' ) { - if( iCL < FTP_CMD_SIZE ) { - cmdLine[ iCL ++ ] = c; - } else { - rc = -2; // Line too long - } - } else { - cmdLine[ iCL ] = 0; - command[ 0 ] = 0; - parameter = NULL; - // empty line? - if( iCL == 0 ) { - rc = 0; - } else { - rc = iCL; - // search for space between command and parameter - parameter = strchr( cmdLine, ' ' ); - if( parameter != NULL ) { - if( parameter - cmdLine > 4 ) { - rc = -2; // Syntax error - } else { - strncpy( command, cmdLine, parameter - cmdLine ); - command[ parameter - cmdLine ] = 0; - while( * ( ++ parameter ) == ' ' ) - ; - } - } else if( strlen( cmdLine ) > 4 ) { - rc = -2; // Syntax error. - } else { - strcpy( command, cmdLine ); - } - iCL = 0; - } - } - } - if( rc > 0 ) - for( uint8_t i = 0 ; i < strlen( command ); i ++ ) { - command[ i ] = toupper( command[ i ] ); - } - if( rc == -2 ) { - iCL = 0; - client << F("500 Syntax error") << eol; - } + if (client.available()) { + char c = client.read(); + log_esp3d("read %c", c); + if (c == '\\') { + c = '/'; } - return rc; + if (c != '\r') { + if (c != '\n') { + if (iCL < FTP_CMD_SIZE) { + cmdLine[iCL++] = c; + } else { + rc = -2; // Line too long + } + } else { + cmdLine[iCL] = 0; + command[0] = 0; + parameter = NULL; + // empty line? + if (iCL == 0) { + rc = 0; + } else { + rc = iCL; + // search for space between command and parameter + parameter = strchr(cmdLine, ' '); + if (parameter != NULL) { + if (parameter - cmdLine > 4) { + rc = -2; // Syntax error + } else { + strncpy(command, cmdLine, parameter - cmdLine); + command[parameter - cmdLine] = 0; + while (*(++parameter) == ' ') + ; + } + } else if (strlen(cmdLine) > 4) { + rc = -2; // Syntax error. + } else { + strcpy(command, cmdLine); + } + iCL = 0; + } + } + } + if (rc > 0) + for (uint8_t i = 0; i < strlen(command); i++) { + command[i] = toupper(command[i]); + } + if (rc == -2) { + iCL = 0; + client << F("500 Syntax error") << eol; + log_esp3d_e("FTP: Syntax error"); + } + } + return rc; } -bool FtpServer::haveParameter() -{ - if( parameter != NULL && strlen( parameter ) > 0 ) { - return true; - } - client << "501 No file name" << eol; - return false; +bool FtpServer::haveParameter() { + if (parameter != NULL && strlen(parameter) > 0) { + return true; + } + client << "501 No file name" << eol; + log_esp3d_e("FTP: No file name"); + return false; } // Make complete path/name from cwdName and param // -// 3 possible cases: parameter can be absolute path, relative path or only the name +// 3 possible cases: parameter can be absolute path, relative path or only the +// name // // parameter: // fullName : where to store the path/name @@ -1260,54 +1310,65 @@ bool FtpServer::haveParameter() // return: // true, if done -bool FtpServer::makePath( char * fullName, char * param ) -{ - if( param == NULL ) { - param = parameter; - } +bool FtpServer::makePath(char* fullName, char* param) { + if (param == NULL) { + param = parameter; + } - // Root or empty? - if( strcmp( param, "/" ) == 0 || strlen( param ) == 0 ) { - strcpy( fullName, "/" ); - return true; - } - // If relative path, concatenate with current dir - if( param[0] != '/' ) { - strcpy( fullName, cwdName ); - if( fullName[ strlen( fullName ) - 1 ] != '/' ) { - strncat( fullName, "/", FTP_CWD_SIZE ); - } - strncat( fullName, param, FTP_CWD_SIZE ); - } else { - strcpy( fullName, param ); - } - // If ends with '/', remove it - uint16_t strl = strlen( fullName ) - 1; - if( fullName[ strl ] == '/' && strl > 1 ) { - fullName[ strl ] = 0; - } - if( strlen( fullName ) >= FTP_CWD_SIZE ) { - client << F("500 Command line too long") << eol; - return false; - } - for( uint8_t i = 0; i < strlen( fullName ); i ++ ) - if( ! legalChar( fullName[i])) { - client << F("553 File name not allowed") << eol; - return false; - } + // Root or empty? + if (strcmp(param, "/") == 0 || strlen(param) == 0) { + strcpy(fullName, "/"); return true; + } + // If relative path, concatenate with current dir + if (param[0] != '/') { + strcpy(fullName, cwdName); + if (fullName[strlen(fullName) - 1] != '/') { + strncat(fullName, "/", FTP_CWD_SIZE); + } + strncat(fullName, param, FTP_CWD_SIZE); + } else { + strcpy(fullName, param); + } + // If ends with '/', remove it + uint16_t strl = strlen(fullName) - 1; + if (fullName[strl] == '/' && strl > 1) { + fullName[strl] = 0; + } + if (strlen(fullName) >= FTP_CWD_SIZE) { + client << F("500 Command line too long") << eol; + log_esp3d_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"); + return false; + } + return true; } -bool FtpServer::makeExistsPath( char * path, char * param ) -{ - if( ! makePath( path, param )) { - return false; - } - if( FTPFS::exists( path )) { - return true; - } - client << F("550 ") << path << F(" not found.") << eol; +bool FtpServer::makeExistsPath(char* path, char* param) { + if (!makePath(path, param)) { return false; + } + bool pathExists = false; + log_esp3d("FTP: check accessFS"); + if (accessFS(path)) { + pathExists = FTPFS::exists(path); + log_esp3d("FTP: releaseFS"); + releaseFS(); + } else { + pathExists = false; + log_esp3d_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); + return false; } // Calculate year, month, day, hour, minute and second @@ -1327,45 +1388,46 @@ bool FtpServer::makeExistsPath( char * path, char * param ) // Date/time are expressed as a 14 digits long string // terminated by a space and followed by name of file -uint8_t FtpServer::getDateTime( char * dt, uint16_t * pyear, uint8_t * pmonth, uint8_t * pday, - uint8_t * phour, uint8_t * pminute, uint8_t * psecond ) -{ - uint8_t i; - dt[ 0 ] = 0; - if( strlen( parameter ) < 15 ) { //|| parameter[ 14 ] != ' ' ) - return 0; +uint8_t FtpServer::getDateTime(char* dt, uint16_t* pyear, uint8_t* pmonth, + uint8_t* pday, uint8_t* phour, uint8_t* pminute, + uint8_t* psecond) { + uint8_t i; + dt[0] = 0; + if (strlen(parameter) < 15) { //|| parameter[ 14 ] != ' ' ) + return 0; + } + for (i = 0; i < 14; i++) + if (!isdigit(parameter[i])) { + return 0; } - for( i = 0; i < 14; i ++ ) - if( ! isdigit( parameter[ i ])) { - return 0; - } - for( i = 14; i < 18; i ++ ) - if( parameter[ i ] == ' ' ) { - break; - } else if( ! isdigit( parameter[ i ])) { - return 0; - } - if( i == 18 ) { - return 0; + for (i = 14; i < 18; i++) + if (parameter[i] == ' ') { + break; + } else if (!isdigit(parameter[i])) { + return 0; } - i ++ ; + if (i == 18) { + return 0; + } + i++; - strncpy( dt, parameter, 14 ); - dt[ 14 ] = 0; - * psecond = atoi( dt + 12 ); - dt[ 12 ] = 0; - * pminute = atoi( dt + 10 ); - dt[ 10 ] = 0; - * phour = atoi( dt + 8 ); - dt[ 8 ] = 0; - * pday = atoi( dt + 6 ); - dt[ 6 ] = 0 ; - * pmonth = atoi( dt + 4 ); - dt[ 4 ] = 0 ; - * pyear = atoi( dt ); - strncpy( dt, parameter, 14 ); - log_esp3d(" Modification time: %d/%d/%d %d:%d:%d of file: %s", * pyear, * pmonth, * pday, * phour, * pminute, * psecond, (char *) ( parameter + i )); - return i; + strncpy(dt, parameter, 14); + dt[14] = 0; + *psecond = atoi(dt + 12); + dt[12] = 0; + *pminute = atoi(dt + 10); + dt[10] = 0; + *phour = atoi(dt + 8); + dt[8] = 0; + *pday = atoi(dt + 6); + dt[6] = 0; + *pmonth = atoi(dt + 4); + dt[4] = 0; + *pyear = atoi(dt); + strncpy(dt, parameter, 14); + log_esp3d(" Modification time: %d/%d/%d %d:%d:%d of file: %s", *pyear, + *pmonth, *pday, *phour, *pminute, *psecond, (char*)(parameter + i)); + return i; } // Create string YYYYMMDDHHMMSS from time_t @@ -1377,11 +1439,12 @@ uint8_t FtpServer::getDateTime( char * dt, uint16_t * pyear, uint8_t * pmonth, u // return: // pointer to tstr -char * FtpServer::makeDateTimeStr( char * tstr, time_t timefile ) -{ - struct tm * tmstruct = localtime(&timefile); - sprintf( tstr, "%04u%02u%02u%02u%02u%02u",(tmstruct->tm_year)+1900,(tmstruct->tm_mon)+1, tmstruct->tm_mday, tmstruct->tm_hour, tmstruct->tm_min, tmstruct->tm_sec); - return tstr; +char* FtpServer::makeDateTimeStr(char* tstr, time_t timefile) { + struct tm* tmstruct = localtime(&timefile); + sprintf(tstr, "%04u%02u%02u%02u%02u%02u", (tmstruct->tm_year) + 1900, + (tmstruct->tm_mon) + 1, tmstruct->tm_mday, tmstruct->tm_hour, + tmstruct->tm_min, tmstruct->tm_sec); + return tstr; } // Create string MMM DD YYYY or MMM DD HH:MM from time_t @@ -1393,47 +1456,45 @@ char * FtpServer::makeDateTimeStr( char * tstr, time_t timefile ) // return: // pointer to tstr -char * FtpServer::makeDateTimeString( char * tstr, time_t timefile ) -{ - struct tm * tmstruct = localtime(&timefile); - time_t now; - time(&now); - struct tm tmstructnow; - localtime_r(&now, &tmstructnow); - if ((tmstruct->tm_year == tmstructnow.tm_year) && (timefile != 0)) { - strftime (tstr, 13, "%b %d %R", tmstruct); - } else { - strftime (tstr, 13, "%b %d %Y", tmstruct); - } - return tstr; +char* FtpServer::makeDateTimeString(char* tstr, time_t timefile) { + struct tm* tmstruct = localtime(&timefile); + time_t now; + time(&now); + struct tm tmstructnow; + localtime_r(&now, &tmstructnow); + if ((tmstruct->tm_year == tmstructnow.tm_year) && (timefile != 0)) { + strftime(tstr, 13, "%b %d %R", tmstruct); + } else { + strftime(tstr, 13, "%b %d %Y", tmstruct); + } + return tstr; } - -bool FtpServer::getFileModTime(const char * path, time_t & t) -{ - FTPFile f = FTPFS::open(path); - if (f) { - t = f.getLastWrite(); - f.close(); - return true; - } - log_esp3d("Cannot get getLastWrite"); - t = 0; - return false; +bool FtpServer::getFileModTime(const char* path, time_t& t) { + FTPFile f = FTPFS::open(path); + if (f) { + t = f.getLastWrite(); + f.close(); + return true; + } + log_esp3d_e("Cannot get getLastWrite"); + t = 0; + return false; } -//TODO -bool FtpServer::timeStamp( const char * path, uint16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t minute, uint8_t second ) -{ - //TODO - //Not available yet - (void)path; - (void ) year; - (void ) month; - (void ) day; - (void ) hour; - (void ) minute; - (void ) second ; - return false; +// TODO +bool FtpServer::timeStamp(const char* path, uint16_t year, uint8_t month, + uint8_t day, uint8_t hour, uint8_t minute, + uint8_t second) { + // TODO + // Not available yet + (void)path; + (void)year; + (void)month; + (void)day; + (void)hour; + (void)minute; + (void)second; + return false; } -#endif //FTP_FEATURE +#endif // FTP_FEATURE diff --git a/esp3d/src/modules/gcode_host/gcode_host.cpp b/esp3d/src/modules/gcode_host/gcode_host.cpp index 87cb85e6..2e1c7846 100644 --- a/esp3d/src/modules/gcode_host/gcode_host.cpp +++ b/esp3d/src/modules/gcode_host/gcode_host.cpp @@ -17,574 +17,565 @@ 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_DEBUG_FEATURE DEBUG_OUTPUT_SERIAL0 +// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 #include "../../include/esp3d_config.h" #if defined(GCODE_HOST_FEATURE) -#include "gcode_host.h" -#include "../../core/settings_esp3d.h" #include "../../core/commands.h" #include "../../core/esp3doutput.h" +#include "../../core/settings_esp3d.h" +#include "gcode_host.h" + #if defined(FILESYSTEM_FEATURE) #include "../filesystem/esp_filesystem.h" ESP_File FSfileHandle; -#endif //FILESYSTEM_FEATURE +#endif // FILESYSTEM_FEATURE #if defined(SD_DEVICE) #include "../filesystem/esp_sd.h" ESP_SDFile SDfileHandle; -#endif //FILESYSTEM_FEATURE +#endif // FILESYSTEM_FEATURE #define ESP_HOST_TIMEOUT 16000 #define MAX_TRY_2_SEND 5 - GcodeHost esp3d_gcode_host; -GcodeHost::GcodeHost() -{ - end(); +GcodeHost::GcodeHost() { end(); } + +GcodeHost::~GcodeHost() { end(); } + +bool GcodeHost::begin() { + end(); + return true; } -GcodeHost::~GcodeHost() -{ - end(); +void GcodeHost::end() { + _commandNumber = 0; + _error = ERROR_NO_ERROR; + _step = HOST_NO_STREAM; + _currentPosition = 0; + _bufferSize = 0; + _outputStream.client(ESP_STREAM_HOST_CLIENT); + _totalSize = 0; + _processedSize = 0; } -bool GcodeHost::begin() -{ - end(); - return true; -} - -void GcodeHost::end() -{ - _commandNumber = 0; - _error = ERROR_NO_ERROR; - _step = HOST_NO_STREAM; - _currentPosition = 0; - _bufferSize = 0; - _outputStream.client(ESP_STREAM_HOST_CLIENT); - _totalSize = 0; - _processedSize = 0; -} - -bool GcodeHost::push(const uint8_t * sbuf, size_t len) -{ - if (_step == HOST_NO_STREAM) { - return false; - } - log_esp3d("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') { - flush(); - } else { - //fill buffer until it is full - if (_bufferSize < ESP_HOST_BUFFER_SIZE) { - _buffer[_bufferSize++] = sbuf[i]; - } else { - //buffer is full flush it - flush(); - _buffer[_bufferSize++] = sbuf[i]; - } - _buffer[_bufferSize] =0; - } - } - flush(); - - return true; -} - -bool GcodeHost::isAck(String & line) -{ - if (line.indexOf("ok") != -1) { - log_esp3d("got ok"); - return true; - } - if (Settings_ESP3D::GetFirmwareTarget()==SMOOTHIEWARE) { - if (line.indexOf("smoothie out") != -1) { - log_esp3d("got smoothie out"); - return true; - } - } +bool GcodeHost::push(const uint8_t *sbuf, size_t len) { + if (_step == HOST_NO_STREAM) { return false; -} - -void GcodeHost::flush() -{ - //analyze buffer and do action if needed - //look for \n, ok , error, ack - //then clean buffer accordingly - if(_bufferSize==0) { - return; - } - _response = (const char*)_buffer; - log_esp3d("Stream got the response: %s", _response.c_str()); - _response.toLowerCase(); - if (isAck(_response)) { - //check if we have proper ok response - //like if numbering is enabled - if(_step == HOST_WAIT4_ACK) { - _step=HOST_READ_LINE; - } else { - log_esp3d("Got ok but out of the query"); - } + } + log_esp3d("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') { + flush(); } else { - if (_response.indexOf("error") != -1) { - log_esp3d("Got error"); - _step = HOST_ERROR_STREAM; - } + // fill buffer until it is full + if (_bufferSize < ESP_HOST_BUFFER_SIZE) { + _buffer[_bufferSize++] = sbuf[i]; + } else { + // buffer is full flush it + flush(); + _buffer[_bufferSize++] = sbuf[i]; + } + _buffer[_bufferSize] = 0; } - //What is have processing to do - //what if have resend - _bufferSize = 0; + } + flush(); + + return true; } -void GcodeHost::startStream() -{ - if (_fsType ==TYPE_SCRIPT_STREAM) { - _totalSize = _script.length(); - log_esp3d("Script line %s opened, size is %d", _script.c_str(), _totalSize); - } -#if defined(FILESYSTEM_FEATURE) - if (_fsType ==TYPE_FS_STREAM) { - if (ESP_FileSystem::exists(_fileName.c_str())) { - FSfileHandle = ESP_FileSystem::open(_fileName.c_str()); - } - if (FSfileHandle.isOpen()) { - _totalSize = FSfileHandle.size(); - log_esp3d("File %s opened, size is %d", _fileName.c_str(), _totalSize); - } else { - _error = ERROR_FILE_NOT_FOUND; - _step = HOST_ERROR_STREAM; - log_esp3d("File not found: %s", _fileName.c_str()); - return; - } - } -#endif //FILESYSTEM_FEATURE -#if defined(SD_DEVICE) - if (_fsType ==TYPE_SD_STREAM) { - if (!ESP_SD::accessFS()) { - _error = ERROR_FILE_NOT_FOUND; - _step = HOST_ERROR_STREAM; - _needRelease = false; - log_esp3d("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("File not found: %s", _fileName.c_str()); - return; - } - ESP_SD::setState(ESP_SDCARD_BUSY ); - - if (ESP_SD::exists(_fileName.c_str())) { - SDfileHandle = ESP_SD::open(_fileName.c_str()); - } - if (SDfileHandle.isOpen()) { - _totalSize = SDfileHandle.size(); - log_esp3d("File %s opened, size is %d", _fileName.c_str(), _totalSize); - } else { - _error = ERROR_FILE_NOT_FOUND; - _step = HOST_ERROR_STREAM; - log_esp3d("File not found: %s", _fileName.c_str()); - return; - } - } -#endif //SD_DEVICE - _currentPosition = 0; - _response = ""; - _currentPosition = 0; - _error = ERROR_NO_ERROR; - _step = HOST_READ_LINE; - _nextStep = HOST_READ_LINE; - _processedSize = 0; -} - -void GcodeHost::endStream() -{ - log_esp3d("Ending Stream"); -#if defined(FILESYSTEM_FEATURE) - if (_fsType ==TYPE_FS_STREAM) { - if (FSfileHandle.isOpen()) { - FSfileHandle.close(); - } - } -#endif //FILESYSTEM_FEATURE -#if defined(SD_DEVICE) - if (_fsType ==TYPE_SD_STREAM) { - if (SDfileHandle.isOpen()) { - SDfileHandle.close(); - } - if(_needRelease) { - ESP_SD::releaseFS(); - } - } -#endif //SD_DEVICE - _step = HOST_NO_STREAM; -} - -void GcodeHost::readNextCommand() -{ - _currentCommand = ""; - _step = HOST_PROCESS_LINE; - if (_fsType ==TYPE_SCRIPT_STREAM) { - log_esp3d("Reading next command from script"); - if (_currentPosition < _script.length()) { - if (_script.indexOf(';', _currentPosition) != -1) { - _currentCommand = _script.substring(_currentPosition, _script.indexOf(';', _currentPosition)); - _currentPosition = _script.indexOf(';', _currentPosition) + 1; - } else { - _currentCommand = _script.substring(_currentPosition); - _currentPosition = _script.length(); - } - _processedSize = _currentPosition; - log_esp3d("Command is %s", _currentCommand.c_str()); - } else { - _step = HOST_STOP_STREAM; - } - } -#if defined(FILESYSTEM_FEATURE) - if (_fsType ==TYPE_FS_STREAM) { - bool processing = true; - while (processing) { - //to handle file without endline - int c = FSfileHandle.read(); - if (c == -1) { - processing = false; - } else { - _processedSize++; - _currentPosition++; - if (!(((char)c =='\n') || ((char)c =='\r'))) { - _currentCommand+=(char)c; - } else { - processing = false; - } - } - } - if (_currentCommand.length() == 0) { - if (FSfileHandle.available()) { - _step = HOST_READ_LINE; - } else { - _step = HOST_STOP_STREAM; - } - } - } -#endif //FILESYSTEM_FEATURE -#if defined(SD_DEVICE) - if (_fsType ==TYPE_SD_STREAM) { - bool processing = true; - while (processing) { - //to handle file without endline - int c = SDfileHandle.read(); - if (c == -1) { - processing = false; - } else { - _processedSize++; - _currentPosition++; - if (!(((char)c =='\n') || ((char)c =='\r'))) { - _currentCommand+=(char)c; - } else { - processing = false; - } - } - } - if (_currentCommand.length() == 0) { - if (SDfileHandle.available()) { - _step = HOST_READ_LINE; - } else { - _step = HOST_STOP_STREAM; - } - } - } -#endif //SD_DEVICE -} - -bool GcodeHost::isCommand() -{ - //clean the command - if (_currentCommand.indexOf(';') != -1) { - _currentCommand = _currentCommand.substring(0, _currentCommand.indexOf(';')); - } - _currentCommand.trim(); - if (_currentCommand.length() == 0 || _currentCommand.startsWith(";")) { - return false; - } +bool GcodeHost::isAck(String &line) { + if (line.indexOf("ok") != -1) { + log_esp3d("got ok"); return true; + } + if (Settings_ESP3D::GetFirmwareTarget() == SMOOTHIEWARE) { + if (line.indexOf("smoothie out") != -1) { + log_esp3d("got smoothie out"); + return true; + } + } + return false; } -bool GcodeHost::isAckNeeded() -{ - //TODO: what command do not need for ack ? - return true; -} -void GcodeHost::processCommand() -{ - if (!isCommand()) { - log_esp3d("Command %s is not valid", _currentCommand.c_str()); - _step = HOST_READ_LINE; + +void GcodeHost::flush() { + // analyze buffer and do action if needed + // look for \n, ok , error, ack + // then clean buffer accordingly + if (_bufferSize == 0) { + return; + } + _response = (const char *)_buffer; + log_esp3d("Stream got the response: %s", _response.c_str()); + _response.toLowerCase(); + if (isAck(_response)) { + // check if we have proper ok response + // like if numbering is enabled + if (_step == HOST_WAIT4_ACK) { + _step = HOST_READ_LINE; } else { - log_esp3d("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 { - _step = HOST_READ_LINE; - } - } + log_esp3d("Got ok but out of the query"); } + } else { + if (_response.indexOf("error") != -1) { + log_esp3d_e("Got error"); + _step = HOST_ERROR_STREAM; + } + } + // What is have processing to do + // what if have resend + _bufferSize = 0; } -void GcodeHost::handle() -{ - if (_step == HOST_NO_STREAM) { - return; +void GcodeHost::startStream() { + if (_fsType == TYPE_SCRIPT_STREAM) { + _totalSize = _script.length(); + log_esp3d("Script line %s opened, size is %d", _script.c_str(), _totalSize); + } +#if defined(FILESYSTEM_FEATURE) + if (_fsType == TYPE_FS_STREAM) { + if (ESP_FileSystem::exists(_fileName.c_str())) { + FSfileHandle = ESP_FileSystem::open(_fileName.c_str()); } - switch(_step) { - case HOST_START_STREAM: - startStream(); - break; - case HOST_READ_LINE: - if (_nextStep==HOST_PAUSE_STREAM) { - _step = HOST_PAUSE_STREAM; - _nextStep = HOST_READ_LINE; + if (FSfileHandle.isOpen()) { + _totalSize = FSfileHandle.size(); + log_esp3d("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()); + return; + } + } +#endif // FILESYSTEM_FEATURE +#if defined(SD_DEVICE) + if (_fsType == TYPE_SD_STREAM) { + if (!ESP_SD::accessFS()) { + _error = ERROR_FILE_NOT_FOUND; + _step = HOST_ERROR_STREAM; + _needRelease = false; + log_esp3d_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()); + return; + } + ESP_SD::setState(ESP_SDCARD_BUSY); + + if (ESP_SD::exists(_fileName.c_str())) { + SDfileHandle = ESP_SD::open(_fileName.c_str()); + } + if (SDfileHandle.isOpen()) { + _totalSize = SDfileHandle.size(); + log_esp3d("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()); + return; + } + } +#endif // SD_DEVICE + _currentPosition = 0; + _response = ""; + _currentPosition = 0; + _error = ERROR_NO_ERROR; + _step = HOST_READ_LINE; + _nextStep = HOST_READ_LINE; + _processedSize = 0; +} + +void GcodeHost::endStream() { + log_esp3d("Ending Stream"); +#if defined(FILESYSTEM_FEATURE) + if (_fsType == TYPE_FS_STREAM) { + if (FSfileHandle.isOpen()) { + FSfileHandle.close(); + } + } +#endif // FILESYSTEM_FEATURE +#if defined(SD_DEVICE) + if (_fsType == TYPE_SD_STREAM) { + if (SDfileHandle.isOpen()) { + SDfileHandle.close(); + } + if (_needRelease) { + ESP_SD::releaseFS(); + } + } +#endif // SD_DEVICE + _step = HOST_NO_STREAM; +} + +void GcodeHost::readNextCommand() { + _currentCommand = ""; + _step = HOST_PROCESS_LINE; + if (_fsType == TYPE_SCRIPT_STREAM) { + log_esp3d("Reading next command from script"); + if (_currentPosition < _script.length()) { + if (_script.indexOf(';', _currentPosition) != -1) { + _currentCommand = _script.substring( + _currentPosition, _script.indexOf(';', _currentPosition)); + _currentPosition = _script.indexOf(';', _currentPosition) + 1; + } else { + _currentCommand = _script.substring(_currentPosition); + _currentPosition = _script.length(); + } + _processedSize = _currentPosition; + log_esp3d("Command is %s", _currentCommand.c_str()); + } else { + _step = HOST_STOP_STREAM; + } + } +#if defined(FILESYSTEM_FEATURE) + if (_fsType == TYPE_FS_STREAM) { + bool processing = true; + while (processing) { + // to handle file without endline + int c = FSfileHandle.read(); + if (c == -1) { + processing = false; + } else { + _processedSize++; + _currentPosition++; + if (!(((char)c == '\n') || ((char)c == '\r'))) { + _currentCommand += (char)c; } else { - readNextCommand(); + processing = false; } - break; - case HOST_PROCESS_LINE: - processCommand(); - break; - case HOST_WAIT4_ACK: - if (millis() - _startTimeOut > ESP_HOST_TIMEOUT) { - log_esp3d("Timeout waiting for ack"); - _error = ERROR_TIME_OUT; - _step = HOST_ERROR_STREAM; - } - break; - case HOST_PAUSE_STREAM: - //TODO pause stream - break; - case HOST_RESUME_STREAM: - //Any extra action to resume stream? + } + } + if (_currentCommand.length() == 0) { + if (FSfileHandle.available()) { _step = HOST_READ_LINE; - break; - case HOST_STOP_STREAM: - endStream(); - break; - case HOST_ERROR_STREAM: { - String Error; - if (_error == ERROR_NO_ERROR) { - //TODO check _response to put right error - _error = ERROR_UNKNOW; - } - log_esp3d("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()); + } else { _step = HOST_STOP_STREAM; + } } - break; - default: //Not handled step - log_esp3d("Not handled step %d", _step); - break; - } -} - -bool GcodeHost::abort() -{ - if (_step == HOST_NO_STREAM) { - return false; - } - log_esp3d("Aborting script"); - //TODO: what to do in addition ? - _error=ERROR_STREAM_ABORTED; - //we do not use step to do faster abort - endStream(); - return true; -} - -bool GcodeHost::pause() -{ - if (_step == HOST_NO_STREAM) { - return false; - } - _nextStep = HOST_PAUSE_STREAM; - return true; -} - -bool GcodeHost::resume() -{ - if (_step != HOST_PAUSE_STREAM) { - return false; - } - _step = _nextStep; - return true; -} - -uint8_t GcodeHost::Checksum(const char * command, uint32_t commandSize) -{ - uint8_t checksum_val =0; - if (command == NULL) { - return 0; - } - for (uint32_t i=0; i < commandSize; i++) { - checksum_val = checksum_val ^ ((uint8_t)command[i]); - } - return checksum_val; -} - -String GcodeHost::CheckSumCommand(const char* command, uint32_t commandnb) -{ - String commandchecksum = "N" + String((uint32_t)commandnb)+ " " + command; - uint8_t crc = Checksum(commandchecksum.c_str(), commandchecksum.length()); - commandchecksum+="*"+String(crc); - return commandchecksum; -} - -bool GcodeHost::resetCommandNumbering() -{ - String resetcmd = "M110 N0"; - if (Settings_ESP3D::GetFirmwareTarget() == SMOOTHIEWARE) { - resetcmd = "N0 M110"; - } else { - resetcmd = "M110 N0"; - } - _commandNumber = 1; - //need to use process to send command - return _outputStream.printLN(resetcmd.c_str()); -} - -uint32_t GcodeHost::getCommandNumber(String & response) -{ - uint32_t l = 0; - String sresend = "Resend:"; - if ( Settings_ESP3D::GetFirmwareTarget() == SMOOTHIEWARE) { - sresend = "rs N"; - } - int pos = response.indexOf(sresend); - if (pos == -1 ) { - log_esp3d("Cannot find label %d", _error); - return -1; - } - pos+=sresend.length(); - int pos2 = response.indexOf("\n", pos); - String snum = response.substring(pos, pos2); - //remove potential unwished char - snum.replace("\r", ""); - l = snum.toInt(); - log_esp3d("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) -{ - _script = line; - _script.trim(); - log_esp3d("Processing script: %s", _script.c_str()); - if (_script.length() == 0) { - log_esp3d("No script to process"); - return false; - } - if (_step != HOST_NO_STREAM) { - log_esp3d("Streaming already in progress"); - return false; - } - _fsType = TYPE_SCRIPT_STREAM; - _step = HOST_START_STREAM; - _auth_type = auth_type; - return true; -} - -bool GcodeHost::processFile(const char * filename, level_authenticate_type auth_type, ESP3DOutput * output) -{ - 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); - if (_fileName.length() == 0) { - log_esp3d("No file to process"); - return false; - } - if (_step != HOST_NO_STREAM) { - log_esp3d("Streaming already in progress"); - return false; - } - //TODO UD = USB DISK + } +#endif // FILESYSTEM_FEATURE #if defined(SD_DEVICE) - if (_fileName.startsWith(ESP_SD_FS_HEADER)) { - log_esp3d("Processing SD file"); - target_found = true; - _fileName= _fileName.substring(strlen(ESP_SD_FS_HEADER),_fileName.length()); - _fsType = TYPE_SD_STREAM; + if (_fsType == TYPE_SD_STREAM) { + bool processing = true; + while (processing) { + // to handle file without endline + int c = SDfileHandle.read(); + if (c == -1) { + processing = false; + } else { + _processedSize++; + _currentPosition++; + if (!(((char)c == '\n') || ((char)c == '\r'))) { + _currentCommand += (char)c; + } else { + processing = false; + } + } } -#endif //SD_DEVICE -#if defined(FILESYSTEM_FEATURE) - if (!target_found && _fileName.startsWith(ESP_FLASH_FS_HEADER)) { - target_found = true; - _fileName= _fileName.substring(strlen(ESP_FLASH_FS_HEADER),_fileName.length()); - log_esp3d("Processing /FS file %s", _fileName.c_str()); - _fsType = TYPE_FS_STREAM; + if (_currentCommand.length() == 0) { + if (SDfileHandle.available()) { + _step = HOST_READ_LINE; + } else { + _step = HOST_STOP_STREAM; + } } - //if no header it is also an FS file - if (!target_found) { - log_esp3d("Processing FS file %s", _fileName.c_str()); - _fsType = TYPE_FS_STREAM; - target_found = true; - } -#endif //FILESYSTEM_FEATURE - //it is not a file so it is a script - if (!target_found ) { - target_found = true; - _fsType = TYPE_SCRIPT_STREAM; - //remove the / - _script=&_fileName[1]; - log_esp3d("Processing Script file %s", _script.c_str()); - _fileName = ""; - } - _step = HOST_START_STREAM; - _auth_type = auth_type; - return true; + } +#endif // SD_DEVICE } -#endif //GCODE_HOST_FEATURE +bool GcodeHost::isCommand() { + // clean the command + if (_currentCommand.indexOf(';') != -1) { + _currentCommand = + _currentCommand.substring(0, _currentCommand.indexOf(';')); + } + _currentCommand.trim(); + if (_currentCommand.length() == 0 || _currentCommand.startsWith(";")) { + return false; + } + return true; +} +bool GcodeHost::isAckNeeded() { + // TODO: what command do not need for ack ? + return true; +} +void GcodeHost::processCommand() { + if (!isCommand()) { + log_esp3d_e("Command %s is not valid", _currentCommand.c_str()); + _step = HOST_READ_LINE; + } else { + log_esp3d("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 { + _step = HOST_READ_LINE; + } + } + } +} + +void GcodeHost::handle() { + if (_step == HOST_NO_STREAM) { + return; + } + switch (_step) { + case HOST_START_STREAM: + startStream(); + break; + case HOST_READ_LINE: + if (_nextStep == HOST_PAUSE_STREAM) { + _step = HOST_PAUSE_STREAM; + _nextStep = HOST_READ_LINE; + } else { + readNextCommand(); + } + break; + case HOST_PROCESS_LINE: + processCommand(); + break; + case HOST_WAIT4_ACK: + if (millis() - _startTimeOut > ESP_HOST_TIMEOUT) { + log_esp3d("Timeout waiting for ack"); + _error = ERROR_TIME_OUT; + _step = HOST_ERROR_STREAM; + } + break; + case HOST_PAUSE_STREAM: + // TODO pause stream + break; + case HOST_RESUME_STREAM: + // Any extra action to resume stream? + _step = HOST_READ_LINE; + break; + case HOST_STOP_STREAM: + endStream(); + break; + case HOST_ERROR_STREAM: { + String Error; + if (_error == ERROR_NO_ERROR) { + // TODO check _response to put right error + _error = ERROR_UNKNOW; + } + log_esp3d_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()); + _step = HOST_STOP_STREAM; + } break; + default: // Not handled step + log_esp3d("Not handled step %d", _step); + break; + } +} + +bool GcodeHost::abort() { + if (_step == HOST_NO_STREAM) { + return false; + } + log_esp3d("Aborting script"); + // TODO: what to do in addition ? + _error = ERROR_STREAM_ABORTED; + // we do not use step to do faster abort + endStream(); + return true; +} + +bool GcodeHost::pause() { + if (_step == HOST_NO_STREAM) { + return false; + } + _nextStep = HOST_PAUSE_STREAM; + return true; +} + +bool GcodeHost::resume() { + if (_step != HOST_PAUSE_STREAM) { + return false; + } + _step = _nextStep; + return true; +} + +uint8_t GcodeHost::Checksum(const char *command, uint32_t commandSize) { + uint8_t checksum_val = 0; + if (command == NULL) { + return 0; + } + for (uint32_t i = 0; i < commandSize; i++) { + checksum_val = checksum_val ^ ((uint8_t)command[i]); + } + return checksum_val; +} + +String GcodeHost::CheckSumCommand(const char *command, uint32_t commandnb) { + String commandchecksum = "N" + String((uint32_t)commandnb) + " " + command; + uint8_t crc = Checksum(commandchecksum.c_str(), commandchecksum.length()); + commandchecksum += "*" + String(crc); + return commandchecksum; +} + +bool GcodeHost::resetCommandNumbering() { + String resetcmd = "M110 N0"; + if (Settings_ESP3D::GetFirmwareTarget() == SMOOTHIEWARE) { + resetcmd = "N0 M110"; + } else { + resetcmd = "M110 N0"; + } + _commandNumber = 1; + // need to use process to send command + return _outputStream.printLN(resetcmd.c_str()); +} + +uint32_t GcodeHost::getCommandNumber(String &response) { + uint32_t l = 0; + String sresend = "Resend:"; + if (Settings_ESP3D::GetFirmwareTarget() == SMOOTHIEWARE) { + sresend = "rs N"; + } + int pos = response.indexOf(sresend); + if (pos == -1) { + log_esp3d_e("Cannot find label %d", _error); + return -1; + } + pos += sresend.length(); + int pos2 = response.indexOf("\n", pos); + String snum = response.substring(pos, pos2); + // 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()); + return l; +} + +bool GcodeHost::processScript(const char *line, + level_authenticate_type auth_type, + ESP3DOutput *output) { + _script = line; + _script.trim(); + log_esp3d("Processing script: %s", _script.c_str()); + if (_script.length() == 0) { + log_esp3d("No script to process"); + return false; + } + if (_step != HOST_NO_STREAM) { + log_esp3d("Streaming already in progress"); + return false; + } + _fsType = TYPE_SCRIPT_STREAM; + _step = HOST_START_STREAM; + _auth_type = auth_type; + return true; +} + +bool GcodeHost::processFile(const char *filename, + level_authenticate_type auth_type, + ESP3DOutput *output) { + 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); + if (_fileName.length() == 0) { + log_esp3d("No file to process"); + return false; + } + if (_step != HOST_NO_STREAM) { + log_esp3d("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"); + target_found = true; + _fileName = + _fileName.substring(strlen(ESP_SD_FS_HEADER), _fileName.length()); + _fsType = TYPE_SD_STREAM; + } +#endif // SD_DEVICE +#if defined(FILESYSTEM_FEATURE) + if (!target_found && _fileName.startsWith(ESP_FLASH_FS_HEADER)) { + target_found = true; + _fileName = + _fileName.substring(strlen(ESP_FLASH_FS_HEADER), _fileName.length()); + log_esp3d("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()); + _fsType = TYPE_FS_STREAM; + target_found = true; + } +#endif // FILESYSTEM_FEATURE + // it is not a file so it is a script + if (!target_found) { + target_found = true; + _fsType = TYPE_SCRIPT_STREAM; + // remove the / + _script = &_fileName[1]; + log_esp3d("Processing Script file %s", _script.c_str()); + _fileName = ""; + } + _step = HOST_START_STREAM; + _auth_type = auth_type; + return true; +} + +#endif // GCODE_HOST_FEATURE diff --git a/esp3d/src/modules/http/handles/handle-SD-files.cpp b/esp3d/src/modules/http/handles/handle-SD-files.cpp index 4cbe20dc..6842b1e0 100644 --- a/esp3d/src/modules/http/handles/handle-SD-files.cpp +++ b/esp3d/src/modules/http/handles/handle-SD-files.cpp @@ -17,7 +17,7 @@ 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_DEBUG_FEATURE DEBUG_OUTPUT_SERIAL0 +// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 #include "../../../include/esp3d_config.h" #if defined(HTTP_FEATURE) && defined(SD_DEVICE) #include "../http_server.h" diff --git a/esp3d/src/modules/http/handles/handle-filenotfound.cpp b/esp3d/src/modules/http/handles/handle-filenotfound.cpp index 4d690515..68c761df 100644 --- a/esp3d/src/modules/http/handles/handle-filenotfound.cpp +++ b/esp3d/src/modules/http/handles/handle-filenotfound.cpp @@ -18,104 +18,107 @@ 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 -#include "../../filesystem/esp_filesystem.h" +#endif // ARDUINO_ARCH_ESP8266 #include "../../authentication/authentication_service.h" +#include "../../filesystem/esp_filesystem.h" + #if defined(SD_DEVICE) #include "../../filesystem/esp_sd.h" -#endif //SD_DEVICE +#endif // SD_DEVICE #include "../favicon.h" #if defined(ESP3DLIB_ENV) && COMMUNICATION_PROTOCOL == SOCKET_SERIAL #include "../../serial2socket/serial2socket.h" -#endif // ESP3DLIB_ENV && COMMUNICATION_PROTOCOL == SOCKET_SERIAL +#endif // ESP3DLIB_ENV && COMMUNICATION_PROTOCOL == SOCKET_SERIAL -//Handle not registred path on FS neither SD /////////////////////// -void HTTP_Server:: handle_not_found() -{ - if (AuthenticationService::authenticated_level() == LEVEL_GUEST) { - _webserver->send (401, "text/plain", "Wrong authentication!"); - return; +// Handle not registred path on FS neither SD /////////////////////// +void HTTP_Server::handle_not_found() { + if (AuthenticationService::authenticated_level() == LEVEL_GUEST) { + _webserver->send(401, "text/plain", "Wrong authentication!"); + return; + } + String path = _webserver->urlDecode(_webserver->uri()); + String contentType = getContentType(path.c_str()); + String pathWithGz = path + ".gz"; + log_esp3d("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()); + if (ESP_FileSystem::exists(pathWithGz.c_str())) { + _webserver->sendHeader("Content-Encoding", "gzip"); + path = pathWithGz; + log_esp3d("Path is gz `%s`", path.c_str()); } - String path = _webserver->urlDecode(_webserver->uri()); - String contentType = getContentType(path.c_str()); - String pathWithGz = path + ".gz"; - log_esp3d("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()); - if(ESP_FileSystem::exists(pathWithGz.c_str())) { + if (!StreamFSFile(path.c_str(), contentType.c_str())) { + log_esp3d_e("Stream `%s` failed", path.c_str()); + } + return; + } + if (path == "favicon.ico" || path == "/favicon.ico") { + _webserver->sendHeader("Content-Encoding", "gzip"); + _webserver->send_P(200, "image/x-icon", (const char *)favicon, + favicon_size); + return; + } +#endif // #if defined (FILESYSTEM_FEATURE) + +#if defined(SD_DEVICE) + if (path.startsWith("/sd/")) { + path = path.substring(3); + pathWithGz = path + ".gz"; + if (ESP_SD::accessFS()) { + if (ESP_SD::getState(true) != ESP_SDCARD_NOT_PRESENT) { + ESP_SD::setState(ESP_SDCARD_BUSY); + if (ESP_SD::exists(pathWithGz.c_str()) || + ESP_SD::exists(path.c_str())) { + if (ESP_SD::exists(pathWithGz.c_str())) { _webserver->sendHeader("Content-Encoding", "gzip"); path = pathWithGz; - log_esp3d("Path is gz `%s`", path.c_str()); - } - if(!StreamFSFile(path.c_str(),contentType.c_str())) { - log_esp3d("Stream `%s` failed", path.c_str()); - } - return; - } - if (path=="favicon.ico" || path=="/favicon.ico") { - _webserver->sendHeader("Content-Encoding", "gzip"); - _webserver->send_P(200,"image/x-icon",(const char *)favicon,favicon_size); - return; - } -#endif //#if defined (FILESYSTEM_FEATURE) - -#if defined (SD_DEVICE) - if (path.startsWith("/sd/")) { - path = path.substring(3); - pathWithGz = path + ".gz"; - if (ESP_SD::accessFS()) { - if (ESP_SD::getState(true) != ESP_SDCARD_NOT_PRESENT) { - ESP_SD::setState(ESP_SDCARD_BUSY ); - if(ESP_SD::exists(pathWithGz.c_str()) || ESP_SD::exists(path.c_str())) { - if(ESP_SD::exists(pathWithGz.c_str())) { - _webserver->sendHeader("Content-Encoding", "gzip"); - path = pathWithGz; - } + } #if defined(ESP3DLIB_ENV) && COMMUNICATION_PROTOCOL == SOCKET_SERIAL - Serial2Socket.pause(); -#endif // ESP3DLIB_ENV && COMMUNICATION_PROTOCOL == SOCKET_SERIAL - if(!StreamSDFile(path.c_str(),contentType.c_str())) { - log_esp3d("Stream `%s` failed", path.c_str()); - } + 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()); + } #if defined(ESP3DLIB_ENV) && COMMUNICATION_PROTOCOL == SOCKET_SERIAL - Serial2Socket.pause(false); -#endif // ESP3DLIB_ENV && COMMUNICATION_PROTOCOL == SOCKET_SERIAL - ESP_SD::releaseFS(); - return; - } - } - ESP_SD::releaseFS(); + Serial2Socket.pause(false); +#endif // ESP3DLIB_ENV && COMMUNICATION_PROTOCOL == SOCKET_SERIAL + ESP_SD::releaseFS(); + return; } + } + ESP_SD::releaseFS(); } -#endif //#if defined (SD_DEVICE) + } +#endif // #if defined (SD_DEVICE) #ifdef FILESYSTEM_FEATURE - //check local page - path = "/404.htm"; - contentType = getContentType(path.c_str()); - pathWithGz = path + ".gz"; - if(ESP_FileSystem::exists(pathWithGz.c_str()) || ESP_FileSystem::exists(path.c_str())) { - if(ESP_FileSystem::exists(pathWithGz.c_str())) { - _webserver->sendHeader("Content-Encoding", "gzip"); - path = pathWithGz; - } - if(!StreamFSFile(path.c_str(),contentType.c_str())) { - log_esp3d("Stream `%s` failed", path.c_str()); - } - return; + // check local page + path = "/404.htm"; + contentType = getContentType(path.c_str()); + pathWithGz = path + ".gz"; + if (ESP_FileSystem::exists(pathWithGz.c_str()) || + ESP_FileSystem::exists(path.c_str())) { + if (ESP_FileSystem::exists(pathWithGz.c_str())) { + _webserver->sendHeader("Content-Encoding", "gzip"); + path = pathWithGz; } -#endif //FILESYSTEM_FEATURE - //let's keep simple just send minimum - _webserver->send(404); - + if (!StreamFSFile(path.c_str(), contentType.c_str())) { + log_esp3d_e("Stream `%s` failed", path.c_str()); + } + return; + } +#endif // FILESYSTEM_FEATURE + // let's keep simple just send minimum + _webserver->send(404); } -#endif //HTTP_FEATURE +#endif // HTTP_FEATURE diff --git a/esp3d/src/modules/http/handles/handle-root.cpp b/esp3d/src/modules/http/handles/handle-root.cpp index 09e89412..53e849c9 100644 --- a/esp3d/src/modules/http/handles/handle-root.cpp +++ b/esp3d/src/modules/http/handles/handle-root.cpp @@ -18,46 +18,49 @@ 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" -//embedded response file if no files on ESP Filesystem +// embedded response file if no files on ESP Filesystem #include "../embedded.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 "../../filesystem/esp_filesystem.h" -//Root of Webserver///////////////////////////////////////////////////// -void HTTP_Server::handle_root() -{ - String path = ESP3D_HOST_PATH; - //Some sanity check - if (path[0]!='/') { - path ="/" + path; +// Root of Webserver///////////////////////////////////////////////////// +void HTTP_Server::handle_root() { + String path = ESP3D_HOST_PATH; + // Some sanity check + if (path[0] != '/') { + path = "/" + path; + } + if (path[path.length() - 1] != '/') { + path = path + "/"; + } + path += "index.html"; + String contentType = getContentType(path.c_str()); + String pathWithGz = path + ".gz"; + // if have a index.html or gzip version this is default root page + if ((ESP_FileSystem::exists(pathWithGz.c_str()) || + ESP_FileSystem::exists(path.c_str())) && + !_webserver->hasArg("forcefallback") && + _webserver->arg("forcefallback") != "yes") { + log_esp3d("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()); } - if (path[path.length()-1]!='/') { - path = path + "/"; + if (!StreamFSFile(path.c_str(), contentType.c_str())) { + log_esp3d_e("Stream `%s` failed", path.c_str()); } - path += "index.html"; - String contentType = getContentType(path.c_str()); - String pathWithGz = path + ".gz"; - //if have a index.html or gzip version this is default root page - if((ESP_FileSystem::exists(pathWithGz.c_str()) || ESP_FileSystem::exists(path.c_str())) && !_webserver->hasArg("forcefallback") && _webserver->arg("forcefallback")!="yes") { - log_esp3d("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()); - } - if(!StreamFSFile(path.c_str(),contentType.c_str())) { - log_esp3d("Stream `%s` failed", path.c_str()); - } - return; - } - //if no lets launch the default content - _webserver->sendHeader("Content-Encoding", "gzip"); - _webserver->send_P(200,"text/html",(const char *)tool_html_gz,tool_html_gz_size); + return; + } + // if no lets launch the default content + _webserver->sendHeader("Content-Encoding", "gzip"); + _webserver->send_P(200, "text/html", (const char *)tool_html_gz, + tool_html_gz_size); } -#endif //HTTP_FEATURE +#endif // HTTP_FEATURE diff --git a/esp3d/src/modules/http/handles/upload-SD-files.cpp b/esp3d/src/modules/http/handles/upload-SD-files.cpp index ba06ecff..cbfb8ed1 100644 --- a/esp3d/src/modules/http/handles/upload-SD-files.cpp +++ b/esp3d/src/modules/http/handles/upload-SD-files.cpp @@ -17,242 +17,244 @@ 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_DEBUG_FEATURE DEBUG_OUTPUT_SERIAL0 +// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 #include "../../../include/esp3d_config.h" -#if defined (HTTP_FEATURE) && defined(SD_DEVICE) +#if defined(HTTP_FEATURE) && defined(SD_DEVICE) #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 "../../filesystem/esp_sd.h" +#endif // ARDUINO_ARCH_ESP8266 #include "../../authentication/authentication_service.h" +#include "../../filesystem/esp_sd.h" + #ifdef ESP_BENCHMARK_FEATURE #include "../../../core/benchmark.h" -#endif //ESP_BENCHMARK_FEATURE +#endif // ESP_BENCHMARK_FEATURE #if defined(ESP3DLIB_ENV) && COMMUNICATION_PROTOCOL == SOCKET_SERIAL #include "../../serial2socket/serial2socket.h" -#endif // ESP3DLIB_ENV && COMMUNICATION_PROTOCOL == SOCKET_SERIAL +#endif // ESP3DLIB_ENV && COMMUNICATION_PROTOCOL == SOCKET_SERIAL #include "../../websocket/websocket_server.h" -//SD files uploader handle -void HTTP_Server::SDFileupload () -{ +// SD files uploader handle +void HTTP_Server::SDFileupload() { #ifdef ESP_BENCHMARK_FEATURE - static uint64_t bench_start; - static size_t bench_transfered; -#endif//ESP_BENCHMARK_FEATURE - static uint64_t last_WS_update; - //get authentication status - level_authenticate_type auth_level= AuthenticationService::authenticated_level(); - static String filename; - static ESP_SDFile fsUploadFile; - //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(); - String upload_filename = upload.filename; - if ((_upload_status != UPLOAD_STATUS_FAILED) || (upload.status == UPLOAD_FILE_START)) { + static uint64_t bench_start; + static size_t bench_transfered; +#endif // ESP_BENCHMARK_FEATURE + static uint64_t last_WS_update; + // get authentication status + level_authenticate_type auth_level = + AuthenticationService::authenticated_level(); + static String filename; + static ESP_SDFile fsUploadFile; + // 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(); + String upload_filename = upload.filename; + if ((_upload_status != UPLOAD_STATUS_FAILED) || + (upload.status == UPLOAD_FILE_START)) { #if defined(ESP3DLIB_ENV) && COMMUNICATION_PROTOCOL == SOCKET_SERIAL - Serial2Socket.pause(true); -#endif // ESP3DLIB_ENV && COMMUNICATION_PROTOCOL == SOCKET_SERIAL - //Upload start - if (upload.status == UPLOAD_FILE_START) { - last_WS_update = millis(); + Serial2Socket.pause(true); +#endif // ESP3DLIB_ENV && COMMUNICATION_PROTOCOL == SOCKET_SERIAL + // Upload start + if (upload.status == UPLOAD_FILE_START) { + last_WS_update = millis(); #ifdef ESP_BENCHMARK_FEATURE - bench_start = millis(); - bench_transfered = 0; -#endif//ESP_BENCHMARK_FEATURE - _upload_status = UPLOAD_STATUS_ONGOING; - if (!ESP_SD::accessFS()) { - _upload_status=UPLOAD_STATUS_FAILED; - pushError(ESP_ERROR_NO_SD, "Upload rejected"); - return; - } - if (ESP_SD::getState(true) == ESP_SDCARD_NOT_PRESENT) { - log_esp3d("Release Sd called"); - ESP_SD::releaseFS(); - _upload_status=UPLOAD_STATUS_FAILED; - pushError(ESP_ERROR_NO_SD, "Upload rejected"); -#if defined(ESP3DLIB_ENV) && COMMUNICATION_PROTOCOL == SOCKET_SERIAL - Serial2Socket.pause(false); -#endif // ESP3DLIB_ENV && COMMUNICATION_PROTOCOL == SOCKET_SERIAL - return; - } - ESP_SD::setState(ESP_SDCARD_BUSY ); - - if (upload_filename[0] != '/') { - filename = "/" + upload_filename; - } else { - filename = upload.filename; - } - if (_webserver->hasArg ("rpath") ) { - upload_filename = _webserver->arg ("rpath") + filename; - if (upload_filename[0] != '/') { - filename = "/" + upload_filename; - } else { - filename = upload_filename; - } - } - //Sanity check - if (ESP_SD::exists (filename.c_str()) ) { - ESP_SD::remove (filename.c_str()); - } - String path = _webserver->arg ("path"); - if (path[0] != '/') { - path = "/" + path; - } - if (path[path.length()-1] != '/') { - path = path + "/"; - } - if (_webserver->hasArg("createPath") && path.length() > 1) { - if (_webserver->arg("createPath")== "true") { - int pos = path.indexOf('/',1); - while (pos != -1) { - String currentPath = path.substring(0, pos); - if (!ESP_SD::exists (currentPath.c_str()) ) { - if ( !ESP_SD::mkdir (currentPath.c_str()) ) { - pushError(ESP_ERROR_FILE_CREATION, "Failed to create path", 500); - _upload_status=UPLOAD_STATUS_FAILED; - break; - } - } - if ((size_t)(pos+1) >= path.length()-1) { - pos=-1; - break; - } else { - pos = path.indexOf('/',pos+1); - } - - } - } - } - if (fsUploadFile.isOpen() ) { - fsUploadFile.close(); - } - String sizeargname = upload.filename + "S"; - log_esp3d("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(); - size_t filesize = _webserver->arg (sizeargname.c_str()).toInt(); - if (freespace < filesize ) { - _upload_status=UPLOAD_STATUS_FAILED; - pushError(ESP_ERROR_NOT_ENOUGH_SPACE, "Upload rejected"); - } - } - } - if (_upload_status!=UPLOAD_STATUS_FAILED) { - log_esp3d("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"); - } else { - //if no set cancel flag - _upload_status=UPLOAD_STATUS_FAILED; - pushError(ESP_ERROR_FILE_CREATION, "File creation failed"); - log_esp3d("File creation failed"); - } - - } - //Upload write - } else if(upload.status == UPLOAD_FILE_WRITE) { - //check if file is available and no error - if(fsUploadFile && _upload_status == UPLOAD_STATUS_ONGOING) { -#ifdef ESP_BENCHMARK_FEATURE - bench_transfered += upload.currentSize; -#endif//ESP_BENCHMARK_FEATURE - //update websocket every 2000 ms - if (millis()-last_WS_update > 2000) { - websocket_terminal_server.handle(); - last_WS_update = millis(); - } - //no error so write post date - 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("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"); - } - } else { - //we have a problem set flag UPLOAD_STATUS_FAILED - _upload_status=UPLOAD_STATUS_FAILED; - log_esp3d("Error detected"); - pushError(ESP_ERROR_FILE_WRITE, "File write failed"); - } - //Upload end - } else if(upload.status == UPLOAD_FILE_END) { - uint32_t filesize = 0; - //check if file is still open - if(fsUploadFile) { - //close it - fsUploadFile.close(); -#ifdef ESP_BENCHMARK_FEATURE - benchMark("SD upload", bench_start, millis(), bench_transfered); -#endif//ESP_BENCHMARK_FEATURE - //check size - String sizeargname = upload.filename + "S"; - //fsUploadFile = ESP_SD::open (filename, ESP_FILE_READ); - filesize = fsUploadFile.size(); - _upload_status = UPLOAD_STATUS_SUCCESSFUL; - if (_webserver->hasArg (sizeargname.c_str()) ) { - if (_webserver->arg (sizeargname.c_str()) != String(filesize)) { - _upload_status = UPLOAD_STATUS_FAILED; - pushError(ESP_ERROR_SIZE, "File upload failed"); - } - } - if (_upload_status == UPLOAD_STATUS_ONGOING) { - _upload_status = UPLOAD_STATUS_SUCCESSFUL; - } - } else { - //we have a problem set flag UPLOAD_STATUS_FAILED - _upload_status=UPLOAD_STATUS_FAILED; - pushError(ESP_ERROR_FILE_CLOSE, "File close failed"); - } - log_esp3d("Release Sd called"); - ESP_SD::releaseFS(); -#if defined(ESP3DLIB_ENV) && COMMUNICATION_PROTOCOL == SOCKET_SERIAL - Serial2Socket.pause(false); -#endif // ESP3DLIB_ENV && COMMUNICATION_PROTOCOL == SOCKET_SERIAL - //Upload cancelled - } else { - if (_upload_status == UPLOAD_STATUS_ONGOING) { - _upload_status = UPLOAD_STATUS_FAILED; - log_esp3d("Release Sd called"); - ESP_SD::releaseFS(); -#if defined(ESP3DLIB_ENV) && COMMUNICATION_PROTOCOL == SOCKET_SERIAL - Serial2Socket.pause(false); -#endif // ESP3DLIB_ENV && COMMUNICATION_PROTOCOL == SOCKET_SERIAL - } - } + bench_start = millis(); + bench_transfered = 0; +#endif // ESP_BENCHMARK_FEATURE + _upload_status = UPLOAD_STATUS_ONGOING; + if (!ESP_SD::accessFS()) { + _upload_status = UPLOAD_STATUS_FAILED; + pushError(ESP_ERROR_NO_SD, "Upload rejected"); + return; } - } - - if(_upload_status == UPLOAD_STATUS_FAILED) { - cancelUpload(); - if(fsUploadFile) { - fsUploadFile.close(); + if (ESP_SD::getState(true) == ESP_SDCARD_NOT_PRESENT) { + log_esp3d("Release Sd called"); + ESP_SD::releaseFS(); + _upload_status = UPLOAD_STATUS_FAILED; + pushError(ESP_ERROR_NO_SD, "Upload rejected"); +#if defined(ESP3DLIB_ENV) && COMMUNICATION_PROTOCOL == SOCKET_SERIAL + Serial2Socket.pause(false); +#endif // ESP3DLIB_ENV && COMMUNICATION_PROTOCOL == SOCKET_SERIAL + return; } - if (auth_level != LEVEL_GUEST) { - if (ESP_SD::exists (filename.c_str())) { - ESP_SD::remove (filename.c_str()); + ESP_SD::setState(ESP_SDCARD_BUSY); + + if (upload_filename[0] != '/') { + filename = "/" + upload_filename; + } else { + filename = upload.filename; + } + if (_webserver->hasArg("rpath")) { + upload_filename = _webserver->arg("rpath") + filename; + if (upload_filename[0] != '/') { + filename = "/" + upload_filename; + } else { + filename = upload_filename; + } + } + // Sanity check + if (ESP_SD::exists(filename.c_str())) { + ESP_SD::remove(filename.c_str()); + } + String path = _webserver->arg("path"); + if (path[0] != '/') { + path = "/" + path; + } + if (path[path.length() - 1] != '/') { + path = path + "/"; + } + if (_webserver->hasArg("createPath") && path.length() > 1) { + if (_webserver->arg("createPath") == "true") { + int pos = path.indexOf('/', 1); + while (pos != -1) { + String currentPath = path.substring(0, pos); + if (!ESP_SD::exists(currentPath.c_str())) { + if (!ESP_SD::mkdir(currentPath.c_str())) { + pushError(ESP_ERROR_FILE_CREATION, "Failed to create path", + 500); + _upload_status = UPLOAD_STATUS_FAILED; + break; + } + } + if ((size_t)(pos + 1) >= path.length() - 1) { + pos = -1; + break; + } else { + pos = path.indexOf('/', pos + 1); + } } + } + } + if (fsUploadFile.isOpen()) { + fsUploadFile.close(); + } + String sizeargname = upload.filename + "S"; + log_esp3d("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(); + size_t filesize = _webserver->arg(sizeargname.c_str()).toInt(); + if (freespace < filesize) { + _upload_status = UPLOAD_STATUS_FAILED; + pushError(ESP_ERROR_NOT_ENOUGH_SPACE, "Upload rejected"); + } + } + } + if (_upload_status != UPLOAD_STATUS_FAILED) { + log_esp3d("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"); + } 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"); + } + } + // Upload write + } else if (upload.status == UPLOAD_FILE_WRITE) { + // check if file is available and no error + if (fsUploadFile && _upload_status == UPLOAD_STATUS_ONGOING) { +#ifdef ESP_BENCHMARK_FEATURE + bench_transfered += upload.currentSize; +#endif // ESP_BENCHMARK_FEATURE + // update websocket every 2000 ms + if (millis() - last_WS_update > 2000) { + websocket_terminal_server.handle(); + last_WS_update = millis(); + } + // no error so write post date + 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", + writeddatanb, upload.currentSize); + _upload_status = UPLOAD_STATUS_FAILED; + pushError(ESP_ERROR_FILE_WRITE, "File write failed"); + } + } else { + // we have a problem set flag UPLOAD_STATUS_FAILED + _upload_status = UPLOAD_STATUS_FAILED; + log_esp3d_e("Error detected"); + pushError(ESP_ERROR_FILE_WRITE, "File write failed"); + } + // Upload end + } else if (upload.status == UPLOAD_FILE_END) { + uint32_t filesize = 0; + // check if file is still open + if (fsUploadFile) { + // close it + fsUploadFile.close(); +#ifdef ESP_BENCHMARK_FEATURE + benchMark("SD upload", bench_start, millis(), bench_transfered); +#endif // ESP_BENCHMARK_FEATURE + // check size + String sizeargname = upload.filename + "S"; + // fsUploadFile = ESP_SD::open (filename, ESP_FILE_READ); + filesize = fsUploadFile.size(); + _upload_status = UPLOAD_STATUS_SUCCESSFUL; + if (_webserver->hasArg(sizeargname.c_str())) { + if (_webserver->arg(sizeargname.c_str()) != String(filesize)) { + _upload_status = UPLOAD_STATUS_FAILED; + pushError(ESP_ERROR_SIZE, "File upload failed"); + } + } + if (_upload_status == UPLOAD_STATUS_ONGOING) { + _upload_status = UPLOAD_STATUS_SUCCESSFUL; + } + } else { + // we have a problem set flag UPLOAD_STATUS_FAILED + _upload_status = UPLOAD_STATUS_FAILED; + pushError(ESP_ERROR_FILE_CLOSE, "File close failed"); } log_esp3d("Release Sd called"); ESP_SD::releaseFS(); #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 + // Upload cancelled + } else { + if (_upload_status == UPLOAD_STATUS_ONGOING) { + _upload_status = UPLOAD_STATUS_FAILED; + log_esp3d("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); + } + + if (_upload_status == UPLOAD_STATUS_FAILED) { + cancelUpload(); + if (fsUploadFile) { + fsUploadFile.close(); + } + if (auth_level != LEVEL_GUEST) { + if (ESP_SD::exists(filename.c_str())) { + ESP_SD::remove(filename.c_str()); + } + } + log_esp3d("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); } -#endif //HTTP_FEATURE && SD_DEVICE +#endif // HTTP_FEATURE && SD_DEVICE diff --git a/esp3d/src/modules/http/handles/upload-files.cpp b/esp3d/src/modules/http/handles/upload-files.cpp index 2fcce86c..0cce4473 100644 --- a/esp3d/src/modules/http/handles/upload-files.cpp +++ b/esp3d/src/modules/http/handles/upload-files.cpp @@ -17,205 +17,207 @@ 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_DEBUG_FEATURE DEBUG_OUTPUT_SERIAL0 +// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 #include "../../../include/esp3d_config.h" -#if defined (HTTP_FEATURE) && defined(FILESYSTEM_FEATURE) +#if defined(HTTP_FEATURE) && defined(FILESYSTEM_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 -#include "../../filesystem/esp_filesystem.h" +#endif // ARDUINO_ARCH_ESP8266 #include "../../authentication/authentication_service.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 - - +#endif // ESP3DLIB_ENV && COMMUNICATION_PROTOCOL == SOCKET_SERIAL #ifdef ESP_BENCHMARK_FEATURE #include "../../../core/benchmark.h" -#endif //ESP_BENCHMARK_FEATURE +#endif // ESP_BENCHMARK_FEATURE -//FS files uploader handle -void HTTP_Server::FSFileupload () -{ +// FS files uploader handle +void HTTP_Server::FSFileupload() { #ifdef ESP_BENCHMARK_FEATURE - static uint64_t bench_start; - static size_t bench_transfered; -#endif//ESP_BENCHMARK_FEATURE - //get authentication status - level_authenticate_type auth_level= AuthenticationService::authenticated_level(); - static String filename; - static ESP_File fsUploadFile; - //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(); - String upload_filename = upload.filename; - if ((_upload_status != UPLOAD_STATUS_FAILED) || (upload.status == UPLOAD_FILE_START)) { + static uint64_t bench_start; + static size_t bench_transfered; +#endif // ESP_BENCHMARK_FEATURE + // get authentication status + level_authenticate_type auth_level = + AuthenticationService::authenticated_level(); + static String filename; + static ESP_File fsUploadFile; + // 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(); + String upload_filename = upload.filename; + 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) { + Serial2Socket.pause(); +#endif // ESP3DLIB_ENV && COMMUNICATION_PROTOCOL == SOCKET_SERIAL + // Upload start + if (upload.status == UPLOAD_FILE_START) { #ifdef ESP_BENCHMARK_FEATURE - bench_start = millis(); - bench_transfered = 0; -#endif//ESP_BENCHMARK_FEATURE - _upload_status = UPLOAD_STATUS_ONGOING; - if (upload_filename[0] != '/') { - filename = "/" + upload_filename; - } else { - filename = upload.filename; - } - if (_webserver->hasArg ("rpath") ) { - upload_filename = _webserver->arg ("rpath") + filename; - if (upload_filename[0] != '/') { - filename = "/" + upload_filename; - } else { - filename = upload_filename; - } - } - //Sanity check - if (ESP_FileSystem::exists (filename.c_str()) ) { - ESP_FileSystem::remove (filename.c_str()); - } - String path = _webserver->arg ("path"); - if (path[0] != '/') { - path = "/" + path; - } - if (path[path.length()-1] != '/') { - path = path + "/"; - } - if (_webserver->hasArg("createPath") && path.length() > 1) { - if (_webserver->arg("createPath")== "true") { - int pos = path.indexOf('/',1); - while (pos != -1) { - String currentPath = path.substring(0, pos); - if (!ESP_FileSystem::exists (currentPath.c_str()) ) { - if ( !ESP_FileSystem::mkdir (currentPath.c_str()) ) { - pushError(ESP_ERROR_FILE_CREATION, "Failed to create path", 500); - _upload_status=UPLOAD_STATUS_FAILED; - break; - } - } - if ((uint)(pos+1) >= path.length()-1) { - pos=-1; - break; - } else { - pos = path.indexOf('/',pos+1); - } - - } - } - } - if (fsUploadFile.isOpen() ) { - fsUploadFile.close(); - } - String sizeargname = upload.filename + "S"; - if (_webserver->hasArg (sizeargname.c_str()) ) { - size_t freespace = ESP_FileSystem::totalBytes() - ESP_FileSystem::usedBytes(); - size_t filesize = _webserver->arg (sizeargname.c_str()).toInt(); - if (freespace < filesize ) { - _upload_status=UPLOAD_STATUS_FAILED; - pushError(ESP_ERROR_NOT_ENOUGH_SPACE, "Upload rejected"); - } - } - if (_upload_status!=UPLOAD_STATUS_FAILED) { - //create file - fsUploadFile = ESP_FileSystem::open(filename.c_str(), ESP_FILE_WRITE); - //check If creation succeed - if (fsUploadFile) { - //if yes upload is started - _upload_status= UPLOAD_STATUS_ONGOING; - } else { - //if no set cancel flag - _upload_status=UPLOAD_STATUS_FAILED; - pushError(ESP_ERROR_FILE_CREATION, "File creation failed"); - } - - } - //Upload write - } else if(upload.status == UPLOAD_FILE_WRITE) { - //check if file is available and no error - if(fsUploadFile && _upload_status == UPLOAD_STATUS_ONGOING) { - //no error so write post date -#ifdef ESP_BENCHMARK_FEATURE - bench_transfered += upload.currentSize; -#endif//ESP_BENCHMARK_FEATURE - if(upload.currentSize != fsUploadFile.write(upload.buf, upload.currentSize)) { - //we have a problem set flag UPLOAD_STATUS_FAILED - _upload_status=UPLOAD_STATUS_FAILED; - pushError(ESP_ERROR_FILE_WRITE, "File write failed"); - } - } else { - //we have a problem set flag UPLOAD_STATUS_FAILED - _upload_status=UPLOAD_STATUS_FAILED; - pushError(ESP_ERROR_FILE_WRITE, "File write failed"); - } - //Upload end - } else if(upload.status == UPLOAD_FILE_END) { - log_esp3d("upload end"); - //check if file is still open - if(fsUploadFile) { - //close it - fsUploadFile.close(); -#ifdef ESP_BENCHMARK_FEATURE - benchMark("FS upload", bench_start, millis(), bench_transfered); -#endif//ESP_BENCHMARK_FEATURE - //check size - String sizeargname = upload.filename + "S"; - //fsUploadFile = ESP_FileSystem::open (filename, ESP_FILE_READ); - uint32_t filesize = fsUploadFile.size(); - _upload_status = UPLOAD_STATUS_SUCCESSFUL; - if (_webserver->hasArg (sizeargname.c_str()) ) { - log_esp3d("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("Size Error"); - _upload_status = UPLOAD_STATUS_FAILED; - pushError(ESP_ERROR_SIZE, "File upload failed"); - } - } - if (_upload_status == UPLOAD_STATUS_ONGOING) { - _upload_status = UPLOAD_STATUS_SUCCESSFUL; - } - } else { - //we have a problem set flag UPLOAD_STATUS_FAILED - log_esp3d("Close Error"); - _upload_status=UPLOAD_STATUS_FAILED; - pushError(ESP_ERROR_FILE_CLOSE, "File close failed"); - } -#if defined(ESP3DLIB_ENV) && COMMUNICATION_PROTOCOL == SOCKET_SERIAL - Serial2Socket.pause(false); -#endif // ESP3DLIB_ENV && COMMUNICATION_PROTOCOL == SOCKET_SERIAL - //Upload cancelled - } else { - if (_upload_status == UPLOAD_STATUS_ONGOING) { - _upload_status = UPLOAD_STATUS_FAILED; - - } - } + bench_start = millis(); + bench_transfered = 0; +#endif // ESP_BENCHMARK_FEATURE + _upload_status = UPLOAD_STATUS_ONGOING; + if (upload_filename[0] != '/') { + filename = "/" + upload_filename; + } else { + filename = upload.filename; } - } - - if(_upload_status == UPLOAD_STATUS_FAILED) { - cancelUpload(); - if(fsUploadFile) { - fsUploadFile.close(); + if (_webserver->hasArg("rpath")) { + upload_filename = _webserver->arg("rpath") + filename; + if (upload_filename[0] != '/') { + filename = "/" + upload_filename; + } else { + filename = upload_filename; + } } - if (auth_level != LEVEL_GUEST) { - if (ESP_FileSystem::exists (filename.c_str())) { - ESP_FileSystem::remove (filename.c_str()); + // Sanity check + if (ESP_FileSystem::exists(filename.c_str())) { + ESP_FileSystem::remove(filename.c_str()); + } + String path = _webserver->arg("path"); + if (path[0] != '/') { + path = "/" + path; + } + if (path[path.length() - 1] != '/') { + path = path + "/"; + } + if (_webserver->hasArg("createPath") && path.length() > 1) { + if (_webserver->arg("createPath") == "true") { + int pos = path.indexOf('/', 1); + while (pos != -1) { + String currentPath = path.substring(0, pos); + if (!ESP_FileSystem::exists(currentPath.c_str())) { + if (!ESP_FileSystem::mkdir(currentPath.c_str())) { + pushError(ESP_ERROR_FILE_CREATION, "Failed to create path", + 500); + _upload_status = UPLOAD_STATUS_FAILED; + break; + } + } + if ((uint)(pos + 1) >= path.length() - 1) { + pos = -1; + break; + } else { + pos = path.indexOf('/', pos + 1); + } } + } + } + if (fsUploadFile.isOpen()) { + fsUploadFile.close(); + } + String sizeargname = upload.filename + "S"; + if (_webserver->hasArg(sizeargname.c_str())) { + size_t freespace = + ESP_FileSystem::totalBytes() - ESP_FileSystem::usedBytes(); + size_t filesize = _webserver->arg(sizeargname.c_str()).toInt(); + if (freespace < filesize) { + _upload_status = UPLOAD_STATUS_FAILED; + pushError(ESP_ERROR_NOT_ENOUGH_SPACE, "Upload rejected"); + } + } + if (_upload_status != UPLOAD_STATUS_FAILED) { + // create file + fsUploadFile = ESP_FileSystem::open(filename.c_str(), ESP_FILE_WRITE); + // check If creation succeed + if (fsUploadFile) { + // if yes upload is started + _upload_status = UPLOAD_STATUS_ONGOING; + } else { + // if no set cancel flag + _upload_status = UPLOAD_STATUS_FAILED; + pushError(ESP_ERROR_FILE_CREATION, "File creation failed"); + } + } + // Upload write + } else if (upload.status == UPLOAD_FILE_WRITE) { + // check if file is available and no error + if (fsUploadFile && _upload_status == UPLOAD_STATUS_ONGOING) { + // no error so write post date +#ifdef ESP_BENCHMARK_FEATURE + bench_transfered += upload.currentSize; +#endif // ESP_BENCHMARK_FEATURE + if (upload.currentSize != + fsUploadFile.write(upload.buf, upload.currentSize)) { + // we have a problem set flag UPLOAD_STATUS_FAILED + _upload_status = UPLOAD_STATUS_FAILED; + pushError(ESP_ERROR_FILE_WRITE, "File write failed"); + } + } else { + // we have a problem set flag UPLOAD_STATUS_FAILED + _upload_status = UPLOAD_STATUS_FAILED; + pushError(ESP_ERROR_FILE_WRITE, "File write failed"); + } + // Upload end + } else if (upload.status == UPLOAD_FILE_END) { + log_esp3d("upload end"); + // check if file is still open + if (fsUploadFile) { + // close it + fsUploadFile.close(); +#ifdef ESP_BENCHMARK_FEATURE + benchMark("FS upload", bench_start, millis(), bench_transfered); +#endif // ESP_BENCHMARK_FEATURE + // check size + String sizeargname = upload.filename + "S"; + // fsUploadFile = ESP_FileSystem::open (filename, ESP_FILE_READ); + uint32_t filesize = fsUploadFile.size(); + _upload_status = UPLOAD_STATUS_SUCCESSFUL; + if (_webserver->hasArg(sizeargname.c_str())) { + log_esp3d("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"); + _upload_status = UPLOAD_STATUS_FAILED; + pushError(ESP_ERROR_SIZE, "File upload failed"); + } + } + if (_upload_status == UPLOAD_STATUS_ONGOING) { + _upload_status = UPLOAD_STATUS_SUCCESSFUL; + } + } else { + // we have a problem set flag UPLOAD_STATUS_FAILED + log_esp3d_e("Close Error"); + _upload_status = UPLOAD_STATUS_FAILED; + pushError(ESP_ERROR_FILE_CLOSE, "File close failed"); } #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 + // Upload cancelled + } else { + if (_upload_status == UPLOAD_STATUS_ONGOING) { + _upload_status = UPLOAD_STATUS_FAILED; + } + } } + } + + if (_upload_status == UPLOAD_STATUS_FAILED) { + cancelUpload(); + if (fsUploadFile) { + fsUploadFile.close(); + } + if (auth_level != LEVEL_GUEST) { + if (ESP_FileSystem::exists(filename.c_str())) { + ESP_FileSystem::remove(filename.c_str()); + } + } +#if defined(ESP3DLIB_ENV) && COMMUNICATION_PROTOCOL == SOCKET_SERIAL + Serial2Socket.pause(false); +#endif // ESP3DLIB_ENV && COMMUNICATION_PROTOCOL == SOCKET_SERIAL + } } -#endif //HTTP_FEATURE && FILESYSTEM_FEATURE +#endif // HTTP_FEATURE && FILESYSTEM_FEATURE diff --git a/esp3d/src/modules/mDNS/mDNS.cpp b/esp3d/src/modules/mDNS/mDNS.cpp index f12236ad..3a5da49c 100644 --- a/esp3d/src/modules/mDNS/mDNS.cpp +++ b/esp3d/src/modules/mDNS/mDNS.cpp @@ -17,7 +17,7 @@ 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_DEBUG_FEATURE DEBUG_OUTPUT_SERIAL0 +// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 #include "../../include/esp3d_config.h" #ifdef MDNS_FEATURE @@ -97,38 +97,38 @@ void mDNS_Service::end() { if (_hMDNSServiceQuery) { log_esp3d("Remove mdns service for %s", _hostname.c_str()); if (!MDNS.removeServiceQuery(_hMDNSServiceQuery)) { - log_esp3d("failed"); + log_esp3d_e("failed"); } } _hMDNSServiceQuery = 0; log_esp3d("Remove mdns for %s", _hostname.c_str()); if (!MDNS.removeService(_hostname.c_str(), MDNS_SERVICE_NAME, MDNS_SERVICE_TYPE)) { - log_esp3d("failed"); + log_esp3d_e("failed"); } #if defined(HTTP_FEATURE) if (!MDNS.removeService(_hostname.c_str(), "http", "tcp")) { - log_esp3d("failed"); + log_esp3d_e("failed"); } #endif // HTTP_FEATURE #if defined(FTP_FEATURE) if (!MDNS.removeService(_hostname.c_str(), "ftp", "tcp")) { - log_esp3d("failed"); + log_esp3d_e("failed"); } #endif // FTP_FEATURE #if defined(TELNET_FEATURE) if (!MDNS.removeService(_hostname.c_str(), "telnet", "tcp")) { - log_esp3d("failed"); + log_esp3d_e("failed"); } #endif // TELNET_FEATURE #if defined(WEBDAV_FEATURE) if (!MDNS.removeService(_hostname.c_str(), "webdav", "tcp")) { - log_esp3d("failed"); + log_esp3d_e("failed"); } #endif // WEBDAV_FEATURE #if defined(WS_DATA_FEATURE) if (!MDNS.removeService(_hostname.c_str(), "websocket", "tcp")) { - log_esp3d("failed"); + log_esp3d_e("failed"); } #endif // WS_DATA_FEATURE #endif // ARDUINO_ARCH_ESP8266 @@ -194,7 +194,7 @@ void mDNS_Service::addESP3DServices(uint16_t port) { if (_hMDNSServiceQuery) { log_esp3d("MDNS Service query services installed."); } else { - log_esp3d("MDNS Service query services installation failed."); + log_esp3d_e("MDNS Service query services installation failed."); } #endif // ARDUINO_ARCH_ESP8266 } diff --git a/esp3d/src/modules/mks/mks_service.cpp b/esp3d/src/modules/mks/mks_service.cpp index 13d8eb16..a45dde3e 100644 --- a/esp3d/src/modules/mks/mks_service.cpp +++ b/esp3d/src/modules/mks/mks_service.cpp @@ -20,84 +20,82 @@ #include "../../include/esp3d_config.h" #if COMMUNICATION_PROTOCOL == MKS_SERIAL -#include "mks_service.h" -#include "../../core/settings_esp3d.h" #include "../../core/esp3doutput.h" -#include "../network/netconfig.h" -#include "../wifi/wificonfig.h" -#include "../telnet/telnet_server.h" +#include "../../core/settings_esp3d.h" #include "../http/http_server.h" #include "../network/netconfig.h" #include "../serial/serial_service.h" +#include "../telnet/telnet_server.h" +#include "../wifi/wificonfig.h" +#include "mks_service.h" -//Flag Pins -#define ESP_FLAG_PIN 0 -#define BOARD_FLAG_PIN 4 -//Flag pins values -#define BOARD_READY_FLAG_VALUE LOW +// Flag Pins +#define ESP_FLAG_PIN 0 +#define BOARD_FLAG_PIN 4 +// Flag pins values +#define BOARD_READY_FLAG_VALUE LOW -//Frame offsets -#define MKS_FRAME_HEAD_OFFSET 0 -#define MKS_FRAME_TYPE_OFFSET 1 -#define MKS_FRAME_DATALEN_OFFSET 2 -#define MKS_FRAME_DATA_OFFSET 4 +// Frame offsets +#define MKS_FRAME_HEAD_OFFSET 0 +#define MKS_FRAME_TYPE_OFFSET 1 +#define MKS_FRAME_DATALEN_OFFSET 2 +#define MKS_FRAME_DATA_OFFSET 4 -//Frame flags +// Frame flags #define MKS_FRAME_HEAD_FLAG (char)0xa5 #define MKS_FRAME_TAIL_FLAG (char)0xfc -//Network states +// Network states #define MKS_FRAME_NETWORK_OK_STATE (char)0x0a #define MKS_FRAME_NETWORK_FAIL_STATE (char)0x05 #define MKS_FRAME_NETWORK_ERROR_STATE (char)0x0e -//Network modes +// Network modes #define MKS_FRAME_NETWORK_AP_MODE (char)0x01 #define MKS_FRAME_NETWORK_STA_MODE (char)0x02 #define MKS_FRAME_NETWORK_APSTA_MODE (char)0x03 -//Cloud states +// Cloud states #define MKS_FRAME_CLOUD_BINDED_STATE (char)0x12 #define MKS_FRAME_CLOUD_NOT_BINDED_STATE (char)0x13 #define MKS_FRAME_CLOUD_DISCONNECTED_STATE (char)0x10 #define MKS_FRAME_CLOUD_DISABLED_STATE (char)0x00 +// Data types +#define MKS_FRAME_DATA_NETWORK_TYPE (char)0x0 +#define MKS_FRAME_DATA_COMMAND_TYPE (char)0x1 +#define MKS_FRAME_DATA_FIRST_FRAGMENT_TYPE (char)0x2 +#define MKS_FRAME_DATA_FRAGMENT_TYPE (char)0x3 +#define MKS_FRAME_DATA_HOTSPOTS_LIST_TYPE (char)0x4 +#define MKS_FRAME_DATA_STATIC_IP_TYPE (char)0x5 -//Data types -#define MKS_FRAME_DATA_NETWORK_TYPE (char)0x0 -#define MKS_FRAME_DATA_COMMAND_TYPE (char)0x1 -#define MKS_FRAME_DATA_FIRST_FRAGMENT_TYPE (char)0x2 -#define MKS_FRAME_DATA_FRAGMENT_TYPE (char)0x3 -#define MKS_FRAME_DATA_HOTSPOTS_LIST_TYPE (char)0x4 -#define MKS_FRAME_DATA_STATIC_IP_TYPE (char)0x5 +#define MKS_TYPE_NET (char)0x0 +#define MKS_TYPE_PRINTER (char)0x1 +#define MKS_TYPE_TRANSFER (char)0x2 +#define MKS_TYPE_EXCEPTION (char)0x3 +#define MKS_TYPE_CLOUD (char)0x4 +#define MKS_TYPE_UNBIND (char)0x5 +#define MKS_TYPE_WID (char)0x6 +#define MKS_TYPE_SCAN_WIFI (char)0x7 +#define MKS_TYPE_MANUAL_IP (char)0x8 +#define MKS_TYPE_WIFI_CTRL (char)0x9 -#define MKS_TYPE_NET (char)0x0 -#define MKS_TYPE_PRINTER (char)0x1 -#define MKS_TYPE_TRANSFER (char)0x2 -#define MKS_TYPE_EXCEPTION (char)0x3 -#define MKS_TYPE_CLOUD (char)0x4 -#define MKS_TYPE_UNBIND (char)0x5 -#define MKS_TYPE_WID (char)0x6 -#define MKS_TYPE_SCAN_WIFI (char)0x7 -#define MKS_TYPE_MANUAL_IP (char)0x8 -#define MKS_TYPE_WIFI_CTRL (char)0x9 +#define CONNECT_STA 0x1 +#define DISCONNECT_STA 0x2 +#define REMOVE_STA_INFO 0x3 -#define CONNECT_STA 0x1 -#define DISCONNECT_STA 0x2 -#define REMOVE_STA_INFO 0x3 +#define UNKNOW_STATE 0x0 +#define ERROR_STATE 0x1 +#define SUCCESS_STATE 0x2 -#define UNKNOW_STATE 0x0 -#define ERROR_STATE 0x1 -#define SUCCESS_STATE 0x2 +#define NB_HOTSPOT_MAX 15 -#define NB_HOTSPOT_MAX 15 +// Timeouts +#define FRAME_WAIT_TO_SEND_TIMEOUT 2000 +#define ACK_TIMEOUT 5000 +#define NET_FRAME_REFRESH_TIME 10000 -//Timeouts -#define FRAME_WAIT_TO_SEND_TIMEOUT 2000 -#define ACK_TIMEOUT 5000 -#define NET_FRAME_REFRESH_TIME 10000 - -#define UPLOAD_BAUD_RATE 1958400 +#define UPLOAD_BAUD_RATE 1958400 bool MKSService::_started = false; uint8_t MKSService::_frame[MKS_FRAME_SIZE] = {0}; @@ -106,655 +104,634 @@ uint8_t MKSService::_uploadStatus = UNKNOW_STATE; long MKSService::_commandBaudRate = 115200; bool MKSService::_uploadMode = false; -bool MKSService::isHead(const char c) -{ - return (c==MKS_FRAME_HEAD_FLAG); -} -bool MKSService::isTail(const char c) -{ - return (c==MKS_FRAME_TAIL_FLAG); -} -bool MKSService::isCommand(const char c) -{ - return (c==MKS_TYPE_TRANSFER); -} -bool MKSService::isFrame(const char c) -{ - if ((c>=MKS_TYPE_NET)&& (c<=MKS_TYPE_WIFI_CTRL)) { - return true; - } - return false; -} -bool MKSService::begin() -{ - //setup the pins - pinMode(BOARD_FLAG_PIN, INPUT); - pinMode(ESP_FLAG_PIN, OUTPUT); - _started = true; - //max size is 21 - sprintf (_moduleId, "HJNLM000%02X%02X%02X%02X%02X%02X", WiFi.macAddress()[0], WiFi.macAddress()[1], WiFi.macAddress()[2], WiFi.macAddress()[3], WiFi.macAddress()[4], WiFi.macAddress()[5]); - commandMode(true); +bool MKSService::isHead(const char c) { return (c == MKS_FRAME_HEAD_FLAG); } +bool MKSService::isTail(const char c) { return (c == MKS_FRAME_TAIL_FLAG); } +bool MKSService::isCommand(const char c) { return (c == MKS_TYPE_TRANSFER); } +bool MKSService::isFrame(const char c) { + if ((c >= MKS_TYPE_NET) && (c <= MKS_TYPE_WIFI_CTRL)) { return true; + } + return false; +} +bool MKSService::begin() { + // setup the pins + pinMode(BOARD_FLAG_PIN, INPUT); + pinMode(ESP_FLAG_PIN, OUTPUT); + _started = true; + // max size is 21 + sprintf(_moduleId, "HJNLM000%02X%02X%02X%02X%02X%02X", WiFi.macAddress()[0], + WiFi.macAddress()[1], WiFi.macAddress()[2], WiFi.macAddress()[3], + WiFi.macAddress()[4], WiFi.macAddress()[5]); + commandMode(true); + return true; } -void MKSService::commandMode(bool fromSettings) -{ - if (fromSettings) { - _commandBaudRate= Settings_ESP3D::read_uint32(ESP_BAUD_RATE); - } - log_esp3d("Cmd Mode"); - _uploadMode = false; - serial_service.updateBaudRate(_commandBaudRate); - +void MKSService::commandMode(bool fromSettings) { + if (fromSettings) { + _commandBaudRate = Settings_ESP3D::read_uint32(ESP_BAUD_RATE); + } + log_esp3d("Cmd Mode"); + _uploadMode = false; + serial_service.updateBaudRate(_commandBaudRate); } -void MKSService::uploadMode() -{ - log_esp3d("Upload Mode"); - _uploadMode = true; - serial_service.updateBaudRate(UPLOAD_BAUD_RATE); +void MKSService::uploadMode() { + log_esp3d("Upload Mode"); + _uploadMode = true; + serial_service.updateBaudRate(UPLOAD_BAUD_RATE); } -uint MKSService::getFragmentID(uint32_t fragmentNumber, bool isLast) -{ - log_esp3d("Fragment: %d %s",fragmentNumber, isLast?" is last":"" ); - if (isLast) { - fragmentNumber |= (1 << 31); - } else { - fragmentNumber &= ~(1 << 31); - } - log_esp3d("Fragment is now: %d",fragmentNumber); - return fragmentNumber; +uint MKSService::getFragmentID(uint32_t fragmentNumber, bool isLast) { + log_esp3d("Fragment: %d %s", fragmentNumber, isLast ? " is last" : ""); + if (isLast) { + fragmentNumber |= (1 << 31); + } else { + fragmentNumber &= ~(1 << 31); + } + log_esp3d("Fragment is now: %d", fragmentNumber); + return fragmentNumber; } -bool MKSService::sendFirstFragment(const char* filename, size_t filesize) -{ - uint fileNameLen = strlen(filename); - uint dataLen = fileNameLen + 5; - clearFrame(); - //Head Flag - _frame[MKS_FRAME_HEAD_OFFSET] = MKS_FRAME_HEAD_FLAG; - //Type Flag - _frame[MKS_FRAME_TYPE_OFFSET] = MKS_FRAME_DATA_FIRST_FRAGMENT_TYPE; - //Fragment size - _frame[MKS_FRAME_DATALEN_OFFSET] = dataLen & 0xff; - _frame[MKS_FRAME_DATALEN_OFFSET + 1] = dataLen >> 8; - //FileName size - _frame[MKS_FRAME_DATA_OFFSET] = strlen(filename); - //File Size - _frame[MKS_FRAME_DATA_OFFSET+1] = filesize & 0xff; - _frame[MKS_FRAME_DATA_OFFSET+2] = (filesize >> 8) & 0xff; - _frame[MKS_FRAME_DATA_OFFSET+3] = (filesize >> 16) & 0xff; - _frame[MKS_FRAME_DATA_OFFSET+4] = (filesize >> 24) & 0xff; - //Filename - 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 ); - for (uint i =0; i< dataLen + 5 ; i++) { - log_esp3d("%c %x",_frame[i],_frame[i]); - } +bool MKSService::sendFirstFragment(const char *filename, size_t filesize) { + uint fileNameLen = strlen(filename); + uint dataLen = fileNameLen + 5; + clearFrame(); + // Head Flag + _frame[MKS_FRAME_HEAD_OFFSET] = MKS_FRAME_HEAD_FLAG; + // Type Flag + _frame[MKS_FRAME_TYPE_OFFSET] = MKS_FRAME_DATA_FIRST_FRAGMENT_TYPE; + // Fragment size + _frame[MKS_FRAME_DATALEN_OFFSET] = dataLen & 0xff; + _frame[MKS_FRAME_DATALEN_OFFSET + 1] = dataLen >> 8; + // FileName size + _frame[MKS_FRAME_DATA_OFFSET] = strlen(filename); + // File Size + _frame[MKS_FRAME_DATA_OFFSET + 1] = filesize & 0xff; + _frame[MKS_FRAME_DATA_OFFSET + 2] = (filesize >> 8) & 0xff; + _frame[MKS_FRAME_DATA_OFFSET + 3] = (filesize >> 16) & 0xff; + _frame[MKS_FRAME_DATA_OFFSET + 4] = (filesize >> 24) & 0xff; + // Filename + 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); + for (uint i = 0; i < dataLen + 5; i++) { + log_esp3d("%c %x", _frame[i], _frame[i]); + } + _uploadStatus = UNKNOW_STATE; + if (canSendFrame()) { + ESP3DOutput output(ESP_SERIAL_CLIENT); _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"); - sendFrameDone(); - return true; - } + if (output.write(_frame, dataLen + 5) == (dataLen + 5)) { + log_esp3d("First fragment Ok"); + sendFrameDone(); + return true; } - log_esp3d("Failed"); - sendFrameDone(); - return false; + } + log_esp3d("Failed"); + sendFrameDone(); + return false; } - -bool MKSService::sendFragment(const uint8_t * dataFrame, const size_t dataSize,uint fragmentID) -{ - uint dataLen = dataSize + 4; - log_esp3d("Fragment datalen:%d",dataSize); - //Head Flag - _frame[MKS_FRAME_HEAD_OFFSET] = MKS_FRAME_HEAD_FLAG; - //Type Flag - _frame[MKS_FRAME_TYPE_OFFSET] = MKS_FRAME_DATA_FRAGMENT_TYPE; - //Fragment size - _frame[MKS_FRAME_DATALEN_OFFSET] = dataLen & 0xff; - _frame[MKS_FRAME_DATALEN_OFFSET + 1] = dataLen >> 8; - //Fragment ID - _frame[MKS_FRAME_DATA_OFFSET ] = fragmentID & 0xff; - _frame[MKS_FRAME_DATA_OFFSET + 1] = (fragmentID >> 8) & 0xff; - _frame[MKS_FRAME_DATA_OFFSET + 2] = (fragmentID >> 16) & 0xff; - _frame[MKS_FRAME_DATA_OFFSET + 3] = (fragmentID >> 24) & 0xff; - //data - if ((dataSize>0) && (dataFrame!=nullptr)) { - memcpy(&_frame[MKS_FRAME_DATA_OFFSET+ 4], dataFrame, dataSize); +bool MKSService::sendFragment(const uint8_t *dataFrame, const size_t dataSize, + uint fragmentID) { + uint dataLen = dataSize + 4; + log_esp3d("Fragment datalen:%d", dataSize); + // Head Flag + _frame[MKS_FRAME_HEAD_OFFSET] = MKS_FRAME_HEAD_FLAG; + // Type Flag + _frame[MKS_FRAME_TYPE_OFFSET] = MKS_FRAME_DATA_FRAGMENT_TYPE; + // Fragment size + _frame[MKS_FRAME_DATALEN_OFFSET] = dataLen & 0xff; + _frame[MKS_FRAME_DATALEN_OFFSET + 1] = dataLen >> 8; + // Fragment ID + _frame[MKS_FRAME_DATA_OFFSET] = fragmentID & 0xff; + _frame[MKS_FRAME_DATA_OFFSET + 1] = (fragmentID >> 8) & 0xff; + _frame[MKS_FRAME_DATA_OFFSET + 2] = (fragmentID >> 16) & 0xff; + _frame[MKS_FRAME_DATA_OFFSET + 3] = (fragmentID >> 24) & 0xff; + // data + if ((dataSize > 0) && (dataFrame != nullptr)) { + memcpy(&_frame[MKS_FRAME_DATA_OFFSET + 4], dataFrame, dataSize); + } + if (dataSize < MKS_FRAME_DATA_MAX_SIZE) { + clearFrame(dataLen + 4); + } + // 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]); + }*/ + if (canSendFrame()) { + ESP3DOutput output(ESP_SERIAL_CLIENT); + _uploadStatus = UNKNOW_STATE; + if (output.write(_frame, MKS_FRAME_SIZE) == MKS_FRAME_SIZE) { + log_esp3d("Ok"); + sendFrameDone(); + return true; } - if (dataSize NB_HOTSPOT_MAX) { + break; + } + 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, + (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"); + continue; + } + if (signal_rssi < MIN_RSSI) { + log_esp3d("Signal too low, ignored"); + continue; + } + _frame[MKS_FRAME_DATA_OFFSET + dataOffset] = ssid_name_length; + for (uint8_t p = 0; p < ssid_name_length; p++) { + _frame[MKS_FRAME_DATA_OFFSET + dataOffset + 1 + p] = WiFi.SSID(i)[p]; + } + _frame[MKS_FRAME_DATA_OFFSET + dataOffset + ssid_name_length + 1] = + WiFi.RSSI(i); + dataOffset += ssid_name_length + 2; + total_hotspots++; + } + _frame[MKS_FRAME_DATA_OFFSET] = total_hotspots; + _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); + for (uint i = 0; i < dataOffset + 5; i++) { + log_esp3d("%c %x", _frame[i], _frame[i]); + } + if (canSendFrame()) { + ESP3DOutput output(ESP_SERIAL_CLIENT); + if (output.write(_frame, dataOffset + 5) == (dataOffset + 5)) { + log_esp3d("Ok"); + sendFrameDone(); + } else { + log_esp3d_e("Send scan failed"); + } + } else { + log_esp3d_e("Cannot send scan"); + } + // clean memory WiFi.scanDelete(); - int n = WiFi.scanNetworks(); - log_esp3d("scan done"); - if (n == 0) { - log_esp3d("no networks found"); - } else { - log_esp3d("%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; - for (uint8_t i = 0; i < n; ++i) { - int8_t signal_rssi = 0; - if(total_hotspots > NB_HOTSPOT_MAX) { - break; - } - 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,(WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*" ); - ssid_name_length = WiFi.SSID(i).length(); - if(ssid_name_length > MAX_SSID_LENGTH) { - log_esp3d("Name too long, ignored" ); - continue; - } - if(signal_rssi < MIN_RSSI) { - log_esp3d("Signal too low, ignored" ); - continue; - } - _frame[MKS_FRAME_DATA_OFFSET + dataOffset] = ssid_name_length; - for (uint8_t p = 0; p < ssid_name_length; p++) { - _frame[MKS_FRAME_DATA_OFFSET + dataOffset+1+p] = WiFi.SSID(i)[p]; - } - _frame[MKS_FRAME_DATA_OFFSET + dataOffset + ssid_name_length + 1] = WiFi.RSSI(i); - dataOffset+=ssid_name_length+2; - total_hotspots++; - } - _frame[MKS_FRAME_DATA_OFFSET] = total_hotspots; - _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); - for (uint i =0; i< dataOffset + 5 ; i++) { - log_esp3d("%c %x",_frame[i],_frame[i]); - } - if (canSendFrame()) { - ESP3DOutput output(ESP_SERIAL_CLIENT); - if (output.write(_frame,dataOffset+5) == (dataOffset+5)) { - log_esp3d("Ok"); - sendFrameDone(); - } else { - log_esp3d("Send scan failed"); - } - } else { - log_esp3d("Cannot send scan"); - } - //clean memory - WiFi.scanDelete(); - } - //Restore mode - WiFi.mode((WiFiMode_t)currentmode); - sendFrameDone(); + } + // Restore mode + WiFi.mode((WiFiMode_t)currentmode); + sendFrameDone(); } -void MKSService::handleFrame(const uint8_t type, const uint8_t * dataFrame, const size_t dataSize ) -{ - log_esp3d("Command is %d", type); - switch(type) { - //wifi setup +void MKSService::handleFrame(const uint8_t type, const uint8_t *dataFrame, + const size_t dataSize) { + log_esp3d("Command is %d", type); + switch (type) { + // wifi setup case MKS_TYPE_NET: - log_esp3d("************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*************"); - break; - //File transfer if not command - case MKS_TYPE_TRANSFER : - //todo - log_esp3d("************MKS_TYPE_TRANSFER*************"); - break; - //Error when doing transfer - case MKS_TYPE_EXCEPTION : - log_esp3d("************MKS_TYPE_EXCEPTION*************"); - messageException(dataFrame, dataSize); - break; - //not supported (cloud) - case MKS_TYPE_CLOUD : - //ignored - log_esp3d("************MKS_TYPE_CLOUD*************"); - break; - //not supported (cloud) - case MKS_TYPE_WID : - //ignored - log_esp3d("************MKS_TYPE_WID*************"); - break; - //hot spot list - case MKS_TYPE_SCAN_WIFI : - log_esp3d("************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*************"); - break; - //On/Off Wifi - case MKS_TYPE_WIFI_CTRL : - log_esp3d("************MKS_TYPE_WIFI_CTRL*************"); - messageWiFiControl(dataFrame,dataSize); - break; + log_esp3d("************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*************"); + break; + // File transfer if not command + case MKS_TYPE_TRANSFER: + // todo + log_esp3d("************MKS_TYPE_TRANSFER*************"); + break; + // Error when doing transfer + case MKS_TYPE_EXCEPTION: + log_esp3d("************MKS_TYPE_EXCEPTION*************"); + messageException(dataFrame, dataSize); + break; + // not supported (cloud) + case MKS_TYPE_CLOUD: + // ignored + log_esp3d("************MKS_TYPE_CLOUD*************"); + break; + // not supported (cloud) + case MKS_TYPE_WID: + // ignored + log_esp3d("************MKS_TYPE_WID*************"); + break; + // hot spot list + case MKS_TYPE_SCAN_WIFI: + log_esp3d("************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*************"); + break; + // On/Off Wifi + case MKS_TYPE_WIFI_CTRL: + log_esp3d("************MKS_TYPE_WIFI_CTRL*************"); + messageWiFiControl(dataFrame, dataSize); + break; default: - log_esp3d("Unknow type"); - } + log_esp3d_e("Unknow type"); + } } -void MKSService::messageWiFiControl(const uint8_t * dataFrame, const size_t dataSize ) -{ - if(dataSize != 1) { - return; - } - switch (dataFrame[0]) { +void MKSService::messageWiFiControl(const uint8_t *dataFrame, + const size_t dataSize) { + if (dataSize != 1) { + return; + } + switch (dataFrame[0]) { case CONNECT_STA: - log_esp3d("CONNECT_STA"); - if (!NetConfig::started()) { - NetConfig::begin(); - } - break; + log_esp3d("CONNECT_STA"); + if (!NetConfig::started()) { + NetConfig::begin(); + } + break; case DISCONNECT_STA: - log_esp3d("CONNECT_STA"); - if (NetConfig::started()) { - NetConfig::end(); - } - break; + log_esp3d("CONNECT_STA"); + if (NetConfig::started()) { + NetConfig::end(); + } + break; case REMOVE_STA_INFO: - log_esp3d("REMOVE_STA_INFO"); - if (NetConfig::started()) { - NetConfig::end(); - } - Settings_ESP3D::reset(true); - break; + log_esp3d("REMOVE_STA_INFO"); + if (NetConfig::started()) { + NetConfig::end(); + } + Settings_ESP3D::reset(true); + break; default: - log_esp3d("WiFi control flag not supported"); - } + log_esp3d_e("WiFi control flag not supported"); + } } -//Exception handle - but actually not used -void MKSService::messageException(const uint8_t * dataFrame, const size_t dataSize ) -{ - if(dataSize != 1) { - return; - } - if ((dataFrame[0] == ERROR_STATE) || (dataFrame[0] == SUCCESS_STATE)) { - _uploadStatus = dataFrame[0]; - log_esp3d("Tranfer: %s",dataFrame[0] == ERROR_STATE?"Error":"Success" ); - } else { - _uploadStatus = UNKNOW_STATE; - log_esp3d("Tranfer state unknown" ); - } +// Exception handle - but actually not used +void MKSService::messageException(const uint8_t *dataFrame, + const size_t dataSize) { + if (dataSize != 1) { + return; + } + if ((dataFrame[0] == ERROR_STATE) || (dataFrame[0] == SUCCESS_STATE)) { + _uploadStatus = dataFrame[0]; + log_esp3d("Tranfer: %s", dataFrame[0] == ERROR_STATE ? "Error" : "Success"); + } else { + _uploadStatus = UNKNOW_STATE; + log_esp3d_e("Tranfer state unknown"); + } } -void MKSService::messageWiFiConfig(const uint8_t * dataFrame, const size_t dataSize ) -{ - String ssid; - String password; - String savedSsid; - String savedPassword; - bool needrestart = false; - //Sanity check - if(dataSize <2) { - log_esp3d("Invalid data"); - return; +void MKSService::messageWiFiConfig(const uint8_t *dataFrame, + const size_t dataSize) { + String ssid; + String password; + String savedSsid; + String savedPassword; + bool needrestart = false; + // Sanity check + if (dataSize < 2) { + log_esp3d_e("Invalid data"); + return; + } + if ((dataFrame[0] != MKS_FRAME_NETWORK_AP_MODE) && + (dataFrame[0] != MKS_FRAME_NETWORK_STA_MODE)) { + log_esp3d_e("Invalid mode"); + return; + } + if ((dataFrame[1] > dataSize - 3) || (dataFrame[1] == 0) || + (dataFrame[1] > MAX_SSID_LENGTH)) { + log_esp3d_e("Invalid ssid size"); + return; + } + if ((uint)(dataFrame[1] + 3) > dataSize) { + log_esp3d_e("Overflow password size"); + return; + } + if ((dataFrame[dataFrame[1] + 2]) > MAX_PASSWORD_LENGTH) { + log_esp3d_e("Invalid password size"); + return; + } + // get SSID and password + for (uint8_t i = 0; i < dataFrame[1]; i++) { + ssid += (char)dataFrame[2 + i]; + } + for (uint8_t j = 0; j < dataFrame[2 + dataFrame[1]]; j++) { + 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); + needrestart = true; } - if((dataFrame[0] != MKS_FRAME_NETWORK_AP_MODE) && (dataFrame[0] != MKS_FRAME_NETWORK_STA_MODE)) { - log_esp3d("Invalid mode"); - return; + savedSsid = Settings_ESP3D::read_string(ESP_AP_SSID); + savedPassword = Settings_ESP3D::read_string(ESP_AP_PASSWORD); + if (savedSsid != ssid) { + Settings_ESP3D::write_string(ESP_AP_SSID, ssid.c_str()); + needrestart = true; } - if ((dataFrame[1] > dataSize - 3) || (dataFrame[1]==0) || (dataFrame[1]>MAX_SSID_LENGTH)) { - log_esp3d("Invalid ssid size"); - return; + if (savedPassword != password) { + Settings_ESP3D::write_string(ESP_AP_PASSWORD, password.c_str()); + needrestart = true; } - if ((uint)(dataFrame[1]+3)> dataSize) { - log_esp3d("Overflow password size"); - return; + } else { + if (Settings_ESP3D::read_byte(ESP_RADIO_MODE) != ESP_WIFI_STA) { + Settings_ESP3D::write_byte(ESP_RADIO_MODE, ESP_WIFI_STA); + needrestart = true; } - if ((dataFrame[dataFrame[1]+2])> MAX_PASSWORD_LENGTH) { - log_esp3d("Invalid password size"); - return; + savedSsid = Settings_ESP3D::read_string(ESP_STA_SSID); + savedPassword = Settings_ESP3D::read_string(ESP_STA_PASSWORD); + if (savedSsid != ssid) { + Settings_ESP3D::write_string(ESP_STA_SSID, ssid.c_str()); + needrestart = true; } - //get SSID and password - for(uint8_t i = 0; i < dataFrame[1]; i++) { - ssid+=(char)dataFrame[2+i]; - } - for(uint8_t j = 0; j < dataFrame[2+dataFrame[1]]; j++) { - 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); - needrestart=true; - } - savedSsid=Settings_ESP3D::read_string(ESP_AP_SSID); - savedPassword=Settings_ESP3D::read_string(ESP_AP_PASSWORD); - if (savedSsid!=ssid) { - Settings_ESP3D::write_string(ESP_AP_SSID,ssid.c_str()); - needrestart =true; - } - if (savedPassword!=password) { - Settings_ESP3D::write_string(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); - needrestart =true; - } - savedSsid=Settings_ESP3D::read_string(ESP_STA_SSID); - savedPassword=Settings_ESP3D::read_string(ESP_STA_PASSWORD); - if (savedSsid!=ssid) { - Settings_ESP3D::write_string(ESP_STA_SSID,ssid.c_str()); - needrestart =true; - } - if (savedPassword!=password) { - Settings_ESP3D::write_string(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); - } - + if (savedPassword != password) { + Settings_ESP3D::write_string(ESP_STA_PASSWORD, password.c_str()); + needrestart = true; } if (needrestart) { - log_esp3d("Modifications done - restarting network"); - NetConfig::begin(); + // change also to DHCP for new value + Settings_ESP3D::write_byte(ESP_STA_IP_MODE, DHCP_MODE); } + } + if (needrestart) { + log_esp3d("Modifications done - restarting network"); + NetConfig::begin(); + } } -bool MKSService::canSendFrame() -{ - log_esp3d("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"); - return true; - } - Hal::wait(0); +bool MKSService::canSendFrame() { + log_esp3d("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"); + return true; } - log_esp3d("Time out no board answer"); + Hal::wait(0); + } + log_esp3d("Time out no board answer"); + return false; +} + +void MKSService::sendFrameDone() { + digitalWrite(ESP_FLAG_PIN, !BOARD_READY_FLAG_VALUE); +} + +bool MKSService::sendGcodeFrame(const char *cmd) { + if (_uploadMode) { return false; + } + String tmp = cmd; + if (tmp.endsWith("\n")) { + tmp[tmp.length() - 1] = '\0'; + } + log_esp3d("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; + for (uint i = 0; i < strlen(tmp.c_str()); i++) { + _frame[MKS_FRAME_DATA_OFFSET + i] = tmp[i]; + } + _frame[MKS_FRAME_DATA_OFFSET + strlen(tmp.c_str())] = '\r'; + _frame[MKS_FRAME_DATA_OFFSET + strlen(tmp.c_str()) + 1] = '\n'; + _frame[MKS_FRAME_DATA_OFFSET + strlen(tmp.c_str()) + 2] = MKS_FRAME_TAIL_FLAG; + _frame[MKS_FRAME_DATALEN_OFFSET] = (strlen(tmp.c_str()) + 2) & 0xff; + _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); + // for (uint i =0; i< strlen(tmp.c_str())+7;i++){ + // log_esp3d("%c %x",_frame[i],_frame[i]); + // } + + if (canSendFrame()) { + ESP3DOutput output(ESP_SERIAL_CLIENT); + if (output.write(_frame, strlen(tmp.c_str()) + 7) == + (strlen(tmp.c_str()) + 7)) { + log_esp3d("Ok"); + sendFrameDone(); + return true; + } + } + _e("Failed"); + sendFrameDone(); + return false; } -void MKSService::sendFrameDone() -{ - digitalWrite(ESP_FLAG_PIN, !BOARD_READY_FLAG_VALUE); - -} - -bool MKSService::sendGcodeFrame(const char* cmd) -{ - if (_uploadMode) { - return false; - } - String tmp = cmd; - if (tmp.endsWith("\n")) { - tmp[tmp.length()-1]='\0'; - } - log_esp3d("Packing: *%s*, size=%d", tmp.c_str(), strlen(tmp.c_str())); +bool MKSService::sendNetworkFrame() { + size_t dataOffset = 0; + String s; + static uint32_t lastsend = 0; + if (_uploadMode) { + return false; + } + if ((millis() - lastsend) > NET_FRAME_REFRESH_TIME) { + lastsend = millis(); + log_esp3d("Network frame preparation"); + // Prepare clearFrame(); _frame[MKS_FRAME_HEAD_OFFSET] = MKS_FRAME_HEAD_FLAG; - _frame[MKS_FRAME_TYPE_OFFSET] = MKS_FRAME_DATA_COMMAND_TYPE; - for(uint i = 0 ; i < strlen(tmp.c_str()); i++) { - _frame[MKS_FRAME_DATA_OFFSET + i]=tmp[i]; + _frame[MKS_FRAME_TYPE_OFFSET] = MKS_FRAME_DATA_NETWORK_TYPE; + if (NetConfig::getMode() == ESP_WIFI_STA) { + log_esp3d("STA Mode"); + if (WiFi.status() == WL_CONNECTED) { + /////////////////////////////////// + // IP Segment + // IP value + IPAddress ip = NetConfig::localIPAddress(); + _frame[MKS_FRAME_DATA_OFFSET] = ip[0]; + _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], + _frame[MKS_FRAME_DATA_OFFSET + 1], + _frame[MKS_FRAME_DATA_OFFSET + 2], + _frame[MKS_FRAME_DATA_OFFSET + 3]); + ////////////////////////////////// + // State Segment + // Connected state (OK) + _frame[MKS_FRAME_DATA_OFFSET + 6] = MKS_FRAME_NETWORK_OK_STATE; + } else { + /////////////////////////////////// + // IP Segment + // No need - bytes are already cleared + ////////////////////////////////// + // State Segment + // Connected state (Disconnected) + _frame[MKS_FRAME_DATA_OFFSET + 6] = MKS_FRAME_NETWORK_FAIL_STATE; + } + ////////////////////////////////// + // Mode Segment + _frame[MKS_FRAME_DATA_OFFSET + 7] = MKS_FRAME_NETWORK_STA_MODE; + ////////////////////////////////// + // Wifi_name_len Segment + s = Settings_ESP3D::read_string(ESP_STA_SSID); + _frame[MKS_FRAME_DATA_OFFSET + 8] = s.length(); + dataOffset = MKS_FRAME_DATA_OFFSET + 9; + ////////////////////////////////// + // Wifi_name Segment + strcpy((char *)&_frame[dataOffset], s.c_str()); + dataOffset += s.length(); + ////////////////////////////////// + // Wifi_key_len Segment + s = Settings_ESP3D::read_string(ESP_STA_PASSWORD); + _frame[dataOffset] = s.length(); + dataOffset++; + ////////////////////////////////// + // Wifi_key Segment + strcpy((char *)&_frame[dataOffset], s.c_str()); + dataOffset += s.length(); + } else if (NetConfig::getMode() == ESP_WIFI_AP || + (NetConfig::getMode() == ESP_AP_SETUP)) { + log_esp3d("AP Mode"); + /////////////////////////////////// + // IP Segment + // IP value + IPAddress ip = NetConfig::localIPAddress(); + _frame[MKS_FRAME_DATA_OFFSET] = ip[0]; + _frame[MKS_FRAME_DATA_OFFSET + 1] = ip[1]; + _frame[MKS_FRAME_DATA_OFFSET + 2] = ip[2]; + _frame[MKS_FRAME_DATA_OFFSET + 3] = ip[3]; + ////////////////////////////////// + // State Segment + // Connected state (OK) + _frame[MKS_FRAME_DATA_OFFSET + 6] = MKS_FRAME_NETWORK_OK_STATE; + ////////////////////////////////// + // Mode Segment + _frame[MKS_FRAME_DATA_OFFSET + 7] = MKS_FRAME_NETWORK_AP_MODE; + ////////////////////////////////// + // Wifi_name_len Segment + String s = Settings_ESP3D::read_string(ESP_AP_SSID); + _frame[MKS_FRAME_DATA_OFFSET + 8] = s.length(); + dataOffset = MKS_FRAME_DATA_OFFSET + 9; + ////////////////////////////////// + // Wifi_name Segment + strcpy((char *)&_frame[dataOffset], s.c_str()); + dataOffset += s.length(); + ////////////////////////////////// + // Wifi_key_len Segment + s = Settings_ESP3D::read_string(ESP_AP_PASSWORD); + _frame[dataOffset] = s.length(); + dataOffset++; + ////////////////////////////////// + // Wifi_key Segment + strcpy((char *)&_frame[dataOffset], s.c_str()); + dataOffset += s.length(); + } else { + // not supported + log_esp3d_e("Mode not supported : %d ", NetConfig::getMode()); + return false; } - _frame[MKS_FRAME_DATA_OFFSET + strlen(tmp.c_str())] = '\r'; - _frame[MKS_FRAME_DATA_OFFSET + strlen(tmp.c_str())+1] = '\n'; - _frame[MKS_FRAME_DATA_OFFSET + strlen(tmp.c_str())+2] = MKS_FRAME_TAIL_FLAG; - _frame[MKS_FRAME_DATALEN_OFFSET] = (strlen(tmp.c_str())+2) & 0xff; - _frame[MKS_FRAME_DATALEN_OFFSET+1] = ((strlen(tmp.c_str())+2) >> 8) & 0xff; + ////////////////////////////////// + // Cloud Services port Segment + // 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())); - log_esp3d("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]); - //} + ////////////////////////////////// + // Cloud State Segment + // hard coded as disabled in upstream FW + _frame[dataOffset] = MKS_FRAME_CLOUD_DISABLED_STATE; + dataOffset++; + ////////////////////////////////// + // Cloud host len Segment + // Use ESP3D IP instead + s = NetConfig::localIPAddress().toString(); + _frame[dataOffset] = s.length(); + dataOffset++; + ////////////////////////////////// + // Cloud host Segment + // Use ESP3D IP instead + strcpy((char *)&_frame[dataOffset], s.c_str()); + dataOffset += s.length(); + ////////////////////////////////// + // Cloud host port Segment + // use webserver port instead + _frame[dataOffset] = (HTTP_Server::port()) & 0xff; + dataOffset++; + _frame[dataOffset] = ((HTTP_Server::port()) >> 8) & 0xff; + dataOffset++; + ////////////////////////////////// + // Module id len Segment + // Use hostname instead + _frame[dataOffset] = strlen(_moduleId); + dataOffset++; + ////////////////////////////////// + // Module id Segment + strcpy((char *)&_frame[dataOffset], _moduleId); + dataOffset += strlen(_moduleId); + ////////////////////////////////// + // FW version len Segment + _frame[dataOffset] = strlen(FW_VERSION) + 6; + dataOffset++; + ////////////////////////////////// + // FW version Segment + strcpy((char *)&_frame[dataOffset], "ESP3D_" FW_VERSION); + dataOffset += strlen(FW_VERSION) + 6; + ////////////////////////////////// + // Tail Segment + _frame[dataOffset] = MKS_FRAME_TAIL_FLAG; + ////////////////////////////////// + // Data len Segment + // 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); if (canSendFrame()) { - ESP3DOutput output(ESP_SERIAL_CLIENT); - if (output.write(_frame,strlen(tmp.c_str())+7) == (strlen(tmp.c_str())+7)) { - log_esp3d("Ok"); - sendFrameDone(); - return true; - } - } - log_esp3d("Failed"); - sendFrameDone(); - return false; -} - -bool MKSService::sendNetworkFrame() -{ - - size_t dataOffset = 0; - String s; - static uint32_t lastsend = 0; - if (_uploadMode) { - return false; - } - if ((millis() - lastsend)> NET_FRAME_REFRESH_TIME) { - lastsend = millis(); - log_esp3d("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"); - if(WiFi.status() == WL_CONNECTED) { - /////////////////////////////////// - //IP Segment - //IP value - IPAddress ip = NetConfig::localIPAddress(); - _frame[MKS_FRAME_DATA_OFFSET] = ip[0]; - _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],_frame[MKS_FRAME_DATA_OFFSET + 1],_frame[MKS_FRAME_DATA_OFFSET + 2],_frame[MKS_FRAME_DATA_OFFSET + 3]); - ////////////////////////////////// - //State Segment - //Connected state (OK) - _frame[MKS_FRAME_DATA_OFFSET + 6] = MKS_FRAME_NETWORK_OK_STATE; - } else { - /////////////////////////////////// - //IP Segment - //No need - bytes are already cleared - ////////////////////////////////// - //State Segment - //Connected state (Disconnected) - _frame[MKS_FRAME_DATA_OFFSET + 6] = MKS_FRAME_NETWORK_FAIL_STATE; - } - ////////////////////////////////// - //Mode Segment - _frame[MKS_FRAME_DATA_OFFSET + 7] = MKS_FRAME_NETWORK_STA_MODE; - ////////////////////////////////// - //Wifi_name_len Segment - s = Settings_ESP3D::read_string(ESP_STA_SSID); - _frame[MKS_FRAME_DATA_OFFSET + 8] = s.length(); - dataOffset = MKS_FRAME_DATA_OFFSET + 9; - ////////////////////////////////// - //Wifi_name Segment - strcpy((char *)&_frame[dataOffset], s.c_str()); - dataOffset+=s.length(); - ////////////////////////////////// - //Wifi_key_len Segment - s = Settings_ESP3D::read_string(ESP_STA_PASSWORD); - _frame[dataOffset] = s.length(); - dataOffset++; - ////////////////////////////////// - //Wifi_key Segment - strcpy((char *)&_frame[dataOffset], s.c_str()); - dataOffset+=s.length(); - } else if (NetConfig::getMode() == ESP_WIFI_AP || (NetConfig::getMode() == ESP_AP_SETUP)) { - log_esp3d("AP Mode"); - /////////////////////////////////// - //IP Segment - //IP value - IPAddress ip = NetConfig::localIPAddress(); - _frame[MKS_FRAME_DATA_OFFSET] = ip[0]; - _frame[MKS_FRAME_DATA_OFFSET + 1] = ip[1]; - _frame[MKS_FRAME_DATA_OFFSET + 2] = ip[2]; - _frame[MKS_FRAME_DATA_OFFSET + 3] = ip[3]; - ////////////////////////////////// - //State Segment - //Connected state (OK) - _frame[MKS_FRAME_DATA_OFFSET + 6] = MKS_FRAME_NETWORK_OK_STATE; - ////////////////////////////////// - //Mode Segment - _frame[MKS_FRAME_DATA_OFFSET + 7] = MKS_FRAME_NETWORK_AP_MODE; - ////////////////////////////////// - //Wifi_name_len Segment - String s = Settings_ESP3D::read_string(ESP_AP_SSID); - _frame[MKS_FRAME_DATA_OFFSET + 8] = s.length(); - dataOffset = MKS_FRAME_DATA_OFFSET + 9; - ////////////////////////////////// - //Wifi_name Segment - strcpy((char *)&_frame[dataOffset], s.c_str()); - dataOffset+=s.length(); - ////////////////////////////////// - //Wifi_key_len Segment - s = Settings_ESP3D::read_string(ESP_AP_PASSWORD); - _frame[dataOffset] = s.length(); - dataOffset++; - ////////////////////////////////// - //Wifi_key Segment - strcpy((char *)&_frame[dataOffset], s.c_str()); - dataOffset+=s.length(); - } else { - //not supported - log_esp3d("Mode not supported : %d ", NetConfig::getMode()); - return false; - } - ////////////////////////////////// - //Cloud Services port Segment - //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())); - - ////////////////////////////////// - //Cloud State Segment - //hard coded as disabled in upstream FW - _frame[dataOffset] = MKS_FRAME_CLOUD_DISABLED_STATE; - dataOffset++; - ////////////////////////////////// - //Cloud host len Segment - //Use ESP3D IP instead - s = NetConfig::localIPAddress().toString(); - _frame[dataOffset] = s.length(); - dataOffset++; - ////////////////////////////////// - //Cloud host Segment - //Use ESP3D IP instead - strcpy((char *)&_frame[dataOffset], s.c_str()); - dataOffset+=s.length(); - ////////////////////////////////// - //Cloud host port Segment - //use webserver port instead - _frame[dataOffset] = (HTTP_Server::port()) & 0xff; - dataOffset++; - _frame[dataOffset] = ((HTTP_Server::port())>> 8 ) & 0xff; - dataOffset++; - ////////////////////////////////// - //Module id len Segment - //Use hostname instead - _frame[dataOffset] = strlen(_moduleId); - dataOffset++; - ////////////////////////////////// - //Module id Segment - strcpy((char *)&_frame[dataOffset], _moduleId); - dataOffset+=strlen(_moduleId); - ////////////////////////////////// - //FW version len Segment - _frame[dataOffset] = strlen(FW_VERSION)+6; - dataOffset++; - ////////////////////////////////// - //FW version Segment - strcpy((char *)&_frame[dataOffset], "ESP3D_" FW_VERSION); - dataOffset+=strlen(FW_VERSION)+6; - ////////////////////////////////// - //Tail Segment - _frame[dataOffset] = MKS_FRAME_TAIL_FLAG; - - ////////////////////////////////// - //Data len Segment - //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); - if (canSendFrame()) { - ESP3DOutput output(ESP_SERIAL_CLIENT); - if (output.write(_frame,dataOffset+1) == (dataOffset+1)) { - log_esp3d("Ok"); - sendFrameDone(); - return true; - } - } + ESP3DOutput output(ESP_SERIAL_CLIENT); + if (output.write(_frame, dataOffset + 1) == (dataOffset + 1)) { + log_esp3d("Ok"); sendFrameDone(); - log_esp3d("Failed"); + return true; + } } + sendFrameDone(); + log_esp3d_e("Failed"); + } - return false; + return false; } -void MKSService::clearFrame(uint start) -{ - memset(&_frame[start], 0, sizeof(_frame)-start); +void MKSService::clearFrame(uint start) { + memset(&_frame[start], 0, sizeof(_frame) - start); } -void MKSService::handle() -{ - if (_started ) { - sendNetworkFrame(); - } - //network frame every 10s -} -void MKSService::end() -{ - _started = false; +void MKSService::handle() { + if (_started) { + sendNetworkFrame(); + } + // network frame every 10s } +void MKSService::end() { _started = false; } - - -#endif //COMMUNICATION_PROTOCOL == MKS_SERIAL +#endif // COMMUNICATION_PROTOCOL == MKS_SERIAL diff --git a/esp3d/src/modules/network/netconfig.cpp b/esp3d/src/modules/network/netconfig.cpp index ffba3131..b10a271a 100644 --- a/esp3d/src/modules/network/netconfig.cpp +++ b/esp3d/src/modules/network/netconfig.cpp @@ -19,30 +19,30 @@ */ #include "../../include/esp3d_config.h" -#if defined (WIFI_FEATURE) || defined (ETH_FEATURE) || defined (BLUETOOTH_FEATURE) +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) || defined(BLUETOOTH_FEATURE) #ifdef ARDUINO_ARCH_ESP32 #define WIFI_EVENT_STAMODE_CONNECTED ARDUINO_EVENT_WIFI_STA_CONNECTED #define WIFI_EVENT_STAMODE_DISCONNECTED ARDUINO_EVENT_WIFI_STA_DISCONNECTED #define WIFI_EVENT_STAMODE_GOT_IP ARDUINO_EVENT_WIFI_STA_GOT_IP #define WIFI_EVENT_SOFTAPMODE_STACONNECTED ARDUINO_EVENT_WIFI_AP_STACONNECTED #define RADIO_OFF_MSG "Radio Off" -#endif //ARDUINO_ARCH_ESP32 +#endif // ARDUINO_ARCH_ESP32 #ifdef ARDUINO_ARCH_ESP8266 #define RADIO_OFF_MSG "WiFi Off" -#endif //ARDUINO_ARCH_ESP8266 +#endif // ARDUINO_ARCH_ESP8266 #include "netconfig.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 -#include "netservices.h" +#endif // BLUETOOTH_FEATURE #include "../../core/esp3doutput.h" #include "../../core/settings_esp3d.h" +#include "netservices.h" String NetConfig::_hostname = ""; bool NetConfig::_needReconnect2AP = false; @@ -50,428 +50,407 @@ bool NetConfig::_events_registered = false; bool NetConfig::_started = false; uint8_t NetConfig::_mode = ESP_NO_NETWORK; -//just simple helper to convert mac address to string -char * NetConfig::mac2str (uint8_t mac [8]) -{ - static char macstr [18]; - if (0 > sprintf (macstr, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]) ) { - strcpy (macstr, "00:00:00:00:00:00"); - } - return macstr; +// just simple helper to convert mac address to string +char* NetConfig::mac2str(uint8_t mac[8]) { + static char macstr[18]; + if (0 > sprintf(macstr, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], + mac[2], mac[3], mac[4], mac[5])) { + strcpy(macstr, "00:00:00:00:00:00"); + } + return macstr; } - /** * Helper to convert IP string to int */ -uint32_t NetConfig::IP_int_from_string(const char * s) -{ - uint32_t ip_int = 0; - IPAddress ipaddr; - if (ipaddr.fromString(s)) { - ip_int = ipaddr; - } - return ip_int; +uint32_t NetConfig::IP_int_from_string(const char* s) { + uint32_t ip_int = 0; + IPAddress ipaddr; + if (ipaddr.fromString(s)) { + ip_int = ipaddr; + } + return ip_int; } /** * Helper to convert int to IP string */ -String NetConfig::IP_string_from_int(uint32_t ip_int) -{ - IPAddress ipaddr(ip_int); - return ipaddr.toString(); +String NetConfig::IP_string_from_int(uint32_t ip_int) { + IPAddress ipaddr(ip_int); + return ipaddr.toString(); } /** * Check if Hostname string is valid */ -bool NetConfig::isHostnameValid (const char * hostname) -{ - //limited size - char c; - if (strlen (hostname) > MAX_HOSTNAME_LENGTH || strlen (hostname) < MIN_HOSTNAME_LENGTH) { - return false; +bool NetConfig::isHostnameValid(const char* hostname) { + // limited size + char c; + if (strlen(hostname) > MAX_HOSTNAME_LENGTH || + strlen(hostname) < MIN_HOSTNAME_LENGTH) { + return false; + } + // only letter and digit + for (uint i = 0; i < strlen(hostname); i++) { + c = hostname[i]; + if (!(isdigit(c) || isalpha(c) || c == '-')) { + return false; } - //only letter and digit - for (uint i = 0; i < strlen (hostname); i++) { - c = hostname[i]; - if (! (isdigit (c) || isalpha (c) || c == '-') ) { - return false; - } - if (c == ' ') { - return false; - } + if (c == ' ') { + return false; } - return true; + } + return true; } - /** * Get IP Integer what ever is enabled */ -IPAddress NetConfig::localIPAddress() -{ - IPAddress current_ip = IPAddress(0,0,0,0); -#if defined( WIFI_FEATURE) - if (WiFi.getMode() == WIFI_STA) { - current_ip = WiFi.localIP(); - } else if (WiFi.getMode() == WIFI_AP) { - current_ip = WiFi.softAPIP(); - } -#endif //WIFI_FEATURE -#if defined (ETH_FEATURE) - if (EthConfig::started()) { - current_ip = ETH.localIP(); - } -#endif //ETH_FEATURE +IPAddress NetConfig::localIPAddress() { + IPAddress current_ip = IPAddress(0, 0, 0, 0); +#if defined(WIFI_FEATURE) + if (WiFi.getMode() == WIFI_STA) { + current_ip = WiFi.localIP(); + } else if (WiFi.getMode() == WIFI_AP) { + current_ip = WiFi.softAPIP(); + } +#endif // WIFI_FEATURE +#if defined(ETH_FEATURE) + if (EthConfig::started()) { + current_ip = ETH.localIP(); + } +#endif // ETH_FEATURE - return current_ip; + return current_ip; } /** * Get IP string what ever is enabled */ -String NetConfig::localIP() -{ - static String currentIP = ""; -#if defined( WIFI_FEATURE) - if (WiFi.getMode() == WIFI_STA) { - currentIP = WiFi.localIP().toString(); - } else if (WiFi.getMode() == WIFI_AP) { - currentIP = WiFi.softAPIP().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; +String NetConfig::localIP() { + static String currentIP = ""; +#if defined(WIFI_FEATURE) + if (WiFi.getMode() == WIFI_STA) { + currentIP = WiFi.localIP().toString(); + } else if (WiFi.getMode() == WIFI_AP) { + currentIP = WiFi.softAPIP().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; } /** * Check if IP string is valid */ -bool NetConfig::isValidIP(const char * string) -{ - IPAddress ip; - return ip.fromString(string); +bool NetConfig::isValidIP(const char* string) { + IPAddress ip; + return ip.fromString(string); } - -//wifi event -void NetConfig::onWiFiEvent(WiFiEvent_t event) -{ - ESP3DOutput output(ESP_ALL_CLIENTS); - switch (event) { +// wifi event +void NetConfig::onWiFiEvent(WiFiEvent_t event) { + ESP3DOutput output(ESP_ALL_CLIENTS); + switch (event) { case WIFI_EVENT_STAMODE_CONNECTED: - _needReconnect2AP = false; - break; + _needReconnect2AP = false; + break; case WIFI_EVENT_STAMODE_DISCONNECTED: { - if(_started) { - output.printMSG ("Disconnected"); - //_needReconnect2AP = true; - } - } - break; + if (_started) { + output.printMSG("Disconnected"); + //_needReconnect2AP = true; + } + } break; case WIFI_EVENT_STAMODE_GOT_IP: { #if COMMUNICATION_PROTOCOL != MKS_SERIAL - output.printMSG (WiFi.localIP().toString().c_str()); -#endif //#if COMMUNICATION_PROTOCOL == MKS_SERIAL - } - break; + output.printMSG(WiFi.localIP().toString().c_str()); +#endif // #if COMMUNICATION_PROTOCOL == MKS_SERIAL + } break; case WIFI_EVENT_SOFTAPMODE_STACONNECTED: { - output.printMSG ("New client"); - } - break; + output.printMSG("New client"); + } break; #ifdef ARDUINO_ARCH_ESP32 case ARDUINO_EVENT_WIFI_STA_LOST_IP: - if(_started) { - _needReconnect2AP = true; - } - break; + if (_started) { + _needReconnect2AP = true; + } + break; #ifdef ETH_FEATURE case ARDUINO_EVENT_ETH_START: { - EthConfig::setConnected(false); - if (Settings_ESP3D::isVerboseBoot()) { - output.printMSG ("Checking connection"); - } - } - break; + EthConfig::setConnected(false); + if (Settings_ESP3D::isVerboseBoot()) { + output.printMSG("Checking connection"); + } + } break; case ARDUINO_EVENT_ETH_CONNECTED: { - output.printMSG ("Cable connected"); - EthConfig::setConnected(true); - } - break; + output.printMSG("Cable connected"); + EthConfig::setConnected(true); + } break; case ARDUINO_EVENT_ETH_DISCONNECTED: { - output.printMSG ("Cable disconnected"); - EthConfig::setConnected(false); - } - break; + output.printMSG("Cable disconnected"); + EthConfig::setConnected(false); + } break; case ARDUINO_EVENT_ETH_GOT_IP: - output.printMSG (ETH.localIP().toString().c_str()); - EthConfig::setConnected(true); - break; + output.printMSG(ETH.localIP().toString().c_str()); + EthConfig::setConnected(true); + break; case ARDUINO_EVENT_ETH_STOP: - EthConfig::setConnected(false); - break; -#endif //ETH_FEATURE -#endif //ARDUINO_ARCH_ESP32 + EthConfig::setConnected(false); + break; +#endif // ETH_FEATURE +#endif // ARDUINO_ARCH_ESP32 default: - break; - } + break; + } } -void NetConfig::setMode(uint8_t mode) -{ - _mode=mode; -} +void NetConfig::setMode(uint8_t mode) { _mode = mode; } -uint8_t NetConfig::getMode() -{ - return _mode; -} +uint8_t NetConfig::getMode() { return _mode; } /** * begin WiFi setup */ -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"); - if (espMode != ESP_NO_NETWORK) { - if (Settings_ESP3D::isVerboseBoot()) { - output.printMSG("Starting Network"); - } +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"); + if (espMode != ESP_NO_NETWORK) { + if (Settings_ESP3D::isVerboseBoot()) { + output.printMSG("Starting Network"); } - //setup events - if(!_events_registered) { + } + // setup events + if (!_events_registered) { #ifdef ARDUINO_ARCH_ESP8266 #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - WiFi.onEvent(NetConfig::onWiFiEvent, WIFI_EVENT_ANY); + WiFi.onEvent(NetConfig::onWiFiEvent, WIFI_EVENT_ANY); #pragma GCC diagnostic pop #endif #ifdef ARDUINO_ARCH_ESP32 - WiFi.onEvent(NetConfig::onWiFiEvent); + WiFi.onEvent(NetConfig::onWiFiEvent); #endif - _events_registered = true; - } - //Get hostname - _hostname = Settings_ESP3D::read_string(ESP_HOSTNAME); - _mode = espMode; - if (espMode == ESP_NO_NETWORK) { - output.printMSG("Disable Network"); - 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(); - } - return true; - } -#if defined (WIFI_FEATURE) - if ((espMode == ESP_AP_SETUP) || (espMode == ESP_WIFI_AP) || (espMode == ESP_WIFI_STA)) { - output.printMSG("Setup wifi"); - res = WiFiConfig::begin(espMode); - } -#endif //WIFI_FEATURE -#if defined (ETH_FEATURE) - //if ((espMode == ESP_ETH_STA) || (espMode == ESP_ETH_SRV)) { - if ((espMode == ESP_ETH_STA)) { - WiFi.mode(WIFI_OFF); - res = EthConfig::begin(espMode); + _events_registered = true; + } + // Get hostname + _hostname = Settings_ESP3D::read_string(ESP_HOSTNAME); + _mode = espMode; + if (espMode == ESP_NO_NETWORK) { + output.printMSG("Disable Network"); + 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(); } + return true; + } +#if defined(WIFI_FEATURE) + if ((espMode == ESP_AP_SETUP) || (espMode == ESP_WIFI_AP) || + (espMode == ESP_WIFI_STA)) { + output.printMSG("Setup wifi"); + res = WiFiConfig::begin(espMode); + } +#endif // WIFI_FEATURE +#if defined(ETH_FEATURE) + // if ((espMode == ESP_ETH_STA) || (espMode == ESP_ETH_SRV)) { + if ((espMode == ESP_ETH_STA)) { + WiFi.mode(WIFI_OFF); + res = EthConfig::begin(espMode); + } #else - //if Eth and no Eth enabled let's go to no network - if (espMode == ESP_ETH_STA) { - espMode = ESP_NO_NETWORK; - } -#endif //ETH_FEATURE + // if Eth and no Eth enabled let's go to no network + if (espMode == ESP_ETH_STA) { + espMode = ESP_NO_NETWORK; + } +#endif // ETH_FEATURE -#if defined (BLUETOOTH_FEATURE) - if (espMode == ESP_BT) { - WiFi.mode(WIFI_OFF); - String msg = "BT On"; - ESP3DOutput::toScreen(ESP_OUTPUT_STATUS, msg.c_str()); - res = bt_service.begin(); - } +#if defined(BLUETOOTH_FEATURE) + if (espMode == ESP_BT) { + WiFi.mode(WIFI_OFF); + String msg = "BT On"; + ESP3DOutput::toScreen(ESP_OUTPUT_STATUS, msg.c_str()); + res = bt_service.begin(); + } #else - //if BT and no BT enabled let's go to no network - if (espMode == ESP_BT) { - espMode = ESP_NO_NETWORK; - } -#endif //BLUETOOTH_FEATURE + // if BT and no BT enabled let's go to no network + if (espMode == ESP_BT) { + espMode = ESP_NO_NETWORK; + } +#endif // BLUETOOTH_FEATURE - if (espMode == ESP_NO_NETWORK) { - output.printMSG("Disable Network"); - 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(); - } - return true; + if (espMode == ESP_NO_NETWORK) { + output.printMSG("Disable Network"); + 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 network is up, let's start services - if (res) { - _started = true; - bool start_services = false; -#if defined (ETH_FEATURE) - if (EthConfig::started()) { - start_services = true; - } -#endif //ETH_FEATURE -#if defined (WIFI_FEATURE) - if (WiFiConfig::started()) { - start_services = true; - } -#endif //WIFI_FEATURE - if (start_services) { - log_esp3d("Starting service"); - res = NetServices::begin(); - } + return true; + } + // if network is up, let's start services + if (res) { + _started = true; + bool start_services = false; +#if defined(ETH_FEATURE) + if (EthConfig::started()) { + start_services = true; } - //work around as every services seems reset the AP name +#endif // ETH_FEATURE +#if defined(WIFI_FEATURE) + if (WiFiConfig::started()) { + start_services = true; + } +#endif // WIFI_FEATURE + if (start_services) { + log_esp3d("Starting service"); + res = NetServices::begin(); + } + } + // work around as every services seems reset the AP name #ifdef ARDUINO_ARCH_ESP32 -#if defined (WIFI_FEATURE) - if (WiFi.getMode() == WIFI_AP) { - WiFi.softAPsetHostname(_hostname.c_str()); - } -#endif //WIFI_FEATURE -#endif //ARDUINO_ARCH_ESP32 - DEBUG_ESP3D_NETWORK_INIT - if (res) { - log_esp3d("Network config started"); - } else { - end(); - log_esp3d("Network config failed"); - } - ESP3DOutput::toScreen(ESP_OUTPUT_IP_ADDRESS,nullptr); - return res; +#if defined(WIFI_FEATURE) + if (WiFi.getMode() == WIFI_AP) { + WiFi.softAPsetHostname(_hostname.c_str()); + } +#endif // WIFI_FEATURE +#endif // ARDUINO_ARCH_ESP32 + LOG_ESP3D_NETWORK_INIT + if (res) { + log_esp3d("Network config started"); + + } else { + end(); + log_esp3d_e("Network config failed"); + } + ESP3DOutput::toScreen(ESP_OUTPUT_IP_ADDRESS, nullptr); + return res; } /** * End WiFi */ -void NetConfig::end() -{ - NetServices::end(); - DEBUG_ESP3D_NETWORK_END - _mode = ESP_NO_NETWORK; -#if defined (WIFI_FEATURE) - WiFiConfig::end(); - _needReconnect2AP=false; +void NetConfig::end() { + NetServices::end(); + LOG_ESP3D_NETWORK_END + _mode = ESP_NO_NETWORK; +#if defined(WIFI_FEATURE) + WiFiConfig::end(); + _needReconnect2AP = false; #else - WiFi.mode(WIFI_OFF); -#endif //WIFI_FEATURE + WiFi.mode(WIFI_OFF); +#endif // WIFI_FEATURE -#if defined (ETH_FEATURE) - EthConfig::end(); -#endif //ETH_FEATURE -#if defined (BLUETOOTH_FEATURE) - bt_service.end(); -#endif //BLUETOOTH_FEATURE - _started = false; +#if defined(ETH_FEATURE) + EthConfig::end(); +#endif // ETH_FEATURE +#if defined(BLUETOOTH_FEATURE) + bt_service.end(); +#endif // BLUETOOTH_FEATURE + _started = false; } -const char* NetConfig::hostname(bool fromsettings) -{ - if (fromsettings) { - _hostname = Settings_ESP3D::read_string(ESP_HOSTNAME); - return _hostname.c_str(); - } -#if defined (WIFI_FEATURE) - if(WiFi.getMode()!= WIFI_OFF) { - _hostname = WiFiConfig::hostname(); - return _hostname.c_str(); - } -#endif //WIFI_FEATURE -#if defined (ETH_FEATURE) - if(EthConfig::started()) { - return ETH.getHostname(); - } -#endif //ETH_FEATURE - -#if defined (BLUETOOTH_FEATURE) - if(bt_service.started()) { - return bt_service.hostname(); - } -#endif //BLUETOOTH_FEATURE +const char* NetConfig::hostname(bool fromsettings) { + if (fromsettings) { + _hostname = Settings_ESP3D::read_string(ESP_HOSTNAME); return _hostname.c_str(); + } +#if defined(WIFI_FEATURE) + if (WiFi.getMode() != WIFI_OFF) { + _hostname = WiFiConfig::hostname(); + return _hostname.c_str(); + } +#endif // WIFI_FEATURE +#if defined(ETH_FEATURE) + if (EthConfig::started()) { + return ETH.getHostname(); + } +#endif // ETH_FEATURE + +#if defined(BLUETOOTH_FEATURE) + if (bt_service.started()) { + return bt_service.hostname(); + } +#endif // BLUETOOTH_FEATURE + return _hostname.c_str(); } /** * Handle not critical actions that must be done in sync environement */ -void NetConfig::handle() -{ - if (_started) { -#if defined (WIFI_FEATURE) - if(_needReconnect2AP) { - - if(WiFi.getMode()!= WIFI_OFF) { - begin(); - } - } - WiFiConfig::handle(); -#endif //WIFI_FEATURE -#if defined (ETH_FEATURE) - EthConfig::handle(); -#endif //ETH_FEATURE -#if defined (BLUETOOTH_FEATURE) - bt_service.handle(); -#endif //BLUETOOTH_FEATURE - NetServices::handle(); - //Debug - DEBUG_ESP3D_NETWORK_HANDLE +void NetConfig::handle() { + if (_started) { +#if defined(WIFI_FEATURE) + if (_needReconnect2AP) { + if (WiFi.getMode() != WIFI_OFF) { + begin(); + } } + WiFiConfig::handle(); +#endif // WIFI_FEATURE +#if defined(ETH_FEATURE) + EthConfig::handle(); +#endif // ETH_FEATURE +#if defined(BLUETOOTH_FEATURE) + bt_service.handle(); +#endif // BLUETOOTH_FEATURE + NetServices::handle(); + // Debug + LOG_ESP3D_NETWORK_HANDLE + } } -bool NetConfig::isIPModeDHCP (uint8_t mode) -{ - bool started = false; +bool NetConfig::isIPModeDHCP(uint8_t mode) { + bool started = false; #ifdef ARDUINO_ARCH_ESP32 - tcpip_adapter_dhcp_status_t dhcp_status; - tcpip_adapter_dhcpc_get_status ((mode == ESP_WIFI_STA)?TCPIP_ADAPTER_IF_STA:(mode == ESP_WIFI_AP)?TCPIP_ADAPTER_IF_AP:TCPIP_ADAPTER_IF_ETH, &dhcp_status); - started = (dhcp_status == TCPIP_ADAPTER_DHCP_STARTED); -#endif //ARDUINO_ARCH_ESP32 + tcpip_adapter_dhcp_status_t dhcp_status; + tcpip_adapter_dhcpc_get_status((mode == ESP_WIFI_STA) ? TCPIP_ADAPTER_IF_STA + : (mode == ESP_WIFI_AP) ? TCPIP_ADAPTER_IF_AP + : TCPIP_ADAPTER_IF_ETH, + &dhcp_status); + started = (dhcp_status == TCPIP_ADAPTER_DHCP_STARTED); +#endif // ARDUINO_ARCH_ESP32 #ifdef ARDUINO_ARCH_ESP8266 - (void)mode; - started = (wifi_station_dhcpc_status() == DHCP_STARTED); -#endif //ARDUINO_ARCH_ESP8266 - return started; + (void)mode; + started = (wifi_station_dhcpc_status() == DHCP_STARTED); +#endif // ARDUINO_ARCH_ESP8266 + return started; } -bool NetConfig::isDHCPServer (uint8_t mode) -{ - bool itis = false; +bool NetConfig::isDHCPServer(uint8_t mode) { + bool itis = false; #ifdef ARDUINO_ARCH_ESP32 - tcpip_adapter_dhcp_status_t dhcp_status; - tcpip_adapter_dhcps_get_status ((mode == ESP_WIFI_STA)?TCPIP_ADAPTER_IF_STA:(mode == ESP_WIFI_AP)?TCPIP_ADAPTER_IF_AP:TCPIP_ADAPTER_IF_ETH, &dhcp_status); - itis = (dhcp_status == TCPIP_ADAPTER_DHCP_STARTED); -#endif //ARDUINO_ARCH_ESP32 + tcpip_adapter_dhcp_status_t dhcp_status; + tcpip_adapter_dhcps_get_status((mode == ESP_WIFI_STA) ? TCPIP_ADAPTER_IF_STA + : (mode == ESP_WIFI_AP) ? TCPIP_ADAPTER_IF_AP + : TCPIP_ADAPTER_IF_ETH, + &dhcp_status); + itis = (dhcp_status == TCPIP_ADAPTER_DHCP_STARTED); +#endif // ARDUINO_ARCH_ESP32 #ifdef ARDUINO_ARCH_ESP8266 - (void)mode; - itis = (wifi_softap_dhcps_status() == DHCP_STARTED); -#endif //ARDUINO_ARCH_ESP8266 - return itis; + (void)mode; + itis = (wifi_softap_dhcps_status() == DHCP_STARTED); +#endif // ARDUINO_ARCH_ESP8266 + return itis; } -#endif // WIFI_FEATURE || ETH_FEATURE - +#endif // WIFI_FEATURE || ETH_FEATURE diff --git a/esp3d/src/modules/notifications/notifications_service.cpp b/esp3d/src/modules/notifications/notifications_service.cpp index f7ffe34b..c2a24978 100644 --- a/esp3d/src/modules/notifications/notifications_service.cpp +++ b/esp3d/src/modules/notifications/notifications_service.cpp @@ -17,613 +17,630 @@ License along with This code; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -//Inspired by following sources +// Inspired by following sources //* Line : -// - https://github.com/TridentTD/TridentTD_LineNotify -// - https://notify-bot.line.me/doc/en/ +// - https://github.com/TridentTD/TridentTD_LineNotify +// - https://notify-bot.line.me/doc/en/ //* Pushover: -// - https://github.com/ArduinoHannover/Pushover -// - https://pushover.net/api +// - https://github.com/ArduinoHannover/Pushover +// - https://pushover.net/api //* Email: -// - https://github.com/CosmicBoris/ESP8266SMTP -// - https://www.electronicshub.org/send-an-email-using-esp8266/ +// - https://github.com/CosmicBoris/ESP8266SMTP +// - https://www.electronicshub.org/send-an-email-using-esp8266/ //* Telegram -// - https://medium.com/@xabaras/sending-a-message-to-a-telegram-channel-the-easy-way-eb0a0b32968 +// - +// https://medium.com/@xabaras/sending-a-message-to-a-telegram-channel-the-easy-way-eb0a0b32968 #include "../../include/esp3d_config.h" #ifdef NOTIFICATION_FEATURE -#include "notifications_service.h" -#include "../../core/settings_esp3d.h" -#include "../../core/esp3doutput.h" -#include "../network/netconfig.h" #include -#if defined( ARDUINO_ARCH_ESP8266) -#include +#include "../../core/esp3doutput.h" +#include "../../core/settings_esp3d.h" +#include "../network/netconfig.h" +#include "notifications_service.h" + +#if defined(ARDUINO_ARCH_ESP8266) #include +#include #include -#endif //ARDUINO_ARCH_ESP8266 + +#endif // ARDUINO_ARCH_ESP8266 #if defined(ARDUINO_ARCH_ESP32) -#include #include +#include + extern "C" { #include "libb64/cdecode.h" } -#endif //ARDUINO_ARCH_ESP32 -#if defined (HTTP_FEATURE) || defined(WS_DATA_FEATURE) +#endif // ARDUINO_ARCH_ESP32 +#if defined(HTTP_FEATURE) || defined(WS_DATA_FEATURE) #include "../websocket/websocket_server.h" -#endif //HTTP_FEATURE || WS_DATA_FEATURE -#if defined (DISPLAY_DEVICE) +#endif // HTTP_FEATURE || WS_DATA_FEATURE +#if defined(DISPLAY_DEVICE) #include "../display/display.h" -#endif //DISPLAY_DEVICE +#endif // DISPLAY_DEVICE #include #define PUSHOVERTIMEOUT 5000 #define PUSHOVERSERVER "api.pushover.net" -#define PUSHOVERPORT 443 +#define PUSHOVERPORT 443 #define LINETIMEOUT 5000 #define LINESERVER "notify-api.line.me" -#define LINEPORT 443 +#define LINEPORT 443 #define TELEGRAMTIMEOUT 5000 #define TELEGRAMSERVER "api.telegram.org" -#define TELEGRAMPORT 443 +#define TELEGRAMPORT 443 #define IFTTTTIMEOUT 5000 #define IFTTTSERVER "maker.ifttt.com" -#define IFTTTPORT 443 +#define IFTTTPORT 443 #define EMAILTIMEOUT 5000 NotificationsService notificationsservice; #if defined(ARDUINO_ARCH_ESP8266) -void NotificationsService::BearSSLSetup(WiFiClientSecure & Notificationclient) -{ - if (Notificationclient.probeMaxFragmentLength(_serveraddress.c_str(), _port, BEARSSL_MFLN_SIZE)) { - log_esp3d("Handshake success"); - Notificationclient.setBufferSizes(BEARSSL_MFLN_SIZE, 512); - } else { - log_esp3d("Handshake failed"); - Notificationclient.setBufferSizes(BEARSSL_MFLN_SIZE_FALLBACK, 512); - } +void NotificationsService::BearSSLSetup(WiFiClientSecure& Notificationclient) { + if (Notificationclient.probeMaxFragmentLength(_serveraddress.c_str(), _port, + BEARSSL_MFLN_SIZE)) { + log_esp3d("Handshake success"); + Notificationclient.setBufferSizes(BEARSSL_MFLN_SIZE, 512); + } else { + log_esp3d_e("Handshake failed"); + Notificationclient.setBufferSizes(BEARSSL_MFLN_SIZE_FALLBACK, 512); + } } -#endif //ARDUINO_ARCH_ESP8266 +#endif // ARDUINO_ARCH_ESP8266 -//TODO: put error in variable to allow better error handling -bool NotificationsService::Wait4Answer(WiFiClientSecure & client, const char * linetrigger, const char * expected_answer, uint32_t timeout) -{ - if(client.connected()) { - String answer; - uint32_t starttimeout = millis(); - while (client.connected() && ((millis() -starttimeout) < timeout)) { - answer = client.readStringUntil('\n'); - log_esp3d("Answer: %s", answer.c_str()); - if ((answer.indexOf(linetrigger) != -1) || (strlen(linetrigger) == 0)) { - break; - } - Hal::wait(10); - } - if (strlen(expected_answer) == 0) { - log_esp3d("Answer ignored as requested"); - return true; - } - if(answer.indexOf(expected_answer) == -1) { - log_esp3d("Did not got answer!"); - return false; - } else { - log_esp3d("Got expected answer"); - return true; - } +// TODO: put error in variable to allow better error handling +bool NotificationsService::Wait4Answer(WiFiClientSecure& client, + const char* linetrigger, + const char* expected_answer, + uint32_t timeout) { + if (client.connected()) { + String answer; + uint32_t starttimeout = millis(); + while (client.connected() && ((millis() - starttimeout) < timeout)) { + answer = client.readStringUntil('\n'); + log_esp3d("Answer: %s", answer.c_str()); + if ((answer.indexOf(linetrigger) != -1) || (strlen(linetrigger) == 0)) { + break; + } + Hal::wait(10); } - log_esp3d("Failed to send message"); + if (strlen(expected_answer) == 0) { + log_esp3d("Answer ignored as requested"); + return true; + } + if (answer.indexOf(expected_answer) == -1) { + log_esp3d("Did not got answer!"); + return false; + } else { + log_esp3d("Got expected answer"); + return true; + } + } + log_esp3d_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"); return false; + } + String msgtpl = msg; + // check if has variable to change + if (msgtpl.indexOf("%") != -1) { + msgtpl.replace("%ESP_IP%", WiFi.localIP().toString().c_str()); + msgtpl.replace("%ESP_NAME%", NetConfig::hostname()); + } + if (!sendMSG(ESP_NOTIFICATION_TITLE, msgtpl.c_str())) { + log_esp3d_e("Auto notification failed"); + return false; + } else { + log_esp3d("Auto notification sent"); + return true; + } } -bool NotificationsService::sendAutoNotification(const char * msg) -{ - if (!(NetConfig::started()) || (NetConfig::getMode() != ESP_WIFI_STA)|| (!_started) || (!_autonotification)) { - log_esp3d("Auto notification rejected"); - return false; - } - String msgtpl = msg; - //check if has variable to change - if (msgtpl.indexOf("%") != -1) { - msgtpl.replace("%ESP_IP%", WiFi.localIP().toString().c_str()); - msgtpl.replace("%ESP_NAME%", NetConfig::hostname()); - } - if (!sendMSG(ESP_NOTIFICATION_TITLE, msgtpl.c_str())) { - log_esp3d("Auto notification failed"); - return false; - } else { - log_esp3d("Auto notification sent"); - return true; - } +NotificationsService::NotificationsService() { + _started = false; + _notificationType = 0; + _token1 = ""; + _token1 = ""; + _settings = ""; } +NotificationsService::~NotificationsService() { end(); } -NotificationsService::NotificationsService() -{ - _started = false; - _notificationType = 0; - _token1 = ""; - _token1 = ""; - _settings = ""; -} -NotificationsService::~NotificationsService() -{ - end(); -} +bool NotificationsService::started() { return _started; } -bool NotificationsService::started() -{ - return _started; -} - -const char * NotificationsService::getTypeString() -{ - switch(_notificationType) { +const char* NotificationsService::getTypeString() { + switch (_notificationType) { case ESP_PUSHOVER_NOTIFICATION: - return "pushover"; + return "pushover"; case ESP_EMAIL_NOTIFICATION: - return "email"; + return "email"; case ESP_LINE_NOTIFICATION: - return "line"; + return "line"; case ESP_TELEGRAM_NOTIFICATION: - return "telegram"; + return "telegram"; case ESP_IFTTT_NOTIFICATION: - return "IFTTT"; + return "IFTTT"; default: - break; - } - return "none"; + break; + } + return "none"; } -bool NotificationsService::sendMSG(const char * title, const char * message) -{ - if(!_started) { - log_esp3d("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:"; +bool NotificationsService::sendMSG(const char* title, const char* message) { + if (!_started) { + log_esp3d_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 + 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); - break; - case ESP_EMAIL_NOTIFICATION: - return sendEmailMSG(title,message); - break; - case ESP_LINE_NOTIFICATION : - return sendLineMSG(title,message); - break; - case ESP_TELEGRAM_NOTIFICATION : - return sendTelegramMSG(title,message); - break; - case ESP_IFTTT_NOTIFICATION : - return sendIFTTTMSG(title,message); - break; - default: - break; - } + esp3d_display.setStatus(message); +#endif // DISPLAY_DEVICE + switch (_notificationType) { + case ESP_PUSHOVER_NOTIFICATION: + return sendPushoverMSG(title, message); + break; + case ESP_EMAIL_NOTIFICATION: + return sendEmailMSG(title, message); + break; + case ESP_LINE_NOTIFICATION: + return sendLineMSG(title, message); + break; + case ESP_TELEGRAM_NOTIFICATION: + return sendTelegramMSG(title, message); + break; + case ESP_IFTTT_NOTIFICATION: + return sendIFTTTMSG(title, message); + break; + default: + break; } + } + return true; +} +// Messages are currently limited to 1024 4-byte UTF-8 characters +// but we do not do any check +// TODO: put error in variable to allow better error handling +bool NotificationsService::sendPushoverMSG(const char* title, + const char* message) { + String data; + String postcmd; + bool res; +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" + WiFiClientSecure Notificationclient; +#pragma GCC diagnostic pop + Notificationclient.setInsecure(); +#if defined(ARDUINO_ARCH_ESP8266) + BearSSLSetup(Notificationclient); +#endif // ARDUINO_ARCH_ESP8266 + if (!Notificationclient.connect(_serveraddress.c_str(), _port)) { + log_esp3d_e("Error connecting server %s:%d", _serveraddress.c_str(), + _port); + return false; + } + // build data for post + data = "user="; + data += _token1; + data += "&token="; + data += _token2; + data += "&title="; + data += title; + data += "&message="; + data += message; + data += "&device="; + data += NetConfig::hostname(); + // build post query + postcmd = + "POST /1/messages.json HTTP/1.1\r\nHost: api.pushover.net\r\nConnection: " + "close\r\nCache-Control: no-cache\r\nUser-Agent: ESP3D\r\nAccept: " + "text/html,application/xhtml+xml,application/xml;q=0.9,*/" + "*;q=0.8\r\nContent-Length: "; + postcmd += data.length(); + postcmd += "\r\n\r\n"; + postcmd += data; + log_esp3d("Query: %s", postcmd.c_str()); + // send query + Notificationclient.print(postcmd); + res = Wait4Answer(Notificationclient, "{", "\"status\":1", PUSHOVERTIMEOUT); + Notificationclient.stop(); + return res; +} + +// Telegram +// TODO: put error in variable to allow better error handling +bool NotificationsService::sendTelegramMSG(const char* title, + const char* message) { + String data; + String postcmd; + bool res; +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" + WiFiClientSecure Notificationclient; +#pragma GCC diagnostic pop + Notificationclient.setInsecure(); +#if defined(ARDUINO_ARCH_ESP8266) + BearSSLSetup(Notificationclient); +#endif // ARDUINO_ARCH_ESP8266 + if (!Notificationclient.connect(_serveraddress.c_str(), _port)) { + log_esp3d("Error connecting server %s:%d", _serveraddress.c_str(), _port); + return false; + } + (void)title; + // build url for get + data = "chat_id="; + data += _token2; + data += "&text="; + data += message; + + // build post query + postcmd = "POST /bot"; + postcmd += _token1; + postcmd += + "/sendMessage HTTP/1.1\r\nHost: api.telegram.org\r\nConnection: " + "close\r\nContent-Type: " + "application/x-www-form-urlencoded\r\nCache-Control: " + "no-cache\r\nUser-Agent: ESP3D\r\nAccept: " + "text/html,application/xhtml+xml,application/xml;q=0.9,*/" + "*;q=0.8\r\nContent-Length: "; + postcmd += data.length(); + postcmd += "\r\n\r\n"; + postcmd += data; + log_esp3d("Query: %s", postcmd.c_str()); + // send query + Notificationclient.print(postcmd); + res = Wait4Answer(Notificationclient, "{", "\"ok\":true", TELEGRAMTIMEOUT); + Notificationclient.stop(); + return res; +} + +// TODO: put error in variable to allow better error handling +bool NotificationsService::sendEmailMSG(const char* title, + const char* message) { +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" + WiFiClientSecure Notificationclient; +#pragma GCC diagnostic pop + Notificationclient.setInsecure(); +#if defined(ARDUINO_ARCH_ESP8266) + BearSSLSetup(Notificationclient); +#endif // ARDUINO_ARCH_ESP8266 + log_esp3d("Connect to server"); + if (!Notificationclient.connect(_serveraddress.c_str(), _port)) { + log_esp3d_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!"); + return false; + } + // Do HELO + log_esp3d("HELO"); + Notificationclient.print("HELO friend\r\n"); + if (!Wait4Answer(Notificationclient, "250", "250", EMAILTIMEOUT)) { + log_esp3d_e("HELO failed!"); + return false; + } + log_esp3d("AUTH LOGIN"); + // Request AUthentication + Notificationclient.print("AUTH LOGIN\r\n"); + if (!Wait4Answer(Notificationclient, "334", "334", EMAILTIMEOUT)) { + log_esp3d("AUTH LOGIN failed!"); + return false; + } + log_esp3d("Send LOGIN"); + // sent Login + Notificationclient.printf("%s\r\n", _token1.c_str()); + if (!Wait4Answer(Notificationclient, "334", "334", EMAILTIMEOUT)) { + log_esp3d_e("Sent login failed!"); + return false; + } + log_esp3d("Send PASSWORD"); + // Send password + Notificationclient.printf("%s\r\n", _token2.c_str()); + if (!Wait4Answer(Notificationclient, "235", "235", EMAILTIMEOUT)) { + log_esp3d_e("Sent password failed!"); + return false; + } + log_esp3d("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!"); + return false; + } + log_esp3d("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!"); + return false; + } + log_esp3d("DATA"); + // Send Data + Notificationclient.print("DATA\r\n"); + if (!Wait4Answer(Notificationclient, "354", "354", EMAILTIMEOUT)) { + log_esp3d_e("Preparing DATA failed!"); + return false; + } + log_esp3d("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"); + // Send Final dot + Notificationclient.print(".\r\n"); + if (!Wait4Answer(Notificationclient, "250", "250", EMAILTIMEOUT)) { + log_esp3d_e("Sending final dot failed!"); + return false; + } + log_esp3d("QUIT"); + // Quit + Notificationclient.print("QUIT\r\n"); + if (!Wait4Answer(Notificationclient, "221", "221", EMAILTIMEOUT)) { + log_esp3d_e("QUIT failed!"); + return false; + } + + Notificationclient.stop(); + return true; +} +bool NotificationsService::sendLineMSG(const char* title, const char* message) { + String data; + String postcmd; + bool res; +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" + WiFiClientSecure Notificationclient; +#pragma GCC diagnostic pop + Notificationclient.setInsecure(); +#if defined(ARDUINO_ARCH_ESP8266) + BearSSLSetup(Notificationclient); +#endif // ARDUINO_ARCH_ESP8266 + (void)title; + if (!Notificationclient.connect(_serveraddress.c_str(), _port)) { + log_esp3d_e("Error connecting server %s:%d", _serveraddress.c_str(), + _port); + return false; + } + // build data for post + data = "message="; + data += message; + // build post query + postcmd = + "POST /api/notify HTTP/1.1\r\nHost: notify-api.line.me\r\nConnection: " + "close\r\nCache-Control: no-cache\r\nUser-Agent: ESP3D\r\nAccept: " + "text/html,application/xhtml+xml,application/xml;q=0.9,*/" + "*;q=0.8\r\nContent-Type: application/x-www-form-urlencoded\r\n"; + postcmd += "Authorization: Bearer "; + postcmd += _token1 + "\r\n"; + postcmd += "Content-Length: "; + postcmd += data.length(); + postcmd += "\r\n\r\n"; + postcmd += data; + log_esp3d("Query: %s", postcmd.c_str()); + // send query + Notificationclient.print(postcmd); + res = Wait4Answer(Notificationclient, "{", "\"status\":200", LINETIMEOUT); + Notificationclient.stop(); + return res; +} + +// IFTTT +bool NotificationsService::sendIFTTTMSG(const char* title, + const char* message) { + String data; + String postcmd; + bool res; +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" + WiFiClientSecure Notificationclient; +#pragma GCC diagnostic pop + Notificationclient.setInsecure(); +#if defined(ARDUINO_ARCH_ESP8266) + BearSSLSetup(Notificationclient); +#endif // ARDUINO_ARCH_ESP8266 + (void)title; + if (!Notificationclient.connect(_serveraddress.c_str(), _port)) { + log_esp3d_e("Error connecting server %s:%d", _serveraddress.c_str(), + _port); + return false; + } + + // build data for post + + data = "value1="; + data += title; + data += "&value2="; + data += message; + data += "&value3="; + data += NetConfig::hostname(); + + // build post query + postcmd = "POST /trigger/" + _token1 + "/with/key/" + _token2 + + " HTTP/1.1\r\nHost: maker.ifttt.com\r\nConnection: " + "close\r\nCache-Control: no-cache\r\nUser-Agent: ESP3D\r\nAccept: " + "text/html,application/xhtml+xml,application/xml;q=0.9,*/" + "*;q=0.8\r\nContent-Type: " + "application/x-www-form-urlencoded\r\nContent-Length: "; + postcmd += data.length(); + postcmd += "\r\n\r\n"; + postcmd += data; + + // log_esp3d("Query: %s", postcmd.c_str()); + // send query + Notificationclient.print(postcmd); + res = Wait4Answer(Notificationclient, "Congratulations", "Congratulations", + IFTTTTIMEOUT); + Notificationclient.stop(); + return res; +} + +// Email#serveraddress:port +bool NotificationsService::getPortFromSettings() { + String tmp = Settings_ESP3D::read_string(ESP_NOTIFICATION_SETTINGS); + int pos = tmp.lastIndexOf(':'); + if (pos == -1) { + return false; + } + _port = tmp.substring(pos + 1).toInt(); + log_esp3d("port : %d", _port); + if (_port > 0) { return true; + } else { + return false; + } } -//Messages are currently limited to 1024 4-byte UTF-8 characters -//but we do not do any check -//TODO: put error in variable to allow better error handling -bool NotificationsService::sendPushoverMSG(const char * title, const char * message) -{ - String data; - String postcmd; - bool res; -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wdeprecated-declarations" - WiFiClientSecure Notificationclient; -#pragma GCC diagnostic pop - Notificationclient.setInsecure(); -#if defined(ARDUINO_ARCH_ESP8266) - BearSSLSetup(Notificationclient); -#endif //ARDUINO_ARCH_ESP8266 - if (!Notificationclient.connect(_serveraddress.c_str(), _port)) { - log_esp3d("Error connecting server %s:%d", _serveraddress.c_str(), _port); - return false; - } - //build data for post - data = "user="; - data += _token1; - data += "&token="; - data += _token2; - data +="&title="; - data += title; - data += "&message="; - data += message; - data += "&device="; - data += NetConfig::hostname(); - //build post query - postcmd = "POST /1/messages.json HTTP/1.1\r\nHost: api.pushover.net\r\nConnection: close\r\nCache-Control: no-cache\r\nUser-Agent: ESP3D\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nContent-Length: "; - postcmd += data.length(); - postcmd +="\r\n\r\n"; - postcmd +=data; - log_esp3d("Query: %s", postcmd.c_str()); - //send query - Notificationclient.print(postcmd); - res = Wait4Answer(Notificationclient, "{", "\"status\":1", PUSHOVERTIMEOUT); - Notificationclient.stop(); - return res; +// Email#serveraddress:port +bool NotificationsService::getServerAddressFromSettings() { + String tmp = Settings_ESP3D::read_string(ESP_NOTIFICATION_SETTINGS); + int pos1 = tmp.indexOf('#'); + int pos2 = tmp.lastIndexOf(':'); + if ((pos1 == -1) || (pos2 == -1)) { + return false; + } + + // TODO add a check for valid email ? + _serveraddress = tmp.substring(pos1 + 1, pos2); + log_esp3d("server : %s", _serveraddress.c_str()); + return true; +} +// Email#serveraddress:port +bool NotificationsService::getEmailFromSettings() { + String tmp = Settings_ESP3D::read_string(ESP_NOTIFICATION_SETTINGS); + int pos = tmp.indexOf('#'); + if (pos == -1) { + return false; + } + _settings = tmp.substring(0, pos); + log_esp3d("email : %s", _settings.c_str()); + // TODO add a check for valid email ? + return true; } -//Telegram -//TODO: put error in variable to allow better error handling -bool NotificationsService::sendTelegramMSG(const char * title, const char * message) -{ - String data; - String postcmd; - bool res; -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wdeprecated-declarations" - WiFiClientSecure Notificationclient; -#pragma GCC diagnostic pop - Notificationclient.setInsecure(); -#if defined(ARDUINO_ARCH_ESP8266) - BearSSLSetup(Notificationclient); -#endif //ARDUINO_ARCH_ESP8266 - if (!Notificationclient.connect(_serveraddress.c_str(), _port)) { - log_esp3d("Error connecting server %s:%d", _serveraddress.c_str(), _port); - return false; - } - (void)title; - //build url for get - data = "chat_id="; - data += _token2; - data += "&text="; - data += message; - - //build post query - postcmd = "POST /bot"; - postcmd +=_token1; - postcmd += "/sendMessage HTTP/1.1\r\nHost: api.telegram.org\r\nConnection: close\r\nContent-Type: application/x-www-form-urlencoded\r\nCache-Control: no-cache\r\nUser-Agent: ESP3D\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nContent-Length: "; - postcmd += data.length(); - postcmd +="\r\n\r\n"; - postcmd +=data; - log_esp3d("Query: %s", postcmd.c_str()); - //send query - Notificationclient.print(postcmd); - res = Wait4Answer(Notificationclient, "{", "\"ok\":true", TELEGRAMTIMEOUT); - Notificationclient.stop(); - return res; +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); + return (out_len > 0); } -//TODO: put error in variable to allow better error handling -bool NotificationsService::sendEmailMSG(const char * title, const char * message) -{ -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wdeprecated-declarations" - WiFiClientSecure Notificationclient; -#pragma GCC diagnostic pop - Notificationclient.setInsecure(); -#if defined(ARDUINO_ARCH_ESP8266) - BearSSLSetup(Notificationclient); -#endif //ARDUINO_ARCH_ESP8266 - log_esp3d("Connect to server"); - if (!Notificationclient.connect(_serveraddress.c_str(), _port)) { - log_esp3d("Error connecting server %s:%d", _serveraddress.c_str(), _port); - return false; +bool NotificationsService::GET(const char* URL64) { + // TODO do we need https client ? + WiFiClient client; + HTTPClient http; // must be declared after WiFiClient for correct destruction + // order, because used by http.begin(client,...) + char* decodedurl[255]; + bool res = false; + if (decode64(URL64, (char*)decodedurl)) { + http.begin(client, (const char*)decodedurl); + int httpCode = http.GET(); + log_esp3d("HTTP code: %d", httpCode); + if (httpCode > 0) { + if (httpCode == HTTP_CODE_OK) { + res = true; + } } - //Check answer of connection - if(!Wait4Answer(Notificationclient, "220", "220", EMAILTIMEOUT)) { - log_esp3d("Connection failed!"); - return false; - } - //Do HELO - log_esp3d("HELO"); - Notificationclient.print("HELO friend\r\n"); - if(!Wait4Answer(Notificationclient, "250", "250", EMAILTIMEOUT)) { - log_esp3d("HELO failed!"); - return false; - } - log_esp3d("AUTH LOGIN"); - //Request AUthentication - Notificationclient.print("AUTH LOGIN\r\n"); - if(!Wait4Answer(Notificationclient, "334", "334", EMAILTIMEOUT)) { - log_esp3d("AUTH LOGIN failed!"); - return false; - } - log_esp3d("Send LOGIN"); - //sent Login - Notificationclient.printf("%s\r\n",_token1.c_str()); - if(!Wait4Answer(Notificationclient, "334", "334", EMAILTIMEOUT)) { - log_esp3d("Sent login failed!"); - return false; - } - log_esp3d("Send PASSWORD"); - //Send password - Notificationclient.printf("%s\r\n",_token2.c_str()); - if(!Wait4Answer(Notificationclient, "235", "235", EMAILTIMEOUT)) { - log_esp3d("Sent password failed!"); - return false; - } - log_esp3d("MAIL FROM"); - //Send From - Notificationclient.printf("MAIL FROM: <%s>\r\n",_settings.c_str()); - if(!Wait4Answer(Notificationclient, "250", "250", EMAILTIMEOUT)) { - log_esp3d("MAIL FROM failed!"); - return false; - } - log_esp3d("RCPT TO"); - //Send To - Notificationclient.printf("RCPT TO: <%s>\r\n",_settings.c_str()); - if(!Wait4Answer(Notificationclient, "250", "250", EMAILTIMEOUT)) { - log_esp3d("RCPT TO failed!"); - return false; - } - log_esp3d("DATA"); - //Send Data - Notificationclient.print("DATA\r\n"); - if(!Wait4Answer(Notificationclient, "354", "354", EMAILTIMEOUT)) { - log_esp3d("Preparing DATA failed!"); - return false; - } - log_esp3d("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"); - //Send Final dot - Notificationclient.print(".\r\n"); - if(!Wait4Answer(Notificationclient, "250", "250", EMAILTIMEOUT)) { - log_esp3d("Sending final dot failed!"); - return false; - } - log_esp3d("QUIT"); - //Quit - Notificationclient.print("QUIT\r\n"); - if(!Wait4Answer(Notificationclient, "221", "221", EMAILTIMEOUT)) { - log_esp3d("QUIT failed!"); - return false; - } - - Notificationclient.stop(); - return true; -} -bool NotificationsService::sendLineMSG(const char * title, const char * message) -{ - String data; - String postcmd; - bool res; -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wdeprecated-declarations" - WiFiClientSecure Notificationclient; -#pragma GCC diagnostic pop - Notificationclient.setInsecure(); -#if defined(ARDUINO_ARCH_ESP8266) - BearSSLSetup(Notificationclient); -#endif //ARDUINO_ARCH_ESP8266 - (void)title; - if (!Notificationclient.connect(_serveraddress.c_str(), _port)) { - log_esp3d("Error connecting server %s:%d", _serveraddress.c_str(), _port); - return false; - } - //build data for post - data = "message="; - data += message; - //build post query - postcmd = "POST /api/notify HTTP/1.1\r\nHost: notify-api.line.me\r\nConnection: close\r\nCache-Control: no-cache\r\nUser-Agent: ESP3D\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nContent-Type: application/x-www-form-urlencoded\r\n"; - postcmd +="Authorization: Bearer "; - postcmd += _token1 + "\r\n"; - postcmd += "Content-Length: "; - postcmd += data.length(); - postcmd +="\r\n\r\n"; - postcmd +=data; - log_esp3d("Query: %s", postcmd.c_str()); - //send query - Notificationclient.print(postcmd); - res = Wait4Answer(Notificationclient, "{", "\"status\":200", LINETIMEOUT); - Notificationclient.stop(); - return res; + http.end(); + } + return res; } -//IFTTT -bool NotificationsService::sendIFTTTMSG(const char * title, const char * message) -{ - String data; - String postcmd; - bool res; -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wdeprecated-declarations" - WiFiClientSecure Notificationclient; -#pragma GCC diagnostic pop - Notificationclient.setInsecure(); -#if defined(ARDUINO_ARCH_ESP8266) - BearSSLSetup(Notificationclient); -#endif //ARDUINO_ARCH_ESP8266 - (void)title; - if (!Notificationclient.connect(_serveraddress.c_str(), _port)) { - log_esp3d("Error connecting server %s:%d", _serveraddress.c_str(), _port); - return false; - } - - //build data for post - - data ="value1="; - data += title; - data += "&value2="; - data += message; - data += "&value3="; - data += NetConfig::hostname(); - - //build post query - postcmd = "POST /trigger/" + _token1 + "/with/key/" + _token2 + " HTTP/1.1\r\nHost: maker.ifttt.com\r\nConnection: close\r\nCache-Control: no-cache\r\nUser-Agent: ESP3D\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: "; - postcmd += data.length(); - postcmd +="\r\n\r\n"; - postcmd +=data; - - //log_esp3d("Query: %s", postcmd.c_str()); - //send query - Notificationclient.print(postcmd); - res = Wait4Answer(Notificationclient, "Congratulations", "Congratulations", IFTTTTIMEOUT); - Notificationclient.stop(); - return res; -} - -//Email#serveraddress:port -bool NotificationsService::getPortFromSettings() -{ - String tmp = Settings_ESP3D::read_string(ESP_NOTIFICATION_SETTINGS); - int pos = tmp.lastIndexOf(':'); - if (pos == -1) { - return false; - } - _port= tmp.substring(pos+1).toInt(); - log_esp3d("port : %d", _port); - if (_port > 0) { - return true; - } else { - return false; - } -} -//Email#serveraddress:port -bool NotificationsService::getServerAddressFromSettings() -{ - String tmp = Settings_ESP3D::read_string(ESP_NOTIFICATION_SETTINGS); - int pos1 = tmp.indexOf('#'); - int pos2 = tmp.lastIndexOf(':'); - if ((pos1 == -1) || (pos2 == -1)) { - return false; - } - - //TODO add a check for valid email ? - _serveraddress = tmp.substring(pos1+1, pos2); - log_esp3d("server : %s", _serveraddress.c_str()); - return true; -} -//Email#serveraddress:port -bool NotificationsService::getEmailFromSettings() -{ - String tmp = Settings_ESP3D::read_string(ESP_NOTIFICATION_SETTINGS); - int pos = tmp.indexOf('#'); - if (pos == -1) { - return false; - } - _settings = tmp.substring(0, pos); - log_esp3d("email : %s", _settings.c_str()); - //TODO add a check for valid email ? - return true; -} - -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); - return (out_len>0); -} - -bool NotificationsService::GET(const char * URL64) -{ - //TODO do we need https client ? - WiFiClient client; - HTTPClient http; //must be declared after WiFiClient for correct destruction order, because used by http.begin(client,...) - char * decodedurl[255]; - bool res = false; - if (decode64(URL64, (char*)decodedurl)) { - http.begin(client, (const char*)decodedurl); - int httpCode = http.GET(); - log_esp3d("HTTP code: %d", httpCode); - if (httpCode > 0) { - if(httpCode == HTTP_CODE_OK) { - res = true; - } - } - http.end(); - } - return res; -} - -bool NotificationsService::begin() -{ - bool res = true; - end(); - _notificationType = Settings_ESP3D::read_byte(ESP_NOTIFICATION_TYPE); - switch(_notificationType) { - case 0: //no notification = no error but no start - _started=true; - return true; +bool NotificationsService::begin() { + bool res = true; + end(); + _notificationType = Settings_ESP3D::read_byte(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); - _port = PUSHOVERPORT; - _serveraddress = PUSHOVERSERVER; - break; + _token1 = Settings_ESP3D::read_string(ESP_NOTIFICATION_TOKEN1); + _token2 = Settings_ESP3D::read_string(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); - _port = TELEGRAMPORT; - _serveraddress = TELEGRAMSERVER; - break; + _token1 = Settings_ESP3D::read_string(ESP_NOTIFICATION_TOKEN1); + _token2 = Settings_ESP3D::read_string(ESP_NOTIFICATION_TOKEN2); + _port = TELEGRAMPORT; + _serveraddress = TELEGRAMSERVER; + break; case ESP_LINE_NOTIFICATION: - _token1 = Settings_ESP3D::read_string(ESP_NOTIFICATION_TOKEN1); - _port = LINEPORT; - _serveraddress = LINESERVER; - break; + _token1 = Settings_ESP3D::read_string(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); - _port = IFTTTPORT; - _serveraddress = IFTTTSERVER; - break; + _token1 = Settings_ESP3D::read_string(ESP_NOTIFICATION_TOKEN1); + _token2 = Settings_ESP3D::read_string(ESP_NOTIFICATION_TOKEN2); + _port = IFTTTPORT; + _serveraddress = IFTTTSERVER; + break; case ESP_EMAIL_NOTIFICATION: - _token1 = base64::encode(Settings_ESP3D::read_string(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)); - if(!getEmailFromSettings() || !getPortFromSettings()|| !getServerAddressFromSettings()) { - return false; - } - break; - default: + _token1 = + base64::encode(Settings_ESP3D::read_string(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)); + if (!getEmailFromSettings() || !getPortFromSettings() || + !getServerAddressFromSettings()) { return false; - break; - } - _autonotification = (Settings_ESP3D::read_byte(ESP_AUTO_NOTIFICATION) == 0) ? false: true; - if (!res) { - end(); - } - _started = res; - return _started; + } + break; + default: + return false; + break; + } + _autonotification = + (Settings_ESP3D::read_byte(ESP_AUTO_NOTIFICATION) == 0) ? false : true; + if (!res) { + end(); + } + _started = res; + return _started; } -void NotificationsService::end() -{ - if(!_started) { - return; - } - _started = false; - _notificationType = 0; - _token1 = ""; - _token1 = ""; - _settings = ""; - _serveraddress = ""; - _port = 0; +void NotificationsService::end() { + if (!_started) { + return; + } + _started = false; + _notificationType = 0; + _token1 = ""; + _token1 = ""; + _settings = ""; + _serveraddress = ""; + _port = 0; } -void NotificationsService::handle() -{ - if (_started) { - } +void NotificationsService::handle() { + if (_started) { + } } -#endif //NOTIFICATION_FEATURE +#endif // NOTIFICATION_FEATURE diff --git a/esp3d/src/modules/sensor/bmx280.cpp b/esp3d/src/modules/sensor/bmx280.cpp index 6ae3c23d..3ea47cf2 100644 --- a/esp3d/src/modules/sensor/bmx280.cpp +++ b/esp3d/src/modules/sensor/bmx280.cpp @@ -20,187 +20,169 @@ #include "../../include/esp3d_config.h" #ifdef SENSOR_DEVICE -#if SENSOR_DEVICE==BMP280_DEVICE || SENSOR_DEVICE==BME280_DEVICE -#include "bmx280.h" -#include "../../core/settings_esp3d.h" -#include "../../core/esp3doutput.h" +#if SENSOR_DEVICE == BMP280_DEVICE || SENSOR_DEVICE == BME280_DEVICE #include #include +#include "../../core/esp3doutput.h" +#include "../../core/settings_esp3d.h" +#include "bmx280.h" + + #define NB_TYPE_SENSOR 2 -const char * SENSOR_NAME[NB_TYPE_SENSOR] = {"BMP280", "BME280"}; +const char *SENSOR_NAME[NB_TYPE_SENSOR] = {"BMP280", "BME280"}; const uint8_t SENSOR_ID[NB_TYPE_SENSOR] = {BMP280_DEVICE, BME280_DEVICE}; -BMx280I2C * bmx280_device; +BMx280I2C *bmx280_device; -BMX280SensorDevice::BMX280SensorDevice() -{ - bmx280_device = nullptr; -} +BMX280SensorDevice::BMX280SensorDevice() { bmx280_device = nullptr; } -BMX280SensorDevice::~BMX280SensorDevice() -{ - end(); -} +BMX280SensorDevice::~BMX280SensorDevice() { end(); } -bool BMX280SensorDevice::begin() -{ - end(); - uint8_t sensortype= Settings_ESP3D::read_byte(ESP_SENSOR_TYPE); - if (sensortype == 0) { - log_esp3d("No Sensor active"); - return true; - } - if (!isModelValid(sensortype)) { - log_esp3d("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); - bmx280_device = new BMx280I2C(SENSOR_ADDR); - if (!bmx280_device) { - log_esp3d("Cannot instanciate sensor"); - return false; - } - if (!bmx280_device->begin()) { - log_esp3d("No valid sensor status"); - return false; - } - //reset sensor to default parameters. - bmx280_device->resetToDefaults(); - - //by default sensing is disabled and must be enabled by setting a non-zero - //oversampling setting. - //set an oversampling setting for pressure and temperature measurements. - bmx280_device->writeOversamplingPressure(BMx280MI::OSRS_P_x16); - bmx280_device->writeOversamplingTemperature(BMx280MI::OSRS_T_x16); - - //if sensor is a BME280, set an oversampling setting for humidity measurements. - if (bmx280_device->isBME280()) { - bmx280_device->writeOversamplingHumidity(BMx280MI::OSRS_H_x16); - } +bool BMX280SensorDevice::begin() { + end(); + uint8_t sensortype = Settings_ESP3D::read_byte(ESP_SENSOR_TYPE); + if (sensortype == 0) { + log_esp3d("No Sensor active"); return true; -} - -void BMX280SensorDevice::end() -{ - if (bmx280_device) { - delete bmx280_device; - } - bmx280_device = nullptr; -} - -bool BMX280SensorDevice::isModelValid(uint8_t model) -{ - for (uint8_t i = 0; i < NB_TYPE_SENSOR; i++) { - if (model == SENSOR_ID[i]) { - return true; - } - } + } + if (!isModelValid(sensortype)) { + log_esp3d_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); + bmx280_device = new BMx280I2C(SENSOR_ADDR); + if (!bmx280_device) { + log_esp3d_e("Cannot instanciate sensor"); + return false; + } + if (!bmx280_device->begin()) { + log_esp3d("No valid sensor status"); + return false; + } + // reset sensor to default parameters. + bmx280_device->resetToDefaults(); + + // by default sensing is disabled and must be enabled by setting a non-zero + // oversampling setting. + // set an oversampling setting for pressure and temperature measurements. + bmx280_device->writeOversamplingPressure(BMx280MI::OSRS_P_x16); + bmx280_device->writeOversamplingTemperature(BMx280MI::OSRS_T_x16); + + // if sensor is a BME280, set an oversampling setting for humidity + // measurements. + if (bmx280_device->isBME280()) { + bmx280_device->writeOversamplingHumidity(BMx280MI::OSRS_H_x16); + } + return true; } -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]); - if (strcmp(s, SENSOR_NAME[i])==0) { - log_esp3d("found %d",SENSOR_ID[i]); - return SENSOR_ID[i]; - } +void BMX280SensorDevice::end() { + if (bmx280_device) { + delete bmx280_device; + } + bmx280_device = nullptr; +} + +bool BMX280SensorDevice::isModelValid(uint8_t model) { + for (uint8_t i = 0; i < NB_TYPE_SENSOR; i++) { + if (model == SENSOR_ID[i]) { + return true; } - - return 0; + } + return false; } -uint8_t BMX280SensorDevice::nbType() -{ - return NB_TYPE_SENSOR; -} - -uint8_t BMX280SensorDevice::GetModel(uint8_t i) -{ - if (i measure()) { - s="BUSY"; - log_esp3d("sensor is busy"); + s = "BUSY"; + log_esp3d("sensor is busy"); } else { - uint8_t nbtry = 0; - do { - log_esp3d("try sensor %d",nbtry); - Hal::wait(100); - nbtry ++; - } while (!bmx280_device->hasValue() && nbtry < 3); - if (bmx280_device->hasValue()) { - float temperature = bmx280_device->getTemperature(); - float pressure = bmx280_device->getPressure(); - float humidity=0; - if (bmx280_device->isBME280()) { - humidity = bmx280_device->getHumidity(); - } - log_esp3d("T %f P %f H %f",temperature, pressure, humidity); - if ( String(temperature,1)!="nan") { - if (strcmp(SENSOR__UNIT,"F")==0) { - temperature = toFahrenheit(temperature); - } - s= String(temperature,1); - s+= "["; - s+= SENSOR__UNIT; - s+= "] " +String(pressure,1); - s+= "[Pa]"; - if (bmx280_device->isBME280()) { - s+=" " + String(humidity,1) + "[%]"; - } - } else { - s="DISCONNECTED"; - log_esp3d("No valid data"); - } - } else { - s="DISCONNECTED"; - log_esp3d("No valid data"); + uint8_t nbtry = 0; + do { + log_esp3d("try sensor %d", nbtry); + Hal::wait(100); + nbtry++; + } while (!bmx280_device->hasValue() && nbtry < 3); + if (bmx280_device->hasValue()) { + float temperature = bmx280_device->getTemperature(); + float pressure = bmx280_device->getPressure(); + float humidity = 0; + if (bmx280_device->isBME280()) { + humidity = bmx280_device->getHumidity(); } + log_esp3d("T %f P %f H %f", temperature, pressure, humidity); + if (String(temperature, 1) != "nan") { + if (strcmp(SENSOR__UNIT, "F") == 0) { + temperature = toFahrenheit(temperature); + } + s = String(temperature, 1); + s += "["; + s += SENSOR__UNIT; + s += "] " + String(pressure, 1); + s += "[Pa]"; + if (bmx280_device->isBME280()) { + s += " " + String(humidity, 1) + "[%]"; + } + } else { + s = "DISCONNECTED"; + log_esp3d_e("No valid data"); + } + } else { + s = "DISCONNECTED"; + log_esp3_ed("No valid data"); + } } - } else { - s="DISCONNECTED"; - log_esp3d("No device"); - } - return s.c_str(); + } else { + s = "DISCONNECTED"; + log_esp3d_e("No device"); + } + return s.c_str(); } - -#endif //BMP280_DEVICE || BME280_DEVICE -#endif //SENSOR_DEVICE +#endif // BMP280_DEVICE || BME280_DEVICE +#endif // SENSOR_DEVICE diff --git a/esp3d/src/modules/sensor/dht.cpp b/esp3d/src/modules/sensor/dht.cpp index 0cf70e7e..2d0e8db4 100644 --- a/esp3d/src/modules/sensor/dht.cpp +++ b/esp3d/src/modules/sensor/dht.cpp @@ -20,146 +20,134 @@ #include "../../include/esp3d_config.h" #ifdef SENSOR_DEVICE -#if SENSOR_DEVICE==DHT11_DEVICE || SENSOR_DEVICE==DHT22_DEVICE -#include "dht.h" -#include "../../core/settings_esp3d.h" -#include "../../core/esp3doutput.h" +#if SENSOR_DEVICE == DHT11_DEVICE || SENSOR_DEVICE == DHT22_DEVICE #include +#include "../../core/esp3doutput.h" +#include "../../core/settings_esp3d.h" +#include "dht.h" #define NB_TYPE_SENSOR 2 -const char * SENSOR_NAME[NB_TYPE_SENSOR] = {"DHT11", "DHT22"}; +const char *SENSOR_NAME[NB_TYPE_SENSOR] = {"DHT11", "DHT22"}; const uint8_t SENSOR_ID[NB_TYPE_SENSOR] = {DHT11_DEVICE, DHT22_DEVICE}; -const DHTesp::DHT_MODEL_t SENSOR_TYPE[NB_TYPE_SENSOR] = {DHTesp::DHT11, DHTesp::DHT22}; -DHTesp * dht_device; +const DHTesp::DHT_MODEL_t SENSOR_TYPE[NB_TYPE_SENSOR] = {DHTesp::DHT11, + DHTesp::DHT22}; +DHTesp *dht_device; -DHTSensorDevice::DHTSensorDevice() -{ - dht_device = nullptr; -} +DHTSensorDevice::DHTSensorDevice() { dht_device = nullptr; } -DHTSensorDevice::~DHTSensorDevice() -{ - end(); -} +DHTSensorDevice::~DHTSensorDevice() { end(); } -bool DHTSensorDevice::begin() -{ - end(); - uint8_t dhttype= Settings_ESP3D::read_byte(ESP_SENSOR_TYPE); - log_esp3d("Read %d, %s", dhttype, dhttype==1?"DHT11":dhttype==2?"DHT22":dhttype==0?"NONE":"Unknow type"); - if (dhttype == 0) { - log_esp3d("No Sensor active"); - return true; - } - if (!isModelValid(dhttype)) { - log_esp3d("No valid id "); - return false; - } - dht_device = new DHTesp; - if (!dht_device) { - log_esp3d("Cannot instanciate dht"); - return false; - } - log_esp3d("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("No valid dht status: %d, %s",dht_device->getStatus(), dht_device->getStatusString()); - return false; - } - log_esp3d("DHT ok"); +bool DHTSensorDevice::begin() { + end(); + uint8_t dhttype = Settings_ESP3D::read_byte(ESP_SENSOR_TYPE); + log_esp3d("Read %d, %s", dhttype, + dhttype == 1 ? "DHT11" + : dhttype == 2 ? "DHT22" + : dhttype == 0 ? "NONE" + : "Unknow type"); + if (dhttype == 0) { + log_esp3d("No Sensor active"); return true; -} - -void DHTSensorDevice::end() -{ - if (dht_device) { - delete dht_device; - } - dht_device = nullptr; -} - -bool DHTSensorDevice::isModelValid(uint8_t model) -{ - for (uint8_t i = 0; i < NB_TYPE_SENSOR; i++) { - if (model == SENSOR_ID[i]) { - return true; - } - } + } + if (!isModelValid(dhttype)) { + log_esp3d_e("No valid id "); return false; + } + dht_device = new DHTesp; + if (!dht_device) { + log_esp3d_e("Cannot instanciate dht"); + return false; + } + log_esp3d("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(), + dht_device->getStatusString()); + return false; + } + log_esp3d("DHT ok"); + return true; } -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]); - if (strcmp(s, SENSOR_NAME[i])==0) { - log_esp3d("found %d",SENSOR_ID[i]); - return SENSOR_ID[i]; - } +void DHTSensorDevice::end() { + if (dht_device) { + delete dht_device; + } + dht_device = nullptr; +} + +bool DHTSensorDevice::isModelValid(uint8_t model) { + for (uint8_t i = 0; i < NB_TYPE_SENSOR; i++) { + if (model == SENSOR_ID[i]) { + return true; } - - return 0; + } + return false; } -uint8_t DHTSensorDevice::nbType() -{ - return NB_TYPE_SENSOR; -} - -uint8_t DHTSensorDevice::GetModel(uint8_t i) -{ - if (i getTemperature(); + float humidity = dht_device->getHumidity(); + log_esp3d("T %f H %f", temperature, humidity); + if (strcmp(SENSOR__UNIT, "F") == 0) { + temperature = dht_device->toFahrenheit(temperature); } - return "NONE"; -} - -const char * DHTSensorDevice::GetData() -{ - static String s; - if (dht_device) { - float temperature = dht_device->getTemperature(); - float humidity= dht_device->getHumidity(); - log_esp3d("T %f H %f",temperature, humidity); - if (strcmp(SENSOR__UNIT,"F")==0) { - temperature = dht_device->toFahrenheit(temperature); - } - if ( String(humidity,1)!="nan") { - s= String(temperature,1); - s+= "["; - s+= SENSOR__UNIT; - s+="] " + String(humidity,1) + "[%]"; - } else { - s="DISCONNECTED"; - log_esp3d("No valid data"); - } + if (String(humidity, 1) != "nan") { + s = String(temperature, 1); + s += "["; + s += SENSOR__UNIT; + s += "] " + String(humidity, 1) + "[%]"; } else { - s="DISCONNECTED"; - log_esp3d("No device"); + s = "DISCONNECTED"; + log_esp3d_e("No valid data"); } - return s.c_str(); + } else { + s = "DISCONNECTED"; + log_esp3d_e("No device"); + } + return s.c_str(); } - -#endif //DHT11_DEVICE || DHT22_DEVICE -#endif //SENSOR_DEVICE +#endif // DHT11_DEVICE || DHT22_DEVICE +#endif // SENSOR_DEVICE diff --git a/esp3d/src/modules/sensor/sensor.cpp b/esp3d/src/modules/sensor/sensor.cpp index 474ebaa1..4e14bc1a 100644 --- a/esp3d/src/modules/sensor/sensor.cpp +++ b/esp3d/src/modules/sensor/sensor.cpp @@ -20,166 +20,148 @@ #include "../../include/esp3d_config.h" #ifdef SENSOR_DEVICE -#include "sensor.h" -#include "../../core/settings_esp3d.h" #include "../../core/esp3doutput.h" -//Include file according sensor -#if SENSOR_DEVICE==DHT11_DEVICE || SENSOR_DEVICE==DHT22_DEVICE -#include "dht.h" -#endif //DHT11_DEVICE || DHT22_DEVICE -#if SENSOR_DEVICE==ANALOG_DEVICE -#include "analogsensor.h" -#endif //ANALOG_DEVICE -#if SENSOR_DEVICE==BMP280_DEVICE || SENSOR_DEVICE==BME280_DEVICE -#include "bmx280.h" -#endif //BMP280_DEVICE || BME280_DEVICE +#include "../../core/settings_esp3d.h" +#include "sensor.h" -#if defined (WIFI_FEATURE) || defined(ETH_FEATURE) +// Include file according sensor +#if SENSOR_DEVICE == DHT11_DEVICE || SENSOR_DEVICE == DHT22_DEVICE +#include "dht.h" +#endif // DHT11_DEVICE || DHT22_DEVICE +#if SENSOR_DEVICE == ANALOG_DEVICE +#include "analogsensor.h" +#endif // ANALOG_DEVICE +#if SENSOR_DEVICE == BMP280_DEVICE || SENSOR_DEVICE == BME280_DEVICE +#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 +#endif // WIFI_FEATURE || ETH_FEATURE ESP3DSensor esp3d_sensor; -ESP3DSensor::ESP3DSensor() -{ - _started = false; - _interval = 0; - _device = nullptr; +ESP3DSensor::ESP3DSensor() { + _started = false; + _interval = 0; + _device = nullptr; } -ESP3DSensor::~ESP3DSensor() -{ - end(); -} +ESP3DSensor::~ESP3DSensor() { end(); } -bool ESP3DSensor::begin() -{ - log_esp3d("Sensor Begin"); - bool res = true; - end(); - //new _device -#if SENSOR_DEVICE==ANALOG_DEVICE - _device = (ESP3DSensorDevice * )new AnalogSensorDevice(); -#endif //ANALOG_DEVICE -#if SENSOR_DEVICE==DHT11_DEVICE || SENSOR_DEVICE==DHT22_DEVICE - _device = (ESP3DSensorDevice * )new DHTSensorDevice(); -#endif //DHT11_DEVICE || DHT22_DEVICE -#if SENSOR_DEVICE==BMP280_DEVICE || SENSOR_DEVICE==BME280_DEVICE - _device = (ESP3DSensorDevice * )new BMX280SensorDevice(); -#endif //DHT11_DEVICE || DHT22_DEVICE - if (!_device) { - log_esp3d("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); - //No Sensor defined - exit is not an error - if (sensortype == 0) { - log_esp3d("Sensor Device is not active at start"); - return true; - } - _interval = Settings_ESP3D::read_uint32(ESP_SENSOR_INTERVAL); - if (!_device->begin()) { - res = false; - } - _lastReadTime = millis(); - _started = res; - return _started; -} - -void ESP3DSensor::end() -{ - if (_device) { - delete _device; - _device = nullptr; - } - _started = false; - _interval = 0; -} - -uint8_t ESP3DSensor::GetModel(uint8_t i) -{ - if (_device) { - return _device->GetModel(i); - } else { - return 0; - } -} - -uint8_t ESP3DSensor::nbType() -{ - if (_device) { - - return _device->nbType(); - } - return 0; -} - - -bool ESP3DSensor::isModelValid(uint8_t model) -{ - if (_device) { - return _device->isModelValid(model); - } +bool ESP3DSensor::begin() { + log_esp3d("Sensor Begin"); + bool res = true; + end(); + // new _device +#if SENSOR_DEVICE == ANALOG_DEVICE + _device = (ESP3DSensorDevice*)new AnalogSensorDevice(); +#endif // ANALOG_DEVICE +#if SENSOR_DEVICE == DHT11_DEVICE || SENSOR_DEVICE == DHT22_DEVICE + _device = (ESP3DSensorDevice*)new DHTSensorDevice(); +#endif // DHT11_DEVICE || DHT22_DEVICE +#if SENSOR_DEVICE == BMP280_DEVICE || SENSOR_DEVICE == BME280_DEVICE + _device = (ESP3DSensorDevice*)new BMX280SensorDevice(); +#endif // DHT11_DEVICE || DHT22_DEVICE + if (!_device) { + log_esp3d_e("No device created"); return false; -} - -const char * ESP3DSensor::GetCurrentModelString() -{ - if (_device) { - - return _device->GetCurrentModelString(); - } - return "NONE"; -} - -const char * ESP3DSensor::GetModelString(uint8_t i) -{ - if (_device) { - - return _device->GetModelString(i); - } - return "NONE"; -} - -uint8_t ESP3DSensor::getIDFromString(const char * s) -{ - if (_device) { - return _device->getIDFromString(s); - } - return 0; -} - -bool ESP3DSensor::setInterval(uint interval) -{ - _interval = interval; + } + log_esp3d("Sensor Device created"); + uint8_t sensortype = Settings_ESP3D::read_byte(ESP_SENSOR_TYPE); + log_esp3d("Sensor %d", sensortype); + // No Sensor defined - exit is not an error + if (sensortype == 0) { + log_esp3d("Sensor Device is not active at start"); return true; + } + _interval = Settings_ESP3D::read_uint32(ESP_SENSOR_INTERVAL); + if (!_device->begin()) { + res = false; + } + _lastReadTime = millis(); + _started = res; + return _started; } -const char * ESP3DSensor::GetData() -{ - if (_started && _device) { - return _device->GetData(); - } - return ""; +void ESP3DSensor::end() { + if (_device) { + delete _device; + _device = nullptr; + } + _started = false; + _interval = 0; } -void ESP3DSensor::handle() -{ - if (_interval == 0) { - return; - } - if (_started && _device) { - if ((millis() - _lastReadTime) > _interval) { - String data = _device->GetData(); - _lastReadTime = millis(); -#if defined (WIFI_FEATURE) || defined(ETH_FEATURE) - String s = "SENSOR:" + data ; - websocket_terminal_server.pushMSG(s.c_str()); -#endif // WIFI_FEATURE || ETH_FEATURE - } - } +uint8_t ESP3DSensor::GetModel(uint8_t i) { + if (_device) { + return _device->GetModel(i); + } else { + return 0; + } } -#endif //SENSOR_DEVICE +uint8_t ESP3DSensor::nbType() { + if (_device) { + return _device->nbType(); + } + return 0; +} + +bool ESP3DSensor::isModelValid(uint8_t model) { + if (_device) { + return _device->isModelValid(model); + } + return false; +} + +const char* ESP3DSensor::GetCurrentModelString() { + if (_device) { + return _device->GetCurrentModelString(); + } + return "NONE"; +} + +const char* ESP3DSensor::GetModelString(uint8_t i) { + if (_device) { + return _device->GetModelString(i); + } + return "NONE"; +} + +uint8_t ESP3DSensor::getIDFromString(const char* s) { + if (_device) { + return _device->getIDFromString(s); + } + return 0; +} + +bool ESP3DSensor::setInterval(uint interval) { + _interval = interval; + return true; +} + +const char* ESP3DSensor::GetData() { + if (_started && _device) { + return _device->GetData(); + } + return ""; +} + +void ESP3DSensor::handle() { + if (_interval == 0) { + return; + } + if (_started && _device) { + if ((millis() - _lastReadTime) > _interval) { + String data = _device->GetData(); + _lastReadTime = millis(); +#if defined(WIFI_FEATURE) || defined(ETH_FEATURE) + String s = "SENSOR:" + data; + websocket_terminal_server.pushMSG(s.c_str()); +#endif // WIFI_FEATURE || ETH_FEATURE + } + } +} + +#endif // SENSOR_DEVICE diff --git a/esp3d/src/modules/serial/serial_service.cpp b/esp3d/src/modules/serial/serial_service.cpp index f99e3926..6969c2ff 100644 --- a/esp3d/src/modules/serial/serial_service.cpp +++ b/esp3d/src/modules/serial/serial_service.cpp @@ -19,34 +19,35 @@ */ #include "../../include/esp3d_config.h" -#if COMMUNICATION_PROTOCOL == MKS_SERIAL || COMMUNICATION_PROTOCOL == RAW_SERIAL || defined(ESP_SERIAL_BRIDGE_OUTPUT) -#include "serial_service.h" -#include "../../core/settings_esp3d.h" -#include "../../core/esp3doutput.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 "serial_service.h" + #if COMMUNICATION_PROTOCOL == MKS_SERIAL #include "../mks/mks_service.h" -#endif //COMMUNICATION_PROTOCOL == MKS_SERIAL +#endif // COMMUNICATION_PROTOCOL == MKS_SERIAL #include "../authentication/authentication_service.h" -#if defined (ARDUINO_ARCH_ESP8266) +#if defined(ARDUINO_ARCH_ESP8266) #define MAX_SERIAL 2 -HardwareSerial * Serials[MAX_SERIAL] = {&Serial, &Serial1}; -#endif //ARDUINO_ARCH_ESP8266 +HardwareSerial *Serials[MAX_SERIAL] = {&Serial, &Serial1}; +#endif // ARDUINO_ARCH_ESP8266 -#if defined (ARDUINO_ARCH_ESP32) +#if defined(ARDUINO_ARCH_ESP32) - #if defined (CONFIG_IDF_TARGET_ESP32C3) - #define MAX_SERIAL 2 - HardwareSerial * Serials[MAX_SERIAL] = {&Serial, &Serial1}; - #else - #define MAX_SERIAL 3 - HardwareSerial * Serials[MAX_SERIAL] = {&Serial, &Serial1, &Serial2}; - #endif +#if defined(CONFIG_IDF_TARGET_ESP32C3) +#define MAX_SERIAL 2 +HardwareSerial *Serials[MAX_SERIAL] = {&Serial, &Serial1}; +#else +#define MAX_SERIAL 3 +HardwareSerial *Serials[MAX_SERIAL] = {&Serial, &Serial1, &Serial2}; +#endif -#endif //ARDUINO_ARCH_ESP32 +#endif // ARDUINO_ARCH_ESP32 - -//Serial Parameters +// Serial Parameters #define ESP_SERIAL_PARAM SERIAL_8N1 #define ESP3DSERIAL_RUNNING_PRIORITY 1 @@ -56,492 +57,486 @@ HardwareSerial * Serials[MAX_SERIAL] = {&Serial, &Serial1}; SerialService serial_service = SerialService(MAIN_SERIAL); #if defined(ESP_SERIAL_BRIDGE_OUTPUT) SerialService serial_bridge_service = SerialService(BRIDGE_SERIAL); -#endif //ESP_SERIAL_BRIDGE_OUTPUT +#endif // ESP_SERIAL_BRIDGE_OUTPUT #if defined(ARDUINO_ARCH_ESP32) && defined(SERIAL_INDEPENDANT_TASK) -TaskHandle_t _hserialtask= nullptr; -#endif //ARDUINO_ARCH_ESP32 +TaskHandle_t _hserialtask = nullptr; +#endif // ARDUINO_ARCH_ESP32 -const long SupportedBaudList[] = {9600, 19200, 38400, 57600, 74880, 115200, 230400, 250000, 500000, 921600, 1958400}; +const long SupportedBaudList[] = {9600, 19200, 38400, 57600, + 74880, 115200, 230400, 250000, + 500000, 921600, 1958400}; #define TIMEOUT_SERIAL_FLUSH 1500 -//Constructor -SerialService::SerialService(uint8_t id) -{ - _buffer_size = 0; - _started = false; - _needauthentication = true; - _id = id; - switch (_id) { +// Constructor +SerialService::SerialService(uint8_t id) { + _buffer_size = 0; + _started = false; + _needauthentication = true; + _id = id; + switch (_id) { case MAIN_SERIAL: - _rxPin = ESP_RX_PIN; - _txPin = ESP_TX_PIN; - _client=ESP_SERIAL_CLIENT; - break; + _rxPin = ESP_RX_PIN; + _txPin = ESP_TX_PIN; + _client = ESP_SERIAL_CLIENT; + 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; - break; -#endif //ESP_SERIAL_BRIDGE_OUTPUT + _rxPin = ESP_BRIDGE_RX_PIN; + _txPin = ESP_BRIDGE_TX_PIN; + _client = ESP_SERIAL_BRIDGE_CLIENT; + break; +#endif // ESP_SERIAL_BRIDGE_OUTPUT default: - _rxPin = ESP_RX_PIN; - _txPin = ESP_TX_PIN; - _client=ESP_SERIAL_CLIENT; - break; - } + _rxPin = ESP_RX_PIN; + _txPin = ESP_TX_PIN; + _client = ESP_SERIAL_CLIENT; + break; + } } -//Destructor -SerialService::~SerialService() -{ - end(); -} +// Destructor +SerialService::~SerialService() { end(); } -//dedicated serial task +// 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 - } - vTaskDelete( NULL ); +void ESP3DSerialTaskfn(void *parameter) { + for (;;) { + serial_service.process(); + Hal::wait(SERIAL_YIELD); // Yield to other tasks + } + vTaskDelete(NULL); } -#endif //ARDUINO_ARCH_ESP32 +#endif // ARDUINO_ARCH_ESP32 -//extra parameters that do not need a begin -void SerialService::setParameters() -{ -#if defined (AUTHENTICATION_FEATURE) - _needauthentication = (Settings_ESP3D::read_byte (ESP_SECURE_SERIAL)==0)?false:true; +// extra parameters that do not need a begin +void SerialService::setParameters() { +#if defined(AUTHENTICATION_FEATURE) + _needauthentication = + (Settings_ESP3D::read_byte(ESP_SECURE_SERIAL) == 0) ? false : true; #else - _needauthentication = false; -#endif //AUTHENTICATION_FEATURE + _needauthentication = false; +#endif // AUTHENTICATION_FEATURE } -//Setup Serial -bool SerialService::begin(uint8_t serialIndex) -{ - _serialIndex = serialIndex-1; - log_esp3d("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); - return true; - } - if(_serialIndex >= MAX_SERIAL) { - log_esp3d("Serial %d begin for %d failed, index out of range", _serialIndex, _id); - return false; - } - _lastflush = millis(); - //read from settings - long br = 0; - long defaultBr = 0; - switch (_id) { - case MAIN_SERIAL: - br = Settings_ESP3D::read_uint32(ESP_BAUD_RATE); - defaultBr = Settings_ESP3D::get_default_int32_value(ESP_BAUD_RATE); - break; -#if defined(ESP_SERIAL_BRIDGE_OUTPUT) - case BRIDGE_SERIAL: - br = Settings_ESP3D::read_uint32(ESP_SERIAL_BRIDGE_BAUD); - defaultBr = Settings_ESP3D::get_default_int32_value(ESP_SERIAL_BRIDGE_BAUD); - break; -#endif //ESP_SERIAL_BRIDGE_OUTPUT - default: - log_esp3d("Serial %d begin for %d failed, unknown id", _serialIndex, _id); - return false; - } - setParameters(); - log_esp3d("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 ( !is_valid_baudrate(br)) { - br = defaultBr; - } - Serials[_serialIndex]->setRxBufferSize (SERIAL_RX_BUFFER_SIZE); -#ifdef ARDUINO_ARCH_ESP8266 - Serials[_serialIndex]->begin(br, ESP_SERIAL_PARAM, SERIAL_FULL, (_txPin == -1)?1:_txPin); - if (_rxPin != -1) { - Serials[_serialIndex]->pins((_txPin == -1)?1:_txPin, _rxPin); - } - -#endif //ARDUINO_ARCH_ESP8266 -#if defined(ARDUINO_ARCH_ESP32) - 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); - if (_hserialtask == nullptr && _id==MAIN_SERIAL) { - xTaskCreatePinnedToCore( - ESP3DSerialTaskfn, /* Task function. */ - "ESP3D Serial Task", /* name of task. */ - 8192, /* Stack size of task */ - NULL, /* parameter of the task */ - ESP3DSERIAL_RUNNING_PRIORITY, /* priority of the task */ - &_hserialtask, /* Task handle to keep track of created task */ - ESP3DSERIAL_RUNNING_CORE /* Core to run the task */ - ); - } - if (_hserialtask == nullptr) { - log_esp3d("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); +// Setup Serial +bool SerialService::begin(uint8_t serialIndex) { + _serialIndex = serialIndex - 1; + log_esp3d("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); return true; -} -//End serial -bool SerialService::end() -{ - flush(); - delay (100); - swap(); - Serials[_serialIndex]->end(); - _buffer_size = 0; - _started = false; - return true; -} - -//return the array of long and array size -const long * SerialService::get_baudratelist(uint8_t * count) -{ - if (count) { - *count = sizeof(SupportedBaudList)/sizeof(long); - } - return SupportedBaudList; -} - -//check if value is in baudrate list -bool SerialService::is_valid_baudrate(long br) -{ - uint8_t listesize = sizeof(SupportedBaudList)/sizeof(long); - for (uint8_t i = 0; i < listesize ; i++) { - if (SupportedBaudList[i] == br) { - return true; - } - } + } + if (_serialIndex >= MAX_SERIAL) { + log_esp3d_e("Serial %d begin for %d failed, index out of range", + _serialIndex, _id); return false; + } + _lastflush = millis(); + // read from settings + long br = 0; + long defaultBr = 0; + switch (_id) { + case MAIN_SERIAL: + br = Settings_ESP3D::read_uint32(ESP_BAUD_RATE); + defaultBr = Settings_ESP3D::get_default_int32_value(ESP_BAUD_RATE); + break; +#if defined(ESP_SERIAL_BRIDGE_OUTPUT) + case BRIDGE_SERIAL: + br = Settings_ESP3D::read_uint32(ESP_SERIAL_BRIDGE_BAUD); + defaultBr = + Settings_ESP3D::get_default_int32_value(ESP_SERIAL_BRIDGE_BAUD); + break; +#endif // ESP_SERIAL_BRIDGE_OUTPUT + default: + log_esp3d_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); + _buffer_size = 0; + // change only if different from current + if (br != baudRate() || (_rxPin != -1) || (_txPin != -1)) { + if (!is_valid_baudrate(br)) { + br = defaultBr; + } + Serials[_serialIndex]->setRxBufferSize(SERIAL_RX_BUFFER_SIZE); +#ifdef ARDUINO_ARCH_ESP8266 + Serials[_serialIndex]->begin(br, ESP_SERIAL_PARAM, SERIAL_FULL, + (_txPin == -1) ? 1 : _txPin); + if (_rxPin != -1) { + Serials[_serialIndex]->pins((_txPin == -1) ? 1 : _txPin, _rxPin); + } + +#endif // ARDUINO_ARCH_ESP8266 +#if defined(ARDUINO_ARCH_ESP32) + 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); + if (_hserialtask == nullptr && _id == MAIN_SERIAL) { + xTaskCreatePinnedToCore( + ESP3DSerialTaskfn, /* Task function. */ + "ESP3D Serial Task", /* name of task. */ + 8192, /* Stack size of task */ + NULL, /* parameter of the task */ + ESP3DSERIAL_RUNNING_PRIORITY, /* priority of the task */ + &_hserialtask, /* Task handle to keep track of created task */ + ESP3DSERIAL_RUNNING_CORE /* Core to run the task */ + ); + } + if (_hserialtask == nullptr) { + log_esp3d_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); + return true; +} +// End serial +bool SerialService::end() { + flush(); + delay(100); + swap(); + Serials[_serialIndex]->end(); + _buffer_size = 0; + _started = false; + return true; } -//Function which could be called in other loop -void SerialService::process() -{ - if (!_started) { - return; - } - //Do we have some data waiting - size_t len = available(); - if (len > 0) { - //if yes read them - log_esp3d("Got %d chars in serial", len); - 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_SERIAL_FLUSH) && (_buffer_size > 0)) { - flushbuffer(); - } +// return the array of long and array size +const long *SerialService::get_baudratelist(uint8_t *count) { + if (count) { + *count = sizeof(SupportedBaudList) / sizeof(long); + } + return SupportedBaudList; } -//Function which could be called in other loop -void SerialService::handle() -{ - //the serial bridge do not use independant task - //not sure if it is sill necessary to do it for the main serial - //TBC.. +// check if value is in baudrate list +bool SerialService::is_valid_baudrate(long br) { + uint8_t listesize = sizeof(SupportedBaudList) / sizeof(long); + for (uint8_t i = 0; i < listesize; i++) { + if (SupportedBaudList[i] == br) { + return true; + } + } + return false; +} + +// Function which could be called in other loop +void SerialService::process() { + if (!_started) { + return; + } + // Do we have some data waiting + size_t len = available(); + if (len > 0) { + // if yes read them + log_esp3d("Got %d chars in serial", len); + 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_SERIAL_FLUSH) && (_buffer_size > 0)) { + flushbuffer(); + } +} + +// Function which could be called in other loop +void SerialService::handle() { + // the serial bridge do not use independant task + // not sure if it is sill necessary to do it for the main serial + // TBC.. #if defined(ARDUINO_ARCH_ESP32) && defined(SERIAL_INDEPENDANT_TASK) - if (_id==MAIN_SERIAL) { - return; - } -#endif //ARDUINO_ARCH_ESP32 && SERIAL_INDEPENDANT_TASK0 - process(); + if (_id == MAIN_SERIAL) { + return; + } +#endif // ARDUINO_ARCH_ESP32 && SERIAL_INDEPENDANT_TASK0 + process(); } -void SerialService::flushbuffer() -{ - ESP3DOutput output(_client); - _buffer[_buffer_size] = 0x0; - //dispatch command - if (_started) { - esp3d_commands.process(_buffer, _buffer_size, &output,_needauthentication?LEVEL_GUEST:LEVEL_ADMIN); - } - _lastflush = millis(); - _buffer_size = 0; +void SerialService::flushbuffer() { + ESP3DOutput output(_client); + _buffer[_buffer_size] = 0x0; + // dispatch command + if (_started) { + esp3d_commands.process(_buffer, _buffer_size, &output, + _needauthentication ? LEVEL_GUEST : LEVEL_ADMIN); + } + _lastflush = millis(); + _buffer_size = 0; } -//push collected data to buffer and proceed accordingly -void SerialService::push2buffer(uint8_t * sbuf, size_t len) -{ - if (!_started) { - return; - } - log_esp3d("buffer get %d data ", len); +// push collected data to buffer and proceed accordingly +void SerialService::push2buffer(uint8_t *sbuf, size_t len) { + if (!_started) { + return; + } + log_esp3d("buffer get %d data ", len); #if COMMUNICATION_PROTOCOL == MKS_SERIAL - static bool isFrameStarted = false; - static bool isCommandFrame = false; - static uint8_t type; - //expected size - static int16_t framePos = -1; - //currently received - static uint datalen = 0; - for (size_t i = 0; i < len; i++) { - log_esp3d("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]); - if(MKSService::isFrame(char(sbuf[i]))) { - if (MKSService::isCommand(char(sbuf[i]))) { - isCommandFrame =true; - log_esp3d("type: Command"); - } else { - log_esp3d("type: other"); - type = sbuf[i]; - isCommandFrame =false; - } - } else { - log_esp3d("wrong frame type"); - isFrameStarted = false; - _buffer_size = 0; - } - } else if ((framePos==2) || (framePos==3)) { - //add size to int - if (framePos==2) { - datalen = sbuf[i]; - } else { - datalen += (sbuf[i]<<8); - log_esp3d("Data len: %d", datalen); - if (datalen > (ESP3D_SERIAL_BUFFER_SIZE -5)) { - log_esp3d("Overflow in data len"); - isFrameStarted = false; - _buffer_size = 0; - } - } - } else if (MKSService::isTail(char(sbuf[i]))) { - log_esp3d("got tail"); - _buffer[_buffer_size]='\0'; - log_esp3d("size is %d", _buffer_size); - //let check integrity - if (_buffer_size == datalen) { - log_esp3d("Flushing buffer"); - if (isCommandFrame) { - flushbuffer(); - } else { - MKSService::handleFrame(type,(const uint8_t*)_buffer, _buffer_size); - } - } else { - log_esp3d("Error in data len"); - } - //clear frame infos - _buffer_size = 0; - isFrameStarted = false; - - } else { - //it is data - if (_buffer_size < ESP3D_SERIAL_BUFFER_SIZE -5) { - _buffer[_buffer_size] = sbuf[i]; - _buffer_size++; - } else { - log_esp3d("Overflow in data len"); - isFrameStarted = false; - _buffer_size = 0; - } - - } + static bool isFrameStarted = false; + static bool isCommandFrame = false; + static uint8_t type; + // expected size + static int16_t framePos = -1; + // currently received + static uint datalen = 0; + for (size_t i = 0; i < len; i++) { + log_esp3d("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]); + if (MKSService::isFrame(char(sbuf[i]))) { + if (MKSService::isCommand(char(sbuf[i]))) { + isCommandFrame = true; + log_esp3d("type: Command"); + } else { + log_esp3d("type: other"); + type = sbuf[i]; + isCommandFrame = false; + } } else { - //frame is not started let see if it is a head - if (MKSService::isHead(char(sbuf[i]))) { - log_esp3d("got head"); - //yes it is - isFrameStarted = true; - framePos =0; - _buffer_size = 0; - } else { - //no so let reset all and just ignore it - //TODO should we handle these data ? - log_esp3d("Unidentified data : %c %x", sbuf[i],sbuf[i]); - isCommandFrame = false; - framePos = -1; - datalen = 0; - } + log_esp3d_e("wrong frame type"); + isFrameStarted = false; + _buffer_size = 0; } + } else if ((framePos == 2) || (framePos == 3)) { + // add size to int + if (framePos == 2) { + datalen = sbuf[i]; + } else { + datalen += (sbuf[i] << 8); + log_esp3d("Data len: %d", datalen); + if (datalen > (ESP3D_SERIAL_BUFFER_SIZE - 5)) { + log_esp3d_e("Overflow in data len"); + isFrameStarted = false; + _buffer_size = 0; + } + } + } else if (MKSService::isTail(char(sbuf[i]))) { + log_esp3d("got tail"); + _buffer[_buffer_size] = '\0'; + log_esp3d("size is %d", _buffer_size); + // let check integrity + if (_buffer_size == datalen) { + log_esp3d("Flushing buffer"); + if (isCommandFrame) { + flushbuffer(); + } else { + MKSService::handleFrame(type, (const uint8_t *)_buffer, + _buffer_size); + } + } else { + log_esp3d_e("Error in data len"); + } + // clear frame infos + _buffer_size = 0; + isFrameStarted = false; + + } else { + // it is data + if (_buffer_size < ESP3D_SERIAL_BUFFER_SIZE - 5) { + _buffer[_buffer_size] = sbuf[i]; + _buffer_size++; + } else { + log_esp3d_e("Overflow in data len"); + isFrameStarted = false; + _buffer_size = 0; + } + } + } else { + // frame is not started let see if it is a head + if (MKSService::isHead(char(sbuf[i]))) { + log_esp3d("got head"); + // yes it is + isFrameStarted = true; + framePos = 0; + _buffer_size = 0; + } 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]); + isCommandFrame = false; + framePos = -1; + datalen = 0; + } } + } #else - 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_SERIAL_BUFFER_SIZE) { - _buffer[_buffer_size] = sbuf[i]; - _buffer_size++; - } - flushbuffer(); - } else if (isPrintable (char(sbuf[i]) )) { - if (_buffer_size < ESP3D_SERIAL_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(); - } + 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_SERIAL_BUFFER_SIZE) { + _buffer[_buffer_size] = sbuf[i]; + _buffer_size++; + } + flushbuffer(); + } else if (isPrintable(char(sbuf[i]))) { + if (_buffer_size < ESP3D_SERIAL_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(); } + } #endif } -//Reset Serial Setting (baud rate) -bool SerialService::reset() -{ - log_esp3d("Reset serial"); - bool res = false; - switch (_id) { +// Reset Serial Setting (baud rate) +bool SerialService::reset() { + log_esp3d("Reset serial"); + bool res = false; + switch (_id) { case MAIN_SERIAL: - return Settings_ESP3D::write_uint32 (ESP_BAUD_RATE, Settings_ESP3D::get_default_int32_value(ESP_BAUD_RATE)); + return Settings_ESP3D::write_uint32( + ESP_BAUD_RATE, + Settings_ESP3D::get_default_int32_value(ESP_BAUD_RATE)); #if defined(ESP_SERIAL_BRIDGE_OUTPUT) case BRIDGE_SERIAL: - res = Settings_ESP3D::write_byte (ESP_SERIAL_BRIDGE_ON, Settings_ESP3D::get_default_byte_value(ESP_SERIAL_BRIDGE_ON)); - return res && Settings_ESP3D::write_uint32 (ESP_SERIAL_BRIDGE_BAUD, Settings_ESP3D::get_default_int32_value(ESP_SERIAL_BRIDGE_BAUD)); -#endif //ESP_SERIAL_BRIDGE_OUTPUT + res = Settings_ESP3D::write_byte( + ESP_SERIAL_BRIDGE_ON, + Settings_ESP3D::get_default_byte_value(ESP_SERIAL_BRIDGE_ON)); + return res && Settings_ESP3D::write_uint32( + ESP_SERIAL_BRIDGE_BAUD, + Settings_ESP3D::get_default_int32_value( + ESP_SERIAL_BRIDGE_BAUD)); +#endif // ESP_SERIAL_BRIDGE_OUTPUT default: - return res; - } + return res; + } } -void SerialService::updateBaudRate(long br) -{ - if (br!=baudRate()) { - Serials[_serialIndex]->flush(); - Serials[_serialIndex]->updateBaudRate(br); - } -} - -//Get current baud rate -long SerialService::baudRate() -{ - long br = 0; - br = Serials[_serialIndex]->baudRate(); -#ifdef ARDUINO_ARCH_ESP32 - //workaround for ESP32 - if (br == 115201) { - br = 115200; - } - if (br == 230423) { - br = 230400; - } -#endif //ARDUINO_ARCH_ESP32 - 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) -{ - if (!_started) { - return 0; - } - if ((uint)Serials[_serialIndex]->availableForWrite() >= size) { - return Serials[_serialIndex]->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 = Serials[_serialIndex]->availableForWrite(); - if(available>0) { - //in case less is sent - available = Serials[_serialIndex]->write(&buffertmp[sizesent], (available >= sizetosend)?sizetosend:available); - sizetosend-=available; - sizesent+=available; - starttime=millis(); - } else { - Hal::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) -{ - if (!_started) { - return -1; - } - return Serials[_serialIndex]->readBytes(sbuf, len); -} - -void SerialService::flush() -{ - if (!_started) { - return ; - } +void SerialService::updateBaudRate(long br) { + if (br != baudRate()) { Serials[_serialIndex]->flush(); + Serials[_serialIndex]->updateBaudRate(br); + } } -void SerialService::swap() -{ +// Get current baud rate +long SerialService::baudRate() { + long br = 0; + br = Serials[_serialIndex]->baudRate(); +#ifdef ARDUINO_ARCH_ESP32 + // workaround for ESP32 + if (br == 115201) { + br = 115200; + } + if (br == 230423) { + br = 230400; + } +#endif // ARDUINO_ARCH_ESP32 + 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) { + if (!_started) { + return 0; + } + if ((uint)Serials[_serialIndex]->availableForWrite() >= size) { + return Serials[_serialIndex]->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 = Serials[_serialIndex]->availableForWrite(); + if (available > 0) { + // in case less is sent + available = Serials[_serialIndex]->write( + &buffertmp[sizesent], + (available >= sizetosend) ? sizetosend : available); + sizetosend -= available; + sizesent += available; + starttime = millis(); + } else { + Hal::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) { + if (!_started) { + return -1; + } + return Serials[_serialIndex]->readBytes(sbuf, len); +} + +void SerialService::flush() { + if (!_started) { + return; + } + Serials[_serialIndex]->flush(); +} + +void SerialService::swap() { #ifdef ARDUINO_ARCH_ESP8266 - Serials[_serialIndex]->swap(); -#endif //ARDUINO_ARCH_ESP8266 + Serials[_serialIndex]->swap(); +#endif // ARDUINO_ARCH_ESP8266 } -#endif //COMMUNICATION_PROTOCOL == MKS_SERIAL || COMMUNICATION_PROTOCOL == RAW_SERIAL +#endif // COMMUNICATION_PROTOCOL == MKS_SERIAL || COMMUNICATION_PROTOCOL == + // RAW_SERIAL diff --git a/esp3d/src/modules/serial2socket/serial2socket.cpp b/esp3d/src/modules/serial2socket/serial2socket.cpp index 028ed076..81836b6f 100644 --- a/esp3d/src/modules/serial2socket/serial2socket.cpp +++ b/esp3d/src/modules/serial2socket/serial2socket.cpp @@ -18,196 +18,158 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -//#define ESP_DEBUG_FEATURE DEBUG_OUTPUT_SERIAL0 +// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 #include "../../include/esp3d_config.h" #if defined(ESP3DLIB_ENV) && COMMUNICATION_PROTOCOL == SOCKET_SERIAL #include -#include "serial2socket.h" -#include "../../core/esp3doutput.h" + #include "../../core/commands.h" +#include "../../core/esp3doutput.h" +#include "serial2socket.h" Serial_2_Socket Serial2Socket; +Serial_2_Socket::Serial_2_Socket() { end(); } +Serial_2_Socket::~Serial_2_Socket() { end(); } +void Serial_2_Socket::begin(long speed) { end(); } -Serial_2_Socket::Serial_2_Socket() -{ - end(); -} -Serial_2_Socket::~Serial_2_Socket() -{ - end(); -} -void Serial_2_Socket::begin(long speed) -{ - end(); -} +void Serial_2_Socket::enable(bool enable) { _started = enable; } -void Serial_2_Socket::enable(bool enable) -{ - _started = enable; -} - -void Serial_2_Socket::pause(bool state) -{ - _paused = state; - if (_paused) { - _TXbufferSize = 0; - _RXbufferSize = 0; - _RXbufferpos = 0; - } else { - _lastflush = millis(); - } -} - -bool Serial_2_Socket::isPaused() -{ - return _paused; -} - -void Serial_2_Socket::end() -{ +void Serial_2_Socket::pause(bool state) { + _paused = state; + if (_paused) { _TXbufferSize = 0; _RXbufferSize = 0; _RXbufferpos = 0; - _started = false; - _paused = false; + } else { _lastflush = millis(); + } } -long Serial_2_Socket::baudRate() -{ +bool Serial_2_Socket::isPaused() { return _paused; } + +void Serial_2_Socket::end() { + _TXbufferSize = 0; + _RXbufferSize = 0; + _RXbufferpos = 0; + _started = false; + _paused = false; + _lastflush = millis(); +} + +long Serial_2_Socket::baudRate() { return 0; } + +bool Serial_2_Socket::started() { return _started; } + +Serial_2_Socket::operator bool() const { return true; } + +int Serial_2_Socket::available() { + if (_paused) { return 0; + } + return _RXbufferSize; } -bool Serial_2_Socket::started() -{ - return _started; +size_t Serial_2_Socket::write(uint8_t c) { + if (!_started || _paused) { + return 1; + } + return write(&c, 1); } -Serial_2_Socket::operator bool() const -{ - return true; -} - -int Serial_2_Socket::available() -{ - if (_paused) { - return 0; - } - return _RXbufferSize; -} - - -size_t Serial_2_Socket::write(uint8_t c) -{ - if (!_started || _paused) { - return 1; - } - return write(&c,1); -} - -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"); - return size; - } - if (_TXbufferSize==0) { - _lastflush = millis(); - } - //send full line - if (_TXbufferSize + size > S2S_TXBUFFERSIZE) { - flush(); - } - //need periodic check to force to flush in case of no end - for (int i = 0; i < size; i++) { - _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); - flush(); - } - } - handle_flush(); +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"); return size; + } + if (_TXbufferSize == 0) { + _lastflush = millis(); + } + // send full line + if (_TXbufferSize + size > S2S_TXBUFFERSIZE) { + flush(); + } + // need periodic check to force to flush in case of no end + for (int i = 0; i < size; i++) { + _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); + flush(); + } + } + handle_flush(); + return size; } -int Serial_2_Socket::peek(void) -{ - if (_RXbufferSize > 0 && _started) { - return _RXbuffer[_RXbufferpos]; - } else { - return -1; - } +int Serial_2_Socket::peek(void) { + if (_RXbufferSize > 0 && _started) { + return _RXbuffer[_RXbufferpos]; + } else { + return -1; + } } -bool Serial_2_Socket::push (const uint8_t *buffer, size_t size) -{ - if (buffer == NULL || size == 0 || !_started || _paused) { - return false; - } - int data_size = size; - if ((data_size + _RXbufferSize) <= S2S_RXBUFFERSIZE) { - int current = _RXbufferpos + _RXbufferSize; - if (current > S2S_RXBUFFERSIZE) { - current = current - S2S_RXBUFFERSIZE; - } - for (int i = 0; i < data_size; i++) { - if (current > (S2S_RXBUFFERSIZE-1)) { - current = 0; - } - _RXbuffer[current] = buffer[i]; - current ++; - } - _RXbufferSize+=size; - _RXbuffer[current] = 0; - return true; - } +bool Serial_2_Socket::push(const uint8_t *buffer, size_t size) { + if (buffer == NULL || size == 0 || !_started || _paused) { return false; -} - -int Serial_2_Socket::read(void) -{ - if (_RXbufferSize > 0 && _started && !_paused) { - int v = _RXbuffer[_RXbufferpos]; - _RXbufferpos++; - if (_RXbufferpos > (S2S_RXBUFFERSIZE-1)) { - _RXbufferpos = 0; - } - _RXbufferSize--; - return v; - } else { - return -1; + } + int data_size = size; + if ((data_size + _RXbufferSize) <= S2S_RXBUFFERSIZE) { + int current = _RXbufferpos + _RXbufferSize; + if (current > S2S_RXBUFFERSIZE) { + current = current - S2S_RXBUFFERSIZE; } - -} - -void Serial_2_Socket::handle() -{ - handle_flush(); -} - -void Serial_2_Socket::handle_flush() -{ - if (_TXbufferSize > 0 && _started && !_paused) { - if ((_TXbufferSize>=S2S_TXBUFFERSIZE) || ((millis()- _lastflush) > S2S_FLUSHTIMEOUT)) { - log_esp3d("force socket flush"); - flush(); - } - } -} -void Serial_2_Socket::flush(void) -{ - if (_TXbufferSize > 0 && _started && !_paused) { - ESP3DOutput output(ESP_SOCKET_SERIAL_CLIENT); - //dispatch command - esp3d_commands.process(_TXbuffer,_TXbufferSize, &output); - //refresh timout - _lastflush = millis(); - //reset buffer - _TXbufferSize = 0; + for (int i = 0; i < data_size; i++) { + if (current > (S2S_RXBUFFERSIZE - 1)) { + current = 0; + } + _RXbuffer[current] = buffer[i]; + current++; } + _RXbufferSize += size; + _RXbuffer[current] = 0; + return true; + } + return false; } -#endif // ESP3DLIB_ENV +int Serial_2_Socket::read(void) { + if (_RXbufferSize > 0 && _started && !_paused) { + int v = _RXbuffer[_RXbufferpos]; + _RXbufferpos++; + if (_RXbufferpos > (S2S_RXBUFFERSIZE - 1)) { + _RXbufferpos = 0; + } + _RXbufferSize--; + return v; + } else { + return -1; + } +} + +void Serial_2_Socket::handle() { handle_flush(); } + +void Serial_2_Socket::handle_flush() { + if (_TXbufferSize > 0 && _started && !_paused) { + if ((_TXbufferSize >= S2S_TXBUFFERSIZE) || + ((millis() - _lastflush) > S2S_FLUSHTIMEOUT)) { + log_esp3d("force socket flush"); + flush(); + } + } +} +void Serial_2_Socket::flush(void) { + if (_TXbufferSize > 0 && _started && !_paused) { + ESP3DOutput output(ESP_SOCKET_SERIAL_CLIENT); + // dispatch command + esp3d_commands.process(_TXbuffer, _TXbufferSize, &output); + // refresh timout + _lastflush = millis(); + // reset buffer + _TXbufferSize = 0; + } +} + +#endif // ESP3DLIB_ENV diff --git a/esp3d/src/modules/time/time_server.cpp b/esp3d/src/modules/time/time_server.cpp index 8e44a64b..4386c11e 100644 --- a/esp3d/src/modules/time/time_server.cpp +++ b/esp3d/src/modules/time/time_server.cpp @@ -164,7 +164,7 @@ bool TimeServer::setTime(const char* stime) { log_esp3d("Invalid time format, try without seconds"); // allow not to set seconds for lazy guys typing command line if (strptime(stime, "%Y-%m-%dT%H:%M", &tmstruct) == nullptr) { - log_esp3d("Invalid time format"); + log_esp3d_e("Invalid time format"); return false; } } diff --git a/esp3d/src/modules/update/esp_config_file.cpp b/esp3d/src/modules/update/esp_config_file.cpp index 768affe0..91f1e7eb 100644 --- a/esp3d/src/modules/update/esp_config_file.cpp +++ b/esp3d/src/modules/update/esp_config_file.cpp @@ -21,255 +21,245 @@ #include "../../include/esp3d_config.h" #ifdef SD_UPDATE_FEATURE -#include "esp_config_file.h" #include "../filesystem/esp_sd.h" +#include "esp_config_file.h" -#define LINE_MAX_SIZE 255 -#define SECTION_MAX_SIZE 10 -#define KEY_MAX_SIZE 30 -#define VALUE_MAX_SIZE 128 +#define LINE_MAX_SIZE 255 +#define SECTION_MAX_SIZE 10 +#define KEY_MAX_SIZE 30 +#define VALUE_MAX_SIZE 128 -const char * protectedkeys[] = {"NOTIF_TOKEN1","NOTIF_TOKEN2","AP_Password","STA_Password","ADMIN_PASSWORD","USER_PASSWORD"} ; +const char *protectedkeys[] = {"NOTIF_TOKEN1", "NOTIF_TOKEN2", + "AP_Password", "STA_Password", + "ADMIN_PASSWORD", "USER_PASSWORD"}; -ESP_ConfigFile::ESP_ConfigFile(const char * path, TProcessingFunction fn) -{ - _filename = (char *)malloc(strlen(path)+1); - strcpy(_filename, path); - _pfunction = fn; +ESP_ConfigFile::ESP_ConfigFile(const char *path, TProcessingFunction fn) { + _filename = (char *)malloc(strlen(path) + 1); + strcpy(_filename, path); + _pfunction = fn; } -bool ESP_ConfigFile::processFile() -{ - bool res = true; - if (!ESP_SD::exists(_filename)) { - log_esp3d("No ini file"); - return false; - } - ESP_SDFile rFile = ESP_SD::open(_filename); - if (rFile) { - bool processing = true; - char line[LINE_MAX_SIZE+1]; - char section[SECTION_MAX_SIZE+1]; //system / network / services - char key[KEY_MAX_SIZE+1]; - uint8_t pos = 0; - line[0] = '\0'; - section[0]='\0'; - while (processing) { - //to handle file without endline - processing = rFile.available(); - char c = '\0'; - if (processing) { - c = (char)rFile.read(); - if (!((c =='\n') || (c =='\r')) && (pos<(LINE_MAX_SIZE-1))) { - line[pos] = c; - pos++; - } - } - if ((c =='\n') || (c =='\r') || !processing || (pos==(LINE_MAX_SIZE-1))) { - line[pos] = '\0'; - char * stmp = trimSpaces(line); - if(strlen(stmp)>0) { - //is comment ? - if (!isComment(stmp)) { - //is section ? - if(isSection(stmp)) { - strcpy(section,getSectionName(stmp)); - } else { - //is key + value? - if (isValue(stmp) && strlen(section)>0) { - strcpy(key,getKeyName(stmp)); - if(_pfunction) { - if(!_pfunction(section, key, getValue(stmp))) { - res=false; - } - } - } - } - } - } - pos = 0; - line[pos] = '\0'; - } - } - rFile.close(); - return res; - } - log_esp3d("Cannot open ini file"); +bool ESP_ConfigFile::processFile() { + bool res = true; + if (!ESP_SD::exists(_filename)) { + log_esp3d_e("No ini file"); return false; -} - -bool ESP_ConfigFile::isComment(char * line) -{ - if (strlen(line) > 0) { - if((line[0]==';') || (line[0]=='#')) { - return true; + } + ESP_SDFile rFile = ESP_SD::open(_filename); + if (rFile) { + bool processing = true; + char line[LINE_MAX_SIZE + 1]; + char section[SECTION_MAX_SIZE + 1]; // system / network / services + char key[KEY_MAX_SIZE + 1]; + uint8_t pos = 0; + line[0] = '\0'; + section[0] = '\0'; + while (processing) { + // to handle file without endline + processing = rFile.available(); + char c = '\0'; + if (processing) { + c = (char)rFile.read(); + if (!((c == '\n') || (c == '\r')) && (pos < (LINE_MAX_SIZE - 1))) { + line[pos] = c; + pos++; } - } - return false; -} - -bool ESP_ConfigFile::isSection(char * line) -{ - if (strlen(line) > 0) { - if((line[0]=='[') && (line[strlen(line)-1]==']')) { - return true; - } - } - return false; -} - -bool ESP_ConfigFile::isValue(char * line) -{ - if (strlen(line) > 3) { - for(uint8_t i = 1; i < strlen(line)-2; i++) { - if(line[i]=='=') { - return true; - } - } - } - return false; -} - -char * ESP_ConfigFile::getSectionName(char * line) -{ - line[strlen(line)-1]='\0'; - return trimSpaces(&line[1],SECTION_MAX_SIZE); -} - -char * ESP_ConfigFile::getKeyName(char * line) -{ - for(uint8_t i = 0; i < strlen(line); i++) { - if (line[i]=='=') { - line[i]='\0'; - return trimSpaces(line,KEY_MAX_SIZE); - } - } - return NULL; -} - -char * ESP_ConfigFile::getValue(char * line) -{ - char * startptr = line + strlen(line)+1; - while ( * startptr == '\0') { - startptr++; - } - return trimSpaces(startptr,VALUE_MAX_SIZE); -} - -char * ESP_ConfigFile::trimSpaces(char * line, uint8_t maxsize) -{ - char *endptr = line + strlen(line) - 1; - char * startptr = line; - while (endptr >= line && isspace(*endptr)) { - *endptr-- = '\0'; - } - endptr = line + strlen(line) - 1; - while (endptr != startptr && isspace(*startptr)) { - startptr++; - } - if((maxsize>0) && (strlen(startptr)> maxsize)) { - startptr[maxsize]='\0'; - } - return startptr; -} - -ESP_ConfigFile::~ESP_ConfigFile() -{ - free(_filename); -} - -bool ESP_ConfigFile::isScrambleKey(const char *key, const char * str) -{ - if (strlen(key)>strlen(str)) { - return false; - } - for(uint8_t p = 0; p< strlen(str) ; p++) { - if (p 0) { + // is comment ? + if (!isComment(stmp)) { + // is section ? + if (isSection(stmp)) { + strcpy(section, getSectionName(stmp)); + } else { + // is key + value? + if (isValue(stmp) && strlen(section) > 0) { + strcpy(key, getKeyName(stmp)); + if (_pfunction) { + if (!_pfunction(section, key, getValue(stmp))) { + res = false; + } } + } } + } } + pos = 0; + line[pos] = '\0'; + } } - - return false; + rFile.close(); + return res; + } + log_esp3d_e("Cannot open ini file"); + return false; } -bool ESP_ConfigFile::revokeFile() -{ - char * filename; - if (!ESP_SD::exists(_filename)) { - log_esp3d("No ini file to revoke"); - return false; +bool ESP_ConfigFile::isComment(char *line) { + if (strlen(line) > 0) { + if ((line[0] == ';') || (line[0] == '#')) { + return true; } - filename = (char *)malloc(strlen(_filename)+1); - strcpy(filename, _filename); - filename[strlen(filename)-3]='o'; - filename[strlen(filename)-2]='k'; - filename[strlen(filename)-1]='\0'; - ESP_SD::remove(filename); - ESP_SDFile wFile = ESP_SD::open(filename, ESP_FILE_WRITE); - ESP_SDFile rFile = ESP_SD::open(_filename); - free(filename); - if (wFile && rFile) { - bool processing = true; - char line[LINE_MAX_SIZE+1]; - uint8_t pos = 0; - line[0] = '\0'; - while (processing) { - processing = rFile.available(); - char c = '\0'; - if (processing) { - c = (char)rFile.read(); - if (!((c =='\n') || (c =='\r')) && (pos<(LINE_MAX_SIZE-1))) { - line[pos] = c; - pos++; - } - } - if ((c =='\n') || (c =='\r') || !processing || (pos==(LINE_MAX_SIZE-1))) { - line[pos] = '\0'; - char * stmp = trimSpaces(line); - if (strlen(stmp) > 0 ) { - if(sizeof(protectedkeys) > 0) { - bool foundscramble = false; - uint8_t size = sizeof(protectedkeys)/sizeof(char*); - for(uint8_t i = 0; (i < size) && !foundscramble; i++) { - if (isScrambleKey(protectedkeys[i],stmp)) { - strcpy(line, protectedkeys[i]); - strcat(line, "=********"); - stmp = line; - foundscramble = true; - } - } - } - wFile.write((const uint8_t *)stmp, strlen(stmp)); - wFile.write('\r'); - wFile.write('\n'); - } - pos = 0; - line[pos] = '\0'; - } - } - wFile.close(); - rFile.close(); - ESP_SD::remove(_filename); + } + return false; +} + +bool ESP_ConfigFile::isSection(char *line) { + if (strlen(line) > 0) { + if ((line[0] == '[') && (line[strlen(line) - 1] == ']')) { + return true; + } + } + return false; +} + +bool ESP_ConfigFile::isValue(char *line) { + if (strlen(line) > 3) { + for (uint8_t i = 1; i < strlen(line) - 2; i++) { + if (line[i] == '=') { return true; + } } - log_esp3d("Cannot open / create revoked file"); - if (wFile ) { - wFile.close(); - } - if (rFile ) { - rFile.close(); - } - return false; + } + return false; } -#endif //SD_UPDATE_FEATURE +char *ESP_ConfigFile::getSectionName(char *line) { + line[strlen(line) - 1] = '\0'; + return trimSpaces(&line[1], SECTION_MAX_SIZE); +} + +char *ESP_ConfigFile::getKeyName(char *line) { + for (uint8_t i = 0; i < strlen(line); i++) { + if (line[i] == '=') { + line[i] = '\0'; + return trimSpaces(line, KEY_MAX_SIZE); + } + } + return NULL; +} + +char *ESP_ConfigFile::getValue(char *line) { + char *startptr = line + strlen(line) + 1; + while (*startptr == '\0') { + startptr++; + } + return trimSpaces(startptr, VALUE_MAX_SIZE); +} + +char *ESP_ConfigFile::trimSpaces(char *line, uint8_t maxsize) { + char *endptr = line + strlen(line) - 1; + char *startptr = line; + while (endptr >= line && isspace(*endptr)) { + *endptr-- = '\0'; + } + endptr = line + strlen(line) - 1; + while (endptr != startptr && isspace(*startptr)) { + startptr++; + } + if ((maxsize > 0) && (strlen(startptr) > maxsize)) { + startptr[maxsize] = '\0'; + } + return startptr; +} + +ESP_ConfigFile::~ESP_ConfigFile() { free(_filename); } + +bool ESP_ConfigFile::isScrambleKey(const char *key, const char *str) { + if (strlen(key) > strlen(str)) { + return false; + } + for (uint8_t p = 0; p < strlen(str); p++) { + if (p < strlen(key)) { + if (key[p] != str[p]) { + return false; + } + } else { + if (str[p] != ' ') { + if (str[p] == '=') { + return true; + } else { + return false; + } + } + } + } + + return false; +} + +bool ESP_ConfigFile::revokeFile() { + char *filename; + if (!ESP_SD::exists(_filename)) { + log_esp3d("No ini file to revoke"); + return false; + } + filename = (char *)malloc(strlen(_filename) + 1); + strcpy(filename, _filename); + filename[strlen(filename) - 3] = 'o'; + filename[strlen(filename) - 2] = 'k'; + filename[strlen(filename) - 1] = '\0'; + ESP_SD::remove(filename); + ESP_SDFile wFile = ESP_SD::open(filename, ESP_FILE_WRITE); + ESP_SDFile rFile = ESP_SD::open(_filename); + free(filename); + if (wFile && rFile) { + bool processing = true; + char line[LINE_MAX_SIZE + 1]; + uint8_t pos = 0; + line[0] = '\0'; + while (processing) { + processing = rFile.available(); + char c = '\0'; + if (processing) { + c = (char)rFile.read(); + if (!((c == '\n') || (c == '\r')) && (pos < (LINE_MAX_SIZE - 1))) { + line[pos] = c; + pos++; + } + } + if ((c == '\n') || (c == '\r') || !processing || + (pos == (LINE_MAX_SIZE - 1))) { + line[pos] = '\0'; + char *stmp = trimSpaces(line); + if (strlen(stmp) > 0) { + if (sizeof(protectedkeys) > 0) { + bool foundscramble = false; + uint8_t size = sizeof(protectedkeys) / sizeof(char *); + for (uint8_t i = 0; (i < size) && !foundscramble; i++) { + if (isScrambleKey(protectedkeys[i], stmp)) { + strcpy(line, protectedkeys[i]); + strcat(line, "=********"); + stmp = line; + foundscramble = true; + } + } + } + wFile.write((const uint8_t *)stmp, strlen(stmp)); + wFile.write('\r'); + wFile.write('\n'); + } + pos = 0; + line[pos] = '\0'; + } + } + wFile.close(); + rFile.close(); + ESP_SD::remove(_filename); + return true; + } + log_esp3d_e("Cannot open / create revoked file"); + if (wFile) { + wFile.close(); + } + if (rFile) { + rFile.close(); + } + return false; +} + +#endif // SD_UPDATE_FEATURE diff --git a/esp3d/src/modules/update/update_service.cpp b/esp3d/src/modules/update/update_service.cpp index b7c03ef7..9fa84a6b 100644 --- a/esp3d/src/modules/update/update_service.cpp +++ b/esp3d/src/modules/update/update_service.cpp @@ -20,21 +20,21 @@ #include "../../include/esp3d_config.h" #ifdef SD_UPDATE_FEATURE -#include "update_service.h" -#include "../../core/settings_esp3d.h" -#include "../../core/esp3doutput.h" #include "../../core/commands.h" -#include "esp_config_file.h" -#include "../filesystem/esp_sd.h" +#include "../../core/esp3doutput.h" +#include "../../core/settings_esp3d.h" #include "../filesystem/esp_filesystem.h" -#if defined (ARDUINO_ARCH_ESP32) +#include "../filesystem/esp_sd.h" +#include "esp_config_file.h" +#include "update_service.h" + +#if defined(ARDUINO_ARCH_ESP32) #include #define U_FS U_SPIFFS -#endif //ARDUINO_ARCH_ESP32 -#if defined (ARDUINO_ARCH_ESP8266) - -#endif //ARDUINO_ARCH_ESP8266 +#endif // ARDUINO_ARCH_ESP32 +#if defined(ARDUINO_ARCH_ESP8266) +#endif // ARDUINO_ARCH_ESP8266 UpdateService update_service; @@ -42,57 +42,32 @@ UpdateService update_service; #define FW_FILE "/esp3dfw.bin" #define FS_FILE "/esp3dfs.bin" -const char * NetstringKeysVal[] = {"hostname", - "STA_SSID", - "STA_Password", - "AP_SSID", - "AP_Password" - } ; +const char* NetstringKeysVal[] = {"hostname", "STA_SSID", "STA_Password", + "AP_SSID", "AP_Password"}; -const uint16_t NetstringKeysPos[] = {ESP_HOSTNAME, - ESP_STA_SSID, - ESP_STA_PASSWORD, - ESP_AP_SSID, - ESP_AP_PASSWORD - } ; +const uint16_t NetstringKeysPos[] = { + ESP_HOSTNAME, ESP_STA_SSID, ESP_STA_PASSWORD, ESP_AP_SSID, ESP_AP_PASSWORD}; -const char * ServstringKeysVal[] = { - "Time_server1", - "Time_server2", - "Time_server3", - "ADMIN_PASSWORD", - "USER_PASSWORD", - "NOTIF_TOKEN1", - "NOTIF_TOKEN2", - "NOTIF_TOKEN_Settings" -} ; +const char* ServstringKeysVal[] = { + "Time_server1", "Time_server2", "Time_server3", "ADMIN_PASSWORD", + "USER_PASSWORD", "NOTIF_TOKEN1", "NOTIF_TOKEN2", "NOTIF_TOKEN_Settings"}; -const uint16_t ServstringKeysPos[] = { - ESP_TIME_SERVER1, - ESP_TIME_SERVER2, - ESP_TIME_SERVER3, - ESP_ADMIN_PWD, - ESP_USER_PWD, - ESP_NOTIFICATION_TOKEN1, - ESP_NOTIFICATION_TOKEN2, - ESP_NOTIFICATION_SETTINGS -} ; +const uint16_t ServstringKeysPos[] = {ESP_TIME_SERVER1, + ESP_TIME_SERVER2, + ESP_TIME_SERVER3, + ESP_ADMIN_PWD, + ESP_USER_PWD, + ESP_NOTIFICATION_TOKEN1, + ESP_NOTIFICATION_TOKEN2, + ESP_NOTIFICATION_SETTINGS}; -const char * IPKeysVal[] = {"STA_IP", - "STA_GW", - "STA_MSK", - "STA_DNS", - "AP_IP" - } ; +const char* IPKeysVal[] = {"STA_IP", "STA_GW", "STA_MSK", "STA_DNS", "AP_IP"}; -const uint16_t IPKeysPos[] = {ESP_STA_IP_VALUE, - ESP_STA_GATEWAY_VALUE, - ESP_STA_MASK_VALUE, - ESP_STA_DNS_VALUE, - ESP_AP_IP_VALUE - } ; +const uint16_t IPKeysPos[] = {ESP_STA_IP_VALUE, ESP_STA_GATEWAY_VALUE, + ESP_STA_MASK_VALUE, ESP_STA_DNS_VALUE, + ESP_AP_IP_VALUE}; -const char * ServintKeysVal[] = { +const char* ServintKeysVal[] = { "Serial_Bridge_Baud" "HTTP_Port", "TELNET_Port", @@ -101,65 +76,48 @@ const char * ServintKeysVal[] = { "WebDav_Port", "FTP_Control_Port", "FTP_Active_Port ", - "FTP_Passive_Port" -} ; + "FTP_Passive_Port"}; const uint16_t ServintKeysPos[] = { - ESP_SERIAL_BRIDGE_BAUD, - ESP_HTTP_PORT, - ESP_TELNET_PORT, - ESP_SENSOR_INTERVAL, - ESP_WEBSOCKET_PORT, - ESP_WEBDAV_PORT, - ESP_FTP_CTRL_PORT, - ESP_FTP_DATA_ACTIVE_PORT, - ESP_FTP_DATA_PASSIVE_PORT -} ; + ESP_SERIAL_BRIDGE_BAUD, ESP_HTTP_PORT, + ESP_TELNET_PORT, ESP_SENSOR_INTERVAL, + ESP_WEBSOCKET_PORT, ESP_WEBDAV_PORT, + ESP_FTP_CTRL_PORT, ESP_FTP_DATA_ACTIVE_PORT, + ESP_FTP_DATA_PASSIVE_PORT}; -const char * SysintKeysVal[] = {"Baud_rate", - "Boot_delay" - } ; +const char* SysintKeysVal[] = {"Baud_rate", "Boot_delay"}; -const uint16_t SysintKeysPos[] = {ESP_BAUD_RATE, - ESP_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", + "Time_DST", + "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_TIME_IS_DST, 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[] = {"Active_Serial_Bridge", + "Active_Remote_Screen", + "Active_ESP3D_Screen", + "Active_Serial ", + "Active_WebSocket", + "Active_Telnet", + "Active_BT", + "Boot_verbose", + "Secure_serial"}; const uint16_t SysboolKeysPos[] = {ESP_SERIAL_BRIDGE_FLAG, ESP_REMOTE_SCREEN_FLAG, @@ -169,381 +127,389 @@ const uint16_t SysboolKeysPos[] = {ESP_SERIAL_BRIDGE_FLAG, ESP_TELNET_FLAG, ESP_BT_FLAG, ESP_VERBOSE_BOOT, - ESP_SECURE_SERIAL - } ; + ESP_SECURE_SERIAL}; -const char * NetbyteKeysVal[] = { - "AP_channel" -} ; +const char* NetbyteKeysVal[] = {"AP_channel"}; -const uint16_t NetbyteKeysPos[] = { - ESP_AP_CHANNEL -} ; -const char * ServbyteKeysVal[] = {"Time_zone", - "Sesion_timeout", - "SD_SPEED" - } ; +const uint16_t NetbyteKeysPos[] = {ESP_AP_CHANNEL}; +const char* ServbyteKeysVal[] = {"Time_zone", "Sesion_timeout", "SD_SPEED"}; -const uint16_t ServbyteKeysPos[] = {ESP_TIMEZONE, - ESP_SESSION_TIMEOUT, - ESP_SD_SPEED_DIV - } ; +const uint16_t ServbyteKeysPos[] = {ESP_TIMEZONE, ESP_SESSION_TIMEOUT, + ESP_SD_SPEED_DIV}; - -bool processString(const char** keysval, const uint16_t * keypos, const size_t size, const char * key, const char * value, char & T, int & P ) -{ - - for(uint i=0; i< size ; i++) { - if (strcasecmp(keysval[i],key)==0) { - //if it is a previouly saved scrambled password ignore it - if (strcasecmp(value,"********")!=0) { - T='S'; - P=keypos[i]; - return true; - } - } +bool processString(const char** keysval, const uint16_t* keypos, + const size_t size, const char* key, const char* value, + char& T, int& P) { + for (uint i = 0; i < size; i++) { + if (strcasecmp(keysval[i], key) == 0) { + // if it is a previouly saved scrambled password ignore it + if (strcasecmp(value, "********") != 0) { + T = 'S'; + P = keypos[i]; + return true; + } } - return false; + } + return false; } -bool processInt(const char** keysval, const uint16_t * keypos, const size_t size, const char * key, const char * value, char & T, int & P, uint32_t & v) -{ - for(uint i=0; i< size ; i++) { - if (strcasecmp(keysval[i],key)==0) { - T='I'; - P=keypos[i]; - v=String(value).toInt(); - return true; - } +bool processInt(const char** keysval, const uint16_t* keypos, const size_t size, + const char* key, const char* value, char& T, int& P, + uint32_t& v) { + for (uint i = 0; i < size; i++) { + if (strcasecmp(keysval[i], key) == 0) { + T = 'I'; + P = keypos[i]; + v = String(value).toInt(); + return true; } - return false; + } + return false; } -bool processBool(const char** keysval, const uint16_t * keypos, const size_t size, const char * key, const char * value, char & T, int & P, byte & b) -{ - for(uint i=0; i< size ; i++) { - if (strcasecmp(keysval[i],key)==0) { - T='B'; - P=keypos[i]; - if ((strcasecmp("yes",value)==0)||(strcasecmp("on", value)==0)||(strcasecmp("true", value)==0)||(strcasecmp("1", value)==0) ) { - b = 1; - } else if ((strcasecmp("no", value)==0)||(strcasecmp("off", value)==0)||(strcasecmp("false", value)==0)||(strcasecmp("0", value)==0) ) { - b = 0; - } else { - P=-1; - } - return true; - } +bool processBool(const char** keysval, const uint16_t* keypos, + const size_t size, const char* key, const char* value, char& T, + int& P, byte& b) { + for (uint i = 0; i < size; i++) { + if (strcasecmp(keysval[i], key) == 0) { + T = 'B'; + P = keypos[i]; + if ((strcasecmp("yes", value) == 0) || (strcasecmp("on", value) == 0) || + (strcasecmp("true", value) == 0) || (strcasecmp("1", value) == 0)) { + b = 1; + } else if ((strcasecmp("no", value) == 0) || + (strcasecmp("off", value) == 0) || + (strcasecmp("false", value) == 0) || + (strcasecmp("0", value) == 0)) { + b = 0; + } else { + P = -1; + } + return true; } - return false; + } + return false; } - - -//Parsing all entries of file once is faster that checking all possible parameters for each line of file -bool processingFileFunction (const char * section, const char * key, const char * value) -{ - bool res = true; - char T = '\0'; - int P = -1; - uint32_t v = 0; - byte b = 0; - bool done=false; - log_esp3d("[%s]%s=%s",section, key,value); - //network / services / system sections - if (strcasecmp("network",section)==0) { - if (!done) { - done = processString(NetstringKeysVal,NetstringKeysPos,sizeof(NetstringKeysVal)/sizeof(char*), key, value, T, P ); +// Parsing all entries of file once is faster that checking all possible +// parameters for each line of file +bool processingFileFunction(const char* section, const char* key, + const char* value) { + bool res = true; + char T = '\0'; + int P = -1; + uint32_t v = 0; + byte b = 0; + bool done = false; + log_esp3d("[%s]%s=%s", section, key, value); + // network / services / system sections + if (strcasecmp("network", section) == 0) { + if (!done) { + done = processString(NetstringKeysVal, NetstringKeysPos, + sizeof(NetstringKeysVal) / sizeof(char*), key, value, + T, P); + } + if (!done) { + done = processString(IPKeysVal, IPKeysPos, + sizeof(IPKeysVal) / sizeof(char*), key, value, T, P); + if (done) { + T = 'A'; + } + } + if (!done) { + done = processInt(NetbyteKeysVal, NetbyteKeysPos, + sizeof(NetbyteKeysVal) / sizeof(char*), key, value, T, + P, v); + if (done) { + T = 'B'; + b = v; + } + } + // Radio mode BT, WIFI-STA, WIFI-AP, ETH-STA, OFF + if (!done) { + if (strcasecmp("radio_mode", key) == 0) { + T = 'B'; + P = ESP_RADIO_MODE; + done = true; + if (strcasecmp("BT", value) == 0) { + b = ESP_BT; + } else if (strcasecmp("WIFI-STA", value) == 0) { + b = ESP_WIFI_STA; + } else if (strcasecmp("WIFI-AP", value) == 0) { + b = ESP_WIFI_AP; + } else if (strcasecmp("WIFI-SETUP", value) == 0) { + b = ESP_AP_SETUP; + } else if (strcasecmp("ETH-STA", value) == 0) { + b = ESP_ETH_STA; + } else if (strcasecmp("OFF", value) == 0) { + b = ESP_NO_NETWORK; + } else { + P = -1; // invalide value } - if (!done) { - done = processString(IPKeysVal,IPKeysPos,sizeof(IPKeysVal)/sizeof(char*), key, value, T, P ); - if(done) { - T='A'; - } - } - if (!done) { - done = processInt(NetbyteKeysVal,NetbyteKeysPos,sizeof(NetbyteKeysVal)/sizeof(char*), key, value, T, P, v); - if(done) { - T='B'; - b=v; - } - } - //Radio mode BT, WIFI-STA, WIFI-AP, ETH-STA, OFF - if (!done) { - if (strcasecmp("radio_mode",key)==0) { - T='B'; - P=ESP_RADIO_MODE; - done = true; - if (strcasecmp("BT",value)==0) { - b=ESP_BT; - } else if (strcasecmp("WIFI-STA",value)==0) { - b=ESP_WIFI_STA; - } else if (strcasecmp("WIFI-AP",value)==0) { - b=ESP_WIFI_AP; - } else if (strcasecmp("WIFI-SETUP",value)==0) { - b=ESP_AP_SETUP; - } else if (strcasecmp("ETH-STA",value)==0) { - b=ESP_ETH_STA; - } else if (strcasecmp("OFF",value)==0) { - b=ESP_NO_NETWORK; - } else { - P=-1; //invalide value - } - } - } - //STA fallback mode BT, WIFI-AP, OFF - if (!done) { - if (strcasecmp("sta_fallback",key)==0) { - T='B'; - P = ESP_STA_FALLBACK_MODE; - done = true; - if (strcasecmp("BT",value)==0) { - b=ESP_BT; - } else if (strcasecmp("WIFI-SETUP",value)==0) { - b=ESP_AP_SETUP; - } else if (strcasecmp("OFF",value)==0) { - b=ESP_NO_NETWORK; - } else { - P=-1; //invalide value - } - } - } - - //STA IP Mode DHCP / STATIC - if (!done) { - if (strcasecmp("STA_IP_mode",key)==0) { - T='B'; - P=ESP_STA_IP_MODE; - done = true; - if (strcasecmp("DHCP",value)==0) { - b=DHCP_MODE; - } else if (strcasecmp("STATIC",key)==0) { - b=STATIC_IP_MODE; - } else { - P=-1; //invalide value - } - } - } - } else if (strcasecmp("services",section)==0) { - if (!done) { - done = processString(ServstringKeysVal,ServstringKeysPos,sizeof(ServstringKeysVal)/sizeof(char*), key, value, T, P ); - } - if (!done) { - done = processInt(ServintKeysVal,ServintKeysPos,sizeof(ServintKeysVal)/sizeof(char*), key, value, T, P, v); - } - if (!done) { - done = processBool(ServboolKeysVal,ServboolKeysPos,sizeof(ServboolKeysVal)/sizeof(char*), key, value, T, P, b); - } - if (!done) { - done = processInt(ServbyteKeysVal,ServbyteKeysPos,sizeof(ServbyteKeysVal)/sizeof(char*), key, value, T, P, v); - if(done) { - T='B'; - b=v; - } - } - //Notification type None / PushOver / Line / Email / Telegram / IFTTT - if (!done) { - if (strcasecmp("NOTIF_TYPE",key)==0) { - T='B'; - P=ESP_NOTIFICATION_TYPE; - done = true; - if (strcasecmp("None",value)==0) { - b=ESP_NO_NOTIFICATION; - } else if (strcasecmp("PushOver",value)==0) { - b=ESP_PUSHOVER_NOTIFICATION; - } else if (strcasecmp("Line",value)==0) { - b=ESP_LINE_NOTIFICATION; - } else if (strcasecmp("Email",value)==0) { - b=ESP_EMAIL_NOTIFICATION; - } else if (strcasecmp("Telegram",value)==0) { - b=ESP_TELEGRAM_NOTIFICATION; - } else if (strcasecmp("IFTTT",value)==0) { - b=ESP_IFTTT_NOTIFICATION; - } else { - P=-1; //invalide value - } - } - } - //Sensor type if enabled None / DHT11 / DHT22 / ANALOG / BMP280 / BME280 - if (!done) { - if (strcasecmp("SENSOR_TYPE",key)==0) { - T='B'; - P=ESP_SENSOR_TYPE; - done = true; - if (strcasecmp("None",value)==0) { - b=NO_SENSOR_DEVICE; - } else if (strcasecmp("DHT11",key)==0) { - b=DHT11_DEVICE; - } else if (strcasecmp("DHT22",key)==0) { - b=DHT22_DEVICE; - } else if (strcasecmp("ANALOG",key)==0) { - b=ANALOG_DEVICE; - } else if (strcasecmp("BMP280",key)==0) { - b=BMP280_DEVICE; - } else if (strcasecmp("BME280",key)==0) { - b=BME280_DEVICE; - } else { - P=-1; //invalide value - } - } - } - } else if (strcasecmp("system",section)==0) { - if (!done) { - done = processInt(SysintKeysVal,SysintKeysPos,sizeof(SysintKeysVal)/sizeof(char*), key, value, T, P, v); - } - if (!done) { - done = processBool(SysboolKeysVal,SysboolKeysPos,sizeof(SysboolKeysVal)/sizeof(char*), key, value, T, P, b); - } - //Target Firmware None / Marlin / Repetier / MarlinKimbra / Smoothieware / GRBL - if (!done) { - if (strcasecmp("TargetFW",key)==0) { - T='B'; - P=ESP_TARGET_FW; - done = true; - if (strcasecmp("None",value)==0) { - b=UNKNOWN_FW; - } else if (strcasecmp("MARLIN",value)==0) { - b=MARLIN; - } else if (strcasecmp("GRBL",value)==0) { - b=GRBL; - } else if (strcasecmp("REPETIER",value)==0) { - b=REPETIER; - } else if (strcasecmp("SMOOTHIEWARE",value)==0) { - b=SMOOTHIEWARE; - } else { - P=-1; //invalide value - } - } + } + } + // STA fallback mode BT, WIFI-AP, OFF + if (!done) { + if (strcasecmp("sta_fallback", key) == 0) { + T = 'B'; + P = ESP_STA_FALLBACK_MODE; + done = true; + if (strcasecmp("BT", value) == 0) { + b = ESP_BT; + } else if (strcasecmp("WIFI-SETUP", value) == 0) { + b = ESP_AP_SETUP; + } else if (strcasecmp("OFF", value) == 0) { + b = ESP_NO_NETWORK; + } else { + P = -1; // invalide value } + } } - //now we save -handle saving status - //if setting is not recognized it is not a problem - //but if save is fail - that is a problem - so report it - if(P!=-1) { - switch(T) { - case 'S': - log_esp3d("Saving setting to ESP3D"); - res = Settings_ESP3D::write_string (P, value); - break; - case 'B': - case 'F': - res = Settings_ESP3D::write_byte (P, b); - break; - case 'I': - res = Settings_ESP3D::write_uint32 (P, v); - break; - case 'A': - res = Settings_ESP3D::write_IP_String (P, value); - break; - default: - log_esp3d("Unknown flag"); + // STA IP Mode DHCP / STATIC + if (!done) { + if (strcasecmp("STA_IP_mode", key) == 0) { + T = 'B'; + P = ESP_STA_IP_MODE; + done = true; + if (strcasecmp("DHCP", value) == 0) { + b = DHCP_MODE; + } else if (strcasecmp("STATIC", key) == 0) { + b = STATIC_IP_MODE; + } else { + P = -1; // invalide value } + } } - return res; + } else if (strcasecmp("services", section) == 0) { + if (!done) { + done = processString(ServstringKeysVal, ServstringKeysPos, + sizeof(ServstringKeysVal) / sizeof(char*), key, + value, T, P); + } + if (!done) { + done = processInt(ServintKeysVal, ServintKeysPos, + sizeof(ServintKeysVal) / sizeof(char*), key, value, T, + P, v); + } + if (!done) { + done = processBool(ServboolKeysVal, ServboolKeysPos, + sizeof(ServboolKeysVal) / sizeof(char*), key, value, T, + P, b); + } + if (!done) { + done = processInt(ServbyteKeysVal, ServbyteKeysPos, + sizeof(ServbyteKeysVal) / sizeof(char*), key, value, T, + P, v); + if (done) { + T = 'B'; + b = v; + } + } + // Notification type None / PushOver / Line / Email / Telegram / IFTTT + if (!done) { + if (strcasecmp("NOTIF_TYPE", key) == 0) { + T = 'B'; + P = ESP_NOTIFICATION_TYPE; + done = true; + if (strcasecmp("None", value) == 0) { + b = ESP_NO_NOTIFICATION; + } else if (strcasecmp("PushOver", value) == 0) { + b = ESP_PUSHOVER_NOTIFICATION; + } else if (strcasecmp("Line", value) == 0) { + b = ESP_LINE_NOTIFICATION; + } else if (strcasecmp("Email", value) == 0) { + b = ESP_EMAIL_NOTIFICATION; + } else if (strcasecmp("Telegram", value) == 0) { + b = ESP_TELEGRAM_NOTIFICATION; + } else if (strcasecmp("IFTTT", value) == 0) { + b = ESP_IFTTT_NOTIFICATION; + } else { + P = -1; // invalide value + } + } + } + // Sensor type if enabled None / DHT11 / DHT22 / ANALOG / BMP280 / BME280 + if (!done) { + if (strcasecmp("SENSOR_TYPE", key) == 0) { + T = 'B'; + P = ESP_SENSOR_TYPE; + done = true; + if (strcasecmp("None", value) == 0) { + b = NO_SENSOR_DEVICE; + } else if (strcasecmp("DHT11", key) == 0) { + b = DHT11_DEVICE; + } else if (strcasecmp("DHT22", key) == 0) { + b = DHT22_DEVICE; + } else if (strcasecmp("ANALOG", key) == 0) { + b = ANALOG_DEVICE; + } else if (strcasecmp("BMP280", key) == 0) { + b = BMP280_DEVICE; + } else if (strcasecmp("BME280", key) == 0) { + b = BME280_DEVICE; + } else { + P = -1; // invalide value + } + } + } + } else if (strcasecmp("system", section) == 0) { + if (!done) { + done = processInt(SysintKeysVal, SysintKeysPos, + sizeof(SysintKeysVal) / sizeof(char*), key, value, T, P, + v); + } + if (!done) { + done = processBool(SysboolKeysVal, SysboolKeysPos, + sizeof(SysboolKeysVal) / sizeof(char*), key, value, T, + P, b); + } + // Target Firmware None / Marlin / Repetier / MarlinKimbra / Smoothieware / + // GRBL + if (!done) { + if (strcasecmp("TargetFW", key) == 0) { + T = 'B'; + P = ESP_TARGET_FW; + done = true; + if (strcasecmp("None", value) == 0) { + b = UNKNOWN_FW; + } else if (strcasecmp("MARLIN", value) == 0) { + b = MARLIN; + } else if (strcasecmp("GRBL", value) == 0) { + b = GRBL; + } else if (strcasecmp("REPETIER", value) == 0) { + b = REPETIER; + } else if (strcasecmp("SMOOTHIEWARE", value) == 0) { + b = SMOOTHIEWARE; + } else { + P = -1; // invalide value + } + } + } + } + + // now we save -handle saving status + // if setting is not recognized it is not a problem + // but if save is fail - that is a problem - so report it + if (P != -1) { + switch (T) { + case 'S': + log_esp3d("Saving setting to ESP3D"); + res = Settings_ESP3D::write_string(P, value); + break; + case 'B': + case 'F': + res = Settings_ESP3D::write_byte(P, b); + break; + case 'I': + res = Settings_ESP3D::write_uint32(P, v); + break; + case 'A': + res = Settings_ESP3D::write_IP_String(P, value); + break; + default: + log_esp3d("Unknown flag"); + } + } + return res; } UpdateService::UpdateService() {} UpdateService::~UpdateService() {} -bool UpdateService::flash(const char * filename, int type) -{ - bool res = false; - if (ESP_SD::exists (filename)) { - log_esp3d("Update found"); - bool issucess = false; - ESP_SDFile sdfile; - String finalName = filename; - sdfile = ESP_SD::open(filename); - if(sdfile) { - size_t s = sdfile.size(); - size_t rs = 0; - uint8_t v[1] ; - if(Update.begin(s, type)) { - log_esp3d("Update started"); - while (sdfile.available() && (rs <= (s+1))) { - rs++; - v[0]=sdfile.read(); - Update.write(v,1); - Hal::wait(0); - } - if (rs==s) { - log_esp3d("Update done"); - if(Update.end(true)) { - log_esp3d("Update success"); - issucess = true; - } - } else { - Update.end(); - log_esp3d("Wrong size"); - } - } - sdfile.close(); +bool UpdateService::flash(const char* filename, int type) { + bool res = false; + if (ESP_SD::exists(filename)) { + log_esp3d("Update found"); + bool issucess = false; + ESP_SDFile sdfile; + String finalName = filename; + sdfile = ESP_SD::open(filename); + if (sdfile) { + size_t s = sdfile.size(); + size_t rs = 0; + uint8_t v[1]; + if (Update.begin(s, type)) { + log_esp3d("Update started"); + while (sdfile.available() && (rs <= (s + 1))) { + rs++; + v[0] = sdfile.read(); + Update.write(v, 1); + Hal::wait(0); + } + if (rs == s) { + log_esp3d("Update done"); + if (Update.end(true)) { + log_esp3d("Update success"); + issucess = true; + } } else { - log_esp3d("Cannot open file"); - } - if(issucess) { - res = true; - finalName.replace(".bin", ".ok"); - } else { - finalName.replace(".bin", ".bad"); - } - if (ESP_SD::exists (finalName.c_str())) { - String name = filename; - uint8_t n = 1; - log_esp3d("Final name already exists, backup existing"); - name.replace("bin", String(n).c_str()); - while(ESP_SD::exists (name.c_str())) { - n++; - name.replace("bin", String(n).c_str()); - } - ESP_SD::rename(finalName.c_str(),name.c_str()); - } - ESP_SD::rename(filename, finalName.c_str()); - } - return res; -} - -bool UpdateService::begin() -{ - bool res = false; - if(Settings_ESP3D::read_byte(ESP_SD_CHECK_UPDATE_AT_BOOT)!=0) { - if (ESP_SD::accessFS()) { - log_esp3d("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"); - if(updateConfig.revokeFile()) { - log_esp3d("Revoking ini file done"); - res = true; - } else { - log_esp3d("Revoking ini file failed"); - } - } else { - log_esp3d("Processing ini file failed"); - } - if (flash(FW_FILE,U_FLASH)) { - res = true; - } else { - if (flash(FS_FILE,U_FS)) { - res = true; - } - } - } - ESP_SD::releaseFS(); + Update.end(); + log_esp3d_e("Wrong size"); } + } + sdfile.close(); } else { - log_esp3d("No need to check for update"); + log_esp3d_e("Cannot open file"); } + if (issucess) { + res = true; + finalName.replace(".bin", ".ok"); + } else { + finalName.replace(".bin", ".bad"); + } + if (ESP_SD::exists(finalName.c_str())) { + String name = filename; + uint8_t n = 1; + log_esp3d("Final name already exists, backup existing"); + name.replace("bin", String(n).c_str()); + while (ESP_SD::exists(name.c_str())) { + n++; + name.replace("bin", String(n).c_str()); + } + ESP_SD::rename(finalName.c_str(), name.c_str()); + } + ESP_SD::rename(filename, finalName.c_str()); + } + return res; +} - return res; -} -void UpdateService::end() -{ +bool UpdateService::begin() { + bool res = false; + if (Settings_ESP3D::read_byte(ESP_SD_CHECK_UPDATE_AT_BOOT) != 0) { + if (ESP_SD::accessFS()) { + log_esp3d("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"); + if (updateConfig.revokeFile()) { + log_esp3d("Revoking ini file done"); + res = true; + } else { + log_esp3d_e("Revoking ini file failed"); + } + } else { + log_esp3d_e("Processing ini file failed"); + } + if (flash(FW_FILE, U_FLASH)) { + res = true; + } else { + if (flash(FS_FILE, U_FS)) { + res = true; + } + } + } + ESP_SD::releaseFS(); + } + } else { + log_esp3d("No need to check for update"); + } + + return res; } +void UpdateService::end() {} void UpdateService::handle() {} -#endif //SD_UPDATE_FEATURE +#endif // SD_UPDATE_FEATURE diff --git a/esp3d/src/modules/webdav/ESPWebDAV.cpp b/esp3d/src/modules/webdav/ESPWebDAV.cpp index ed102b07..980bc8db 100644 --- a/esp3d/src/modules/webdav/ESPWebDAV.cpp +++ b/esp3d/src/modules/webdav/ESPWebDAV.cpp @@ -27,7 +27,7 @@ Lebosse (ESP3D Integration) */ -// #define ESP_DEBUG_FEATURE DEBUG_OUTPUT_SERIAL0 +// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 #include "../../include/esp3d_config.h" #if defined(WEBDAV_FEATURE) @@ -35,7 +35,6 @@ #include "ESPWebDAV.h" - #if defined(ARDUINO_ARCH_ESP8266) #include #include @@ -821,7 +820,7 @@ void ESPWebDAVCore::handleGet(ResourceType resource, WebDavFile& file, // no lock on GET -#if defined(ESP_DEBUG_FEATURE) +#if defined(ESP_LOG_FEATURE) long tStart = millis(); #endif @@ -899,7 +898,7 @@ void ESPWebDAVCore::handleGet(ResourceType resource, WebDavFile& file, break; } -#if defined(ESP_DEBUG_FEATURE) +#if defined(ESP_LOG_FEATURE) for (size_t i = 0; i < 80 && i < numRead; i++) { log_esp3ds("%c", buf[i] < 32 || buf[i] > 127 ? '.' : buf[i]); } @@ -953,7 +952,7 @@ void ESPWebDAVCore::handlePut(ResourceType resource) { if (contentLengthHeader != 0) { uint8_t buf[BUFFER_SIZE]; -#if defined(ESP_DEBUG_FEATURE) +#if defined(ESP_LOG_FEATURE) long tStart = millis(); #endif size_t numRemaining = contentLengthHeader; @@ -1542,7 +1541,7 @@ void ESPWebDAVCore::send(const String& code, const char* content_type, if (content.length()) { sendContent(content); -#if defined(ESP_DEBUG_FEATURE) +#if defined(ESP_LOG_FEATURE) log_esp3d("send content (%d bytes):", (int)content.length()); for (size_t i = 0; i < DEBUG_LEN && i < content.length(); i++) { log_esp3ds("%c", content[i] < 32 || content[i] > 127 ? '.' : content[i]); @@ -1571,7 +1570,7 @@ bool ESPWebDAVCore::sendContent(const char* data, size_t size) { log_esp3d("---- chunk %s", chunkSize); } -#if defined(ESP_DEBUG_FEATURE) +#if defined(ESP_LOG_FEATURE) log_esp3d("---- %scontent (%d bytes):", _chunked ? "chunked " : "", (int)size); for (size_t i = 0; i < DEBUG_LEN && i < size; i++) { diff --git a/esp3d/src/modules/webdav/WebSrv.cpp b/esp3d/src/modules/webdav/WebSrv.cpp index 580b2ed5..687c177c 100644 --- a/esp3d/src/modules/webdav/WebSrv.cpp +++ b/esp3d/src/modules/webdav/WebSrv.cpp @@ -23,146 +23,141 @@ Modified 8 May 2015 by Hristo Gochkov (proper post and file upload handling) Modified 22 Jan 2021 by Luc Lebosse (ESP3D Integration) */ -//#define ESP_DEBUG_FEATURE DEBUG_OUTPUT_SERIAL0 +// #define ESP_LOG_FEATURE LOG_OUTPUT_SERIAL0 #include "../../include/esp3d_config.h" -#if defined (WEBDAV_FEATURE) +#if defined(WEBDAV_FEATURE) #include "ESPWebDAV.h" // Sections are copied from ESP8266Webserver -String ESPWebDAV::getMimeType(const String& path) -{ - if (path.endsWith(".html")) { - return "text/html"; - } else if (path.endsWith(".htm")) { - return "text/html"; - } else if (path.endsWith(".css")) { - return "text/css"; - } else if (path.endsWith(".txt")) { - return "text/plain"; - } else if (path.endsWith(".js")) { - return "application/javascript"; - } else if (path.endsWith(".json")) { - return "application/json"; - } else if (path.endsWith(".png")) { - return "image/png"; - } else if (path.endsWith(".gif")) { - return "image/gif"; - } else if (path.endsWith(".jpg")) { - return "image/jpeg"; - } else if (path.endsWith(".ico")) { - return "image/x-icon"; - } else if (path.endsWith(".svg")) { - return "image/svg+xml"; - } else if (path.endsWith(".ttf")) { - return "application/x-font-ttf"; - } else if (path.endsWith(".otf")) { - return "application/x-font-opentype"; - } else if (path.endsWith(".woff")) { - return "application/font-woff"; - } else if (path.endsWith(".woff2")) { - return "application/font-woff2"; - } else if (path.endsWith(".eot")) { - return "application/vnd.ms-fontobject"; - } else if (path.endsWith(".sfnt")) { - return "application/font-sfnt"; - } else if (path.endsWith(".xml")) { - return "text/xml"; - } else if (path.endsWith(".pdf")) { - return "application/pdf"; - } else if (path.endsWith(".zip")) { - return "application/zip"; - } else if (path.endsWith(".gz")) { - return "application/x-gzip"; - } else if (path.endsWith(".appcache")) { - return "text/cache-manifest"; - } +String ESPWebDAV::getMimeType(const String& path) { + if (path.endsWith(".html")) { + return "text/html"; + } else if (path.endsWith(".htm")) { + return "text/html"; + } else if (path.endsWith(".css")) { + return "text/css"; + } else if (path.endsWith(".txt")) { + return "text/plain"; + } else if (path.endsWith(".js")) { + return "application/javascript"; + } else if (path.endsWith(".json")) { + return "application/json"; + } else if (path.endsWith(".png")) { + return "image/png"; + } else if (path.endsWith(".gif")) { + return "image/gif"; + } else if (path.endsWith(".jpg")) { + return "image/jpeg"; + } else if (path.endsWith(".ico")) { + return "image/x-icon"; + } else if (path.endsWith(".svg")) { + return "image/svg+xml"; + } else if (path.endsWith(".ttf")) { + return "application/x-font-ttf"; + } else if (path.endsWith(".otf")) { + return "application/x-font-opentype"; + } else if (path.endsWith(".woff")) { + return "application/font-woff"; + } else if (path.endsWith(".woff2")) { + return "application/font-woff2"; + } else if (path.endsWith(".eot")) { + return "application/vnd.ms-fontobject"; + } else if (path.endsWith(".sfnt")) { + return "application/font-sfnt"; + } else if (path.endsWith(".xml")) { + return "text/xml"; + } else if (path.endsWith(".pdf")) { + return "application/pdf"; + } else if (path.endsWith(".zip")) { + return "application/zip"; + } else if (path.endsWith(".gz")) { + return "application/x-gzip"; + } else if (path.endsWith(".appcache")) { + return "text/cache-manifest"; + } - return "application/octet-stream"; + return "application/octet-stream"; } - - - -String ESPWebDAV::urlDecode(const String& text) -{ - String decoded = ""; - char temp[] = "0x00"; - unsigned int len = text.length(); - unsigned int i = 0; - while (i < len) { - char decodedChar; - char encodedChar = text.charAt(i++); - if ((encodedChar == '%') && (i + 1 < len)) { - temp[2] = text.charAt(i++); - temp[3] = text.charAt(i++); - decodedChar = strtol(temp, NULL, 16); - } else { - if (encodedChar == '+') { - decodedChar = ' '; - } else { - decodedChar = encodedChar; // normal ascii char - } - } - decoded += decodedChar; +String ESPWebDAV::urlDecode(const String& text) { + String decoded = ""; + char temp[] = "0x00"; + unsigned int len = text.length(); + unsigned int i = 0; + while (i < len) { + char decodedChar; + char encodedChar = text.charAt(i++); + if ((encodedChar == '%') && (i + 1 < len)) { + temp[2] = text.charAt(i++); + temp[3] = text.charAt(i++); + decodedChar = strtol(temp, NULL, 16); + } else { + if (encodedChar == '+') { + decodedChar = ' '; + } else { + decodedChar = encodedChar; // normal ascii char + } } - return decoded; + decoded += decodedChar; + } + return decoded; } -void ESPWebDAV::handleClient() -{ - if (!server) { - log_esp3d("handleClient: server is null"); - return; - } - - if (server->hasClient()) { - if (!locClient || !locClient.available()) { - // no or sleeping current client - // take it over - locClient = server->available(); - m_persistent_timer_ms = millis(); - log_esp3d("NEW CLIENT-------------------------------------------------------"); - } - } +void ESPWebDAV::handleClient() { + if (!server) { + log_esp3d_e("handleClient: server is null"); + return; + } + if (server->hasClient()) { if (!locClient || !locClient.available()) { - // no current client - //do not put debug here or it will flood the serial - return; + // no or sleeping current client + // take it over + locClient = server->available(); + m_persistent_timer_ms = millis(); + log_esp3d( + "NEW CLIENT-------------------------------------------------------"); } + } - // extract uri, headers etc - parseRequest(); + if (!locClient || !locClient.available()) { + // no current client + // do not put debug here or it will flood the serial + return; + } - if (!m_persistent) - // close the connection - { - log_esp3d("CLOSE CONNECTION-------------------------------------------------------"); - locClient.stop(); - } + // extract uri, headers etc + parseRequest(); + + if (!m_persistent) + // close the connection + { + log_esp3d( + "CLOSE " + "CONNECTION-------------------------------------------------------"); + locClient.stop(); + } } +bool ESPWebDAV::parseRequest() { + // Read the first line of HTTP request + String req = locClient.readStringUntil('\r'); + locClient.readStringUntil('\n'); -bool ESPWebDAV::parseRequest() -{ - // Read the first line of HTTP request - String req = locClient.readStringUntil('\r'); - locClient.readStringUntil('\n'); + // First line of HTTP request looks like "GET /path HTTP/1.1" + // Retrieve the "/path" part by finding the spaces + int addr_start = req.indexOf(' '); + int addr_end = req.indexOf(' ', addr_start + 1); + if (addr_start == -1 || addr_end == -1) { + log_esp3d("Invalid request %s", req.c_str()); + return false; + } - // First line of HTTP request looks like "GET /path HTTP/1.1" - // Retrieve the "/path" part by finding the spaces - int addr_start = req.indexOf(' '); - int addr_end = req.indexOf(' ', addr_start + 1); - if (addr_start == -1 || addr_end == -1) { - log_esp3d("Invalid request %s", req.c_str()); - return false; - } - - method = req.substring(0, addr_start); - uri = urlDecode(req.substring(addr_start + 1, addr_end)); - return ESPWebDAVCore::parseRequest(method, uri, &locClient, getMimeType); + method = req.substring(0, addr_start); + uri = urlDecode(req.substring(addr_start + 1, addr_end)); + return ESPWebDAVCore::parseRequest(method, uri, &locClient, getMimeType); } -#endif //WEBDAV_FEATURE +#endif // WEBDAV_FEATURE diff --git a/esp3d/src/modules/websocket/websocket_server.cpp b/esp3d/src/modules/websocket/websocket_server.cpp index 0a7b7857..769306ff 100644 --- a/esp3d/src/modules/websocket/websocket_server.cpp +++ b/esp3d/src/modules/websocket/websocket_server.cpp @@ -18,350 +18,320 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - #include "../../include/esp3d_config.h" -#if defined (HTTP_FEATURE) || defined(WS_DATA_FEATURE) +#if defined(HTTP_FEATURE) || defined(WS_DATA_FEATURE) - -#include "websocket_server.h" #include -#include "../../core/settings_esp3d.h" -#include "../../core/esp3doutput.h" + #include "../../core/commands.h" +#include "../../core/esp3doutput.h" +#include "../../core/settings_esp3d.h" #include "../authentication/authentication_service.h" +#include "websocket_server.h" + WebSocket_Server websocket_terminal_server("webui-v3"); #if defined(WS_DATA_FEATURE) WebSocket_Server websocket_data_server("arduino"); -#endif //WS_DATA_FEATURE -void WebSocket_Server::pushMSG (const char * data) -{ - if (_websocket_server) { - _websocket_server->broadcastTXT(data); - log_esp3d("[%u]Broadcast %s", _current_id,data); - } +#endif // WS_DATA_FEATURE +void WebSocket_Server::pushMSG(const char *data) { + if (_websocket_server) { + _websocket_server->broadcastTXT(data); + log_esp3d("[%u]Broadcast %s", _current_id, data); + } } -void WebSocket_Server::enableOnly (uint num) -{ - //some sanity check - if (_websocket_server) { - for (uint8_t i=0; iclientIsConnected(i)) { - _websocket_server->disconnect(i); - } - } +void WebSocket_Server::enableOnly(uint num) { + // some sanity check + if (_websocket_server) { + for (uint8_t i = 0; i < WEBSOCKETS_SERVER_CLIENT_MAX; i++) + if (i != num && _websocket_server->clientIsConnected(i)) { + _websocket_server->disconnect(i); + } + } } - -void WebSocket_Server::pushMSG (uint num, const char * data) -{ - if (_websocket_server) { - _websocket_server->sendTXT(num, data); - log_esp3d("[%u]Send %s", num,data); - } +void WebSocket_Server::pushMSG(uint num, const char *data) { + if (_websocket_server) { + _websocket_server->sendTXT(num, data); + log_esp3d("[%u]Send %s", num, data); + } } -void WebSocket_Server::closeClients() -{ - if (_websocket_server) { - _websocket_server->disconnect(); - } +void WebSocket_Server::closeClients() { + if (_websocket_server) { + _websocket_server->disconnect(); + } } #if defined(WS_DATA_FEATURE) -//Events for Websocket bridge -void handle_Websocket_Server_Event(uint8_t num, uint8_t type, uint8_t * payload, size_t length) -{ - (void)num; - switch(type) { +// Events for Websocket bridge +void handle_Websocket_Server_Event(uint8_t num, uint8_t type, uint8_t *payload, + size_t length) { + (void)num; + switch (type) { case WStype_DISCONNECTED: - log_esp3d("[%u] Disconnected! port %d", num,websocket_data_server.port()); - break; + log_esp3d("[%u] Disconnected! port %d", num, + websocket_data_server.port()); + break; case WStype_CONNECTED: { - log_esp3d("[%u] Connected! port %d, %s", num,websocket_data_server.port(), payload); - } - break; + log_esp3d("[%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,websocket_data_server.port()); - websocket_data_server.push2RXbuffer(payload, length); - break; + log_esp3d("[%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,websocket_data_server.port()); - websocket_data_server.push2RXbuffer(payload, length); - break; + log_esp3d("[%u] get binary length: %u port %d", num, length, + websocket_data_server.port()); + websocket_data_server.push2RXbuffer(payload, length); + break; default: - break; - } - + break; + } } -#endif //WS_DATA_FEATURE -#if defined (HTTP_FEATURE) -//Events for Websocket used in WebUI for events and serial bridge -void handle_Websocket_Terminal_Event(uint8_t num, uint8_t type, uint8_t * payload, size_t length) -{ - (void)payload; - (void)length; - String msg; - switch(type) { +#endif // WS_DATA_FEATURE +#if defined(HTTP_FEATURE) +// Events for Websocket used in WebUI for events and serial bridge +void handle_Websocket_Terminal_Event(uint8_t num, uint8_t type, + uint8_t *payload, size_t length) { + (void)payload; + (void)length; + String msg; + switch (type) { case WStype_DISCONNECTED: - log_esp3d("[%u] Socket Disconnected port %d!", num,websocket_terminal_server.port()); - break; + log_esp3d("[%u] Socket Disconnected port %d!", num, + websocket_terminal_server.port()); + break; case WStype_CONNECTED: { - log_esp3d("[%u] Connected! port %d, %s", num,websocket_terminal_server.port(), (const char *)payload); - msg = "currentID:" + String(num); - // send message to client - websocket_terminal_server.set_currentID(num); - websocket_terminal_server.pushMSG(num, msg.c_str()); - msg = "activeID:" + String(num); - websocket_terminal_server.pushMSG(msg.c_str()); - websocket_terminal_server.enableOnly(num); - log_esp3d("[%u] Socket connected port %d", num,websocket_terminal_server.port()); - } - break; + log_esp3d("[%u] Connected! port %d, %s", num, + websocket_terminal_server.port(), (const char *)payload); + msg = "currentID:" + String(num); + // send message to client + websocket_terminal_server.set_currentID(num); + websocket_terminal_server.pushMSG(num, msg.c_str()); + msg = "activeID:" + String(num); + websocket_terminal_server.pushMSG(msg.c_str()); + websocket_terminal_server.enableOnly(num); + log_esp3d("[%u] Socket connected port %d", num, + websocket_terminal_server.port()); + } break; case WStype_TEXT: -#if defined (AUTHENTICATION_FEATURE) - //we do not expect any input but ping to get session timeout if any - if (AuthenticationService::getSessionTimeout() != 0) { - msg = (const char*)payload; - if (msg.startsWith("PING:")) { - String session = msg.substring(5); - String response = "PING:"+String(AuthenticationService::getSessionRemaining(session.c_str())); - response += ":"+String(AuthenticationService::getSessionTimeout()); - websocket_terminal_server.pushMSG(num, response.c_str()); - } +#if defined(AUTHENTICATION_FEATURE) + // we do not expect any input but ping to get session timeout if any + if (AuthenticationService::getSessionTimeout() != 0) { + msg = (const char *)payload; + if (msg.startsWith("PING:")) { + String session = msg.substring(5); + String response = + "PING:" + String(AuthenticationService::getSessionRemaining( + session.c_str())); + response += ":" + String(AuthenticationService::getSessionTimeout()); + websocket_terminal_server.pushMSG(num, response.c_str()); } -#endif //AUTHENTICATION_FEATURE - //log_esp3d("[IGNORED][%u] get Text: %s port %d", num, payload, websocket_terminal_server.port()); - break; + } +#endif // AUTHENTICATION_FEATURE + // log_esp3d("[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()); - break; + // we do not expect any input + // log_esp3d("[IGNORED][%u] get binary length: %u port %d", num, length, + // websocket_terminal_server.port()); + break; default: - break; + break; + } +} +#endif // HTTP_FEATURE + +int WebSocket_Server::available() { return _RXbufferSize; } +int WebSocket_Server::availableForWrite() { + return TXBUFFERSIZE - _TXbufferSize; +} +WebSocket_Server::WebSocket_Server(const char *protocol) { + _websocket_server = nullptr; + _started = false; + _port = 0; + _current_id = 0; + _RXbuffer = nullptr; + _RXbufferSize = 0; + _protocol = protocol; +} +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; + } else { + _port = port; + if (Settings_ESP3D::read_byte(ESP_WEBSOCKET_ON) == 0) { + return true; } + } + _websocket_server = new WebSocketsServer(_port, "", _protocol.c_str()); + if (_websocket_server) { + _websocket_server->begin(); +#if defined(HTTP_FEATURE) // terminal websocket for HTTP + if (port == 0) { + _websocket_server->onEvent(handle_Websocket_Terminal_Event); + } +#endif // HTTP_FEATURE +#if defined(WS_DATA_FEATURE) // terminal websocket for HTTP + if ((port != 0) && _protocol != "log") { + _websocket_server->onEvent(handle_Websocket_Server_Event); + _RXbuffer = (uint8_t *)malloc(RXBUFFERSIZE + 1); + if (!_RXbuffer) { + return false; + } + } +#endif // WS_DATA_FEATURE + _started = true; + } else { + end(); + } + return _started; +} -} -#endif //HTTP_FEATURE - -int WebSocket_Server::available() -{ - return _RXbufferSize; -} -int WebSocket_Server::availableForWrite() -{ - return TXBUFFERSIZE -_TXbufferSize; -} -WebSocket_Server::WebSocket_Server(const char * protocol ) -{ - _websocket_server = nullptr; - _started = false; - _port = 0; - _current_id = 0; +void WebSocket_Server::end() { + _current_id = 0; + _TXbufferSize = 0; + if (_RXbuffer) { + free(_RXbuffer); _RXbuffer = nullptr; - _RXbufferSize = 0; - _protocol = protocol; + } + _RXbufferSize = 0; + if (_websocket_server) { + _websocket_server->close(); + delete _websocket_server; + _websocket_server = nullptr; + _port = 0; + } + _started = false; +} +WebSocket_Server::operator bool() const { return _started; } + +void WebSocket_Server::set_currentID(uint8_t current_id) { + _current_id = current_id; } -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; - } else { - _port = port; - if (Settings_ESP3D::read_byte(ESP_WEBSOCKET_ON) == 0) { - return true; - } +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(const uint8_t *buffer, size_t size) { + if (_started) { + if ((buffer == nullptr) || (!_websocket_server) || (size == 0)) { + return 0; } - _websocket_server = new WebSocketsServer(_port,"",_protocol.c_str()); - if (_websocket_server) { - _websocket_server->begin(); -#if defined (HTTP_FEATURE) //terminal websocket for HTTP - if(port == 0) { - _websocket_server->onEvent(handle_Websocket_Terminal_Event); - } -#endif //HTTP_FEATURE -#if defined (WS_DATA_FEATURE) //terminal websocket for HTTP - if((port != 0) && _protocol!="debug") { - _websocket_server->onEvent(handle_Websocket_Server_Event); - _RXbuffer= (uint8_t *)malloc(RXBUFFERSIZE +1); - if (!_RXbuffer) { - return false; - } - } -#endif //WS_DATA_FEATURE - _started = true; - } else { - end(); + if (_TXbufferSize == 0) { + _lastTXflush = millis(); } - return _started; -} - -void WebSocket_Server::end() -{ - _current_id = 0; - _TXbufferSize = 0; - if(_RXbuffer) { - free(_RXbuffer); - _RXbuffer = nullptr; + // send full line + if (_TXbufferSize + size > TXBUFFERSIZE) { + flushTXbuffer(); } - _RXbufferSize = 0; - if (_websocket_server) { - _websocket_server->close(); - delete _websocket_server; - _websocket_server = nullptr; - _port = 0; + if (_websocket_server->connectedClients() == 0) { + return 0; } - _started = false; -} - - -WebSocket_Server::operator bool() const -{ - return _started; -} - -void WebSocket_Server::set_currentID(uint8_t current_id) -{ - _current_id = 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(const uint8_t *buffer, size_t size) -{ - if (_started) { - if((buffer == nullptr) ||(!_websocket_server) || (size == 0)) { - return 0; - } - if (_TXbufferSize==0) { - _lastTXflush = millis(); - } - //send full line - if (_TXbufferSize + size > TXBUFFERSIZE) { - flushTXbuffer(); - } - if(_websocket_server->connectedClients() == 0) { - return 0; - } - //need periodic check to force to flush in case of no end - for (uint i = 0; i < size; i++) { - _TXbuffer[_TXbufferSize] = buffer[i]; - _TXbufferSize++; - } - return size; + // need periodic check to force to flush in case of no end + for (uint i = 0; i < size; i++) { + _TXbuffer[_TXbufferSize] = buffer[i]; + _TXbufferSize++; } - return 0; + return size; + } + return 0; } -void WebSocket_Server::push2RXbuffer(uint8_t * sbuf, size_t len) -{ - if (!_RXbuffer || !_started) { - return; - } - for (size_t i = 0; i < len; i++) { - _lastRXflush = millis(); - //command is defined - if ((char(sbuf[i]) == '\n')|| (char(sbuf[i]) == '\r')) { - if (_RXbufferSize < RXBUFFERSIZE) { - _RXbuffer[_RXbufferSize] = sbuf[i]; - _RXbufferSize++; - } - flushRXbuffer(); - } else if (isPrintable (char(sbuf[i]) ) ) { - if (_RXbufferSize < RXBUFFERSIZE) { - _RXbuffer[_RXbufferSize] = sbuf[i]; - _RXbufferSize++; - } else { - flushRXbuffer(); - _RXbuffer[_RXbufferSize] = sbuf[i]; - _RXbufferSize++; - } - } else { //it is not printable char - //clean buffer first - if (_RXbufferSize > 0) { - flushRXbuffer(); - } - //process char - _RXbuffer[_RXbufferSize] = sbuf[i]; - _RXbufferSize++; - flushRXbuffer(); - } - } -} - -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); +void WebSocket_Server::push2RXbuffer(uint8_t *sbuf, size_t len) { + if (!_RXbuffer || !_started) { + return; + } + for (size_t i = 0; i < len; i++) { _lastRXflush = millis(); + // command is defined + if ((char(sbuf[i]) == '\n') || (char(sbuf[i]) == '\r')) { + if (_RXbufferSize < RXBUFFERSIZE) { + _RXbuffer[_RXbufferSize] = sbuf[i]; + _RXbufferSize++; + } + flushRXbuffer(); + } else if (isPrintable(char(sbuf[i]))) { + if (_RXbufferSize < RXBUFFERSIZE) { + _RXbuffer[_RXbufferSize] = sbuf[i]; + _RXbufferSize++; + } else { + flushRXbuffer(); + _RXbuffer[_RXbufferSize] = sbuf[i]; + _RXbufferSize++; + } + } else { // it is not printable char + // clean buffer first + if (_RXbufferSize > 0) { + flushRXbuffer(); + } + // process char + _RXbuffer[_RXbufferSize] = sbuf[i]; + _RXbufferSize++; + flushRXbuffer(); + } + } +} + +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); + _lastRXflush = millis(); + _RXbufferSize = 0; } - -void WebSocket_Server::handle() -{ - Hal::wait(0); - if (_started) { - if (_TXbufferSize > 0) { - if ((_TXbufferSize>=TXBUFFERSIZE) || ((millis()- _lastTXflush) > FLUSHTIMEOUT)) { - flushTXbuffer(); - } - } - if (_RXbufferSize > 0) { - if ((_RXbufferSize>=RXBUFFERSIZE) || ((millis()- _lastRXflush) > FLUSHTIMEOUT)) { - flushRXbuffer(); - } - } - if (_websocket_server) { - _websocket_server->loop(); - } +void WebSocket_Server::handle() { + Hal::wait(0); + if (_started) { + if (_TXbufferSize > 0) { + if ((_TXbufferSize >= TXBUFFERSIZE) || + ((millis() - _lastTXflush) > FLUSHTIMEOUT)) { + flushTXbuffer(); + } } -} - -void WebSocket_Server::flush(void) -{ - flushTXbuffer(); - flushRXbuffer(); -} - -void WebSocket_Server::flushTXbuffer(void) -{ - if (_started) { - 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); - } - //refresh timout - _lastTXflush = millis(); - - } + if (_RXbufferSize > 0) { + if ((_RXbufferSize >= RXBUFFERSIZE) || + ((millis() - _lastRXflush) > FLUSHTIMEOUT)) { + flushRXbuffer(); + } } - //reset buffer - _TXbufferSize = 0; + if (_websocket_server) { + _websocket_server->loop(); + } + } } +void WebSocket_Server::flush(void) { + flushTXbuffer(); + flushRXbuffer(); +} +void WebSocket_Server::flushTXbuffer(void) { + if (_started) { + 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); + } + // refresh timout + _lastTXflush = millis(); + } + } + // reset buffer + _TXbufferSize = 0; +} -#endif // HTTP_FEATURE || WS_DATA_FEATURE - +#endif // HTTP_FEATURE || WS_DATA_FEATURE diff --git a/esp3d/src/modules/wifi/wificonfig.cpp b/esp3d/src/modules/wifi/wificonfig.cpp index cd407614..a928462c 100644 --- a/esp3d/src/modules/wifi/wificonfig.cpp +++ b/esp3d/src/modules/wifi/wificonfig.cpp @@ -19,562 +19,546 @@ */ #include "../../include/esp3d_config.h" -#if defined (WIFI_FEATURE) +#if defined(WIFI_FEATURE) #ifdef ARDUINO_ARCH_ESP32 #include -#endif //ARDUINO_ARCH_ESP32 +#endif // ARDUINO_ARCH_ESP32 #ifdef ARDUINO_ARCH_ESP8266 -#endif //ARDUINO_ARCH_ESP8266 -#include "../wifi/wificonfig.h" -#include "../network/netconfig.h" +#endif // ARDUINO_ARCH_ESP8266 #include "../../core/esp3doutput.h" #include "../../core/settings_esp3d.h" +#include "../network/netconfig.h" +#include "../wifi/wificonfig.h" -const uint8_t DEFAULT_AP_MASK_VALUE[] = {255, 255, 255, 0}; +const uint8_t DEFAULT_AP_MASK_VALUE[] = {255, 255, 255, 0}; /** * Check if SSID string is valid */ -bool WiFiConfig::isSSIDValid (const char * ssid) -{ - //limited size - //char c; - if (strlen (ssid) > MAX_SSID_LENGTH || strlen (ssid) < MIN_SSID_LENGTH) { - return false; +bool WiFiConfig::isSSIDValid(const char* ssid) { + // limited size + // char c; + if (strlen(ssid) > MAX_SSID_LENGTH || strlen(ssid) < MIN_SSID_LENGTH) { + return false; + } + // only printable + for (uint i = 0; i < strlen(ssid); i++) { + if (!isPrintable(ssid[i])) { + return false; } - //only printable - for (uint i = 0; i < strlen (ssid); i++) { - if (!isPrintable (ssid[i]) ) { - return false; - } - } - return true; + } + return true; } -const char * WiFiConfig::hostname() -{ - static String tmp; -#if defined (ARDUINO_ARCH_ESP8266) - if (WiFi.getMode() == WIFI_AP) { - //No API for AP - tmp = NetConfig::hostname(true); - } else { - tmp = WiFi.hostname(); - - } -#endif //ARDUINO_ARCH_ESP8266 -#if defined (ARDUINO_ARCH_ESP32) - if (WiFi.getMode() == WIFI_AP) { - //tmp = NetConfig::hostname(true); - //Set API is not working so far - tmp = WiFi.softAPgetHostname(); - } else { - tmp = WiFi.getHostname(); - } -#endif //ARDUINO_ARCH_ESP8266 - return tmp.c_str(); +const char* WiFiConfig::hostname() { + static String tmp; +#if defined(ARDUINO_ARCH_ESP8266) + if (WiFi.getMode() == WIFI_AP) { + // No API for AP + tmp = NetConfig::hostname(true); + } else { + tmp = WiFi.hostname(); + } +#endif // ARDUINO_ARCH_ESP8266 +#if defined(ARDUINO_ARCH_ESP32) + if (WiFi.getMode() == WIFI_AP) { + // tmp = NetConfig::hostname(true); + // Set API is not working so far + tmp = WiFi.softAPgetHostname(); + } else { + tmp = WiFi.getHostname(); + } +#endif // ARDUINO_ARCH_ESP8266 + return tmp.c_str(); } /** * Check if password string is valid */ -bool WiFiConfig::isPasswordValid (const char * password) -{ - if (strlen (password) == 0) { - return true; //open network - } - //limited size - if ((strlen (password) > MAX_PASSWORD_LENGTH) || (strlen (password) < MIN_PASSWORD_LENGTH)) { - return false; - } - return true; +bool WiFiConfig::isPasswordValid(const char* password) { + if (strlen(password) == 0) { + return true; // open network + } + // limited size + if ((strlen(password) > MAX_PASSWORD_LENGTH) || + (strlen(password) < MIN_PASSWORD_LENGTH)) { + return false; + } + return true; } /* * Get WiFi signal strength */ -int32_t WiFiConfig::getSignal (int32_t RSSI, bool filter) -{ - if (RSSI < MIN_RSSI && filter) { - return 0; - } - if (RSSI <= -100 && !filter) { - return 0; - } - if (RSSI >= -50) { - return 100; - } - return (2 * (RSSI + 100) ); - +int32_t WiFiConfig::getSignal(int32_t RSSI, bool filter) { + if (RSSI < MIN_RSSI && filter) { + return 0; + } + if (RSSI <= -100 && !filter) { + return 0; + } + if (RSSI >= -50) { + return 100; + } + return (2 * (RSSI + 100)); } /* * Connect client to AP */ -bool WiFiConfig::ConnectSTA2AP() -{ - String msg, msg_out; - uint8_t count = 0; - uint8_t dot = 0; - wl_status_t status = WiFi.status(); - ESP3DOutput output(ESP_ALL_CLIENTS); - log_esp3d("Connecting"); +bool WiFiConfig::ConnectSTA2AP() { + String msg, msg_out; + uint8_t count = 0; + uint8_t dot = 0; + wl_status_t status = WiFi.status(); + ESP3DOutput output(ESP_ALL_CLIENTS); + log_esp3d("Connecting"); #if COMMUNICATION_PROTOCOL != MKS_SERIAL - if (!Settings_ESP3D::isVerboseBoot()) { - output.printMSG("Connecting"); - output.flush(); - } -#endif //#if COMMUNICATION_PROTOCOL == MKS_SERIAL - while (status != WL_CONNECTED && count < 40) { - - switch (status) { - case WL_NO_SSID_AVAIL: - msg="No SSID"; - break; - case WL_CONNECT_FAILED: - msg="Connection failed"; - break; - case WL_CONNECTED: - break; - default: - if ((dot>3) || (dot==0) ) { - dot=0; - msg_out = "Connecting"; - } - msg_out+="."; - msg= msg_out; - log_esp3d("..."); - dot++; - break; + if (!Settings_ESP3D::isVerboseBoot()) { + output.printMSG("Connecting"); + output.flush(); + } +#endif // #if COMMUNICATION_PROTOCOL == MKS_SERIAL + while (status != WL_CONNECTED && count < 40) { + switch (status) { + case WL_NO_SSID_AVAIL: + msg = "No SSID"; + break; + case WL_CONNECT_FAILED: + msg = "Connection failed"; + break; + case WL_CONNECTED: + break; + default: + if ((dot > 3) || (dot == 0)) { + dot = 0; + msg_out = "Connecting"; } - if (Settings_ESP3D::isVerboseBoot()) { - output.printMSG(msg.c_str()); - output.flush(); - } - Hal::wait (500); - count++; - status = WiFi.status(); + msg_out += "."; + msg = msg_out; + log_esp3d("..."); + dot++; + break; } - return (status == WL_CONNECTED); + if (Settings_ESP3D::isVerboseBoot()) { + output.printMSG(msg.c_str()); + output.flush(); + } + Hal::wait(500); + count++; + status = WiFi.status(); + } + return (status == WL_CONNECTED); } /* * Start client mode (Station) */ -bool WiFiConfig::StartSTA() -{ - log_esp3d("StartSTA"); - if((WiFi.getMode() == WIFI_AP) || (WiFi.getMode() == WIFI_AP_STA)) { - WiFi.softAPdisconnect(); - } - WiFi.enableAP (false); - WiFi.enableSTA (true); - WiFi.mode(WIFI_STA); -#if defined (ARDUINO_ARCH_ESP32) - esp_wifi_start(); - WiFi.setMinSecurity(WIFI_AUTH_WEP); - WiFi.setScanMethod(WIFI_ALL_CHANNEL_SCAN); - 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); +bool WiFiConfig::StartSTA() { + log_esp3d("StartSTA"); + if ((WiFi.getMode() == WIFI_AP) || (WiFi.getMode() == WIFI_AP_STA)) { + WiFi.softAPdisconnect(); + } + WiFi.enableAP(false); + WiFi.enableSTA(true); + WiFi.mode(WIFI_STA); +#if defined(ARDUINO_ARCH_ESP32) + esp_wifi_start(); + WiFi.setMinSecurity(WIFI_AUTH_WEP); + WiFi.setScanMethod(WIFI_ALL_CHANNEL_SCAN); + 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); - 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); - IPAddress ip(IP), mask(MK), gateway(GW), dns(DNS); - WiFi.config(ip, gateway,mask,dns); - } - ESP3DOutput output(ESP_ALL_CLIENTS); - if (Settings_ESP3D::isVerboseBoot()) { - String stmp; - stmp = "Connecting to '" + SSID + "'";; - output.printMSG(stmp.c_str()); - } - if (WiFi.begin(SSID.c_str(), (password.length() > 0)?password.c_str():nullptr)) { -#if defined (ARDUINO_ARCH_ESP8266) - WiFi.setSleepMode(WIFI_NONE_SLEEP); - WiFi.hostname(NetConfig::hostname(true)); -#endif //ARDUINO_ARCH_ESP8266 -#if defined (ARDUINO_ARCH_ESP32) - WiFi.setSleep(false); - WiFi.setHostname(NetConfig::hostname(true)); -#endif //ARDUINO_ARCH_ESP32 - return ConnectSTA2AP(); - } else { - output.printERROR("Starting client failed"); - return false; - } + 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); + IPAddress ip(IP), mask(MK), gateway(GW), dns(DNS); + WiFi.config(ip, gateway, mask, dns); + } + ESP3DOutput output(ESP_ALL_CLIENTS); + if (Settings_ESP3D::isVerboseBoot()) { + String stmp; + stmp = "Connecting to '" + SSID + "'"; + ; + output.printMSG(stmp.c_str()); + } + if (WiFi.begin(SSID.c_str(), + (password.length() > 0) ? password.c_str() : nullptr)) { +#if defined(ARDUINO_ARCH_ESP8266) + WiFi.setSleepMode(WIFI_NONE_SLEEP); + WiFi.hostname(NetConfig::hostname(true)); +#endif // ARDUINO_ARCH_ESP8266 +#if defined(ARDUINO_ARCH_ESP32) + WiFi.setSleep(false); + WiFi.setHostname(NetConfig::hostname(true)); +#endif // ARDUINO_ARCH_ESP32 + return ConnectSTA2AP(); + } else { + output.printERROR("Starting client failed"); + return false; + } } /** * Setup and start Access point */ -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()) { - WiFi.disconnect(); - } +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()) { + WiFi.disconnect(); } - if((WiFi.getMode() == WIFI_AP) || (WiFi.getMode() == WIFI_AP_STA)) { - WiFi.softAPdisconnect(); - } - WiFi.enableAP (true); - WiFi.enableSTA (false); - WiFi.mode(WIFI_AP); - //Set Sleep Mode to none -#if defined (ARDUINO_ARCH_ESP8266) - WiFi.setSleepMode(WIFI_NONE_SLEEP); -#endif //ARDUINO_ARCH_ESP8266 + } + if ((WiFi.getMode() == WIFI_AP) || (WiFi.getMode() == WIFI_AP_STA)) { + WiFi.softAPdisconnect(); + } + WiFi.enableAP(true); + WiFi.enableSTA(false); + WiFi.mode(WIFI_AP); + // Set Sleep Mode to none +#if defined(ARDUINO_ARCH_ESP8266) + 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); - //channel - int8_t channel = Settings_ESP3D::read_byte (ESP_AP_CHANNEL); - //IP - int32_t IP = Settings_ESP3D::read_IP(ESP_AP_IP_VALUE); + String SSID = Settings_ESP3D::read_string(ESP_AP_SSID); + String password = Settings_ESP3D::read_string(ESP_AP_PASSWORD); + // channel + int8_t channel = Settings_ESP3D::read_byte(ESP_AP_CHANNEL); + // IP + int32_t IP = Settings_ESP3D::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(),mask.toString().c_str()); - if (!WiFi.softAPConfig(ip, setupMode?ip:gw, mask)) { - output.printERROR("Set IP to AP failed"); + 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(), + mask.toString().c_str()); + if (!WiFi.softAPConfig(ip, setupMode ? ip : gw, mask)) { + output.printERROR("Set IP to AP failed"); + } else { + output.printMSG(ip.toString().c_str()); + } +#endif // ARDUINO_ARCH_ESP8266 + // Start AP + if (WiFi.softAP(SSID.c_str(), + (password.length() > 0) ? password.c_str() : nullptr, + channel)) { + String stmp = "AP SSID: '" + SSID; + if (password.length() > 0) { + stmp += "' is started and protected by password"; } else { - output.printMSG(ip.toString().c_str()); + stmp += " is started not protected by password"; } -#endif //ARDUINO_ARCH_ESP8266 - //Start AP - if(WiFi.softAP(SSID.c_str(), (password.length() > 0)?password.c_str():nullptr, channel)) { - String stmp = "AP SSID: '" + SSID; - if (password.length() > 0) { - stmp +="' is started and protected by password"; - } else { - stmp +=" is started not protected by password"; - } - if (setupMode) { - stmp += " (setup mode)"; - } - output.printMSG(stmp.c_str()); - log_esp3d("%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); - //Set static IP - log_esp3d("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"); - } else { - output.printMSG(ip.toString().c_str()); - } - WiFi.setSleep(false); - WiFi.softAPsetHostname(NetConfig::hostname(true)); -#endif //ARDUINO_ARCH_ESP32 - return true; + if (setupMode) { + stmp += " (setup mode)"; + } + output.printMSG(stmp.c_str()); + log_esp3d("%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); + // Set static IP + log_esp3d("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"); } else { - output.printERROR("Starting AP failed"); - log_esp3d("Starting AP failed"); - return false; + output.printMSG(ip.toString().c_str()); } + WiFi.setSleep(false); + WiFi.softAPsetHostname(NetConfig::hostname(true)); +#endif // ARDUINO_ARCH_ESP32 + return true; + } else { + output.printERROR("Starting AP failed"); + log_esp3d_e("Starting AP failed"); + return false; + } } -bool WiFiConfig::started() -{ - return (WiFi.getMode() != WIFI_OFF); -} +bool WiFiConfig::started() { return (WiFi.getMode() != WIFI_OFF); } /** * begin WiFi setup */ -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"); +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"); + } + int8_t wifiMode = espMode; + if (wifiMode == ESP_WIFI_AP || wifiMode == ESP_AP_SETUP) { + log_esp3d("Starting AP mode"); + res = StartAP(wifiMode == ESP_AP_SETUP); + } else if (wifiMode == ESP_WIFI_STA) { + log_esp3d("Starting STA"); + res = StartSTA(); + // AP is backup mode + if (!res) { + if (Settings_ESP3D::isVerboseBoot()) { + output.printMSG("Starting fallback mode"); + } + espMode = Settings_ESP3D::read_byte(ESP_STA_FALLBACK_MODE); + NetConfig::setMode(espMode); + if (espMode == ESP_AP_SETUP) { + log_esp3d("Starting AP mode in setup mode"); + res = StartAP(true); + } else { + // let setup to handle the change + res = true; + } } - int8_t wifiMode = espMode; - if (wifiMode == ESP_WIFI_AP || wifiMode == ESP_AP_SETUP) { - log_esp3d("Starting AP mode"); - res = StartAP(wifiMode == ESP_AP_SETUP); - } else if (wifiMode == ESP_WIFI_STA) { - log_esp3d("Starting STA"); - res = StartSTA(); - //AP is backup mode - if(!res) { - if (Settings_ESP3D::isVerboseBoot()) { - output.printMSG("Starting fallback mode"); - } - espMode = Settings_ESP3D::read_byte(ESP_STA_FALLBACK_MODE); - NetConfig::setMode(espMode); - if (espMode == ESP_AP_SETUP) { - log_esp3d("Starting AP mode in setup mode"); - res = StartAP(true); - } else { - //let setup to handle the change - res = true; - } - - } - } - return res; + } + return res; } /** * End WiFi */ -void WiFiConfig::end() -{ - //Sanity check - if((WiFi.getMode() == WIFI_STA) || (WiFi.getMode() == WIFI_AP_STA)) { - if(WiFi.isConnected()) { - WiFi.disconnect(true); - } +void WiFiConfig::end() { + // Sanity check + if ((WiFi.getMode() == WIFI_STA) || (WiFi.getMode() == WIFI_AP_STA)) { + if (WiFi.isConnected()) { + WiFi.disconnect(true); } - if((WiFi.getMode() == WIFI_AP) || (WiFi.getMode() == WIFI_AP_STA)) { - if(WiFi.isConnected()) { - WiFi.softAPdisconnect(true); - } + } + if ((WiFi.getMode() == WIFI_AP) || (WiFi.getMode() == WIFI_AP_STA)) { + if (WiFi.isConnected()) { + WiFi.softAPdisconnect(true); } - WiFi.mode(WIFI_OFF); + } + WiFi.mode(WIFI_OFF); } /** * Handle not critical actions that must be done in sync environement */ -void WiFiConfig::handle() -{ - //to avoid mixed mode - if (WiFi.getMode() == WIFI_AP_STA) { - if (WiFi.scanComplete() != WIFI_SCAN_RUNNING) { - WiFi.enableSTA (false); - } +void WiFiConfig::handle() { + // to avoid mixed mode + if (WiFi.getMode() == WIFI_AP_STA) { + if (WiFi.scanComplete() != WIFI_SCAN_RUNNING) { + WiFi.enableSTA(false); } + } } -const char* WiFiConfig::getSleepModeString () -{ +const char* WiFiConfig::getSleepModeString() { #ifdef ARDUINO_ARCH_ESP32 - if (WiFi.getSleep()) { - return "modem"; - } else { - return "none"; - } -#endif //ARDUINO_ARCH_ESP32 + if (WiFi.getSleep()) { + return "modem"; + } else { + return "none"; + } +#endif // ARDUINO_ARCH_ESP32 #ifdef ARDUINO_ARCH_ESP8266 - WiFiSleepType_t ps_type = WiFi.getSleepMode(); - if (ps_type == WIFI_NONE_SLEEP) { - return "none"; - } else if (ps_type == WIFI_LIGHT_SLEEP) { - return "light"; - } else if (ps_type == WIFI_MODEM_SLEEP) { - return "modem"; - } else { - return "unknown"; - } -#endif //ARDUINO_ARCH_ESP8266 + WiFiSleepType_t ps_type = WiFi.getSleepMode(); + if (ps_type == WIFI_NONE_SLEEP) { + return "none"; + } else if (ps_type == WIFI_LIGHT_SLEEP) { + return "light"; + } else if (ps_type == WIFI_MODEM_SLEEP) { + return "modem"; + } else { + return "unknown"; + } +#endif // ARDUINO_ARCH_ESP8266 } -const char* WiFiConfig::getPHYModeString (uint8_t wifimode) -{ +const char* WiFiConfig::getPHYModeString(uint8_t wifimode) { #ifdef ARDUINO_ARCH_ESP32 - uint8_t PhyMode; - esp_wifi_get_protocol ((wifi_interface_t)((wifimode == WIFI_STA)?ESP_IF_WIFI_STA:ESP_IF_WIFI_AP), &PhyMode); -#endif //ARDUINO_ARCH_ESP32 + uint8_t PhyMode; + esp_wifi_get_protocol( + (wifi_interface_t)((wifimode == WIFI_STA) ? ESP_IF_WIFI_STA + : ESP_IF_WIFI_AP), + &PhyMode); +#endif // ARDUINO_ARCH_ESP32 #ifdef ARDUINO_ARCH_ESP8266 - (void)wifimode; - WiFiPhyMode_t PhyMode = WiFi.getPhyMode(); -#endif //ARDUINO_ARCH_ESP8266 - if (PhyMode == (WIFI_PHY_MODE_11G) ) { - return "11g"; - } else if (PhyMode == (WIFI_PHY_MODE_11B) ) { - return "11b"; - } else if (PhyMode == (WIFI_PHY_MODE_11N) ) { - return "11n"; - } else { - return "unknown"; - } + (void)wifimode; + WiFiPhyMode_t PhyMode = WiFi.getPhyMode(); +#endif // ARDUINO_ARCH_ESP8266 + if (PhyMode == (WIFI_PHY_MODE_11G)) { + return "11g"; + } else if (PhyMode == (WIFI_PHY_MODE_11B)) { + return "11b"; + } else if (PhyMode == (WIFI_PHY_MODE_11N)) { + return "11n"; + } else { + return "unknown"; + } } -bool WiFiConfig::is_AP_visible() -{ +bool WiFiConfig::is_AP_visible() { #ifdef ARDUINO_ARCH_ESP32 - wifi_config_t conf; - esp_wifi_get_config ((wifi_interface_t)ESP_IF_WIFI_AP, &conf); - return (conf.ap.ssid_hidden == 0); -#endif //ARDUINO_ARCH_ESP32 + wifi_config_t conf; + esp_wifi_get_config((wifi_interface_t)ESP_IF_WIFI_AP, &conf); + return (conf.ap.ssid_hidden == 0); +#endif // ARDUINO_ARCH_ESP32 #ifdef ARDUINO_ARCH_ESP8266 - struct softap_config apconfig; - wifi_softap_get_config (&apconfig); - return (apconfig.ssid_hidden == 0); -#endif //ARDUINO_ARCH_ESP8266 + struct softap_config apconfig; + wifi_softap_get_config(&apconfig); + return (apconfig.ssid_hidden == 0); +#endif // ARDUINO_ARCH_ESP8266 } -const char * WiFiConfig::AP_SSID() -{ - static String ssid; +const char* WiFiConfig::AP_SSID() { + static String ssid; #ifdef ARDUINO_ARCH_ESP32 - wifi_config_t conf; - esp_wifi_get_config ((wifi_interface_t)ESP_IF_WIFI_AP, &conf); - ssid = (const char*) conf.ap.ssid; -#endif //ARDUINO_ARCH_ESP32 + wifi_config_t conf; + esp_wifi_get_config((wifi_interface_t)ESP_IF_WIFI_AP, &conf); + ssid = (const char*)conf.ap.ssid; +#endif // ARDUINO_ARCH_ESP32 #ifdef ARDUINO_ARCH_ESP8266 - struct softap_config apconfig; - wifi_softap_get_config (&apconfig); - ssid = (const char*) apconfig.ssid; -#endif //ARDUINO_ARCH_ESP8266 - return ssid.c_str(); + struct softap_config apconfig; + wifi_softap_get_config(&apconfig); + ssid = (const char*)apconfig.ssid; +#endif // ARDUINO_ARCH_ESP8266 + return ssid.c_str(); } -const char * WiFiConfig::AP_Auth_String() -{ - uint8_t mode = 0; +const char* WiFiConfig::AP_Auth_String() { + uint8_t mode = 0; #ifdef ARDUINO_ARCH_ESP32 - wifi_config_t conf; - esp_wifi_get_config ((wifi_interface_t)ESP_IF_WIFI_AP, &conf); - mode = conf.ap.authmode; + wifi_config_t conf; + esp_wifi_get_config((wifi_interface_t)ESP_IF_WIFI_AP, &conf); + mode = conf.ap.authmode; -#endif //ARDUINO_ARCH_ESP32 +#endif // ARDUINO_ARCH_ESP32 #ifdef ARDUINO_ARCH_ESP8266 - struct softap_config apconfig; - wifi_softap_get_config (&apconfig); - mode = apconfig.authmode; -#endif //ARDUINO_ARCH_ESP8266 - if (mode == AUTH_OPEN) { - return "none"; - } else if (mode == AUTH_WEP) { - return "WEP"; - } else if (mode == AUTH_WPA_PSK) { - return "WPA"; - } else if (mode == AUTH_WPA2_PSK) { - return "WPA2"; - } else { - return "WPA/WPA2"; - } + struct softap_config apconfig; + wifi_softap_get_config(&apconfig); + mode = apconfig.authmode; +#endif // ARDUINO_ARCH_ESP8266 + if (mode == AUTH_OPEN) { + return "none"; + } else if (mode == AUTH_WEP) { + return "WEP"; + } else if (mode == AUTH_WPA_PSK) { + return "WPA"; + } else if (mode == AUTH_WPA2_PSK) { + return "WPA2"; + } else { + return "WPA/WPA2"; + } } -const char * WiFiConfig::AP_Gateway_String() -{ - static String tmp; +const char* WiFiConfig::AP_Gateway_String() { + static String tmp; #ifdef ARDUINO_ARCH_ESP32 - tcpip_adapter_ip_info_t ip_AP; - tcpip_adapter_get_ip_info (TCPIP_ADAPTER_IF_AP, &ip_AP); - tmp = IPAddress (ip_AP.gw.addr).toString(); -#endif //ARDUINO_ARCH_ESP32 + tcpip_adapter_ip_info_t ip_AP; + tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_AP, &ip_AP); + tmp = IPAddress(ip_AP.gw.addr).toString(); +#endif // ARDUINO_ARCH_ESP32 #ifdef ARDUINO_ARCH_ESP8266 - struct ip_info ip_AP; - if (!wifi_get_ip_info (SOFTAP_IF, &ip_AP)) { - log_esp3d("Error getting gateway ip"); - } - tmp = IPAddress (ip_AP.gw).toString(); -#endif //ARDUINO_ARCH_ESP8266 - return tmp.c_str(); + struct ip_info ip_AP; + if (!wifi_get_ip_info(SOFTAP_IF, &ip_AP)) { + log_esp3d_e("Error getting gateway ip"); + } + tmp = IPAddress(ip_AP.gw).toString(); +#endif // ARDUINO_ARCH_ESP8266 + return tmp.c_str(); } -const char * WiFiConfig::AP_Mask_String() -{ - static String tmp; +const char* WiFiConfig::AP_Mask_String() { + static String tmp; #ifdef ARDUINO_ARCH_ESP32 - tcpip_adapter_ip_info_t ip_AP; - tcpip_adapter_get_ip_info (TCPIP_ADAPTER_IF_AP, &ip_AP); - tmp = IPAddress (ip_AP.netmask.addr).toString(); -#endif //ARDUINO_ARCH_ESP32 + tcpip_adapter_ip_info_t ip_AP; + tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_AP, &ip_AP); + tmp = IPAddress(ip_AP.netmask.addr).toString(); +#endif // ARDUINO_ARCH_ESP32 #ifdef ARDUINO_ARCH_ESP8266 - struct ip_info ip_AP; - if (!wifi_get_ip_info (SOFTAP_IF, &ip_AP)) { - log_esp3d("Error getting mask ip"); - } - tmp = IPAddress (ip_AP.netmask).toString(); -#endif //ARDUINO_ARCH_ESP8266 - return tmp.c_str(); + struct ip_info ip_AP; + if (!wifi_get_ip_info(SOFTAP_IF, &ip_AP)) { + log_esp3d_e("Error getting mask ip"); + } + tmp = IPAddress(ip_AP.netmask).toString(); +#endif // ARDUINO_ARCH_ESP8266 + return tmp.c_str(); } -const char * WiFiConfig::getConnectedSTA(uint8_t * totalcount, bool reset) -{ - static uint8_t count = 0; - static uint8_t current = 0; - static String data; - data = ""; +const char* WiFiConfig::getConnectedSTA(uint8_t* totalcount, bool reset) { + static uint8_t count = 0; + static uint8_t current = 0; + static String data; + data = ""; #ifdef ARDUINO_ARCH_ESP32 - if (current > count) { - current =0; - } - static wifi_sta_list_t station; - static tcpip_adapter_sta_list_t tcpip_sta_list; - if (reset) { - count = 0; - } - if (count == 0) { - current = 0; - esp_wifi_ap_get_sta_list (&station); - tcpip_adapter_get_sta_list (&station, &tcpip_sta_list); - count = station.num; - } - if (count > 0) { - data = IPAddress (tcpip_sta_list.sta[current].ip.addr).toString(); - data += "("; - data += NetConfig::mac2str(tcpip_sta_list.sta[current].mac); - data += ")"; - current++; - } + if (current > count) { + current = 0; + } + static wifi_sta_list_t station; + static tcpip_adapter_sta_list_t tcpip_sta_list; + if (reset) { + count = 0; + } + if (count == 0) { + current = 0; + esp_wifi_ap_get_sta_list(&station); + tcpip_adapter_get_sta_list(&station, &tcpip_sta_list); + count = station.num; + } + if (count > 0) { + data = IPAddress(tcpip_sta_list.sta[current].ip.addr).toString(); + data += "("; + data += NetConfig::mac2str(tcpip_sta_list.sta[current].mac); + data += ")"; + current++; + } -#endif //ARDUINO_ARCH_ESP32 +#endif // ARDUINO_ARCH_ESP32 #ifdef ARDUINO_ARCH_ESP8266 - static struct station_info * station; - if (current > count) { - current = 0; - count = 0; + static struct station_info* station; + if (current > count) { + current = 0; + count = 0; + } + if (reset) { + count = 0; + } + if (count == 0) { + current = 0; + station = wifi_softap_get_station_info(); + struct station_info* station_tmp = station; + while (station) { + // go next record + count++; + station = STAILQ_NEXT(station, next); } - if (reset) { - count = 0; + station = station_tmp; + } + if ((count > 0) && station) { + data = IPAddress((const uint8_t*)&station->ip).toString(); + data += "("; + data += NetConfig::mac2str(station->bssid); + data += ")"; + current++; + station = STAILQ_NEXT(station, next); + if ((current == count) || !station) { + wifi_softap_free_station_info(); } - if (count == 0) { - current = 0; - station = wifi_softap_get_station_info(); - struct station_info * station_tmp = station; - while (station) { - //go next record - count++; - station = STAILQ_NEXT (station, next); - } - station = station_tmp; - } - if ((count > 0) && station) { - data = IPAddress ((const uint8_t *) &station->ip).toString(); - data += "("; - data += NetConfig::mac2str(station->bssid); - data += ")"; - current++; - station = STAILQ_NEXT (station, next); - if ((current == count) || !station) { - wifi_softap_free_station_info(); - } - } -#endif //ARDUINO_ARCH_ESP8266 - if(totalcount) { - *totalcount = count; - } - return data.c_str(); + } +#endif // ARDUINO_ARCH_ESP8266 + if (totalcount) { + *totalcount = count; + } + return data.c_str(); } -#endif // WIFI_FEATURE - +#endif // WIFI_FEATURE