Repository: theelims/ESP32-sveltekit Branch: main Commit: 81827a2af941 Files: 231 Total size: 797.0 KB Directory structure: gitextract_e2fr6h29/ ├── .github/ │ └── workflows/ │ └── ci.yaml ├── .gitignore ├── CHANGELOG.md ├── ESP32-sveltekit.code-workspace ├── LICENSE ├── README.md ├── docs/ │ ├── buildprocess.md │ ├── components.md │ ├── gettingstarted.md │ ├── index.md │ ├── restfulapi.md │ ├── statefulservice.md │ ├── stores.md │ ├── structure.md │ └── sveltekit.md ├── factory_settings.ini ├── features.ini ├── interface/ │ ├── .eslintignore │ ├── .eslintrc.cjs │ ├── .gitignore │ ├── .npmrc │ ├── .prettierignore │ ├── .prettierrc │ ├── LICENSE │ ├── package.json │ ├── src/ │ │ ├── app.css │ │ ├── app.d.ts │ │ ├── app.html │ │ ├── lib/ │ │ │ ├── DaisyUiHelper.ts │ │ │ ├── components/ │ │ │ │ ├── BatteryIndicator.svelte │ │ │ │ ├── Collapsible.svelte │ │ │ │ ├── ConfirmDialog.svelte │ │ │ │ ├── DraggableList.svelte │ │ │ │ ├── FirmwareUpdateDialog.svelte │ │ │ │ ├── InfoDialog.svelte │ │ │ │ ├── InputPassword.svelte │ │ │ │ ├── RSSIIndicator.svelte │ │ │ │ ├── SettingsCard.svelte │ │ │ │ ├── Spinner.svelte │ │ │ │ ├── UpdateIndicator.svelte │ │ │ │ └── toasts/ │ │ │ │ ├── Toast.svelte │ │ │ │ └── notifications.ts │ │ │ ├── stores/ │ │ │ │ ├── analytics.ts │ │ │ │ ├── battery.ts │ │ │ │ ├── socket.ts │ │ │ │ ├── telemetry.ts │ │ │ │ └── user.ts │ │ │ └── types/ │ │ │ └── models.ts │ │ └── routes/ │ │ ├── +error.svelte │ │ ├── +layout.svelte │ │ ├── +layout.ts │ │ ├── +page.svelte │ │ ├── connections/ │ │ │ ├── +page.ts │ │ │ ├── mqtt/ │ │ │ │ ├── +page.svelte │ │ │ │ ├── +page.ts │ │ │ │ ├── MQTT.svelte │ │ │ │ └── MQTTConfig.svelte │ │ │ └── ntp/ │ │ │ ├── +page.svelte │ │ │ ├── +page.ts │ │ │ ├── NTP.svelte │ │ │ └── timezones.ts │ │ ├── demo/ │ │ │ ├── +page.svelte │ │ │ ├── +page.ts │ │ │ └── Demo.svelte │ │ ├── ethernet/ │ │ │ ├── +page.svelte │ │ │ ├── +page.ts │ │ │ └── Ethernet.svelte │ │ ├── login.svelte │ │ ├── menu.svelte │ │ ├── statusbar.svelte │ │ ├── system/ │ │ │ ├── +page.ts │ │ │ ├── coredump/ │ │ │ │ ├── +page.svelte │ │ │ │ └── +page.ts │ │ │ ├── metrics/ │ │ │ │ ├── +page.svelte │ │ │ │ ├── +page.ts │ │ │ │ ├── BatteryMetrics.svelte │ │ │ │ └── SystemMetrics.svelte │ │ │ ├── status/ │ │ │ │ ├── +page.svelte │ │ │ │ ├── +page.ts │ │ │ │ └── SystemStatus.svelte │ │ │ └── update/ │ │ │ ├── +page.svelte │ │ │ ├── +page.ts │ │ │ ├── GithubFirmwareManager.svelte │ │ │ └── UploadFirmware.svelte │ │ ├── user/ │ │ │ ├── +page.svelte │ │ │ ├── +page.ts │ │ │ └── EditUser.svelte │ │ └── wifi/ │ │ ├── +page.ts │ │ ├── ap/ │ │ │ ├── +page.svelte │ │ │ ├── +page.ts │ │ │ └── Accesspoint.svelte │ │ └── sta/ │ │ ├── +page.svelte │ │ ├── +page.ts │ │ ├── EditNetwork.svelte │ │ ├── Scan.svelte │ │ └── Wifi.svelte │ ├── static/ │ │ └── manifest.json │ ├── svelte.config.js │ ├── tsconfig.json │ ├── vite-plugin-littlefs.ts │ └── vite.config.ts ├── lib/ │ ├── PsychicHttp/ │ │ ├── .gitignore │ │ ├── CHANGELOG.md │ │ ├── LICENSE │ │ ├── README.md │ │ ├── RELEASE.md │ │ ├── library.json │ │ ├── request flow.drawio │ │ └── src/ │ │ ├── ChunkPrinter.cpp │ │ ├── ChunkPrinter.h │ │ ├── PsychicClient.cpp │ │ ├── PsychicClient.h │ │ ├── PsychicCore.h │ │ ├── PsychicEndpoint.cpp │ │ ├── PsychicEndpoint.h │ │ ├── PsychicEventSource.cpp │ │ ├── PsychicEventSource.h │ │ ├── PsychicFileResponse.cpp │ │ ├── PsychicFileResponse.h │ │ ├── PsychicHandler.cpp │ │ ├── PsychicHandler.h │ │ ├── PsychicHttp.h │ │ ├── PsychicHttpServer.cpp │ │ ├── PsychicHttpServer.h │ │ ├── PsychicHttpsServer.cpp │ │ ├── PsychicHttpsServer.h │ │ ├── PsychicJson.cpp │ │ ├── PsychicJson.h │ │ ├── PsychicRequest.cpp │ │ ├── PsychicRequest.h │ │ ├── PsychicResponse.cpp │ │ ├── PsychicResponse.h │ │ ├── PsychicStaticFileHander.cpp │ │ ├── PsychicStaticFileHandler.h │ │ ├── PsychicStreamResponse.cpp │ │ ├── PsychicStreamResponse.h │ │ ├── PsychicUploadHandler.cpp │ │ ├── PsychicUploadHandler.h │ │ ├── PsychicWebHandler.cpp │ │ ├── PsychicWebHandler.h │ │ ├── PsychicWebParameter.h │ │ ├── PsychicWebSocket.cpp │ │ ├── PsychicWebSocket.h │ │ ├── TemplatePrinter.cpp │ │ ├── TemplatePrinter.h │ │ ├── http_status.cpp │ │ └── http_status.h │ └── framework/ │ ├── APSettingsService.cpp │ ├── APSettingsService.h │ ├── APStatus.cpp │ ├── APStatus.h │ ├── AnalyticsService.h │ ├── ArduinoJsonJWT.cpp │ ├── ArduinoJsonJWT.h │ ├── AuthenticationService.cpp │ ├── AuthenticationService.h │ ├── BatteryService.cpp │ ├── BatteryService.h │ ├── CoreDump.cpp │ ├── CoreDump.h │ ├── DownloadFirmwareService.cpp │ ├── DownloadFirmwareService.h │ ├── ESP32SvelteKit.cpp │ ├── ESP32SvelteKit.h │ ├── ESPFS.h │ ├── EthernetSettingsService.cpp │ ├── EthernetSettingsService.h │ ├── EthernetStatus.cpp │ ├── EthernetStatus.h │ ├── EventEndpoint.h │ ├── EventSocket.cpp │ ├── EventSocket.h │ ├── FSPersistence.h │ ├── FactoryResetService.cpp │ ├── FactoryResetService.h │ ├── Features.h │ ├── FeaturesService.cpp │ ├── FeaturesService.h │ ├── FirmwareUpdateEvents.h │ ├── HttpEndpoint.h │ ├── IPUtils.h │ ├── JsonUtils.h │ ├── LICENSE │ ├── MqttEndpoint.cpp │ ├── MqttEndpoint.h │ ├── MqttSettingsService.cpp │ ├── MqttSettingsService.h │ ├── MqttStatus.cpp │ ├── MqttStatus.h │ ├── NTPSettingsService.cpp │ ├── NTPSettingsService.h │ ├── NTPStatus.cpp │ ├── NTPStatus.h │ ├── NotificationService.cpp │ ├── NotificationService.h │ ├── RestartService.cpp │ ├── RestartService.h │ ├── SecurityManager.h │ ├── SecuritySettingsService.cpp │ ├── SecuritySettingsService.h │ ├── SettingValue.cpp │ ├── SettingValue.h │ ├── SleepService.cpp │ ├── SleepService.h │ ├── StatefulService.cpp │ ├── StatefulService.h │ ├── SystemStatus.cpp │ ├── SystemStatus.h │ ├── UploadFirmwareService.cpp │ ├── UploadFirmwareService.h │ ├── WebSocketServer.h │ ├── WiFiScanner.cpp │ ├── WiFiScanner.h │ ├── WiFiSettingsService.cpp │ ├── WiFiSettingsService.h │ ├── WiFiStatus.cpp │ └── WiFiStatus.h ├── mkdocs.yml ├── platformio.ini ├── scripts/ │ ├── build_interface.py │ ├── generate_cert_bundle.py │ ├── merge_bin.py │ ├── prebuild_utils.py │ ├── rename_fw.py │ └── save_elf.py ├── src/ │ ├── LightMqttSettingsService.cpp │ ├── LightMqttSettingsService.h │ ├── LightStateService.cpp │ ├── LightStateService.h │ └── main.cpp └── ssl_certs/ └── DigiCert_Global_Root_CA.pem ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/ci.yaml ================================================ name: ci on: push: branches: - master - main permissions: contents: write jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-python@v4 with: python-version: 3.x - run: echo "cache_id=$(date --utc '+%V')" >> $GITHUB_ENV - uses: actions/cache@v3 with: key: mkdocs-material-${{ env.cache_id }} path: .cache restore-keys: | mkdocs-material- - run: pip install mkdocs-material - run: mkdocs gh-deploy --force ================================================ FILE: .gitignore ================================================ .pio .clang_complete .gcc-flags.json *Thumbs.db /data/www /interface/build /interface/node_modules /interface/.eslintcache .vscode node_modules /releases /src/certs /temp /build /lib/framework/WWWData.h *WWWData.h lib/framework/WWWData.h ssl_certs/cacert.pem /logs .aid /scripts/__pycache__ .DS_Store *.bak ================================================ FILE: CHANGELOG.md ================================================ # Changelog All notable changes to this project will be documented in this file. ## [WIP] - Next Release ### Added - Add originID to StateUpdateResult update [#110](https://github.com/theelims/ESP32-sveltekit/pull/110) - Add originID to StateUpdateResult update [#110](https://github.com/theelims/ESP32-sveltekit/pull/110) - Ethernet Support [#113](https://github.com/theelims/ESP32-sveltekit/pull/113) ### Changed - Changed the width of the confirm dialog. - SvelteKit bundling as single files to reduce heap consumption. - Rework of firmware upload [#107](https://github.com/theelims/ESP32-sveltekit/pull/107) ### Fixes - WiFi reconnection issues [#109](https://github.com/theelims/ESP32-sveltekit/issues/109) - Blurred toast notifications [#114](https://github.com/theelims/ESP32-sveltekit/issues/114) ## [0.6.0] - 2025-11-03 > [!CAUTION] > This update has breaking changes! ### Added - Added `GEMINI.md` to store notes about the repository for the Gemini CLI. We are now using the Gemini CLI for development. - Added a build script to create a merged firmware file to use with [ESP Web Tools](https://esphome.github.io/esp-web-tools/) - Added compatibility with ESP32-C6 - Added getIP() function to WiFiSettingsService. - Added Arduino Log Colors - Possibility to add a loop callback to ESP32-Sveltekit to leverage its loop threat. Meant to include custom services so no separate task is needed for them. - Change wake-up pin in SleepService during runtime. It is also possible to use the internal pull-up or pull-down resistors now. - Get current connection status from ESP32-SvelteKit. Useful for status LED or displays. - Battery history graph to gauge battery consumption and device life. - Add a status topic (`online` or `offline`) to the MQTT client. It retains its message and sends `offline` as last will and testament, signalling all subscribers when it goes missing. - FeatureService sends updates through the event system. - WiFiSettingsService can set the WiFi station mode to offline, without deleting the list of networks. - Expands menu on selected subitem [#77](https://github.com/theelims/ESP32-sveltekit/pull/77) - Refactor System Status and Metrics, added PSRAM [#79](https://github.com/theelims/ESP32-sveltekit/pull/79) - Add /rest/coreDump endpoint [#87](https://github.com/theelims/ESP32-sveltekit/pull/87) & [#94](https://github.com/theelims/ESP32-sveltekit/pull/94) - Rate limiting for MQTT publish messages. Can be configured as factory setting or at runtime. `0` will disable the rate limiting. - Added [discord](https://discord.gg/MTn9mVUG5n) invite to readme.md and docs. - Created DraggableList component based on svelte-dnd-action (used in WiFi Settings) [#100](https://github.com/theelims/ESP32-sveltekit/pull/100) - Extended Collapsible and SettingsCard components to support a dirty status [#100](https://github.com/theelims/ESP32-sveltekit/pull/100) - Enhanced ConfirmDialog, InfoDialog and Toast components to support HTML content [#100](https://github.com/theelims/ESP32-sveltekit/pull/100) - Added connection check to WebSocket store (socket.ts) and allow secure WebSocket connections [#100](https://github.com/theelims/ESP32-sveltekit/pull/100) - Added a delayed reconnect function to WifiSettingsService.cpp to allow the last POST request from frontend (providing new network settings) to be properly responded to. In the previous implementation, the POST request was never responded to by the backend, as the connection was closed immediately upon receiving the request in the backend. This resulted in the user receiving no feedback about whether the settings update was successful, only a timeout that suggested something had gone wrong. [#100](https://github.com/theelims/ESP32-sveltekit/pull/100) - Added scripts/prebuild_utils.py that allows other build scripts to be executed depending on the type of the executed task (e.g. I don't want to have the interface built or the certificate bundle created on clean tasks) [#100](https://github.com/theelims/ESP32-sveltekit/pull/100) - Added build flag `-D TELEPLOT_TASKS` to plot task heap high water mark with teleplot. You can include this in your tasks as well: ```cpp #ifdef TELEPLOT_TASKS static int lastTime = 0; if (millis() - lastTime > 1000) { lastTime = millis(); Serial.printf(">ESP32SveltekitTask:%i:%i\n", millis(), uxTaskGetStackHighWaterMark(NULL)); } #endif ``` ### Changed - Lightstate example uses simpler, less explicit constructor - MQTT library updated - Analytics task was refactored into a loop() function which is called by the ESP32-sveltekit main task. - Updated PsychicHttp to v1.2.1 incl. patches. - Updated to DaisyUI 5 and Tailwind CSS 4 - Updated Svelte 5 --> see [Svelte 5 Migration Guide](https://svelte.dev/docs/svelte/v5-migration-guide) - Changed platform to [PIO Arduino](https://github.com/pioarduino/platform-espressif32) using Arduino 3 Core. Also upgrades ESP-IDF to v5. - ESPD_LOGx: replace first argument with TAG and define TAG as 🐼 [#85](https://github.com/theelims/ESP32-sveltekit/pull/85) - Replace rtc_get_reset_reason(0) with esp_reset_reason() [#86](https://github.com/theelims/ESP32-sveltekit/pull/86) - Default build_interface.py script to npm, if no lock file is found. - Replaced `svelte-dnd-list` with `svelte-dnd-action` as `svelte-dnd-list` creates build warnings and appears to no longer be maintained, while svelte-dnd-action is under active community development. [#100](https://github.com/theelims/ESP32-sveltekit/pull/100) - Made Spinner component more flexible (to allow other texts than "Loading..." or no text at all) [#100](https://github.com/theelims/ESP32-sveltekit/pull/100) - Reworked WiFi Settings (Station) dialog: added edit dialog for networks, rearranged UI components, used new DraggableList component [#100](https://github.com/theelims/ESP32-sveltekit/pull/100) ### Fixed - Ensure thread safety for client subscriptions [#58](https://github.com/theelims/ESP32-sveltekit/pull/58) - Deferred websocket event connection to after user validation & login [#72](https://github.com/theelims/ESP32-sveltekit/pull/72) - Wrong return type battery service - Wrong return types in various getService functions. - Add file.close in fileHandler handleRequest [#73](https://github.com/theelims/ESP32-sveltekit/pull/73) - Fixed bug in WiFiSettingsService preventing discovery of networks other than the first - Fixed mixup pull up and pull down when configuring wake up pin in SleepService.cpp - Wifi: Multiple edits bug resolved [#79](https://github.com/theelims/ESP32-sveltekit/pull/79) - Fixed broken link to Adafruit SSL Cert Store [#93](https://github.com/theelims/ESP32-sveltekit/issues/93) - Fixed JSON creation in WiFiSettingsService.h [#91](https://github.com/theelims/ESP32-sveltekit/pull/91) - Fixed preprocessor warning: usage of #ifdef with OR operator [#100](https://github.com/theelims/ESP32-sveltekit/pull/100) - Fixed preprocessor warning: redefinition of ESP_PLATFORM [#100](https://github.com/theelims/ESP32-sveltekit/pull/100) - Fixed deprecated usage of merge-bin and its parameters in scripts/merge_bin.py [#100](https://github.com/theelims/ESP32-sveltekit/pull/100) - Fixed Download OTA. Issues with certificate validation might remain, but build flag `-D DOWNLOAD_OTA_SKIP_CERT_VERIFY` allows to circumvent issue by sacrificing certificate validation. ### Removed - Removed async workers in PsychicHttp, as these were not used, but caused linker errors. ### Depreciate - Support for ESP Arduino 2 and ESP-IDF v4 will depreciate some time in the future. Try to migrate to the current Arduino 3 / ESP-IDF v5 based branch. ### Migration Guide #### PIO Arduino & ESP-IDF 5 The firmware is based on the community maintained fork [PIO Arduino](https://github.com/pioarduino/platform-espressif32) of Arduino 3 for ESP32. Which is based on ESP-IDF 5. Please make sure all your dependencies and application code is compatible with ESP-IDF 5. #### Frontend SvelteKit was updated to v2 and Svelte to v5. Please check the migration guides for [SvelteKit 2](https://svelte.dev/docs/kit/migrating-to-sveltekit-2) and the [Svelte 5 Migration Guide](https://svelte.dev/docs/svelte/v5-migration-guide) for the changes required on your frontend code. To migrate your frontend run ``` npm install --force npx sv migrate svelte-5 ``` Also DaisyUI and Tailwind CSS have been updated to their last major versions. Run the official Tailwind upgrade tool: ``` npx @tailwindcss/upgrade ``` This will migrate some of your svelte files to the new naming convention of Tailwind. For DaisyUI follow this [guide](https://daisyui.com/docs/upgrade/#changes-from-v4). Likely you'll need to redo all forms, as the components behave differently. Forms will need the `fieldset` class. Inputs will need an additional `w-full` to have the same behavior as before. And [labels](https://daisyui.com/components/label/) have a different syntax, too. The themes are to be found in `app.css` now. Add them back if they had been changed from the default. ### Acknowledgment Many thanks to @runeharlyk, @ewowi, @hmbacher, and @stamp who contributed significantly to this new release. ## [0.5.0] - 2024-05-06 Changes the Event Socket System to use a clearer message structure and MessagePack. Brings breaking changes to the `EventSocket.h` API. Updated daisyUI to v4. This has changes in the colors and switches to OKLCH. Also button groups and input groups have been depreciated in favor of join. This might require changes to custom parts of the code. Please double check all websites if the still have the desired looks. Updates ArduinoJSON from v6 to v7 to increase the available free heap. If you make use of ArduinoJSON, changes might be required. ### Added - Debug buildflag to switch between MessagePack and JSON for event messages. - Show SSID of the current WiFi Station as tooltip of the RSSI icon. ### Changed - Moved MQTT types to models.ts as well. [#49](https://github.com/theelims/ESP32-sveltekit/pull/49) - Updated daisyUI to 4.10.2 [#48](https://github.com/theelims/ESP32-sveltekit/pull/48) - Fixed spelling error in models.ts - Changed ArduinoJson from v6 to v7 increasing the free heap by ~40kb - Split NotificationService out of EventSocket into own class - Changed API of EventSocket.h. Now uses `void emitEvent(String event, JsonObject &jsonObject, const char *originId = "", bool onlyToSameOrigin = false);`. - Changed event socket message format to MessagePack ### Fixed - Fixes to WiFi.svelte and models.ts to fix type errors and visibility rights. - Fixes bug in highlighting the menu when navigating with the browser (back/forward) - Made WiFi connection routine more robust by using BSSID. Ensures that the STA truly connects to the strongest hotspot, even if several hotspots are in reach. ### Removed - Removed duplicate in ESP32SvelteKit.cpp [#47](https://github.com/theelims/ESP32-sveltekit/pull/47) and WiFi.svelte [#50](https://github.com/theelims/ESP32-sveltekit/pull/50) ### Acknowledgment Many thanks to @runeharlyk who contributed significantly to the new event socket system and fixed many smaller issues with the front-end. ## [0.4.0] - 2024-04-21 This upgrade might require one minor change as `MqttPubSub.h` and its class had been renamed to `MqttEndpoint.h` and `MqttEndoint` respectively. However, it is strongly advised, that you change all existing WebSocketServer endpoints to the new event socket system. > [!NOTE] > The new Event Socket system is likely to change with coming updates. ### Added - Added build flag `-D SERIAL_INFO` to platformio.ini to enable / disable all `Serial.print()` statements. On some boards with native USB those Serial prints have been reported to block and make the server unresponsive. - Added a hook handler to StatefulService. Unlike an UPDATE a hook is called every time a state receives an updated, even if the result is UNCHANGED or ERROR. - Added missing include for S2 in SystemStatus.cpp [#23](https://github.com/theelims/ESP32-sveltekit/issues/23) - Added awareness of front end build script for all 3 major JS package managers. The script will auto-identify the package manager by the lock-file. [#40](https://github.com/theelims/ESP32-sveltekit/pull/40) - Added a new event socket to bundle the websocket server and the notifications events. This saves on open sockets and allows for concurrent visitors of the internal website. The normal websocket server endpoint remains as an option, should a pure websocket connection be desired. An EventEndpoint was added to use this with Stateful Services. [#29](https://github.com/theelims/ESP32-sveltekit/issues/29) and [#43](https://github.com/theelims/ESP32-sveltekit/pull/43) - TS Types definition in one central place for the frontend. ### Changed - more generic board definition in platformio.ini [#20](https://github.com/theelims/ESP32-sveltekit/pull/20) - Renamed `MqttPubSub.h` and class to `MqttEndpoint.h` and class. - refactored MqttEndpoint.h into a single class to improve readability - Moves appName and copyright to `layout.ts` to keep customization in one place [#31](https://github.com/theelims/ESP32-sveltekit/pull/31) - Make event source use timeout for reconnect [#34](https://github.com/theelims/ESP32-sveltekit/pull/34) - Make each toasts disappear after timeout [#35](https://github.com/theelims/ESP32-sveltekit/pull/35) - Fixed version `platform = espressif32 @ 6.6.0` in platformio.ini - Analytics data limited to 1000 data points (roughly 33 minutes). - postcss.config.cjs as ESM module [#24](https://github.com/theelims/ESP32-sveltekit/issues/24) ### Fixed - Fixed compile error with FLAG `-D SERVE_CONFIG_FILES` - Fixed typo in telemetry.ts [#38](https://github.com/theelims/ESP32-sveltekit/pull/38) - Fixed the development warning: `Loading /rest/features using 'window.fetch'. For best results, use the 'fetch' that is passed to your 'load' function:` ### Removed - Duplicate method in FeatureService [#18](https://github.com/theelims/ESP32-sveltekit/pull/18) - Duplicate lines in Systems Settings view. - Removes duplicate begin [#36](https://github.com/theelims/ESP32-sveltekit/pull/36) - Temporary disabled OTA progress update due to crash with PsychicHttp [#32](https://github.com/theelims/ESP32-sveltekit/issues/32) until a fix is found. ### Known Issues - On ESP32-C3 the security features should be disabled in features.ini: `-D FT_SECURITY=0`. If enabled the ESP32-C3 becomes extremely sluggish with frequent connection drops. ## [0.3.0] - 2024-02-05 > [!CAUTION] > This update has breaking changes! This is a major change getting rid of all ESPAsyncTCP and ESPAsyncWebserver dependencies. Despite their popularity they are plagued with countless bugs, since years unmaintained, not SSL capable and simply not suitable for a production build. Although several attempts exist to fix the most pressing bugs even these libraries lead to frequent crashes. This new version replaces them with ESP-IDF based components. [PsychicHttp](https://github.com/hoeken/PsychicHttp) and [PsychicMqttClient](https://github.com/theelims/PsychicMqttClient) both wrap the ESP-IDF components in a familiar wrapper for easy porting of the code base. However, this will break existing code and will require some effort on your codebase. In return the stability is improved greatly and the RAM usage more friendly. Now e.g. running Bluetooth in parallel becomes possible. ### Added - Added postscript to platform.io build process to copy, rename and calculate MD5 checksum of \*.bin file. These files are ready for uploading to the Github Release page. - Added more information to SystemStatus API - Added generateToken API for security settings - Added Multi-WiFi capability. Add up to five WiFi configurations and connect to either strongest network (default), or by priority. - Added InfoDialog as a simpler version of the ConfirmDialog for a simple notification modal. - Added Adafruit certificate repository as the default choice for the X509 certificate bundle. ### Changed - Better route protection for user page with deep link. - Changed build_interface.py script to check for modified files in the interface sources before re-building the interface. Saves some time on the compilation process. - Upload firmware binary allows uploading of MD5 checksum file in advance to verify downloaded firmware package. - GithubFirmwareManager checks against PIO build_target in filename to support Github OTA for binaries build for various targets. You should rename your old release \*.bin files on the Github release pages for backward compatibility. - Changed MQTT Client to an ESP-IDF backed one which supports SSL/TLS X509 root CA bundles and transport over WS. - Changed the `PROGMEM_WWW` flag to `EMBED_WWW` as there is technically speaking no PROGMEM on ESP32's. - Updated dependencies to the latest version. Except SvelteKit. ### Fixed - Fixed reactivity of System Status page. ### Removed - Removed support for Arduino ESP OTA. - HttpEndpoints and Websocket Server without a securityManager are no longer possible. ### Migrate from ESPAsyncWebServer to PsychicHttp #### Migrate `main.cpp` Change the server and ESPSvelteKit instances to PsychicHttpServer and give the ESP32SvelteKit constructor the number of http endpoints of your project. ``` PsychicHttpServer server; ESP32SvelteKit esp32sveltekit(&server, 120); ``` Remove `server.begin();` in `void setup()`. This is handled by ESP32SvelteKit now. #### Migrate `platformio.ini` Remove the following `build_flags`: ```ini ; Increase queue size of SSE and WS -D SSE_MAX_QUEUED_MESSAGES=64 -D WS_MAX_QUEUED_MESSAGES=64 -D CONFIG_ASYNC_TCP_RUNNING_CORE=0 -D NO_GLOBAL_ARDUINOOTA -D PROGMEM_WWW ``` Add the following `build_flags` and adjust to your app, if needed: ```ini -D BUILD_TARGET=\"$PIOENV\" -D APP_NAME=\"ESP32-Sveltekit\" ; Must only contain characters from [a-zA-Z0-9-_] as this is converted into a filename -D APP_VERSION=\"0.3.0\" ; semver compatible version string -D EMBED_WWW ``` Remove the lib dependency `esphome/AsyncTCP-esphome @ ^2.0.0` and add `https://github.com/theelims/PsychicMqttClient.git` Consider adjusting `board_ssl_cert_source = adafruit`, so that the new MQTT client has universal SSL/TLS support with a wide range of CA root certificates. #### Migrate `factory_settings.ini` The new MQTT client has slightly renamed factory settings: ```ini ; MQTT settings -D FACTORY_MQTT_ENABLED=false -D FACTORY_MQTT_URI=\"mqtts://mqtt.eclipseprojects.io:8883\" -D FACTORY_MQTT_USERNAME=\"\" ; supports placeholders -D FACTORY_MQTT_PASSWORD=\"\" -D FACTORY_MQTT_CLIENT_ID=\"#{platform}-#{unique_id}\" ; supports placeholders -D FACTORY_MQTT_KEEP_ALIVE=120 -D FACTORY_MQTT_CLEAN_SESSION=true ``` Max Topic Length is no longer needed. #### Custom Stateful Services Adapt the class constructor (`(PsychicHttpServer *server, ...`) to PsychicHttpServer. Due to the loading sequence HttpEndoint and WebsocketServer both have gotten a `begin()` function to register their http endpoints with the server. This must be called in your stateful services' own `begin()` function: ```cpp void LightStateService::begin() { _httpEndpoint.begin(); _webSocketServer.begin(); _state.ledOn = DEFAULT_LED_STATE; onConfigUpdated(); } ``` ## [0.2.2] - 2023-10-08 ### Added - Status reports reset-reason & uptime. - AnalyticsService to draw graphs about heap usage and other time dependent values - Added ping to WebSocket Server - Use telemetry store with RSSI messages to gauge health of connection. Automatic reconnect for SSE and WS. - Added user supplied features to FeatureService - Compiler flag to let it serve the config JSONs for debug purposes - Hard fork of ESPAsyncWebserver as it is unmaintained to fix bugs and add features ### Changed - Changed JSON format for websocket server and removed "payload" property. JSON is the same as for MQTT or HTTP now. - Changed features.ini to default `FT_SLEEP=0` - Updated dependencies to latest version. ## [0.2.1] - 2023-09-11 ### Fixed - Fixed the boot loop issue for Arduino 6.4.0 ## [0.2.0] - 2023-08-03 ### Added - Introduced CHANGELOG.md - Added core temperature to the system status API - Added mDNS / Bonjour / zeroConf for better discoverability in local network - Added recovery mode which forces AP to spin up regardless from its settings - Added push notification service to show notification toasts on all clients - Added SSE to update RSSI in status bar on client - Added firmware version to System Status API - Added sleep service to send ESP32 into deep sleep. Wake-up with button using EXT1 - Added battery service to show battery state of charge in the status bar. Uses SSE. - Added download firmware manager to pull firmware binaries e.g. from github release pages - modified generate_cert_bundle.py from Espressif included into the build process to automatically create SSL Root CA Bundle ### Changed - Improved system status with more meaningful presentation of available data - Improved layout on small screens - Increased queue size for SSE and WS to 64 instead of 32 - ESP32-SvelteKit loop()-function is its own task now - ArduinoOTA handle runs in own task now - AsyncTCP tasks run on Core 0 to move all networking related stuff to Core 0 and free up Core 1 for business logic - Compiler flag on which core ESP32-sveltekit tasks should run - Renamed WebSocketRxTx.h to WebSocketServer.h to create a distinction between WS Client and WS Server interfaces - Made code of LightStateExample slightly more verbose - getServer() returning a pointer to the AsyncWebServer instance. - Updated frontend dependencies and packages to newest version. ### Depreciated - ArduinoOTA feature is set to depreciate. It is unstable with mDNS causing some reset loops until it finally settles. ### Removed - `FT_PROJECT` feature flag removed. ## [0.1.0] - 2023-05-18 This is the initial release of ESP32-sveltekit. With this it is feature complete to [rjwats/esp8266-react](https://github.com/rjwats/esp8266-react), where it forked from. ### Added - Added copyright notes ### Changed - Renaming into ESP32-sveltekit - Small changes to reflect the slightly different file structure of sveltekit - Build process for sveltekit ### Removed - Dropping support for ESP8266 ================================================ FILE: ESP32-sveltekit.code-workspace ================================================ { "folders": [ { "path": "." } ], "settings": { "files.associations": { "*.tcc": "cpp", "algorithm": "cpp", "esp32-hal-misc.c": "cpp", "esp_crt_bundle.h": "c", "functional": "cpp", "array": "cpp", "atomic": "cpp", "bitset": "cpp", "cctype": "cpp", "clocale": "cpp", "cmath": "cpp", "cstdarg": "cpp", "cstddef": "cpp", "cstdint": "cpp", "cstdio": "cpp", "cstdlib": "cpp", "cstring": "cpp", "ctime": "cpp", "cwchar": "cpp", "cwctype": "cpp", "deque": "cpp", "list": "cpp", "unordered_map": "cpp", "vector": "cpp", "exception": "cpp", "iterator": "cpp", "map": "cpp", "memory": "cpp", "memory_resource": "cpp", "numeric": "cpp", "optional": "cpp", "random": "cpp", "regex": "cpp", "string": "cpp", "string_view": "cpp", "system_error": "cpp", "tuple": "cpp", "type_traits": "cpp", "utility": "cpp", "fstream": "cpp", "initializer_list": "cpp", "iosfwd": "cpp", "istream": "cpp", "limits": "cpp", "new": "cpp", "ostream": "cpp", "sstream": "cpp", "stdexcept": "cpp", "streambuf": "cpp", "cinttypes": "cpp", "typeinfo": "cpp", "unordered_set": "cpp", "iomanip": "cpp" } } } ================================================ FILE: LICENSE ================================================ ESP32 SvelteKit is distributed with two licenses for different sections of the code. The back end code inherits the GNU LESSER GENERAL PUBLIC LICENSE Version 3 and is therefore distributed with said license. The front end code is distributed under the MIT License. MIT License Copyright (C) 2023 - 2024 theelims Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. ================================================ FILE: README.md ================================================ # ESP32 SvelteKit - Create Amazing IoT Projects
A simple and extensible framework for ESP32 based IoT projects with a feature-rich, beautiful, and responsive front-end build with [Sveltekit](https://kit.svelte.dev/), [TailwindCSS](https://tailwindcss.com/) and [DaisyUI](https://daisyui.com/). This is a project template to get you started in no time backed by a powerful back end service, an amazing front end served from the ESP32 and an easy to use build chain to get everything going. It was forked from the fabulous [rjwats/esp8266-react](https://github.com/rjwats/esp8266-react) project, from where it inherited the mighty back end services. > **Tip**: This template repository is not meant to be used stand alone. If you're just looking for a WiFi manager there are plenty of options available. This is a starting point when you need a rich web UI. ## Features ### :butterfly: Beautiful UI powered by DaisyUI and TailwindCSS Beautiful, responsive UI which works equally well on desktop and on mobile. Gently animated for a snappy and modern feeling without ever being obtrusive or in the way. Easy theming with DaisyUI and media-queries to respect the users wish for a light or dark theme. ### :t-rex: Low Memory Footprint and Easy Customization by Courtesy of SvelteKit SvelteKit is ideally suited to be served from constrained devices like an ESP32. It's unique approach leads to very slim files. No bloatware like other popular JS frameworks. Not only the low memory footprint make it ideal but the developer experience is also outstanding letting you customize the front end with ease. Adapt and add functionality as you need it. The back end has you covered as well. ### :telephone: Rich Communication Interfaces Comes with a rich set of communication interfaces to cover most standard needs of an IoT application. Like MQTT client, HTTP RESTful API, a WebSocket based Event Socket and a classic Websocket Server. All communication channels are stateful and fully synchronized. Changes propagate and are communicated to all other participants. The states can be persisted on the file system as well. For accurate time keeping time can by synchronized over NTP. ### :file_cabinet: WiFi Provisioning and Management Naturally ESP32 SvelteKit comes with rich features to manage all your WiFi needs. From pulling up an access point for provisioning or as fall back, to fully manage your WiFi networks. Scan for available networks and connect to them. Advanced configuration options like static IP are on board as well. ### :old_key: Secured API and User Management Manage different user of your app with two authorization levels. An administrator and a guest user. Authenticate their API calls with a JWT token. Manage the user's profile from the admin interface. Use at own risk, as it is neither secure without the ability to use TLS/SSL encryption on the ESP32 server, nor very convenient, as only an admin can change passwords. ### :airplane: OTA Upgrade Service The framework can provide two different channels for Over-the-Air updates. Either by uploading a \*.bin file from the web interface. Or by pulling a firmware image from an update server. This is implemented with the github release page as an example. It is even possible to have different build environments at the same time and the Github OTA process pulls the correct binary. ### :building_construction: Automated Build Chain The automated build chain takes out the pain and tears of getting all the bits and pieces play nice together. The repository contains a PlatformIO project at its heart. A SvelteKit project for the frontend code and a mkdocs project for the documentation go alongside. The PlatformIO build tools not only build the SvelteKit frontend with Vite, but also ensure that the build results are gzipped and find their way into the flash memory of the ESP32. You have two choices to serve the frontend either from the flash partition, or embedded into the firmware binary. The latter is much more friendly if your frontend code should be distributed OTA as well, leaving all configuration files intact. ### :icecream: Compatible with all ESP32 Flavours The code runs on many variants of the ESP32 chip family. From the plain old ESP32, the ESP32-S3 and ESP32-C3. Other ESP32 variants might work, but haven't been tested. Sorry, no support for the older ESP8266. Go with one of the ESP32's instead. ## Visit the Project Site [https://theelims.github.io/ESP32-sveltekit/](https://theelims.github.io/ESP32-sveltekit/) ## Join our [Discord](https://discord.gg/MTn9mVUG5n) ## Libraries Used - [SvelteKit](https://kit.svelte.dev/) - [Tailwind CSS](https://tailwindcss.com/) - [DaisyUI](https://daisyui.com/) - [tabler ICONS](https://tabler-icons.io/) - [unplugin-icons](https://github.com/antfu/unplugin-icons) - [svelte-modals](https://svelte-modals.mattjennings.io/) - [svelte-dnd-action](https://github.com/isaacHagoel/svelte-dnd-action) - [ArduinoJson](https://github.com/bblanchon/ArduinoJson) - [PsychicHttp](https://github.com/hoeken/PsychicHttp) - [PsychicMqttClient](https://github.com/theelims/PsychicMqttClient) ## Licensing ESP32 SvelteKit is distributed with two licenses for different sections of the code. The back end code inherits the GNU LESSER GENERAL PUBLIC LICENSE Version 3 and is therefore distributed with said license. The front end code is distributed under the MIT License. See the [LICENSE](LICENSE) for a full text of both licenses. ================================================ FILE: docs/buildprocess.md ================================================ # Build Process The build process is controlled by [platformio.ini](https://github.com/theelims/ESP32-sveltekit/platformio.ini) and automates the build of the front end website with Vite as well as the binary compilation for the ESP32 firmware. Whenever PlatformIO is building a new binary it will call the python script [build_interface.py](https://github.com/theelims/ESP32-sveltekit/scripts/build_interface.py) to action. It will check the frontend files for changes. If necessary it will start the Vite build and gzip the resulting files either to the `data/` directory or embed them into a header file. In case the WWW files go into a LITTLEFS partition a file system image for the flash is created for the default build environment and upload to the ESP32. ## Changing the JS package manager This project uses NPM as the default package manager. However, many users might have different preferences and like to use YARN or PNPM instead. Just switch the interface to one of the other package managers. The build script identify the package manager by the presence of its lock-file and start the vite build process accordingly. ## Serving from Flash or Embedding into the Binary The front end website can be served either from the LITTLEFS partition of the flash, or embedded into the firmware binary (default). Later has the advantage that only one binary needs to be distributed easing the OTA process. Further more this is desirable if you like to preserve the settings stored in the LITTLEFS partition, or have other files there that need to survive a firmware update. To serve from the LITTLEFS partition instead please comment the following build flag out: ```ini build_flags = ... -D EMBED_WWW ``` ### Partitioning If you choose to embed the frontend it becomes part of the firmware binary (default). As many ESP32 modules only come with 4MB built-in flash this results in the binary being too large for the reserved flash. Therefor a partition scheme with a larger section for the executable code is selected. However, this limits the LITTLEFS partition to 200kb. There are a great number of [default partition tables](https://github.com/espressif/arduino-esp32/tree/master/tools/partitions) for Arduino-ESP32 to choose from. If you have 8MB or 16MB flash this would be your first choice. If you don't need OTA you can choose a partition scheme without OTA. Should you want to deploy the frontend from the flash's LITTLEFS partition on a 4MB chip you need to comment out the following two lines. Otherwise the 200kb will not be large enough to host the front end code. ```ini board_build.partitions = min_spiffs.csv ``` ## Selecting Features Many of the framework's built in features may be enabled or disabled as required at compile time. This can help save sketch space and memory if your project does not require the full suite of features. The access point and WiFi management features are "core features" and are always enabled. Feature selection may be controlled with the build flags defined in [features.ini](https://github.com/theelims/ESP32-sveltekit/blob/main/features.ini). Customize the settings as you see fit. A value of 0 will disable the specified feature: ```ini -D FT_SECURITY=1 -D FT_MQTT=1 -D FT_NTP=1 -D FT_UPLOAD_FIRMWARE=1 -D FT_DOWNLOAD_FIRMWARE=1 -D FT_SLEEP=1 -D FT_BATTERY=1 -D FT_ETHERNET=1 ``` | Flag | Description | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | FT_SECURITY | Controls whether the [security features](statefulservice.md#security-features) are enabled. Disabling this means you won't need to authenticate to access the device and all authentication predicates will be bypassed. | | FT_MQTT | Controls whether the MQTT features are enabled. Disable this if your project does not require MQTT support. | | FT_NTP | Controls whether network time protocol synchronization features are enabled. Disable this if your project does not require accurate time. | | FT_UPLOAD_FIRMWARE | Controls whether the manual upload firmware feature is enabled. Disable this if you won't be manually uploading firmware. | | FT_DOWNLOAD_FIRMWARE | Controls whether the firmware download feature is enabled. Disable this if you won't firmware pulled from a server. | | FT_SLEEP | Controls whether the deep sleep feature is enabled. Disable this if your device is not battery operated or you don't need to place it in deep sleep to save energy. | | FT_BATTERY | Controls whether the battery state of charge shall be reported to the clients. Disable this if your device is not battery operated. | | FT_ETHERNET | Controls whether an ethernet interface will be used. Disable this if your device has no ethernet interface connected. | In addition custom features might be added or removed at runtime. See [Custom Features](statefulservice.md#custom-features) on how to use this in your application. ## Factory Settings The framework has built-in factory settings which act as default values for the various configurable services where settings are not saved on the file system. These settings can be overridden using the build flags defined in [factory_settings.ini](https://github.com/theelims/ESP32-sveltekit/blob/main/factory_settings.ini). All strings entered here must be escaped, especially special characters. Customize the settings as you see fit, for example you might configure your home WiFi network as the factory default: ```ini -D FACTORY_WIFI_SSID=\"My\ Awesome\ WiFi\ Network\" -D FACTORY_WIFI_PASSWORD=\"secret\" -D FACTORY_WIFI_HOSTNAME=\"awesome_light_controller\" ``` ### Default access point settings By default, the factory settings configure the device to bring up an access point on start up which can be used to configure the device: - SSID: ESP32-Sveltekit - Password: esp-sveltekit ### Security settings and user credentials By default, the factory settings configure two user accounts with the following credentials: | Username | Password | | -------- | -------- | | admin | admin | | guest | guest | It is recommended that you change the user credentials from their defaults to better protect your device. You can do this in the user interface, or by modifying [factory_settings.ini](https://github.com/theelims/ESP32-sveltekit/blob/main/factory_settings.ini) as mentioned above. ### Customizing the factory time zone setting Changing factory time zone setting is a common requirement. This requires a little effort because the time zone name and POSIX format are stored as separate values for the moment. The time zone names and POSIX formats are contained in the UI code in [timezones.ts](https://github.com/theelims/ESP32-sveltekit/blob/main/interface/src/routes/connections/timezones.ts). Take the appropriate pair of values from there, for example, for Los Angeles you would use: ```ini -D FACTORY_NTP_TIME_ZONE_LABEL=\"America/Los_Angeles\" -D FACTORY_NTP_TIME_ZONE_FORMAT=\"PST8PDT,M3.2.0,M11.1.0\" ``` ### Placeholder substitution Various settings support placeholder substitution, indicated by comments in [factory_settings.ini](https://github.com/theelims/ESP32-sveltekit/blob/main/factory_settings.ini). This can be particularly useful where settings need to be unique, such as the Access Point SSID or MQTT client id. The following placeholders are supported: | Placeholder | Substituted value | | ------------ | --------------------------------------------------------------------- | | #{platform} | The microcontroller platform, e.g. "esp32" or "esp32c3" | | #{unique_id} | A unique identifier derived from the MAC address, e.g. "0b0a859d6816" | | #{random} | A random number encoded as a hex string, e.g. "55722f94" | ## Other Build Flags ### Cross-Origin Resource Sharing If you need to enable Cross-Origin Resource Sharing (CORS) on the ESP32 server just uncomment the following build flags: ```ini build_flags = ... ; Uncomment to configure Cross-Origin Resource Sharing -D ENABLE_CORS -D CORS_ORIGIN=\"*\" ``` This will add the `Access-Control-Allow-Origin` and `Access-Control-Allow-Credentials` headers to any request made. ### ESP32 `CORE_DEBUG_LEVEL` The ESP32 Arduino Core and many other libraries use the ESP Logging tools. To enable these debug and error messages from deep inside your libraries uncomment the following build flag. ```ini build_flags = ... -D CORE_DEBUG_LEVEL=5 ``` It accepts values from 5 (Verbose) to 1 (Errors) for different information depths to be logged on the serial terminal. If commented out there won't be debug messages from the core libraries. For a production build you should comment this out. ### Serve Config Files By enabling this build flag the ESP32 will serve all config files stored on the LittleFS flash partition under `http:\\[IP]\config\[filename].json`. This can be helpful to troubleshoot problems. However, it is strongly advised to disable this for production builds. ```ini build_flags = ... -D SERVE_CONFIG_FILES ``` ### Serial Info In some circumstances it might be beneficial to not print any information on the serial consol (Serial1 or USB CDC). By commenting out the following build flag ESP32-Sveltekit will not print any information on the serial console. ```ini build_flags = ... -D SERIAL_INFO ``` ## SSL Root Certificate Store Some features like firmware download or the MQTT client require a SSL connection. For that the SSL Root CA certificate must be known to the ESP32. The build system contains a python script derived from Espressif ESP-IDF building a certificate store containing one or more certificates. In order to create the store you must uncomment the three lines below in `platformio.ini`. ```ini extra_scripts = pre:scripts/generate_cert_bundle.py board_build.embed_files = src/certs/x509_crt_bundle.bin board_ssl_cert_source = adafruit ``` The script will download a public certificate store from Mozilla (`board_ssl_cert_source = mozilla`) or a repository curated by Adafruit (`board_ssl_cert_source = adafruit`) or (`board_ssl_cert_source = adafruit-full`), builds a binary containing all certs and embeds this into the firmware. This will add ~65kb to the firmware image. Should you only need a few known certificates you can place their `*.pem` or `*.der` files in the [ssl_certs](https://github.com/theelims/ESP32-sveltekit/blob/main/ssl_certs) folder and change `board_ssl_cert_source = folder`. Then only these certificates will be included in the store. This is especially useful, if you only need to connect to know servers and need to shave some kb off the firmware image: !!! info To enable SSL the feature `FT_NTP=1` must be enabled as well. !!! bug At the moment there is a bug with the certificate bundle when using the firmware download e.g. from Github. By using the build flag `-D DOWNLOAD_OTA_SKIP_CERT_VERIFY` you may skip certificate validation to keep OTA working. Only OTA seems affected, not MQTT. Keep in mind, that this voids the main security feature of SSL and allows man-in-the-middle attacks. ## Vite and LittleFS 32 Character Limit The static files for the website are build using vite. By default vite adds a unique hash value to all filenames for improved caching performance. However, LittleFS on the ESP32 is limited to filenames with 32 characters. This restricts the number of characters available for the user to name svelte files. To give a little bit more headroom a vite-plugin removes all hash values, as they offer no benefit on an ESP32. However, have the 32 character limit in mind when naming files. Excessively long names may still cause some issues when building the LittleFS binary. ## Merged Firmware File for Web Flasher The PIO build system calls a script `merge_bin.py` to create a merged firmware binary ready to be used with [ESP Web Tools](https://esphome.github.io/esp-web-tools/). The file is located under the PIO build folder. Typically `build/merged/{APP_NAME}_{$PIOENV}_{APP_VERSION}.bin`. ================================================ FILE: docs/components.md ================================================ # Components The project includes a number of components to create the user interface. Even though DaisyUI has a huge set of components, it is often beneficial to recreate them as a Svelte component. This offers a much better integration into the Svelte way of doing things, is less troublesome with animations and results in a overall better user experience. ## Collapsible A collapsible container to hide / show content by clicking on the arrow button. ```ts import Collapsible from "$lib/components/Collapsible.svelte"; ``` It exports a closed / open state with `export open` which you can use to determine the mounting behavior of the component. ### Slots The component has two slots. A named slot `title` for the collapsible title and the main slot for the content that can be hidden or shown. ``` Title ... ``` The `class` attribute may be used as normal to style the container. By default there is no special styling like background or shadows to accentuate the container element. ### Events The collapsible component dispatches two events. `on:closed` when the collapsible is closed and `on:opened` when it is opened. You can bind to them as to any other event. ## InputPassword This is an input field specifically for passwords. It comes with an "eye"-button on the right border to toggle the visibility of the password. It natively blends into the style from DaisyUI. ```ts import InputPassword from "$lib/components/InputPassword.svelte"; ``` You may use it like any other form element: ``` ``` ## RSSIIndicator This shows the popular WiFi strength indicator icon with differently highlighted circles depending on the received signal strength (RSSI) of the WiFi signal. In addition it can display the signal strength in raw "dBm" as an indicator badge. ```ts import RssiIndicator from "$lib/components/RSSIIndicator.svelte"; ``` Just use and style as you please. It doesn't have any slots or events. ``` ``` Two exports control the behavior of the component. `rssi_dbm` accepts a negative number of the raw RSSI in dBm and is used to determine how many circles of reception should be shown. An optional boolean `showDBm` (defaults to `false`) shows the indicator badge with the dBm value. ## Settings Card A Settings Card is in many ways similar to a [collapsible](#collapsible). However, it is styled and is the main element of many settings menus. It also accepts an icon in a dedicate slot and unlike collapsible has no events. ```ts import SettingsCard from "$lib/components/SettingsCard.svelte"; ``` ### Slots Three slots are available. Besides the main slot for the content there is a named slot for the `title` and s second one for the `icon`. ``` Title ... ``` The component exports two properties to determine its behavior. `collapsible` is a boolean describing wether the component should behave like a collapsible in the first place. `open` is a boolean as well and if set true shows the full content of the body on mount. ## Spinner A small component showing an animated spinner which can be used while waiting for data. ```ts import Spinner from "$lib/components/Spinner.svelte"; ``` No slots, no events, no properties. Just use `` whenever something is loading. ## Toast Notifications Toast notifications are implemented as a writable store and are easy to use from any script section. They are an easy way to feedback to the user. To use them just import the notifications store ```ts import { notifications } from "$lib/components/toasts/notifications"; ``` and call one of the 4 toast methods: | Method | Description | | -------------------------------------------------- | --------------------------------------------------- | | `notification.error(msg:string, timeout:number)` | :octicons-x-circle-16: Shows an error message | | `notification.warning(msg:string, timeout:number)` | :octicons-alert-16: Shows a warning message | | `notification.info(msg:string, timeout:number)` | :octicons-info-16: Shows an info message | | `notification.success(msg:string, timeout:number)` | :octicons-check-circle-16: Shows as success message | Each method takes an `msg`-string as an argument, which will be shown as the message body. It accepts HTML to enrich your toasts, if you should desire to do so. The `timeout` argument specifies how many milliseconds the toast notification shall be shown to the user. ## Github Update Dialog This is a modal showing the update progress, possible error messages and makes a full page refresh 5 seconds after the OTA was successful. ## Update Indicator The update indicator is a small widget shown in the upper right corner of the status bar. It indicates the availability of a newer firmware release then the current one. Upon pressing the icon it will automatically update the firmware to the latest release. By default this works through the Github Latest Release API. This must be customized should you use a different update server. Have a look at the [source file](https://github.com/theelims/ESP32-sveltekit/blob/main/interface/src/lib/components/GithubUpdateDialog.svelte) to see what portions to update. ## Info Dialog Shows a modal on the UI which must be deliberately dismissed. It features a `title` and a `message` property. The dismiss button can be customized via the `dismiss` property with a label and an icon. `onDismiss` call back must close the modal and can be used to do something when closing the info dialog. ```ts import InfoDialog from "$lib/components/InfoDialog.svelte"; modals.open(InfoDialog, { title: 'You have a new Info', message: 'Something really important happened that justifies showing you a modal which must be clicked away.', dismiss: { label: 'OK', icon: Check }, onDismiss: () => modals.close(); }); ``` This modal is based on [svelte-modals](https://svelte-modals.mattjennings.io/) where you can find further information. ## Confirm Dialog Shows a confirm modal on the UI which must be confirmed to proceed, or can be canceled. It features a `title` and a `message` property. The `confirm` and `cancel` buttons can be customized via the `labels` property with a label and an icon. `onConfirm` call back must close the modal and can be used to trigger further actions. ```ts import ConfirmDialog from "$lib/components/ConfirmDialog.svelte"; modals.open(ConfirmDialog, { title: "Confirm what you are doing", message: "Are you sure you want to proceed? This could break stuff!", labels: { cancel: { label: "Abort", icon: Cancel }, confirm: { label: "Confirm", icon: Check }, }, onConfirm: () => modals.close(), }); ``` This modal is based on [svelte-modals](https://svelte-modals.mattjennings.io/) where you can find further information. ================================================ FILE: docs/gettingstarted.md ================================================ # Getting Started ## Prerequisites This project has quite a complicated build chain to prepare the frontend code for the ESP32. You will need to install some tools to make this all work, starting with a powerful code editor. ### Softwares to Install Please install the following software, if you haven't already: - [VSCode](https://code.visualstudio.com/) - IDE for development - [Node.js](https://nodejs.org) - For building the interface with npm ### VSCode Plugins and Setups Please install the following mandatory VSCode Plugins: - [PlatformIO](https://platformio.org/) - Embedded development platform - [Prettier](https://prettier.io/) - Automated code formatter - Svelte for VS Code - Makes working with Svelte much easier - Svelte Intellisense - Another Svelte tool - Tailwind CSS Intellisense - Makes working with Tailwind CSS much easier - [Prettier plugin for Tailwind CSS](https://github.com/tailwindlabs/prettier-plugin-tailwindcss) - Automatically sorts the Tailwind classes into their recommended order Lastly, if you want to make use of Materials for MkDocs as your documentation engine, install [Material for MkDocs](https://squidfunk.github.io/mkdocs-material/) by typing the following into the VSCode terminal: ```bash pip install mkdocs-material ``` !!! tip You might need to run this as administrator, if you getting an error message. ### Project Structure | Resource | Description | | -------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | | [.github/](https://github.com/theelims/ESP32-sveltekit/blob/main/.github) | Github CI pipeline to deploy MkDocs to gh-pages | | [docs/](https://github.com/theelims/ESP32-sveltekit/blob/main/docs) | MkDocs documentation files | | [interface/](https://github.com/theelims/ESP32-sveltekit/blob/main/interface) | SvelteKit based front end | | [lib/framework/](https://github.com/theelims/ESP32-sveltekit/blob/main/lib/framework) | C++ back end for the ESP32 device | | [src/](https://github.com/theelims/ESP32-sveltekit/blob/main/src) | The main.cpp and demo project to get you started | | [scripts/](https://github.com/theelims/ESP32-sveltekit/tree/main/scripts) | Scripts that build the interface as part of the platformio build | | [platformio.ini](https://github.com/theelims/ESP32-sveltekit/blob/main/platformio.ini) | PlatformIO project configuration file | | [mkdocs.yaml](https://github.com/theelims/ESP32-sveltekit/blob/main/mkdocs.yaml) | MkDocs project configuration file | ## Setting up PlatformIO ### Setup Build Target !!! danger "Do not use the PlatformIO UI for editing platformio.ini" It is tempting to use the PlatformIO user interface to add dependencies or parameters to platformio.ini. However, doing so will remove all "irrelevant" information like comments from the file. Please edit the file directly in the editor. [platformio.ini](https://github.com/theelims/ESP32-sveltekit/blob/main/platformio.ini) is the central file controlling the whole build process. It comes pre-configure with a few boards which have different ESP32 chips. It needs to be adapted to the board you want to program. ```ini [platformio] ... default_envs = esp32-s3-devkitc-1 ... [env:adafruit_feather_esp32_v2] board = adafruit_feather_esp32_v2 board_build.mcu = esp32 [env:lolin_c3_mini] board = lolin_c3_mini board_build.mcu = esp32c3 [env:esp32-s3-devkitc-1] board = esp32-s3-devkitc-1 board_build.mcu = esp32s3 ``` If your board is not listed in the platformio.ini you may look in the [official board list](https://docs.platformio.org/en/latest/boards/index.html#espressif-32) for supported boards and add their information accordingly. Either delete the obsolete `[env:...]` sections, or change your board as `default_envs = ...`. !!! info "Default setup is for an ESP32-S3-DevKitC/M board" The projects platformio.ini defaults for an ESP32-S3-DevKitC/M board by Espressif connected to the UART USB port. If you use an other board and the projects shows an undesired behavior it is likely that some parts do not match with pin definitions. ### Build & Upload Process After you've changed [platformio.ini](https://github.com/theelims/ESP32-sveltekit/blob/main/platformio.ini) to suit your board you can upload the sample code to your board. This will download all ESP32 libraries and execute `node install` to install all node packages as well. Select your board's environment under the PlatformIO tab and hit `Upload and Monitor`. ![PIO Build](media/PIO-upload.png) The first build process will take a while. After a couple of minutes you can see the ESP32 outputting information on the terminal. Some of the python scripts might need to install additional packages. In that case the first build process will fail. Just run it a second time. !!! tip "Use several terminals in parallel" VSCode allows you to have more then one terminal running at the same time. You can dedicate one terminal to the serial monitor, while having the development server running in an other terminal. ## Setting up SvelteKit ### Setup Proxy for Development To ease the frontend development you can deploy the back end code on an ESP32 board and pass the websocket and REST API calls through the development server's proxy. The [vite.config.ts](https://github.com/theelims/ESP32-sveltekit/blob/main/interface/vite.config.ts) file defines the location of the services which the development server will proxy. This is defined by the "target" property, which will need to be changed to the the IP address or hostname of the device running the firmware. Change this for both, "http://" and "ws://". ```ts proxy: { // Proxying REST: http://localhost:5173/rest/bar -> http://192.168.1.83/rest/bar '/rest': { target: 'http://192.168.1.83', changeOrigin: true, }, // Proxying websockets ws://localhost:5173/ws -> ws://192.168.1.83/ws '/ws': { target: 'ws://192.168.1.83', changeOrigin: true, ws: true, }, }, ``` !!! tip You must restart the development server for changes of the proxy location to come into effect. ### Development Server The interface comes with Vite as a development server. It allows hot module reloading reflecting code changes to the front end instantly in your browser. Open a new terminal session and execute the following commands: ```bash cd interface npm run dev ``` Follow the link to access the front end in your browser. ## Setup Material for mkdocs Material for MkDocs allows you to create great technical documentation pages just from markup. If you don't want to use it just delete the `.github` and `docs` folder, as well as `mkdocs.yaml`. Otherwise initiate the github CI pipeline by committing and pushing to your repository once. This triggers the automatic build. After a few minutes a new branch `gh-pages` containing the static website with your documentation should appear. To deploy it go to your github repository go under settings and complete the following steps. ![Deploy on gh-pages](media/mkdocs_gh-pages.PNG) ### Development Server MkDocs comes with a build-in development server which supports hot reload as well. Open a new terminal session in VSCode and type ``` mkdocs serve ``` ================================================ FILE: docs/index.md ================================================ --- hide: - navigation - toc --- # ESP32 SvelteKit - Create Amazing IoT Projects
A simple and extensible framework for ESP32 based IoT projects with a feature-rich, beautiful, and responsive front-end build with [Sveltekit](https://kit.svelte.dev/), [TailwindCSS](https://tailwindcss.com/) and [DaisyUI](https://daisyui.com/). This is a project template to get you started in no time backed by a powerful back end service, an amazing front end served from the ESP32 and an easy to use build chain to get everything going. It was forked from the fabulous [rjwats/esp8266-react](https://github.com/rjwats/esp8266-react) project, from where it inherited the mighty back end services. !!! info This template repository is not meant to be used stand alone. If you're just looking for a WiFi manager there are plenty of options available. This is a starting point when you need a rich web UI. ## Features ### :butterfly: Beautiful UI powered by DaisyUI and TailwindCSS Beautiful, responsive UI which works equally well on desktop and on mobile. Gently animated for a snappy and modern feeling without ever being obtrusive or in the way. Easy theming with DaisyUI and media-queries to respect the users wish for a light or dark theme. ### :simple-svelte: Low Memory Footprint and Easy Customization by Courtesy of SvelteKit SvelteKit is ideally suited to be served from constrained devices like an ESP32. It's unique approach leads to very slim files. No bloatware like other popular JS frameworks. Not only the low memory footprint make it ideal but the developer experience is also outstanding letting you customize the front end with ease. Adapt and add functionality as you need it. The back end has you covered as well. ### :telephone: Rich Communication Interfaces Comes with a rich set of communication interfaces to cover most standard needs of an IoT application. Like MQTT client, HTTP RESTful API, a WebSocket based Event Socket and a classic Websocket Server. All communication channels are stateful and fully synchronized. Changes propagate and are communicated to all other participants. The states can be persisted on the file system as well. For accurate time keeping time can by synchronized over NTP. ### :file_cabinet: WiFi Provisioning and Management Naturally ESP32 SvelteKit comes with rich features to manage all your WiFi needs. From pulling up an access point for provisioning or as fall back, to fully manage your WiFi networks. Scan for available networks and connect to them. Advanced configuration options like static IP are on board as well. ### :people_with_bunny_ears_partying: Secured API and User Management Manage different user of your app with two authorization levels. An administrator and a guest user. Authenticate their API calls with a JWT token. Manage the user's profile from the admin interface. Use at own risk, as it is neither secure without the ability to use TLS/SSL encryption on the ESP32 server, nor very convenient, as only an admin can change passwords. ### :airplane: OTA Upgrade Service The framework can provide two different channels for Over-the-Air updates. Either by uploading a \*.bin file from the web interface. Or by pulling a firmware image from an update server. This is implemented with the github release page as an example. It is even possible to have different build environments at the same time and the Github OTA process pulls the correct binary. ### :construction_site: Automated Build Chain The automated build chain takes out the pain and tears of getting all the bits and pieces play nice together. The repository contains a PlatformIO project at its heart. A SvelteKit project for the frontend code and a mkdocs project for the documentation go alongside. The PlatformIO build tools not only build the SvelteKit frontend with Vite, but also ensure that the build results are gzipped and find their way into the flash memory of the ESP32. You have two choices to serve the frontend either from the flash partition, or embedded into the firmware binary. The latter is much more friendly if your frontend code should be distributed OTA as well, leaving all configuration files intact. ### :fontawesome-solid-microchip: Compatible with all ESP32 Flavours The code runs on all variants of the ESP32 chip family. From the plain old ESP32, the ESP32-S3 and ESP32-C3. Other ESP32 variants might work, but haven't been tested. Sorry, no support for the older ESP8266. Go with one of the ESP32's instead. [Let's get started!](gettingstarted.md) ## License ESP32 SvelteKit is distributed with two licenses for different sections of the code. The back end code inherits the GNU LESSER GENERAL PUBLIC LICENSE Version 3 and is therefore distributed with said license. The front end code is distributed under the MIT License. See the [LICENSE](https://github.com/theelims/ESP32-sveltekit/blob/main/LICENSE) for a full text of both licenses. ================================================ FILE: docs/restfulapi.md ================================================ # RESTful API The back end exposes a number of API endpoints which are referenced in the table below. | Method | Request URL | Authentication | POST JSON Body | Info | | ------ | --------------------------------------- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | | GET | /rest/features | `NONE_REQUIRED` | none | Tells the client which features of the UI should be use | | GET | /rest/mqttStatus | `IS_AUTHENTICATED` | none | Current MQTT connection status | | GET | /rest/mqttSettings | `IS_ADMIN` | none | Currently used MQTT settings | | POST | /rest/mqttSettings | `IS_ADMIN` | `{"enabled":false,"uri":"mqtt://192.168.1.12:1883","username":"","password":"","client_id":"esp32-f412fa4495f8","keep_alive":120,"clean_session":true,"message_interval_ms":0}` | Update MQTT settings with new parameters | | GET | /rest/ntpStatus | `IS_AUTHENTICATED` | none | Current NTP connection status | | GET | /rest/ntpSettings | `IS_ADMIN` | none | Current NTP settings | | POST | /rest/ntpSettings | `IS_ADMIN` | `{"enabled": true,"server": "time.google.com","tz_label": "Europe/London","tz_format": "GMT0BST,M3.5.0/1,M10.5.0"}` | Update the NTP settings | | GET | /rest/apStatus | `IS_AUTHENTICATED` | none | Current AP status and client information | | GET | /rest/apSettings | `IS_ADMIN` | none | Current AP settings | | POST | /rest/apSettings | `IS_ADMIN` | `{"provision_mode": 1,"ssid": "ESP32-SvelteKit-e89f6d20372c","password": "esp-sveltekit","channel": 1,"ssid_hidden": false,"max_clients": 4,"local_ip": "192.168.4.1","gateway_ip": "192.168.4.1","subnet_mask": "255.255.255.0"}` | Update AP settings | | GET | /rest/wifiStatus | `IS_AUTHENTICATED` | none | Current status of the wifi client connection | | GET | /rest/scanNetworks | `IS_ADMIN` | none | Async Scan for Networks in Range | | GET | /rest/listNetworks | `IS_ADMIN` | none | List networks in range after successful scanning. Otherwise triggers scanning. | | GET | /rest/wifiSettings | `IS_ADMIN` | none | Current WiFi settings | | POST | /rest/wifiSettings | `IS_ADMIN` | `{"hostname":"esp32-f412fa4495f8","connection_mode":1,"wifi_networks":[{"ssid":"YourSSID","password":"YourPassword","static_ip_config":false}]}` | Update WiFi settings and credentials | | GET | /rest/systemStatus | `IS_AUTHENTICATED` | none | Get system information about the ESP. | | POST | /rest/restart | `IS_ADMIN` | none | Restart the ESP32 | | POST | /rest/factoryReset | `IS_ADMIN` | none | Reset the ESP32 and all settings to their default values | | POST | /rest/uploadFirmware | `IS_ADMIN` | none | File upload of firmware.bin | | POST | /rest/signIn | `NONE_REQUIRED` | `{"password": "admin","username": "admin"}` | Signs a user in and returns access token | | GET | /rest/securitySettings | `IS_ADMIN` | none | retrieves all user information and roles | | POST | /rest/securitySettings | `IS_ADMIN` | `{"jwt_secret": "734cb5bb-5597b722", "users": [{"username": "admin", "password": "admin", "admin": true}, {"username": "guest", "password": "guest", "admin": false, }]}` | retrieves all user information and roles | | GET | /rest/verifyAuthorization | `NONE_REQUIRED` | none | Verifies the content of the auth bearer token | | GET | /rest/generateToken?username={username} | `IS_ADMIN` | `{"token": "734cb5bb-5597b722"}` | Generates a new JWT token for the user from username | | POST | /rest/sleep | `IS_AUTHENTICATED` | none | Puts the device in deep sleep mode | | POST | /rest/downloadUpdate | `IS_ADMIN` | `{"download_url": "https://github.com/theelims/ESP32-sveltekit/releases/download/v0.1.0/firmware_esp32s3.bin"}` | Download link for OTA. This requires a valid SSL certificate and will follow redirects. | | GET | /rest/coreDump | `IS_AUTHENTICATED` | Text | Core dump of the last crash. | ================================================ FILE: docs/statefulservice.md ================================================ # Developing with the Framework The back end is a set of REST endpoints hosted by a [PsychicHttp](https://github.com/hoeken/PsychicHttp) instance. The ['lib/framework'](https://github.com/theelims/ESP32-sveltekit/blob/main/lib/framework) directory contains the majority of the back end code. The framework contains a number of useful utility classes which you can use when extending it. The project also comes with a demo project to give you some help getting started. The framework's source is split up by feature, for example [WiFiScanner.h](https://github.com/theelims/ESP32-sveltekit/blob/main/lib/framework/WiFiScanner.h) implements the end points for scanning for available networks where as [WiFiSettingsService.h](https://github.com/theelims/ESP32-sveltekit/blob/main/lib/framework/WiFiSettingsService.h) handles configuring the WiFi settings and managing the WiFi connection. ## Initializing the framework The ['src/main.cpp'](https://github.com/theelims/ESP32-sveltekit/blob/main/src/main.cpp) file constructs the web server and initializes the framework. You can add endpoints to the server here to support your IoT project. The main loop is also accessible so you can run your own code easily. The following code creates the web server and esp32sveltekit framework: ```cpp PsychicHttpServer server; ESP32SvelteKit esp32sveltekit(&server, 120); ``` ESP32SvelteKit is instantiated with a reference to the server and a number of HTTP endpoints. The underlying ESP-IDF HTTP Server statically allocates memory for each endpoint and needs to know how many there are. Best is to inspect your WWWData.h file for the number of Endpoints from SvelteKit (currently 60), the framework itself has 37 endpoints, and Lighstate Demo has 7 endpoints. Each `_server.on()` counts as an endpoint. Don't forget to add a couple of spare, just in case. Each HttpEndpoint adds 2 endpoints, if CORS is enabled it adds an other endpoint for the CORS preflight request. Now in the `setup()` function the initialization is performed: ```cpp void setup() { // start serial and filesystem Serial.begin(SERIAL_BAUD_RATE); // start the framework and demo project esp32sveltekit.begin(); } ``` `server.begin()` is called by ESP32-SvelteKit, as the start-up sequence is crucial. ## Stateful Service The framework promotes a modular design and exposes features you may re-use to speed up the development of your project. Where possible it is recommended that you use the features the frameworks supplies. These are documented in this section and a comprehensive example is provided by the demo project. The following diagram visualizes how the framework's modular components fit together, each feature is described in detail below. ![framework diagram](media/framework.png) The [StatefulService.h](https://github.com/theelims/ESP32-sveltekit/blob/main/lib/framework/StatefulService.h) class is responsible for managing state. It has an API which allows other code to update or respond to updates in the state it manages. You can define a data class to hold state, then build a StatefulService class to manage it. After that you may attach HTTP endpoints, WebSockets or MQTT topics to the StatefulService instance to provide commonly required features. Here is a simple example of a state class and a StatefulService to manage it: ```cpp class LightState { public: bool on = false; uint8_t brightness = 255; }; class LightStateService : public StatefulService { }; ``` ### Update Handler You may listen for changes to state by registering an update handler callback. It is possible to remove an update handler later if required. ```cpp // register an update handler update_handler_id_t myUpdateHandler = lightStateService.addUpdateHandler( [&](const String& originId) { Serial.print("The light's state has been updated by: "); Serial.println(originId); } ); // remove the update handler lightStateService.removeUpdateHandler(myUpdateHandler); ``` An "originId" is passed to the update handler which may be used to identify the origin of an update. The default origin values the framework provides are: | Origin | Description | | -------------------------- | ----------------------------------------------- | | http | An update sent over REST (HttpEndpoint) | | mqtt | An update sent over MQTT (MqttEndpoint) | | websocketserver:{clientId} | An update sent over WebSocket (WebSocketServer) | ### Hook Handler Sometimes if can be desired to hook into every update of an state, even if the StateUpdateResult is `StateUpdateResult::UNCHANGED` and the update handler isn't called. In such cases you can use the hook handler. Similarly it can be removed later. ```cpp // register an update handler hook_handler_id_t myHookHandler = lightStateService.addHookHandler( [&](const String& originId, StateUpdateResult &result) { Serial.printf("The light's state has been updated by: %s with result %d\n", originId, result); } ); // remove the update handler lightStateService.removeHookHandler(myHookHandler); ``` ### Read & Update State StatefulService exposes a read function which you may use to safely read the state. This function takes care of protecting against parallel access to the state in multi-core environments such as the ESP32. ```cpp lightStateService.read([&](LightState& state) { digitalWrite(LED_PIN, state.on ? HIGH : LOW); // apply the state update to the LED_PIN }); ``` StatefulService also exposes an update function which allows the caller to update the state with a callback. This function automatically calls the registered update handlers if the state has been changed. The example below changes the state of the light (turns it on) using the arbitrary origin "timer" and returns the "CHANGED" state update result, indicating that a change was made: ```cpp lightStateService.update([&](LightState& state) { if (state.on) { return StateUpdateResult::UNCHANGED; // lights were already on, return UNCHANGED } state.on = true; // turn on the lights return StateUpdateResult::CHANGED; // notify StatefulService by returning CHANGED }, "timer"); ``` There are three possible return values for an update function which are as follows: | Origin | Description | | ---------------------------- | ------------------------------------------------------------------------ | | StateUpdateResult::CHANGED | The update changed the state, propagation should take place if required | | StateUpdateResult::UNCHANGED | The state was unchanged, propagation should not take place | | StateUpdateResult::ERROR | There was an error updating the state, propagation should not take place | ### JSON Serialization When reading or updating state from an external source (HTTP, WebSockets, or MQTT for example) the state must be marshalled into a serializable form (JSON). SettingsService provides two callback patterns which facilitate this internally: | Callback | Signature | Purpose | | ---------------- | ------------------------------------------------------- | --------------------------------------------------------------------------------- | | JsonStateReader | void read(T& settings, JsonObject& root) | Reading the state object into a JsonObject | | JsonStateUpdater | StateUpdateResult update(JsonObject& root, T& settings) | Updating the state from a JsonObject, returning the appropriate StateUpdateResult | The static functions below can be used to facilitate the serialization/deserialization of the light state: ```cpp class LightState { public: bool on = false; uint8_t brightness = 255; static void read(LightState& state, JsonObject& root) { root["on"] = state.on; root["brightness"] = state.brightness; } static StateUpdateResult update(JsonObject& root, LightState& state) { state.on = root["on"] | false; state.brightness = root["brightness"] | 255; return StateUpdateResult::CHANGED; } }; ``` For convenience, the StatefulService class provides overloads of its `update` and `read` functions which utilize these functions. Read the state to a JsonObject using a serializer: ```cpp JsonObject jsonObject = jsonDocument.to(); lightStateService->read(jsonObject, LightState::read); ``` Update the state from a JsonObject using a deserializer: ```cpp JsonObject jsonObject = jsonDocument.as(); lightStateService->update(jsonObject, LightState::update, "timer"); ``` ### HTTP RESTful Endpoint The framework provides an [HttpEndpoint.h](https://github.com/theelims/ESP32-sveltekit/blob/main/lib/framework/HttpEndpoint.h) class which may be used to register GET and POST handlers to read and update the state over HTTP. You may construct an HttpEndpoint as a part of the StatefulService or separately if you prefer. The code below demonstrates how to extend the LightStateService class to provide an endpoint: ```cpp class LightStateService : public StatefulService { public: LightStateService(PsychicHttpServer* server, ESP32SvelteKit *sveltekit) : _httpEndpoint(LightState::read, LightState::update, this, server, "/rest/lightState", sveltekit->getSecurityManager(),AuthenticationPredicates::IS_AUTHENTICATED) { } void begin(); { _httpEndpoint.begin(); } private: HttpEndpoint _httpEndpoint; }; ``` Endpoint security is provided by authentication predicates which are [documented below](#security-features). The SecurityManager and authentication predicate must be provided, even if no secure endpoint is required. The placeholder project shows how endpoints can be secured. To register the HTTP endpoints with the web server the function `_httpEndpoint.begin()` must be called in the custom StatefulService Class' own `void begin()` function. ### File System Persistence [FSPersistence.h](https://github.com/theelims/ESP32-sveltekit/blob/main/lib/framework/FSPersistence.h) allows you to save state to the filesystem. FSPersistence automatically writes changes to the file system when state is updated. This feature can be disabled by calling `disableUpdateHandler()` if manual control of persistence is required. The code below demonstrates how to extend the LightStateService class to provide persistence: ```cpp class LightStateService : public StatefulService { public: LightStateService(ESP32SvelteKit *sveltekit) : _fsPersistence(LightState::read, LightState::update, this, sveltekit->getFS(), "/config/lightState.json") { } private: FSPersistence _fsPersistence; }; ``` ### Event Socket Endpoint [EventEndpoint.h](https://github.com/theelims/ESP32-sveltekit/blob/main/lib/framework/EventEndpoint.h) wraps the [Event Socket](#event-socket) into an endpoint compatible with a stateful service. The client may subscribe and unsubscribe to this event to receive updates or push updates to the ESP32. The current state is synchronized upon subscription. The code below demonstrates how to extend the LightStateService class to provide an WebSocket: ```cpp class LightStateService : public StatefulService { public: LightStateService(ESP32SvelteKit *sveltekit) : _eventEndpoint(LightState::read, LightState::update, this, sveltekit->getSocket(), "led") {} void begin() { _eventEndpoint.begin(); } private: EventEndpoint _eventEndpoint; }; ``` To register the event endpoint with the event socket the function `_eventEndpoint.begin()` must be called in the custom StatefulService Class' own `void begin()` function. Since all events run through one websocket connection it is not possible to use the [securityManager](#security-features) to limit access to individual events. The security defaults to `AuthenticationPredicates::IS_AUTHENTICATED`. ### WebSocket Server [WebSocketServer.h](https://github.com/theelims/ESP32-sveltekit/blob/main/lib/framework/WebSocketServer.h) allows you to read and update state over a WebSocket connection. WebSocketServer automatically pushes changes to all connected clients when state is updated. The code below demonstrates how to extend the LightStateService class to provide an WebSocket: ```cpp class LightStateService : public StatefulService { public: LightStateService(PsychicHttpServer* server, ESP32SvelteKit *sveltekit) : _webSocket(LightState::read, LightState::update, this, server, "/ws/lightState", sveltekit->getSecurityManager(), AuthenticationPredicates::IS_AUTHENTICATED), { } void begin() { _webSocketServer.begin(); } private: WebSocketServer _webSocketServer; }; ``` WebSocket security is provided by authentication predicates which are [documented below](#security-features). The SecurityManager and authentication predicate must be provided, even if no secure endpoint is required. The placeholder project shows how endpoints can be secured. To register the WS endpoint with the web server the function `_webSocketServer.begin()` must be called in the custom StatefulService Class' own `void begin()` function. ### MQTT Client The framework includes an MQTT client which can be configured via the UI. MQTT requirements will differ from project to project so the framework exposes the client for you to use as you see fit. The framework does however provide a utility to interface StatefulService to a pair of pub/sub (state/set) topics. This utility can be used to synchronize state with software such as Home Assistant. [MqttEndpoint.h](https://github.com/theelims/ESP32-sveltekit/blob/main/lib/framework/MqttEndpoint.h) allows you to publish and subscribe to synchronize state over a pair of MQTT topics. MqttEndpoint automatically pushes changes to the "pub" topic and reads updates from the "sub" topic. The code below demonstrates how to extend the LightStateService class to interface with MQTT: ```cpp class LightStateService : public StatefulService { public: LightStateService(ESP32SvelteKit *sveltekit) : _mqttEndpoint(LightState::read, LightState::update, this, sveltekit->getMqttClient(), "homeassistant/light/my_light/set", "homeassistant/light/my_light/state") { } private: MqttEndpoint _mqttEndpoint; }; ``` You can re-configure the pub/sub topics at runtime as required: ```cpp _mqttEndpoint.configureBroker("homeassistant/light/desk_lamp/set", "homeassistant/light/desk_lamp/state"); ``` The demo project allows the user to modify the MQTT topics via the UI so they can be changed without re-flashing the firmware. ## Event Socket Beside RESTful HTTP Endpoints the Event Socket System provides a convenient communication path between the client and the ESP32. It uses a single WebSocket connection to synchronize state and to push realtime data to the client. The client needs to subscribe to the topics he is interested. Only clients who have an active subscription will receive data. Every authenticated client may make use of this system as the security settings are set to `AuthenticationPredicates::IS_AUTHENTICATED`. ### Message Format The event messages exchanged between the ESP32 and its clients consists of an "event" head and the "data" payload. For the LightState example a message looks like this in JSON representation: ```JSON { "event": "led", "data": { "led_on": true } } ``` To save on bandwidth the event message is encoded as binary [MessagePack](https://msgpack.org/) instead of a JSON. To subscribe the client has to send the following message (as MessagePack): ```JSON { "event": "subscribe", "data": "analytics" } ``` ### Emit an Event The Event Socket provides an `emitEvent()` function to push data to all subscribed clients. This is used by various esp32sveltekit classes to push real time data to the client. First an event must be registered with the Event Socket by calling `_socket.registerEvent("CustomEvent");`. Only then clients may subscribe to this custom event and you're entitled to emit event data: ```cpp void emitEvent(String event, JsonObject &jsonObject, const char *originId = "", bool onlyToSameOrigin = false); ``` The latter function allowing a selection of the recipient. If `onlyToSameOrigin = false` the payload is distributed to all subscribed clients, except the `originId`. If `onlyToSameOrigin = true` only the client with `originId` will receive the payload. This is used by the [EventEndpoint](#event-socket-endpoint) to sync the initial state when a new client subscribes. ### Receive an Event A callback or lambda function can be registered to receive an ArduinoJSON object and the originId of the client sending the data: ```cpp _socket.onEvent("CostumEvent",[&](JsonObject &root, int originId) { bool ledState = root["led_on"]; }); ``` ### Get Notified on Subscriptions Similarly a callback or lambda function may be registered to get notified when a client subscribes to an event: ```cpp _socket.onSubscribe("CostumEvent",[&](const String &originId) { Serial.println("New Client subscribed: " + originId); }); ``` The boolean parameter provided will always be `true`. ### Push Notifications to All Clients It is possibly to send push notifications to all clients by using the Event Socket. These will be displayed as toasts an the client side. Either directly call ```cpp esp32sveltekit.getNotificationService()->pushNotification("Pushed a message!", PUSHINFO); ``` or keep a local pointer to the `EventSocket` instance. It is possible to send `PUSHINFO`, `PUSHWARNING`, `PUSHERROR` and `PUSHSUCCESS` events to all clients. ## Security features The framework has security features to prevent unauthorized use of the device. This is driven by [SecurityManager.h](https://github.com/theelims/ESP32-sveltekit/blob/main/lib/framework/SecurityManager.h). On successful authentication, the /rest/signIn endpoint issues a [JSON Web Token (JWT)](https://jwt.io/) which is then sent using Bearer Authentication. For this add an `Authorization`-Header to the request with the Content `Bearer {JWT-Secret}`. The framework come with built-in predicates for verifying a users access privileges. The built in AuthenticationPredicates can be found in [SecurityManager.h](https://github.com/theelims/ESP32-sveltekit/blob/main/lib/framework/SecurityManager.h) and are as follows: | Predicate | Description | | ---------------- | --------------------------------------------- | | NONE_REQUIRED | No authentication is required. | | IS_AUTHENTICATED | Any authenticated principal is permitted. | | IS_ADMIN | The authenticated principal must be an admin. | You can use the security manager to wrap any request handler function with an authentication predicate: ```cpp server->on("/rest/someService", HTTP_GET, _securityManager->wrapRequest(std::bind(&SomeService::someService, this, std::placeholders::_1), AuthenticationPredicates::IS_AUTHENTICATED) ); ``` In case of a websocket connection the JWT token is supplied as a search parameter in the URL when establishing the connection: ``` /ws/lightState?access_token={JWT Token} ``` ## Placeholder substitution Various settings support placeholder substitution, indicated by comments in [factory_settings.ini](https://github.com/theelims/ESP32-sveltekit/blob/main/factory_settings.ini). This can be particularly useful where settings need to be unique, such as the Access Point SSID or MQTT client id. Strings must be properly escaped in the ini-file. The following placeholders are supported: | Placeholder | Substituted value | | ------------ | --------------------------------------------------------------------- | | #{platform} | The microcontroller platform, e.g. "esp32" or "esp32c3" | | #{unique_id} | A unique identifier derived from the MAC address, e.g. "0b0a859d6816" | | #{random} | A random number encoded as a hex string, e.g. "55722f94" | You may use SettingValue::format in your own code if you require the use of these placeholders. This is demonstrated in the demo project: ```cpp static StateUpdateResult update(JsonObject& root, LightMqttSettings& settings) { settings.mqttPath = root["mqtt_path"] | SettingValue::format("homeassistant/light/#{unique_id}"); settings.name = root["name"] | SettingValue::format("light-#{unique_id}"); settings.uniqueId = root["unique_id"] | SettingValue::format("light-#{unique_id}"); return StateUpdateResult::CHANGED; } ``` ## Accessing settings and services The framework supplies access to various features via getter functions: | SettingsService | Description | | ---------------------------- | -------------------------------------------------- | | getFS() | The filesystem used by the framework | | getSecurityManager() | The security manager - detailed above | | getSecuritySettingsService() | Configures the users and other security settings | | getWiFiSettingsService() | Configures and manages the WiFi network connection | | getAPSettingsService() | Configures and manages the Access Point | | getNTPSettingsService() | Configures and manages the network time | | getMqttSettingsService() | Configures and manages the MQTT connection | | getMqttClient() | Provides direct access to the MQTT client instance | | getNotificationEvents() | Lets you send push notifications to all clients | | getSleepService() | Send the ESP32 into deep sleep | | getBatteryService() | Update battery information on the client | The core features use the [StatefulService.h](https://github.com/theelims/ESP32-sveltekit/blob/main/lib/framework/StatefulService.h) class and therefore you can change settings or observe changes to settings through the read/update API. Inspect the current WiFi settings: ```cpp esp32sveltekit.getWiFiSettingsService()->read([&](WiFiSettings& wifiSettings) { Serial.print("The ssid is:"); Serial.println(wifiSettings.ssid); }); ``` Configure the WiFi SSID and password manually: ```cpp esp32sveltekit.getWiFiSettingsService()->update([&](WiFiSettings& wifiSettings) { wifiSettings.ssid = "MyNetworkSSID"; wifiSettings.password = "MySuperSecretPassword"; return StateUpdateResult::CHANGED; }, "myapp"); ``` Observe changes to the WiFiSettings: ```cpp esp32sveltekit.getWiFiSettingsService()->addUpdateHandler( [&](const String& originId) { Serial.println("The WiFi Settings were updated!"); } ); ``` ## Other functions provided ### MDNS Instance Name ESP32 SvelteKit uses mDNS / Bonjour to advertise its services into the local network. You can set the mDNS instance name property by calling ```cpp esp32sveltekit.setMDNSAppName("ESP32 SvelteKit Demo App"); ``` making the entry a little bit more verbose. This must be called before `esp32sveltekit.begin();`. If you want to advertise further services just include `#include ` and use `MDNS.addService()` regularly. ### Use ESP32-SvelteKit loop() Function Under some circumstances custom services might want to do something periodically. One solution would be to use a dedicated task or RTOS timer for this. Or you can leverage the ESP32-SvelteKit loop-function and have it executed as a callback every 20ms. ```cpp esp32sveltekit.addLoopFunction(callback) ``` ### Factory Reset A factory reset can not only be evoked from the API, but also by calling ```cpp esp32sveltekit.factoryReset(); ``` from your code. This will erase the complete settings folder, wiping out all settings. This can be a last fall back mode if somebody has forgotten his credentials. ### Recovery Mode There is also a recovery mode present which will force the creation of an access point. By calling ```cpp esp32sveltekit.recoveryMode(); ``` will force a start of the AP regardless of the AP settings. It will not change the the AP settings. To exit the recovery mode restart the device or change the AP settings in the UI. ### Power Down with Deep Sleep This API service can place the ESP32 in the lowest power deep sleep mode consuming only a few µA. It uses the EXT1 wakeup source, so the ESP32 can be woken up with a button or from a peripherals interrupt. Consult the [ESP-IDF Api Reference](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/sleep_modes.html#_CPPv428esp_sleep_enable_ext1_wakeup8uint64_t28esp_sleep_ext1_wakeup_mode_t) which GPIOs can be used for this. The RTC will also be powered down, so an external pull-up or pull-down resistor is required. It is not possible to persist variable state through the deep sleep. To optimize the deep sleep power consumption it is advisable to use the callback function to put pins with external pull-up's or pull-down's in a special isolated state to prevent current leakage. Please consult the [ESP-IDF Api Reference](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/sleep_modes.html#configuring-ios-deep-sleep-only) for this. The settings wakeup pin definition and the signal polarity need to be defined in [factory_settings.ini](https://github.com/theelims/ESP32-sveltekit/blob/main/factory_settings.ini): ```ini ; Deep Sleep Configuration -D WAKEUP_PIN_NUMBER=38 ; pin number to wake up the ESP -D WAKEUP_SIGNAL=0 ; 1 for wakeup on HIGH, 0 for wakeup on LOW ``` In addition it is possible to change this as well at runtime by calling: ```cpp esp32sveltekit.getSleepService()->setWakeUpPin(int pin, bool level, pinTermination termination = pinTermination::FLOATING); ``` With this function it is also possible to configure the internal pull-up or pull-down resistor for this RTC pin. Albeit this might increase the deep sleep current slightly. A callback function can be attached and triggers when the ESP32 is requested to go into deep sleep. This allows you to safely deal with the power down event. Like persisting software state by writing to the flash, tiding up or notify a remote server about the immanent disappearance. ```cpp esp32sveltekit.getSleepService()->attachOnSleepCallback(); ``` Also the code can initiate the power down deep sleep sequence by calling: ```cpp esp32sveltekit.getSleepService()->sleepNow(); ``` ### Battery State of Charge A small helper class let's you update the battery icon in the status bar. This is useful if you have a battery operated IoT device. It must be enabled in [features.ini](https://github.com/theelims/ESP32-sveltekit/blob/main/features.ini). It uses the [Event Socket](#event-socket) and exposes two functions that can be used to update the clients. ```cpp esp32sveltekit.getBatteryService()->updateSOC(float stateOfCharge); // update state of charge in percent (0 - 100%) esp32sveltekit.getBatteryService()->setCharging(boolean isCharging); // notify the client that the device is charging ``` ### ESP32-SvelteKit Connection Status Especially for a cases like a colored status LED it can be useful to have a quick indication of the connection status. By calling: ```cpp ConnectionStatus status = esp32sveltekit.getConnectionStatus(); ``` the current connection status can be accessed. The following stats are available: | Status | Description | | ------------- | ------------------------------------------------------------------------------- | | OFFLINE | Device is completely offline | | AP | Access Point is available, but no client is connected | | AP_CONNECTED | Access Point is used and at least 1 client is connected | | STA | Device connected to a WiFi Station | | STA_CONNECTED | Device connected to a WiFi Station and at least 1 client is connected | | STA_MQTT | Device connected to a WiFi Station and the device is connected to a MQTT server | ### Custom Features You may use the compile time feature service also to enable or disable custom features at runtime and thus control the frontend. A custom feature can only be added during initializing the ESP32 and ESP32-SvelteKit. The frontend queries the features only when first loading the page. Thus the frontend must be refreshed for the changes to become effective. ```cpp esp32sveltekit.getFeatureService()->addFeature("custom_feature", true); // or false to disable it ``` ## OTA Firmware Updates ESP32-SvelteKit offers two different ways to roll out firmware updates to field devices. If the frontend should be updated as well it is necessary to embed it into the firmware binary by activating `-D EMBED_WWW`. ### Firmware Upload Enabling `FT_UPLOAD_FIRMWARE=1` in [features.ini](https://github.com/theelims/ESP32-sveltekit/blob/main/features.ini) creates a REST endpoint that one can post a firmware binary to. The frontend has a file drop zone to upload a new firmware binary from the browser. ### Firmware Download from Update Server By enabling `FT_DOWNLOAD_FIRMWARE=1` in [features.ini](https://github.com/theelims/ESP32-sveltekit/blob/main/features.ini) one can POST a link to a firmware binary which is downloaded for the OTA process. This feature requires SSL and is thus dependent on `FT_NTP=1`. The Frontend contains an implementation which uses GitHub's Releases section as the update server. By specifying a firmware version in [platformio.ini](https://github.com/theelims/ESP32-sveltekit/blob/main/platformio.ini) one can make use of semantic versioning to determine the correct firmware: ```ini -D BUILD_TARGET="$PIOENV" -D APP_NAME=\"ESP32-Sveltekit\" ; Must only contain characters from [a-zA-Z0-9-_] as this is converted into a filename -D APP_VERSION=\"0.3.0\" ; semver compatible version string ``` A build script copies the firmware binary files for all build environment to `build/firmware`. It renames them into `{APP_NAME}_{$PIOENV}_{APP_VERSION}.bin`. It also creates a MD5 checksum file for verification during the OTA process. These files can be used as attachment on the GitHub release pages. !!! info This feature could be unstable on single-core members of the ESP32 family. #### Custom Update Server If Github is not desired as the update server this can be easily modified to any other custom server. The REST API will accept any valid HTTPS-Link. However, SSL is mandatory and may require a different Root CA Certificate then Github to validate correctly. Follow the instructions here how to change the [SSL CA Certificate](buildprocess.md#ssl-root-certificate-for-download-ota). If you use a custom update server you must also adapt the [frontend](structure.md#custom-update-server) code to suit your needs. ================================================ FILE: docs/stores.md ================================================ # Stores ## User The user store holds the current users credentials, if the security features are enabled. Just import it as you would use with any svelte store: ```ts import { user } from "$lib/stores/user"; ``` You can subscribe to it like to any other store with `$user` and it has the following properties: | Property | Type | Description | | -------------------- | --------- | ------------------------------------------------- | | `$user.bearer_token` | `String` | The JWT token to authorize a user at the back end | | `$user.username` | `String` | Username of the current user | | `$user.admin` | `Boolean` | `true` if the current user has admin privileges | In addition to the properties it provides two methods for initializing the user credentials and to invalidate them. `user.init()` takes a valid JWT toke as an argument and extracts the user privileges and username from it. `user.invalidate()` invalidates the user credentials and redirects to the login pages !!! warning "User credentials are stored in the browsers local storage" The user credentials including the JWT token are stored in the browsers local storage. Any javascript executed on the browser can access this making it extremely vulnerable to XSS attacks. Also the HTTP connection between ESP32 and front end is not encrypted making it possible for everyone to read the JWT token in the same network. Fixing these severe security issues is on the todo list for upcoming releases. ## Event Socket The [Event Socket System](statefulservice.md#event-socket) is conveniently provided as a Svelte store. Import the store, subscribe to the data interested with `socket.on`. To unsubscribe simply call `socket.off`. Data can be sent to the ESP32 by calling `socket.sendEvent` ```ts import { socket } from "$lib/stores/socket"; let lightState: LightState = { led_on: false }; onMount(() => { socket.on("led", (data) => { lightState = data; }); }); onDestroy(() => socket.off("led")); socket.sendEvent("led", lightState); ``` Subscribing to an invalid event will only create a warning in the ESP_LOG on the serial console of the ESP32. ## Telemetry The telemetry store can be used to update telemetry data like RSSI via the [Event Socket](statefulservice.md#event-socket) system. ```ts import { telemetry } from "$lib/stores/telemetry"; ``` It exposes the following properties you can subscribe to: | Property | Type | Description | | ---------------------------------- | --------- | ------------------------------------------- | | `$telemetry.rssi.rssi` | `Number` | The RSSI signal strength of the WiFi in dBm | | `$telemetry.rssi.ssid` | `String` | Name of the connected WiFi station | | `$telemetry.rssi.connected` | `Boolean` | Connection status of the WiFi | | `$telemetry.battery.soc` | `Number` | Battery state of charge | | `$telemetry.battery.charging` | `Boolean` | Is battery connected to charger | | `$telemetry.download_ota.status` | `String` | Status of OTA | | `$telemetry.download_ota.progress` | `Number` | Progress of OTA | | `$telemetry.download_ota.error` | `String` | Error Message of OTA | | `$telemetry.ethernet.connected` | `Boolean` | Connection status of the ethernet interface | ## Analytics The analytics store holds a log of heap and other debug information via the [Event Socket](statefulservice.md#event-socket) system. ```ts import { analytics } from "$lib/stores/analytics"; ``` It exposes an array of the following properties you can subscribe to: | Property | Type | Description | | --------------------------- | -------- | ---------------------------------------------- | | `$analytics.uptime` | `Number` | Uptime of the chip in seconds since last reset | | `$analytics.free_heap` | `Number` | Current free heap | | `$analytics.min_free_heap` | `Number` | Minimum free heap that has been | | `$analytics.max_alloc_heap` | `Number` | Biggest continues free chunk of heap | | `$analytics.fs_used` | `Number` | Bytes used on the file system | | `$analytics.fs_total` | `Number` | Total bytes of the file system | | `$analytics.core_temp` | `Number` | Core temperature (on some chips) | By default there is one data point every 2 seconds. It holds 1000 data points worth roughly 33 Minutes of data. ================================================ FILE: docs/structure.md ================================================ # Customizing the Front End The actual code for the front end is located under [interface/src/](https://github.com/theelims/ESP32-sveltekit/tree/main/interface/src) and divided into the "routes" folder and a "lib" folder for assets, stores and components. | Resource | Description | | ------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | | [routes/](https://github.com/theelims/ESP32-sveltekit/tree/main/interface/src/routes/) | Root of the routing system | | [routes/connections/](https://github.com/theelims/ESP32-sveltekit/blob/main/interface/src/routes/connections) | Setting and status pages for MQTT, NTP, etc. | | [routes/demo/](https://github.com/theelims/ESP32-sveltekit/blob/main/interface/src/routes/demo/) | The lightstate demo | | [routes/system/](https://github.com/theelims/ESP32-sveltekit/blob/main/interface/src/routes/system/) | Status page for ESP32 and OTA settings | | [routes/user/](https://github.com/theelims/ESP32-sveltekit/blob/main/interface/src/routes/user/) | Edit and add users and change passwords | | [routes/wifi/](https://github.com/theelims/ESP32-sveltekit/blob/main/interface/src/routes/wifi/) | Status and settings for WiFi station and AP | | [lib/](https://github.com/theelims/ESP32-sveltekit/blob/main/interface/src/lib/) | Library folder for stores, components and assets | | [lib/assets/](https://github.com/theelims/ESP32-sveltekit/blob/main/interface/src/lib/assets/) | Assets like pictures | | [lib/components/](https://github.com/theelims/ESP32-sveltekit/blob/main/interface/src/lib/components/) | Reusable components like modals, password input or collapsible | | [lib/stores](https://github.com/theelims/ESP32-sveltekit/blob/main/interface/src/lib/stores/) | Svelte stores for common access to data | ## Features The back end provides a JSON which features of the back end are enabled by the [feature selection](buildprocess.md#selecting-features). It is fetched with the page load and made available in the `pages`-store and can be accessed on any site with `page.data.features`. It is used to hide any disabled setting element. ## Delete `demo/` Project The light state demo project is included by default to demonstrate the use of the backend and front end. It demonstrates the use of the MQTT-API, websocket API and REST API to switch on the build in LED of the board. [routes/connections/mqtt/MQTTConfig.svelte](https://github.com/theelims/ESP32-sveltekit/blob/main/interface/src/routes/connections/mqtt/MQTTConfig.svelte) is also part of the 'demo/' Project. You can reuse this to set your own MQTT topics, or delete it. Do not forget to adjust `+page.svelte` as well. Use it as an example how to create your own custom API and access it from the front end. It can be deleted safely after it has been [removed from the menu](#adapt-the-menu) as well. ## Create your root `+page.svelte` The root page of the front end is located under [routes/+page.svelte](https://github.com/theelims/ESP32-sveltekit/tree/main/interface/src/routes/+page.svelte). This should be the central place of your app and can be accessed at any time by pressing the logo and app name in the side menu. Just override it to suit your needs. ## Customize the Main Menu The main menu is located in [routes/menu.svelte](https://github.com/theelims/ESP32-sveltekit/tree/main/interface/src/routes/menu.svelte) as a svelte component and defines the main menu including a menu footer. ### Menu Footer The main menu comes with a small footer to add your copyright notice plus links to github and your discord server where users can find help. The `active`-flag is used to disable an element in the UI. Most of these global parameters are set in the [routes/+layout.ts](https://github.com/theelims/ESP32-sveltekit/tree/main/interface/src/routes/+layout.ts). ```ts const discord = { href: ".", active: false }; ``` ### Menu Structure The menu consists of an array of menu items. These are defined as follows: ```ts { title: 'Demo App', icon: Control, href: '/demo', feature: page.data.features.project, }, ``` - Where `title` refers to the page title. It must be identical to `page.data.title` as defined in the `+page.ts` in any of your routes. If they do not match the corresponding menu item is not highlighted on first page load or a page refresh. A minimum `+page.ts` looks like this: ```ts import type { PageLoad } from "./$types"; export const load = (async ({ fetch }) => { return { title: "Demo App", }; }) satisfies PageLoad; ``` - `icon` must be an icon component giving the menu items icon. - `href` is the link to the route the menu item refers to. - `feature` takes a bool and should be set to `true`. It is used by the [feature selector](#features) to hide a menu entry of it is not present on the back end. ## Advanced Customizations On the root level there are two more files which you can customize to your needs. ### Login Page `login.svelte` is a component showing the login screen, when the security features are enabled. By default it shows the app's logo and the login prompt. Change it as you need it. ### Status Bar `statusbar.svelte` contains the top menu bar which you can customize to show state information about your app and IoT device. By default it shows the active menu title and the hamburger icon on small screens. ## Github Firmware Update If the feature `FT_DOWNLOAD_FIRMWARE` is enabled, ESP32 SvelteKit pulls the Github Release section through the Github API for firmware updates once per hour. Also the firmware update menu shows all available firmware releases allowing the user to up- and downgrade has they please. If you're using the Github releases section you must first tell the frontend your correct path to your github repository as described [here](sveltekit.md#changing-the-app-name). Also you must make use of couple build flags in [platformio.ini](https://github.com/theelims/ESP32-sveltekit/blob/main/platformio.ini): ```ini -D BUILD_TARGET=\"$PIOENV\" -D APP_NAME=\"ESP32-Sveltekit\" ; Must only contain characters from [a-zA-Z0-9-_] as this is converted into a filename -D APP_VERSION=\"0.3.0\" ; semver compatible version string ``` Out of these flags the [rename_fw.py](https://github.com/theelims/ESP32-sveltekit/blob/main/scripts/rename_fw.py) script will copy and rename the firmware binary to `/build/firmware/{APP_NAME}_{$PIOENV}_{APP_VERSION}.bin`. In addition it will also create a corresponding MD5 checksum file. These files are ready to be uploaded to the Github release page without any further changes. The frontend searches for the firmware binary which matches the build environment and uses this as the update link. This allows you to serve different build targets (e.g. different boards) from the same release page. ### Custom Update Server The frontend and backend code can be easily adjusted to suit a custom update server. For the backend the changes are described [here](statefulservice.md#custom-update-server). On the frontend only two files must be adapted and changed to switch to a custom update server: [/lib/components/UpdateIndicator.svelte](https://github.com/theelims/ESP32-sveltekit/blob/main/interface/src/lib/components/UpdateIndicator.svelte) and [/routes/system/update/GithubFirmwareManager.svelte](https://github.com/theelims/ESP32-sveltekit/blob/main/interface/src/routes/system/update/GithubFirmwareManager.svelte). !!! info The update server must provide the firmware download through SSL encryption. ================================================ FILE: docs/sveltekit.md ================================================ # Getting Started with SvelteKit SvelteKits unique approach makes it perfect suitable for constraint server. It builds very small files shipping only the minimum required amount of java script. This keeps the memory footprint low so that rich applications can be build with just the 4MB flash of many ESP32 chips. However, since SvelteKit is designed with server-side rendering first, there are some catches and pitfalls one must avoid. Especially as nearly all tutorials found on SvelteKit heavily make use of the combined front and back end features. ## Limitations of `adapter-static` To build a website that can be served from an ESP32 `adapter-static` is used. This means no server functions can be used. The front end is build as a Single-Page Application (SPA) instead. However, SvelteKit will pre-render sites at build time, even if SSR and pre-rendering are disabled. This leads to some restrictions that must be taken into consideration: - You can't use any server-side logic like `+page.server.ts`, `+layout.server.ts` or `+server.ts` files in your project. - The load function in `+page.ts` gets executed on the server and the client. If you try to access browser resources in the load function this will fail. Use a more traditional way like fetching the data in the `+page.svelte` with the `onMount(() => {})` callback. ## Customizing and Theming ### Changing the App Name [+layout.ts](https://github.com/theelims/ESP32-sveltekit/blob/main/interface/src/routes/%2Blayout.ts) bundles a few globally customizable properties like github repository, app name and copyright notice: ```js export const load = (async () => { const result = await fetch('/rest/features'); const item = await result.json(); return { features: item, title: 'ESP32-SvelteKit', github: 'theelims/ESP32-sveltekit', copyright: '2024 theelims', appName: 'ESP32 SvelteKit' }; }) satisfies LayoutLoad; ``` In [menu.svelte](https://github.com/theelims/ESP32-sveltekit/blob/main/interface/src/routes/menu.svelte) there is additionally the possibility to add a discord invite, which is disabled by default. ```js const discord = { href: ".", active: false }; ``` There is also a manifest file which contains the app name to use when adding the app to a mobile device, so you may wish to also edit [interface/static/manifest.json](https://github.com/theelims/ESP32-sveltekit/blob/main/interface/static/manifest.json): ```json { "name": "ESP32 SvelteKit", "icons": [ { "src": "/favicon.png", "sizes": "48x48 72x72 96x96 128x128 256x256" } ], "start_url": "/", "display": "fullscreen", "orientation": "any" } ``` ### Changing the App Icon and Favicon You can replace the apps favicon which is located at [interface/static/favicon.png](https://github.com/theelims/ESP32-sveltekit/blob/main/interface/static/favicon.png) with one of your preference. A 256 x 256 PNG is recommended for best compatibility. Also the Svelte Logo can be replaced with your own. It is located under [interface/src/lib/assets/logo.png](https://github.com/theelims/ESP32-sveltekit/blob/main/interface/src/lib/assets/logo.png). ### Daisy UI Themes The overall theme of the front end is defined by [DaisyUI](https://daisyui.com/docs/themes/) and can be easily changed according to their documentation. Either by selecting one of the standard themes of DaisyUI, or creating your own. By default the `corporate` and `business` for dark are defined in [app.css](https://github.com/theelims/ESP32-sveltekit/blob/main/interface/src/app.css): ```js @plugin "daisyui" { themes: corporate --default, business --prefersdark; } ``` #### Opinionated use of Shadows The front end makes some use of colored shadows with the `shadow-primary` and `shadow-secondary` DaisyUI classes. Just use the search and replace function to change this to a more neutral look, if you find the color too much. #### Color Scheme Helper Some JS modules do not accept DaisyUI/TailwindCSS color class names. A small helper function can be imported and used to convert any CSS variable name for a DaisyUI color into OKCHL. That way modules like e.g. Charts.js can be styled in the current color scheme in a responsive manner. ```js import { daisyColor } from "$lib/DaisyUiHelper"; borderColor: daisyColor('--color-primary'), backgroundColor: daisyColor('--color-primary', 50), ``` ## TS Types Definition All types used throughout the front end are exported from [models.ts](https://github.com/theelims/ESP32-sveltekit/blob/main/interface/src/lib/types/models.ts). It is a convenient location to add your custom types once you expand the front end. ================================================ FILE: factory_settings.ini ================================================ ; The indicated settings support placeholder substitution as follows: ; ; #{platform} - The microcontroller platform, e.g. "esp32" or "esp32c3" ; #{unique_id} - A unique identifier derived from the MAC address, e.g. "0b0a859d6816" ; #{random} - A random number encoded as a hex string, e.g. "55722f94" [factory_settings] build_flags = ; WiFi settings -D FACTORY_WIFI_SSID=\"\" -D FACTORY_WIFI_PASSWORD=\"\" -D FACTORY_WIFI_HOSTNAME=\"#{platform}-#{unique_id}\" ; supports placeholders -D FACTORY_WIFI_RSSI_THRESHOLD=-80 ; dBm, -80 is a good value for most applications ; Access point settings -D FACTORY_AP_PROVISION_MODE=AP_MODE_DISCONNECTED -D FACTORY_AP_SSID=\"ESP32-SvelteKit-#{unique_id}\" ; 1-64 characters, supports placeholders -D FACTORY_AP_PASSWORD=\"esp-sveltekit\" ; 8-64 characters -D FACTORY_AP_CHANNEL=1 -D FACTORY_AP_SSID_HIDDEN=false -D FACTORY_AP_MAX_CLIENTS=4 -D FACTORY_AP_LOCAL_IP=\"192.168.4.1\" -D FACTORY_AP_GATEWAY_IP=\"192.168.4.1\" -D FACTORY_AP_SUBNET_MASK=\"255.255.255.0\" ; User credentials for admin and guest user -D FACTORY_ADMIN_USERNAME=\"admin\" -D FACTORY_ADMIN_PASSWORD=\"admin\" -D FACTORY_GUEST_USERNAME=\"guest\" -D FACTORY_GUEST_PASSWORD=\"guest\" ; NTP settings -D FACTORY_NTP_ENABLED=true -D FACTORY_NTP_TIME_ZONE_LABEL=\"Europe/Berlin\" -D FACTORY_NTP_TIME_ZONE_FORMAT=\"GMT0BST,M3.5.0/1,M10.5.0\" -D FACTORY_NTP_SERVER=\"time.google.com\" ; MQTT settings -D FACTORY_MQTT_ENABLED=false -D FACTORY_MQTT_URI=\"mqtts://broker.hivemq.com:8883\" -D FACTORY_MQTT_USERNAME=\"\" ; supports placeholders -D FACTORY_MQTT_PASSWORD=\"\" -D FACTORY_MQTT_CLIENT_ID=\"#{platform}-#{unique_id}\" ; supports placeholders -D FACTORY_MQTT_KEEP_ALIVE=120 -D FACTORY_MQTT_CLEAN_SESSION=true -D FACTORY_MQTT_STATUS_TOPIC=\"esp32sveltekit/#{unique_id}/status\" ; supports placeholders -D FACTORY_MQTT_MIN_MESSAGE_INTERVAL_MS=0 ; JWT Secret -D FACTORY_JWT_SECRET=\"#{random}-#{random}\" ; supports placeholders ; Deep Sleep Configuration -D WAKEUP_PIN_NUMBER=0 ; pin number to wake up the ESP -D WAKEUP_SIGNAL=0 ; 1 for wakeup on HIGH, 0 for wakeup on LOW ================================================ FILE: features.ini ================================================ [features] build_flags = -D FT_SECURITY=1 -D FT_MQTT=1 -D FT_NTP=1 -D FT_UPLOAD_FIRMWARE=1 -D FT_DOWNLOAD_FIRMWARE=1 ; requires FT_NTP=1 -D FT_SLEEP=1 -D FT_BATTERY=0 -D FT_ANALYTICS=1 -D FT_COREDUMP=1 ; -D FT_ETHERNET=1 ; ethernet feature should be enabled in the board config as not every board supports ethernet ================================================ FILE: interface/.eslintignore ================================================ .DS_Store node_modules /build /.svelte-kit /package .env .env.* !.env.example # Ignore files for PNPM, NPM and YARN pnpm-lock.yaml package-lock.json yarn.lock ================================================ FILE: interface/.eslintrc.cjs ================================================ module.exports = { root: true, parser: '@typescript-eslint/parser', extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended', 'prettier'], plugins: ['svelte3', '@typescript-eslint'], ignorePatterns: ['*.cjs'], overrides: [{ files: ['*.svelte'], processor: 'svelte3/svelte3' }], settings: { 'svelte3/typescript': () => require('typescript') }, parserOptions: { sourceType: 'module', ecmaVersion: 2020 }, env: { browser: true, es2017: true, node: true } }; ================================================ FILE: interface/.gitignore ================================================ .DS_Store node_modules /build /.svelte-kit /package .env .env.* !.env.example vite.config.js.timestamp-* vite.config.ts.timestamp-* ================================================ FILE: interface/.npmrc ================================================ engine-strict=true ================================================ FILE: interface/.prettierignore ================================================ .DS_Store node_modules /build /.svelte-kit /package .env .env.* !.env.example # Ignore files for PNPM, NPM and YARN pnpm-lock.yaml package-lock.json yarn.lock ================================================ FILE: interface/.prettierrc ================================================ { "useTabs": true, "singleQuote": true, "trailingComma": "none", "printWidth": 100, "plugins": ["prettier-plugin-svelte"], "pluginSearchDirs": ["."], "overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }] } ================================================ FILE: interface/LICENSE ================================================ ESP32-SvelteKit is distributed with two licenses for different sections of the code. The back end code inherits the GNU LESSER GENERAL PUBLIC LICENSE Version 3 and is therefore distributed said license. The front end code is distributed under the MIT License. MIT License Copyright (C) 2023 - 2024 theelims Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: interface/package.json ================================================ { "name": "ESP32-Sveltekit Template", "version": "0.2.0", "private": true, "scripts": { "dev": "vite dev --host", "build": "vite build", "preview": "vite preview", "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch", "lint": "prettier --plugin-search-dir . --check . && eslint .", "format": "prettier --plugin-search-dir . --write ." }, "devDependencies": { "@iconify-json/tabler": "^1.2.19", "@sveltejs/adapter-static": "^3.0.8", "@sveltejs/kit": "^2.22.3", "@sveltejs/vite-plugin-svelte": "^4.0.4", "@tailwindcss/vite": "^4.1.11", "@types/msgpack-lite": "^0.1.11", "@typescript-eslint/eslint-plugin": "^8.36.0", "@typescript-eslint/parser": "^8.36.0", "daisyui": "^5.0.46", "eslint": "^9.30.1", "eslint-config-prettier": "^10.1.5", "eslint-plugin-svelte": "^3.10.1", "prettier": "^3.6.2", "prettier-plugin-svelte": "^3.4.0", "prettier-plugin-tailwindcss": "^0.6.14", "svelte": "^5.35.5", "svelte-check": "^4.2.2", "svelte-focus-trap": "^1.2.0", "tailwindcss": "^4.1.11", "terser": "^5.44.0", "tslib": "^2.8.1", "typescript": "^5.8.3", "unplugin-icons": "^22.1.0", "vite": "^5.4.19" }, "type": "module", "dependencies": { "chart.js": "^4.5.0", "chartjs-adapter-luxon": "^1.3.1", "compare-versions": "^6.1.1", "jwt-decode": "^4.0.0", "luxon": "^3.7.1", "msgpack-lite": "^0.1.26", "svelte-dnd-action": "^0.9.65", "svelte-modals": "^2.0.1" } } ================================================ FILE: interface/src/app.css ================================================ @import "tailwindcss"; @plugin "daisyui" { themes: corporate --default, business --prefersdark; } /* The default border color has changed to `currentcolor` in Tailwind CSS v4, so we've added these compatibility styles to make sure everything still looks the same as it did with Tailwind CSS v3. If we ever want to remove these styles, we need to add an explicit border color utility to any element that depends on these defaults. */ @layer base { *, ::after, ::before, ::backdrop, ::file-selector-button { border-color: var(--color-gray-200, currentcolor); } } ================================================ FILE: interface/src/app.d.ts ================================================ // See https://kit.svelte.dev/docs/types#app // for information about these interfaces /// /// declare global { namespace App { // interface Error {} // interface Locals {} // interface PageData {} // interface Platform {} } } export {}; ================================================ FILE: interface/src/app.html ================================================ %sveltekit.head%
%sveltekit.body%
================================================ FILE: interface/src/lib/DaisyUiHelper.ts ================================================ export function daisyColor(name: string, opacity: number = 100) { const color = getComputedStyle(document.documentElement).getPropertyValue(name); // console.debug(`daisyColor: name=${name}, color=${color}, opacity=${opacity}`); // console.debug(`${color}`); // add transparency to the color if opacity is less than 100 if (opacity < 100) { // Convert opacity to a percentage const alpha = Math.min(Math.max(Math.round(opacity), 0), 100) / 100; // Remove any existing alpha value and trailing ')' from the oklch color const oklchColor = color.replace(/(\/\s*\d+(\.\d+)?\))|\)$/, '').trim(); // Append the new alpha value // console.debug(`oklchColor: ${oklchColor} / ${alpha})`); return `${oklchColor} / ${alpha})`; } return `${color}`; // / ${Math.min(Math.max(Math.round(opacity), 0), 100)}%)`; } ================================================ FILE: interface/src/lib/components/BatteryIndicator.svelte ================================================
{#if charging} {:else if soc > 75} {:else if soc > 55} {:else if soc > 30} {:else if soc > 5} {:else} {/if}
================================================ FILE: interface/src/lib/components/Collapsible.svelte ================================================
{#if isDirty}
{/if}
{@render icon?.()} {@render title?.()} {#if isDirty}
{/if}
{#if open}
{@render children?.()}
{/if}
================================================ FILE: interface/src/lib/components/ConfirmDialog.svelte ================================================ {#if isOpen} {@const SvelteComponent = labels?.confirm.icon} {/if} ================================================ FILE: interface/src/lib/components/DraggableList.svelte ================================================
{#each itemsWithIds as item, index (item.id)} {@render children({ item, index, originalItem: items[index] })} {/each}
================================================ FILE: interface/src/lib/components/FirmwareUpdateDialog.svelte ================================================ {#if isOpen} {/if} ================================================ FILE: interface/src/lib/components/InfoDialog.svelte ================================================ {#if isOpen} {/if} ================================================ FILE: interface/src/lib/components/InputPassword.svelte ================================================
(show = false)} role="button" aria-label="Hide password" tabindex="0" width="40" height="40" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" > (show = true)} role="button" aria-label="Show password" tabindex="0" width="40" height="40" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round" >
================================================ FILE: interface/src/lib/components/RSSIIndicator.svelte ================================================
{#if showDBm} {rssi_dbm} dBm {/if} {#if rssi_dbm >= -55} {:else if rssi_dbm >= -75}
{:else if rssi_dbm >= -85}
{:else}
{/if}
================================================ FILE: interface/src/lib/components/SettingsCard.svelte ================================================ {#if collapsible}
{#if isDirty}
{/if}
{@render icon?.()} {@render title?.()} {#if isDirty}
{/if}
{#if open}
{@render children?.()}
{/if}
{:else}
{#if isDirty}
{/if}
{@render icon?.()} {@render title?.()} {#if isDirty}
{/if}
{@render children?.()}
{/if} ================================================ FILE: interface/src/lib/components/Spinner.svelte ================================================

{text}

================================================ FILE: interface/src/lib/components/UpdateIndicator.svelte ================================================ {#if update} {/if} ================================================ FILE: interface/src/lib/components/toasts/Toast.svelte ================================================
{#each $notifications as notification (notification.id)} {@const SvelteComponent = icon[notification.type]}
{@html notification.message}
{/each}
================================================ FILE: interface/src/lib/components/toasts/notifications.ts ================================================ import { writable, derived, type Writable } from 'svelte/store'; type StateType = 'info' | 'success' | 'warning' | 'error'; type State = { id: string; type: StateType; message: string; }; function createNotificationStore() { const state: State[] = []; const notifications = writable(state); const { subscribe } = notifications; function send(message: string, type: StateType = 'info', timeout: number) { const id = generateId(); setTimeout(() => { notifications.update((state) => { return state.filter((n) => n.id !== id); }); }, timeout); notifications.update((state) => { return [...state, { id, type, message }]; }); } return { subscribe, send, error: (msg: string, timeout: number) => send(msg, 'error', timeout), warning: (msg: string, timeout: number) => send(msg, 'warning', timeout), info: (msg: string, timeout: number) => send(msg, 'info', timeout), success: (msg: string, timeout: number) => send(msg, 'success', timeout) }; } function generateId() { return '_' + Math.random().toString(36).substr(2, 9); } export const notifications = createNotificationStore(); ================================================ FILE: interface/src/lib/stores/analytics.ts ================================================ import { type Analytics } from '$lib/types/models'; import { writable } from 'svelte/store'; let analytics_data = { uptime: [], free_heap: [], used_heap: [], total_heap: [], min_free_heap: [], max_alloc_heap: [], fs_used: [], fs_total: [], core_temp: [], free_psram: [], used_psram: [], psram_size: [], }; const maxAnalyticsData = 1000; // roughly 33 Minutes of data at 1 update per 2 seconds function createAnalytics() { const { subscribe, update } = writable(analytics_data); return { subscribe, addData: (content: Analytics) => { update((analytics_data) => ({ ...analytics_data, uptime: [...analytics_data.uptime, content.uptime].slice(-maxAnalyticsData), free_heap: [...analytics_data.free_heap, content.free_heap / 1000].slice(-maxAnalyticsData), used_heap: [...analytics_data.used_heap, content.used_heap / 1000].slice(-maxAnalyticsData), total_heap: [...analytics_data.total_heap, content.total_heap / 1000].slice( -maxAnalyticsData ), min_free_heap: [...analytics_data.min_free_heap, content.min_free_heap / 1000].slice( -maxAnalyticsData ), max_alloc_heap: [...analytics_data.max_alloc_heap, content.max_alloc_heap / 1000].slice( -maxAnalyticsData ), fs_used: [...analytics_data.fs_used, content.fs_used / 1000].slice(-maxAnalyticsData), fs_total: [...analytics_data.fs_total, content.fs_total / 1000].slice(-maxAnalyticsData), core_temp: [...analytics_data.core_temp, content.core_temp].slice(-maxAnalyticsData), free_psram: [...analytics_data.free_psram, content.free_psram / 1000].slice(-maxAnalyticsData), used_psram: [...analytics_data.used_psram, content.used_psram / 1000].slice(-maxAnalyticsData), psram_size: [...analytics_data.psram_size, content.psram_size / 1000].slice(-maxAnalyticsData), })); } }; } export const analytics = createAnalytics(); ================================================ FILE: interface/src/lib/stores/battery.ts ================================================ import { type Battery } from '$lib/types/models'; import { writable } from 'svelte/store'; let battery_history = { soc: [], charging: [], timestamp: [] }; const maxAnalyticsData = 3600; // roughly 5 Hours of data at 1 update per 5 seconds function createBatteryHistory() { const { subscribe, update } = writable(battery_history); return { subscribe, addData: (content: Battery) => { update((battery_history) => ({ ...battery_history, soc: [...battery_history.soc, content.soc].slice(-maxAnalyticsData), charging: [...battery_history.charging, content.charging ? 1 : 0].slice(-maxAnalyticsData), timestamp: [...battery_history.timestamp, Date.now()].slice(-maxAnalyticsData) })); } }; } export const batteryHistory = createBatteryHistory(); ================================================ FILE: interface/src/lib/stores/socket.ts ================================================ import { writable } from 'svelte/store'; import msgpack from 'msgpack-lite'; function createWebSocket() { let listeners = new Map void>>(); const { subscribe, set } = writable(false); const socketEvents = ['open', 'close', 'error', 'message', 'unresponsive'] as const; type SocketEvent = (typeof socketEvents)[number]; let unresponsiveTimeoutId: number; let reconnectTimeoutId: number; let ws: WebSocket; let socketUrl: string | URL; let event_use_json = false; function init(url: string | URL, use_json: boolean = false) { socketUrl = url; event_use_json = use_json; connect(); } function disconnect(reason: SocketEvent, event?: Event) { //console.log('disconnect', reason, event); ws.close(); set(false); clearTimeout(unresponsiveTimeoutId); clearTimeout(reconnectTimeoutId); listeners.get(reason)?.forEach((listener) => listener(event)); reconnectTimeoutId = setTimeout(connect, 1000); } function connect() { //console.log('connect'); ws = new WebSocket(socketUrl); ws.binaryType = 'arraybuffer'; ws.onopen = (ev) => { set(true); clearTimeout(reconnectTimeoutId); listeners.get('open')?.forEach((listener) => listener(ev)); for (const event of listeners.keys()) { if (socketEvents.includes(event as SocketEvent)) continue; sendEvent('subscribe', event); } }; ws.onmessage = (message) => { resetUnresponsiveCheck(); let payload = message.data; const binary = payload instanceof ArrayBuffer; listeners.get(binary ? 'binary' : 'message')?.forEach((listener) => listener(payload)); try { payload = binary ? msgpack.decode(new Uint8Array(payload)) : JSON.parse(payload); } catch (error) { listeners.get('error')?.forEach((listener) => listener(error)); return; } listeners.get('json')?.forEach((listener) => listener(payload)); const { event, data } = payload; if (event) listeners.get(event)?.forEach((listener) => listener(data)); }; ws.onerror = (ev) => disconnect('error', ev); ws.onclose = (ev) => disconnect('close', ev); } function unsubscribe(event: string, listener?: (data: any) => void) { let eventListeners = listeners.get(event); if (!eventListeners) return; if (!eventListeners.size) { sendEvent('unsubscribe', event); } if (listener) { eventListeners?.delete(listener); } else { listeners.delete(event); } } function resetUnresponsiveCheck() { clearTimeout(unresponsiveTimeoutId); unresponsiveTimeoutId = setTimeout(() => disconnect('unresponsive'), 2000); } function send(msg: unknown) { if (!ws || ws.readyState !== WebSocket.OPEN) return; if (event_use_json) { ws.send(JSON.stringify(msg)); } else { ws.send(msgpack.encode(msg)); } } function sendEvent(event: string, data: unknown) { send({ event, data }); } return { subscribe, send, sendEvent, init, on: (event: string, listener: (data: T) => void): (() => void) => { let eventListeners = listeners.get(event); if (!eventListeners) { eventListeners = new Set(); listeners.set(event, eventListeners); // Only send subscription if WebSocket is open and it's not a socket event if (!socketEvents.includes(event as SocketEvent) && ws && ws.readyState === WebSocket.OPEN) { sendEvent('subscribe', event); } } eventListeners.add(listener as (data: any) => void); return () => { unsubscribe(event, listener); }; }, off: (event: string, listener?: (data: any) => void) => { unsubscribe(event, listener); } }; } export const socket = createWebSocket(); ================================================ FILE: interface/src/lib/stores/telemetry.ts ================================================ import { writable } from 'svelte/store'; import type { RSSI } from '../types/models'; import type { Battery } from '../types/models'; import type { OTAStatus } from '../types/models'; import type { Ethernet } from '../types/models'; let telemetry_data = { rssi: { rssi: 0, ssid: '', disconnected: true }, battery: { soc: 100, charging: false }, ota_status: { status: 'none', progress: 0, bytes_written: 0, total_bytes: 0, error: '' }, ethernet: { connected: false } }; function createTelemetry() { const { subscribe, set, update } = writable(telemetry_data); return { subscribe, setRSSI: (data: RSSI) => { if (!isNaN(Number(data.rssi))) { update((telemetry_data) => ({ ...telemetry_data, rssi: { rssi: Number(data.rssi), ssid: data.ssid, disconnected: false } })); } else { update((telemetry_data) => ({ ...telemetry_data, rssi: { rssi: 0, ssid: data.ssid, disconnected: true } })); } }, setBattery: (data: Battery) => { update((telemetry_data) => ({ ...telemetry_data, battery: { soc: data.soc, charging: data.charging } })); }, setOTAStatus: (data: OTAStatus) => { update((telemetry_data) => ({ ...telemetry_data, ota_status: { status: data.status, progress: data.progress, bytes_written: data.bytes_written ?? 0, total_bytes: data.total_bytes ?? 0, error: data.error } })); }, setEthernet: (data: Ethernet) => { update((telemetry_data) => ({ ...telemetry_data, ethernet: { connected: data.connected } })); } }; } export const telemetry = createTelemetry(); ================================================ FILE: interface/src/lib/stores/user.ts ================================================ import { writable } from 'svelte/store'; import { goto } from '$app/navigation'; import { jwtDecode } from 'jwt-decode'; export type userProfile = { username: string; admin: boolean; bearer_token: string; }; type decodedJWT = { username: string; admin: boolean; }; let empty = { username: '', admin: false, bearer_token: '' }; function createStore() { const { subscribe, set } = writable(empty); // retrieve store from sessionStorage / localStorage if available const userdata = localStorage.getItem('user'); if (userdata) { set(JSON.parse(userdata)); } return { subscribe, init: (access_token: string) => { const decoded: decodedJWT = jwtDecode(access_token); const userdata = { bearer_token: access_token, username: decoded.username, admin: decoded.admin }; set(userdata); // persist store in sessionStorage / localStorage localStorage.setItem('user', JSON.stringify(userdata)); }, invalidate: () => { console.log('Log out user'); set(empty); // remove localStorage "user" localStorage.removeItem('user'); // redirect to login page goto('/'); } }; } export const user = createStore(); ================================================ FILE: interface/src/lib/types/models.ts ================================================ export type WifiStatus = { status: number; local_ip: string; mac_address: string; rssi: number; ssid: string; bssid: string; channel: number; subnet_mask: string; gateway_ip: string; dns_ip_1: string; dns_ip_2?: string; }; export type WifiSettings = { hostname: string; connection_mode: number; wifi_networks: KnownNetworkItem[]; }; export type KnownNetworkItem = { ssid: string; password: string; static_ip_config: boolean; local_ip?: string; subnet_mask?: string; gateway_ip?: string; dns_ip_1?: string; dns_ip_2?: string; }; export type NetworkItem = { rssi: number; ssid: string; bssid: string; channel: number; encryption_type: number; }; export type ApStatus = { status: number; ip_address: string; mac_address: string; station_num: number; }; export type ApSettings = { provision_mode: number; ssid: string; password: string; channel: number; ssid_hidden: boolean; max_clients: number; local_ip: string; gateway_ip: string; subnet_mask: string; }; export type LightState = { led_on: boolean; }; export type BrokerSettings = { mqtt_path: string; name: string; unique_id: string; status_topic: string; }; export type NTPStatus = { status: number; utc_time: string; local_time: string; server: string; uptime: number; }; export type NTPSettings = { enabled: boolean; server: string; tz_label: string; tz_format: string; }; export type Analytics = { max_alloc_heap: number; psram_size: number; free_psram: number; used_psram: number; free_heap: number; used_heap: number; total_heap: number; min_free_heap: number; core_temp: number; fs_total: number; fs_used: number; uptime: number; }; export type RSSI = { rssi: number; ssid: string; }; export type Battery = { soc: number; charging: boolean; }; export type OTAStatus = { status: 'none' | 'preparing' | 'progress' | 'finished' | 'error'; progress: number; bytes_written?: number; total_bytes?: number; error: string; }; export type StaticSystemInformation = { esp_platform: string; firmware_version: string; cpu_freq_mhz: number; cpu_type: string; cpu_rev: number; cpu_cores: number; sketch_size: number; free_sketch_space: number; sdk_version: string; arduino_version: string; flash_chip_size: number; flash_chip_speed: number; cpu_reset_reason: string; }; export type SystemInformation = Analytics & StaticSystemInformation; export type MQTTStatus = { enabled: boolean; connected: boolean; client_id: string; last_error: string; }; export type MQTTSettings = { enabled: boolean; uri: string; username: string; password: string; client_id: string; keep_alive: number; clean_session: boolean; message_interval_ms: number; }; export type Ethernet = { connected: boolean; }; export type EthernetStatus = { connected: boolean; local_ip: string; mac_address: string; subnet_mask: string; gateway_ip?: string; dns_ip_1?: string; dns_ip_2?: string; link_speed?: number; }; export type EthernetSettings = { hostname: string; static_ip_config: boolean; local_ip?: string; subnet_mask?: string; gateway_ip?: string; dns_ip_1?: string; dns_ip_2?: string; }; ================================================ FILE: interface/src/routes/+error.svelte ================================================
{page.status}
{page.error?.message}

Oops! Something has gone wrong.

================================================ FILE: interface/src/routes/+layout.svelte ================================================ {page.data.title} {#if page.data.features.security && $user.bearer_token === ''} {:else}
{@render children?.()}
{ menuOpen = false; }} />
{/if} {#snippet backdrop({ close })}
close()} role="button" tabindex="0" aria-label="Close modal" >
{/snippet}
================================================ FILE: interface/src/routes/+layout.ts ================================================ import type { LayoutLoad } from './$types'; // This can be false if you're using a fallback (i.e. SPA mode) export const prerender = false; export const ssr = false; export const load = (async ({ fetch }) => { const result = await fetch('/rest/features'); const item = await result.json(); return { features: item, title: 'ESP32-SvelteKit', github: 'theelims/ESP32-sveltekit', copyright: '2025 theelims', appName: 'ESP32 SvelteKit' }; }) satisfies LayoutLoad; ================================================ FILE: interface/src/routes/+page.svelte ================================================
Logo

Welcome to ESP32-SvelteKit

A simple, secure and extensible framework for IoT projects for ESP32 platforms with responsive SvelteKit front-end built with TailwindCSS and DaisyUI.

notifications.success('You did it!', 1000)}>Start Demo
================================================ FILE: interface/src/routes/connections/+page.ts ================================================ import type { PageLoad } from './$types'; import { goto } from '$app/navigation'; export const load = (async () => { goto('/'); return; }) satisfies PageLoad; ================================================ FILE: interface/src/routes/connections/mqtt/+page.svelte ================================================
================================================ FILE: interface/src/routes/connections/mqtt/+page.ts ================================================ import type { PageLoad } from './$types'; export const load = (async () => { return { title: "MQTT" }; }) satisfies PageLoad; ================================================ FILE: interface/src/routes/connections/mqtt/MQTT.svelte ================================================ {#snippet icon()} {/snippet} {#snippet title()} MQTT {/snippet}
{#await getMQTTStatus()} {:then nothing}
Status
{#if mqttStatus.connected} Connected {:else if !mqttStatus.enabled} MQTT Disabled {:else} {mqttStatus.last_error} {/if}
Client ID
{mqttStatus.client_id}
{/await}
{#if !page.data.features.security || $user.admin} {}} closed={() => {}}> {#snippet title()} Change MQTT Settings {/snippet}
{/if}
================================================ FILE: interface/src/routes/connections/mqtt/MQTTConfig.svelte ================================================ {#snippet icon()} {/snippet} {#snippet title()} MQTT Broker Settings {/snippet}
{#await getBrokerSettings()} {:then nothing}
The LED is controllable via MQTT with the demo project designed to work with Home Assistant's auto discovery feature.
{/await}
================================================ FILE: interface/src/routes/connections/ntp/+page.svelte ================================================
================================================ FILE: interface/src/routes/connections/ntp/+page.ts ================================================ import type { PageLoad } from './$types'; export const load = (async () => { return { title: 'NTP' }; }) satisfies PageLoad; ================================================ FILE: interface/src/routes/connections/ntp/NTP.svelte ================================================ {#snippet icon()} {/snippet} {#snippet title()} Network Time {/snippet}
{#await getNTPStatus()} {:then nothing}
Status
{ntpStatus.status === 1 ? 'Active' : 'Inactive'}
NTP Server
{ntpStatus.server}
Local Time
{new Intl.DateTimeFormat('en-GB', { dateStyle: 'long', timeStyle: 'long' }).format(new Date(ntpStatus.local_time))}
UTC Time
{new Intl.DateTimeFormat('en-GB', { dateStyle: 'long', timeStyle: 'long', timeZone: 'UTC' }).format(new Date(ntpStatus.utc_time))}
Uptime
{convertSeconds(ntpStatus.uptime)}
{/await}
{#if !page.data.features.security || $user.admin} {}} closed={() => {}}> {#snippet title()} Change NTP Settings {/snippet}
{#if formErrors.server}

Please enter a valid NTP server.

{/if}
{/if}
================================================ FILE: interface/src/routes/connections/ntp/timezones.ts ================================================ export type TimeZones = { [name: string]: string }; export const TIME_ZONES: TimeZones = { "Africa/Abidjan": "GMT0", "Africa/Accra": "GMT0", "Africa/Addis_Ababa": "EAT-3", "Africa/Algiers": "CET-1", "Africa/Asmara": "EAT-3", "Africa/Bamako": "GMT0", "Africa/Bangui": "WAT-1", "Africa/Banjul": "GMT0", "Africa/Bissau": "GMT0", "Africa/Blantyre": "CAT-2", "Africa/Brazzaville": "WAT-1", "Africa/Bujumbura": "CAT-2", "Africa/Cairo": "EET-2", "Africa/Casablanca": "UNK-1", "Africa/Ceuta": "CET-1CEST,M3.5.0,M10.5.0/3", "Africa/Conakry": "GMT0", "Africa/Dakar": "GMT0", "Africa/Dar_es_Salaam": "EAT-3", "Africa/Djibouti": "EAT-3", "Africa/Douala": "WAT-1", "Africa/El_Aaiun": "UNK-1", "Africa/Freetown": "GMT0", "Africa/Gaborone": "CAT-2", "Africa/Harare": "CAT-2", "Africa/Johannesburg": "SAST-2", "Africa/Juba": "EAT-3", "Africa/Kampala": "EAT-3", "Africa/Khartoum": "CAT-2", "Africa/Kigali": "CAT-2", "Africa/Kinshasa": "WAT-1", "Africa/Lagos": "WAT-1", "Africa/Libreville": "WAT-1", "Africa/Lome": "GMT0", "Africa/Luanda": "WAT-1", "Africa/Lubumbashi": "CAT-2", "Africa/Lusaka": "CAT-2", "Africa/Malabo": "WAT-1", "Africa/Maputo": "CAT-2", "Africa/Maseru": "SAST-2", "Africa/Mbabane": "SAST-2", "Africa/Mogadishu": "EAT-3", "Africa/Monrovia": "GMT0", "Africa/Nairobi": "EAT-3", "Africa/Ndjamena": "WAT-1", "Africa/Niamey": "WAT-1", "Africa/Nouakchott": "GMT0", "Africa/Ouagadougou": "GMT0", "Africa/Porto-Novo": "WAT-1", "Africa/Sao_Tome": "GMT0", "Africa/Tripoli": "EET-2", "Africa/Tunis": "CET-1", "Africa/Windhoek": "CAT-2", "America/Adak": "HST10HDT,M3.2.0,M11.1.0", "America/Anchorage": "AKST9AKDT,M3.2.0,M11.1.0", "America/Anguilla": "AST4", "America/Antigua": "AST4", "America/Araguaina": "UNK3", "America/Argentina/Buenos_Aires": "UNK3", "America/Argentina/Catamarca": "UNK3", "America/Argentina/Cordoba": "UNK3", "America/Argentina/Jujuy": "UNK3", "America/Argentina/La_Rioja": "UNK3", "America/Argentina/Mendoza": "UNK3", "America/Argentina/Rio_Gallegos": "UNK3", "America/Argentina/Salta": "UNK3", "America/Argentina/San_Juan": "UNK3", "America/Argentina/San_Luis": "UNK3", "America/Argentina/Tucuman": "UNK3", "America/Argentina/Ushuaia": "UNK3", "America/Aruba": "AST4", "America/Asuncion": "UNK4UNK,M10.1.0/0,M3.4.0/0", "America/Atikokan": "EST5", "America/Bahia": "UNK3", "America/Bahia_Banderas": "CST6CDT,M4.1.0,M10.5.0", "America/Barbados": "AST4", "America/Belem": "UNK3", "America/Belize": "CST6", "America/Blanc-Sablon": "AST4", "America/Boa_Vista": "UNK4", "America/Bogota": "UNK5", "America/Boise": "MST7MDT,M3.2.0,M11.1.0", "America/Cambridge_Bay": "MST7MDT,M3.2.0,M11.1.0", "America/Campo_Grande": "UNK4", "America/Cancun": "EST5", "America/Caracas": "UNK4", "America/Cayenne": "UNK3", "America/Cayman": "EST5", "America/Chicago": "CST6CDT,M3.2.0,M11.1.0", "America/Chihuahua": "MST7MDT,M4.1.0,M10.5.0", "America/Costa_Rica": "CST6", "America/Creston": "MST7", "America/Cuiaba": "UNK4", "America/Curacao": "AST4", "America/Danmarkshavn": "GMT0", "America/Dawson": "MST7", "America/Dawson_Creek": "MST7", "America/Denver": "MST7MDT,M3.2.0,M11.1.0", "America/Detroit": "EST5EDT,M3.2.0,M11.1.0", "America/Dominica": "AST4", "America/Edmonton": "MST7MDT,M3.2.0,M11.1.0", "America/Eirunepe": "UNK5", "America/El_Salvador": "CST6", "America/Fort_Nelson": "MST7", "America/Fortaleza": "UNK3", "America/Glace_Bay": "AST4ADT,M3.2.0,M11.1.0", "America/Godthab": "UNK3UNK,M3.5.0/-2,M10.5.0/-1", "America/Goose_Bay": "AST4ADT,M3.2.0,M11.1.0", "America/Grand_Turk": "EST5EDT,M3.2.0,M11.1.0", "America/Grenada": "AST4", "America/Guadeloupe": "AST4", "America/Guatemala": "CST6", "America/Guayaquil": "UNK5", "America/Guyana": "UNK4", "America/Halifax": "AST4ADT,M3.2.0,M11.1.0", "America/Havana": "CST5CDT,M3.2.0/0,M11.1.0/1", "America/Hermosillo": "MST7", "America/Indiana/Indianapolis": "EST5EDT,M3.2.0,M11.1.0", "America/Indiana/Knox": "CST6CDT,M3.2.0,M11.1.0", "America/Indiana/Marengo": "EST5EDT,M3.2.0,M11.1.0", "America/Indiana/Petersburg": "EST5EDT,M3.2.0,M11.1.0", "America/Indiana/Tell_City": "CST6CDT,M3.2.0,M11.1.0", "America/Indiana/Vevay": "EST5EDT,M3.2.0,M11.1.0", "America/Indiana/Vincennes": "EST5EDT,M3.2.0,M11.1.0", "America/Indiana/Winamac": "EST5EDT,M3.2.0,M11.1.0", "America/Inuvik": "MST7MDT,M3.2.0,M11.1.0", "America/Iqaluit": "EST5EDT,M3.2.0,M11.1.0", "America/Jamaica": "EST5", "America/Juneau": "AKST9AKDT,M3.2.0,M11.1.0", "America/Kentucky/Louisville": "EST5EDT,M3.2.0,M11.1.0", "America/Kentucky/Monticello": "EST5EDT,M3.2.0,M11.1.0", "America/Kralendijk": "AST4", "America/La_Paz": "UNK4", "America/Lima": "UNK5", "America/Los_Angeles": "PST8PDT,M3.2.0,M11.1.0", "America/Lower_Princes": "AST4", "America/Maceio": "UNK3", "America/Managua": "CST6", "America/Manaus": "UNK4", "America/Marigot": "AST4", "America/Martinique": "AST4", "America/Matamoros": "CST6CDT,M3.2.0,M11.1.0", "America/Mazatlan": "MST7MDT,M4.1.0,M10.5.0", "America/Menominee": "CST6CDT,M3.2.0,M11.1.0", "America/Merida": "CST6CDT,M4.1.0,M10.5.0", "America/Metlakatla": "AKST9AKDT,M3.2.0,M11.1.0", "America/Mexico_City": "CST6CDT,M4.1.0,M10.5.0", "America/Miquelon": "UNK3UNK,M3.2.0,M11.1.0", "America/Moncton": "AST4ADT,M3.2.0,M11.1.0", "America/Monterrey": "CST6CDT,M4.1.0,M10.5.0", "America/Montevideo": "UNK3", "America/Montreal": "EST5EDT,M3.2.0,M11.1.0", "America/Montserrat": "AST4", "America/Nassau": "EST5EDT,M3.2.0,M11.1.0", "America/New_York": "EST5EDT,M3.2.0,M11.1.0", "America/Nipigon": "EST5EDT,M3.2.0,M11.1.0", "America/Nome": "AKST9AKDT,M3.2.0,M11.1.0", "America/Noronha": "UNK2", "America/North_Dakota/Beulah": "CST6CDT,M3.2.0,M11.1.0", "America/North_Dakota/Center": "CST6CDT,M3.2.0,M11.1.0", "America/North_Dakota/New_Salem": "CST6CDT,M3.2.0,M11.1.0", "America/Ojinaga": "MST7MDT,M3.2.0,M11.1.0", "America/Panama": "EST5", "America/Pangnirtung": "EST5EDT,M3.2.0,M11.1.0", "America/Paramaribo": "UNK3", "America/Phoenix": "MST7", "America/Port-au-Prince": "EST5EDT,M3.2.0,M11.1.0", "America/Port_of_Spain": "AST4", "America/Porto_Velho": "UNK4", "America/Puerto_Rico": "AST4", "America/Punta_Arenas": "UNK3", "America/Rainy_River": "CST6CDT,M3.2.0,M11.1.0", "America/Rankin_Inlet": "CST6CDT,M3.2.0,M11.1.0", "America/Recife": "UNK3", "America/Regina": "CST6", "America/Resolute": "CST6CDT,M3.2.0,M11.1.0", "America/Rio_Branco": "UNK5", "America/Santarem": "UNK3", "America/Santiago": "UNK4UNK,M9.1.6/24,M4.1.6/24", "America/Santo_Domingo": "AST4", "America/Sao_Paulo": "UNK3", "America/Scoresbysund": "UNK1UNK,M3.5.0/0,M10.5.0/1", "America/Sitka": "AKST9AKDT,M3.2.0,M11.1.0", "America/St_Barthelemy": "AST4", "America/St_Johns": "NST3:30NDT,M3.2.0,M11.1.0", "America/St_Kitts": "AST4", "America/St_Lucia": "AST4", "America/St_Thomas": "AST4", "America/St_Vincent": "AST4", "America/Swift_Current": "CST6", "America/Tegucigalpa": "CST6", "America/Thule": "AST4ADT,M3.2.0,M11.1.0", "America/Thunder_Bay": "EST5EDT,M3.2.0,M11.1.0", "America/Tijuana": "PST8PDT,M3.2.0,M11.1.0", "America/Toronto": "EST5EDT,M3.2.0,M11.1.0", "America/Tortola": "AST4", "America/Vancouver": "PST8PDT,M3.2.0,M11.1.0", "America/Whitehorse": "MST7", "America/Winnipeg": "CST6CDT,M3.2.0,M11.1.0", "America/Yakutat": "AKST9AKDT,M3.2.0,M11.1.0", "America/Yellowknife": "MST7MDT,M3.2.0,M11.1.0", "Antarctica/Casey": "UNK-8", "Antarctica/Davis": "UNK-7", "Antarctica/DumontDUrville": "UNK-10", "Antarctica/Macquarie": "UNK-11", "Antarctica/Mawson": "UNK-5", "Antarctica/McMurdo": "NZST-12NZDT,M9.5.0,M4.1.0/3", "Antarctica/Palmer": "UNK3", "Antarctica/Rothera": "UNK3", "Antarctica/Syowa": "UNK-3", "Antarctica/Troll": "UNK0UNK-2,M3.5.0/1,M10.5.0/3", "Antarctica/Vostok": "UNK-6", "Arctic/Longyearbyen": "CET-1CEST,M3.5.0,M10.5.0/3", "Asia/Aden": "UNK-3", "Asia/Almaty": "UNK-6", "Asia/Amman": "EET-2EEST,M3.5.4/24,M10.5.5/1", "Asia/Anadyr": "UNK-12", "Asia/Aqtau": "UNK-5", "Asia/Aqtobe": "UNK-5", "Asia/Ashgabat": "UNK-5", "Asia/Atyrau": "UNK-5", "Asia/Baghdad": "UNK-3", "Asia/Bahrain": "UNK-3", "Asia/Baku": "UNK-4", "Asia/Bangkok": "UNK-7", "Asia/Barnaul": "UNK-7", "Asia/Beirut": "EET-2EEST,M3.5.0/0,M10.5.0/0", "Asia/Bishkek": "UNK-6", "Asia/Brunei": "UNK-8", "Asia/Chita": "UNK-9", "Asia/Choibalsan": "UNK-8", "Asia/Colombo": "UNK-5:30", "Asia/Damascus": "EET-2EEST,M3.5.5/0,M10.5.5/0", "Asia/Dhaka": "UNK-6", "Asia/Dili": "UNK-9", "Asia/Dubai": "UNK-4", "Asia/Dushanbe": "UNK-5", "Asia/Famagusta": "EET-2EEST,M3.5.0/3,M10.5.0/4", "Asia/Gaza": "EET-2EEST,M3.5.5/0,M10.5.6/1", "Asia/Hebron": "EET-2EEST,M3.5.5/0,M10.5.6/1", "Asia/Ho_Chi_Minh": "UNK-7", "Asia/Hong_Kong": "HKT-8", "Asia/Hovd": "UNK-7", "Asia/Irkutsk": "UNK-8", "Asia/Jakarta": "WIB-7", "Asia/Jayapura": "WIT-9", "Asia/Jerusalem": "IST-2IDT,M3.4.4/26,M10.5.0", "Asia/Kabul": "UNK-4:30", "Asia/Kamchatka": "UNK-12", "Asia/Karachi": "PKT-5", "Asia/Kathmandu": "UNK-5:45", "Asia/Khandyga": "UNK-9", "Asia/Kolkata": "IST-5:30", "Asia/Krasnoyarsk": "UNK-7", "Asia/Kuala_Lumpur": "UNK-8", "Asia/Kuching": "UNK-8", "Asia/Kuwait": "UNK-3", "Asia/Macau": "CST-8", "Asia/Magadan": "UNK-11", "Asia/Makassar": "WITA-8", "Asia/Manila": "PST-8", "Asia/Muscat": "UNK-4", "Asia/Nicosia": "EET-2EEST,M3.5.0/3,M10.5.0/4", "Asia/Novokuznetsk": "UNK-7", "Asia/Novosibirsk": "UNK-7", "Asia/Omsk": "UNK-6", "Asia/Oral": "UNK-5", "Asia/Phnom_Penh": "UNK-7", "Asia/Pontianak": "WIB-7", "Asia/Pyongyang": "KST-9", "Asia/Qatar": "UNK-3", "Asia/Qyzylorda": "UNK-5", "Asia/Riyadh": "UNK-3", "Asia/Sakhalin": "UNK-11", "Asia/Samarkand": "UNK-5", "Asia/Seoul": "KST-9", "Asia/Shanghai": "CST-8", "Asia/Singapore": "UNK-8", "Asia/Srednekolymsk": "UNK-11", "Asia/Taipei": "CST-8", "Asia/Tashkent": "UNK-5", "Asia/Tbilisi": "UNK-4", "Asia/Tehran": "UNK-3:30UNK,J79/24,J263/24", "Asia/Thimphu": "UNK-6", "Asia/Tokyo": "JST-9", "Asia/Tomsk": "UNK-7", "Asia/Ulaanbaatar": "UNK-8", "Asia/Urumqi": "UNK-6", "Asia/Ust-Nera": "UNK-10", "Asia/Vientiane": "UNK-7", "Asia/Vladivostok": "UNK-10", "Asia/Yakutsk": "UNK-9", "Asia/Yangon": "UNK-6:30", "Asia/Yekaterinburg": "UNK-5", "Asia/Yerevan": "UNK-4", "Atlantic/Azores": "UNK1UNK,M3.5.0/0,M10.5.0/1", "Atlantic/Bermuda": "AST4ADT,M3.2.0,M11.1.0", "Atlantic/Canary": "WET0WEST,M3.5.0/1,M10.5.0", "Atlantic/Cape_Verde": "UNK1", "Atlantic/Faroe": "WET0WEST,M3.5.0/1,M10.5.0", "Atlantic/Madeira": "WET0WEST,M3.5.0/1,M10.5.0", "Atlantic/Reykjavik": "GMT0", "Atlantic/South_Georgia": "UNK2", "Atlantic/St_Helena": "GMT0", "Atlantic/Stanley": "UNK3", "Australia/Adelaide": "ACST-9:30ACDT,M10.1.0,M4.1.0/3", "Australia/Brisbane": "AEST-10", "Australia/Broken_Hill": "ACST-9:30ACDT,M10.1.0,M4.1.0/3", "Australia/Currie": "AEST-10AEDT,M10.1.0,M4.1.0/3", "Australia/Darwin": "ACST-9:30", "Australia/Eucla": "UNK-8:45", "Australia/Hobart": "AEST-10AEDT,M10.1.0,M4.1.0/3", "Australia/Lindeman": "AEST-10", "Australia/Lord_Howe": "UNK-10:30UNK-11,M10.1.0,M4.1.0", "Australia/Melbourne": "AEST-10AEDT,M10.1.0,M4.1.0/3", "Australia/Perth": "AWST-8", "Australia/Sydney": "AEST-10AEDT,M10.1.0,M4.1.0/3", "Etc/GMT": "GMT0", "Etc/GMT+0": "GMT0", "Etc/GMT+1": "UNK1", "Etc/GMT+10": "UNK10", "Etc/GMT+11": "UNK11", "Etc/GMT+12": "UNK12", "Etc/GMT+2": "UNK2", "Etc/GMT+3": "UNK3", "Etc/GMT+4": "UNK4", "Etc/GMT+5": "UNK5", "Etc/GMT+6": "UNK6", "Etc/GMT+7": "UNK7", "Etc/GMT+8": "UNK8", "Etc/GMT+9": "UNK9", "Etc/GMT-0": "GMT0", "Etc/GMT-1": "UNK-1", "Etc/GMT-10": "UNK-10", "Etc/GMT-11": "UNK-11", "Etc/GMT-12": "UNK-12", "Etc/GMT-13": "UNK-13", "Etc/GMT-14": "UNK-14", "Etc/GMT-2": "UNK-2", "Etc/GMT-3": "UNK-3", "Etc/GMT-4": "UNK-4", "Etc/GMT-5": "UNK-5", "Etc/GMT-6": "UNK-6", "Etc/GMT-7": "UNK-7", "Etc/GMT-8": "UNK-8", "Etc/GMT-9": "UNK-9", "Etc/GMT0": "GMT0", "Etc/Greenwich": "GMT0", "Etc/UCT": "UTC0", "Etc/UTC": "UTC0", "Etc/Universal": "UTC0", "Etc/Zulu": "UTC0", "Europe/Amsterdam": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Andorra": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Astrakhan": "UNK-4", "Europe/Athens": "EET-2EEST,M3.5.0/3,M10.5.0/4", "Europe/Belgrade": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Berlin": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Bratislava": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Brussels": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Bucharest": "EET-2EEST,M3.5.0/3,M10.5.0/4", "Europe/Budapest": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Busingen": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Chisinau": "EET-2EEST,M3.5.0,M10.5.0/3", "Europe/Copenhagen": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Dublin": "IST-1GMT0,M10.5.0,M3.5.0/1", "Europe/Gibraltar": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Guernsey": "GMT0BST,M3.5.0/1,M10.5.0", "Europe/Helsinki": "EET-2EEST,M3.5.0/3,M10.5.0/4", "Europe/Isle_of_Man": "GMT0BST,M3.5.0/1,M10.5.0", "Europe/Istanbul": "UNK-3", "Europe/Jersey": "GMT0BST,M3.5.0/1,M10.5.0", "Europe/Kaliningrad": "EET-2", "Europe/Kiev": "EET-2EEST,M3.5.0/3,M10.5.0/4", "Europe/Kirov": "UNK-3", "Europe/Lisbon": "WET0WEST,M3.5.0/1,M10.5.0", "Europe/Ljubljana": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/London": "GMT0BST,M3.5.0/1,M10.5.0", "Europe/Luxembourg": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Madrid": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Malta": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Mariehamn": "EET-2EEST,M3.5.0/3,M10.5.0/4", "Europe/Minsk": "UNK-3", "Europe/Monaco": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Moscow": "MSK-3", "Europe/Oslo": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Paris": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Podgorica": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Prague": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Riga": "EET-2EEST,M3.5.0/3,M10.5.0/4", "Europe/Rome": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Samara": "UNK-4", "Europe/San_Marino": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Sarajevo": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Saratov": "UNK-4", "Europe/Simferopol": "MSK-3", "Europe/Skopje": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Sofia": "EET-2EEST,M3.5.0/3,M10.5.0/4", "Europe/Stockholm": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Tallinn": "EET-2EEST,M3.5.0/3,M10.5.0/4", "Europe/Tirane": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Ulyanovsk": "UNK-4", "Europe/Uzhgorod": "EET-2EEST,M3.5.0/3,M10.5.0/4", "Europe/Vaduz": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Vatican": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Vienna": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Vilnius": "EET-2EEST,M3.5.0/3,M10.5.0/4", "Europe/Volgograd": "UNK-4", "Europe/Warsaw": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Zagreb": "CET-1CEST,M3.5.0,M10.5.0/3", "Europe/Zaporozhye": "EET-2EEST,M3.5.0/3,M10.5.0/4", "Europe/Zurich": "CET-1CEST,M3.5.0,M10.5.0/3", "Indian/Antananarivo": "EAT-3", "Indian/Chagos": "UNK-6", "Indian/Christmas": "UNK-7", "Indian/Cocos": "UNK-6:30", "Indian/Comoro": "EAT-3", "Indian/Kerguelen": "UNK-5", "Indian/Mahe": "UNK-4", "Indian/Maldives": "UNK-5", "Indian/Mauritius": "UNK-4", "Indian/Mayotte": "EAT-3", "Indian/Reunion": "UNK-4", "Pacific/Apia": "UNK-13UNK,M9.5.0/3,M4.1.0/4", "Pacific/Auckland": "NZST-12NZDT,M9.5.0,M4.1.0/3", "Pacific/Bougainville": "UNK-11", "Pacific/Chatham": "UNK-12:45UNK,M9.5.0/2:45,M4.1.0/3:45", "Pacific/Chuuk": "UNK-10", "Pacific/Easter": "UNK6UNK,M9.1.6/22,M4.1.6/22", "Pacific/Efate": "UNK-11", "Pacific/Enderbury": "UNK-13", "Pacific/Fakaofo": "UNK-13", "Pacific/Fiji": "UNK-12UNK,M11.2.0,M1.2.3/99", "Pacific/Funafuti": "UNK-12", "Pacific/Galapagos": "UNK6", "Pacific/Gambier": "UNK9", "Pacific/Guadalcanal": "UNK-11", "Pacific/Guam": "ChST-10", "Pacific/Honolulu": "HST10", "Pacific/Kiritimati": "UNK-14", "Pacific/Kosrae": "UNK-11", "Pacific/Kwajalein": "UNK-12", "Pacific/Majuro": "UNK-12", "Pacific/Marquesas": "UNK9:30", "Pacific/Midway": "SST11", "Pacific/Nauru": "UNK-12", "Pacific/Niue": "UNK11", "Pacific/Norfolk": "UNK-11UNK,M10.1.0,M4.1.0/3", "Pacific/Noumea": "UNK-11", "Pacific/Pago_Pago": "SST11", "Pacific/Palau": "UNK-9", "Pacific/Pitcairn": "UNK8", "Pacific/Pohnpei": "UNK-11", "Pacific/Port_Moresby": "UNK-10", "Pacific/Rarotonga": "UNK10", "Pacific/Saipan": "ChST-10", "Pacific/Tahiti": "UNK10", "Pacific/Tarawa": "UNK-12", "Pacific/Tongatapu": "UNK-13", "Pacific/Wake": "UNK-12", "Pacific/Wallis": "UNK-12" }; ================================================ FILE: interface/src/routes/demo/+page.svelte ================================================
================================================ FILE: interface/src/routes/demo/+page.ts ================================================ import type { PageLoad } from './$types'; export const load = (async ({ fetch }) => { return { title: 'Demo App' }; }) satisfies PageLoad; ================================================ FILE: interface/src/routes/demo/Demo.svelte ================================================ {#snippet icon()} {/snippet} {#snippet title()} Light State {/snippet}

REST Example

The form below controls the LED via the RESTful service exposed by the ESP device.

Event Socket Example

The switch below controls the LED via the event system which uses WebSocket under the hood. It will automatically update whenever the LED state changes.
================================================ FILE: interface/src/routes/ethernet/+page.svelte ================================================
================================================ FILE: interface/src/routes/ethernet/+page.ts ================================================ import type { PageLoad } from './$types'; export const load = (async () => { return { title: 'Ethernet' }; }) satisfies PageLoad; ================================================ FILE: interface/src/routes/ethernet/Ethernet.svelte ================================================ {#snippet icon()} {/snippet} {#snippet title()} Ethernet Connection {/snippet} {#await getEthernetData()} {:then nothing}
Status
{ethernetStatus.connected ? 'Connected' : 'Disconnected'}
{#if ethernetStatus.connected}
IP Address
{ethernetStatus.local_ip}
MAC Address
{ethernetStatus.mac_address}
Link Speed
{ethernetStatus.link_speed} Mbps
Gateway IP
{ethernetStatus.gateway_ip}
Subnet Mask
{ethernetStatus.subnet_mask}
DNS
{ethernetStatus.dns_ip_1}
{/if}
{#if !page.data.features.security || $user.admin} {#snippet icon()} {/snippet} {#snippet title()} Settings {/snippet}
{#if formErrors.hostname}
{/if}
{#if ethernetEditable.static_ip_config}
{#if formErrors.local_ip}
{/if}
{#if formErrors.gateway_ip}
{/if}
{#if formErrors.subnet_mask}
{/if}
{#if formErrors.dns_1}
{/if}
{#if formErrors.dns_2}
{/if}
{/if}
{/if} {/await}
================================================ FILE: interface/src/routes/login.svelte ================================================
Logo

Login

================================================ FILE: interface/src/routes/menu.svelte ================================================
setActiveMenuItem('')} > Logo

{page.data.appName}

{#if page.data.features.security}
{$user.username}
{ user.invalidate(); }} >
{/if}
{#if github.active} {/if} {#if discord.active} {/if}
{page.data.copyright}
================================================ FILE: interface/src/routes/statusbar.svelte ================================================ ================================================ FILE: interface/src/routes/system/+page.ts ================================================ import type { PageLoad } from './$types'; import { goto } from '$app/navigation'; export const load = (async () => { goto('/'); return; }) satisfies PageLoad; ================================================ FILE: interface/src/routes/system/coredump/+page.svelte ================================================
{#snippet icon()} {/snippet} {#snippet title()} Core Dump {/snippet}
This page displays the last core dump of the device. The core dump is a snapshot of the memory when the device crashed. This information is useful for debugging.
{#if coreDumpBlob} {:else if errorMessage}

{errorMessage}

{:else}

Loading core dump...

{/if}
================================================ FILE: interface/src/routes/system/coredump/+page.ts ================================================ import type { PageLoad } from './$types'; export const load = (async () => { return { title: 'Core Dump' }; }) satisfies PageLoad; ================================================ FILE: interface/src/routes/system/metrics/+page.svelte ================================================
{#if page.data.features.analytics} {/if} {#if page.data.features.battery} {/if}
================================================ FILE: interface/src/routes/system/metrics/+page.ts ================================================ import type { PageLoad } from './$types'; export const load = (async () => { return { title: 'System Metrics' }; }) satisfies PageLoad; ================================================ FILE: interface/src/routes/system/metrics/BatteryMetrics.svelte ================================================ {#snippet icon()} {/snippet} {#snippet title()} Battery History {/snippet}
================================================ FILE: interface/src/routes/system/metrics/SystemMetrics.svelte ================================================ {#snippet icon()} {/snippet} {#snippet title()} System Metrics {/snippet}
{#if hasPsramData}
{/if}
================================================ FILE: interface/src/routes/system/status/+page.svelte ================================================
================================================ FILE: interface/src/routes/system/status/+page.ts ================================================ import type { PageLoad } from './$types'; export const load = (async () => { return { title: 'System Status' }; }) satisfies PageLoad; ================================================ FILE: interface/src/routes/system/status/SystemStatus.svelte ================================================ {#snippet icon()} {/snippet} {#snippet title()} System Status {/snippet}
{#await getSystemStatus()} {:then nothing}
Uptime
{convertSeconds(systemInformation.uptime)}
Memory
{( ((systemInformation.total_heap - systemInformation.free_heap) / systemInformation.total_heap) * 100 ).toFixed(1)} % of {Math.round(systemInformation.total_heap / 1000).toLocaleString( 'en-US' )} KB ({Math.round(systemInformation.free_heap / 1000).toLocaleString('en-US')} KB free, Max alloc {Math.round(systemInformation.max_alloc_heap / 1000).toLocaleString('en-US')} KB)
{#if systemInformation.psram_size}
PSRAM
{((systemInformation.used_psram / systemInformation.psram_size) * 100).toFixed(1)} % of {Math.round(systemInformation.psram_size / 1000).toLocaleString('en-US')} KB ({Math.round(systemInformation.free_psram / 1000).toLocaleString('en-US')} KB free)
{/if}
File System
{((systemInformation.fs_used / systemInformation.fs_total) * 100).toFixed(1)} % of {Math.round( systemInformation.fs_total / 1000 ).toLocaleString('en-US')} KB ({Math.round( (systemInformation.fs_total - systemInformation.fs_used) / 1000 ).toLocaleString('en-US')} KB free)
Core Temperature
{systemInformation.core_temp == 53.33 ? 'NaN' : systemInformation.core_temp.toFixed(2) + ' °C'}
Reset Reason
{systemInformation.cpu_reset_reason}
Sketch
{( (systemInformation.sketch_size / systemInformation.free_sketch_space) * 100 ).toFixed(1)} % of {Math.round(systemInformation.free_sketch_space / 1000).toLocaleString('en-US')} KB ({Math.round( (systemInformation.free_sketch_space - systemInformation.sketch_size) / 1000 ).toLocaleString('en-US')} KB free)
Firmware Version
{systemInformation.firmware_version}
Chip
{systemInformation.cpu_type} Rev {systemInformation.cpu_rev}
SDK Version
ESP-IDF {systemInformation.sdk_version} / Arduino {systemInformation.arduino_version}
CPU Frequency
{systemInformation.cpu_freq_mhz} MHz {systemInformation.cpu_cores == 2 ? 'Dual Core' : 'Single Core'}
Flash Chip
{Math.round(systemInformation.flash_chip_size / 1000).toLocaleString('en-US')} KB / {( systemInformation.flash_chip_speed / 1000000 ).toLocaleString('en-US')} MHz
{/await}
{#if page.data.features.sleep} {/if} {#if !page.data.features.security || $user.admin} {/if}
================================================ FILE: interface/src/routes/system/update/+page.svelte ================================================
{#if page.data.features.download_firmware && (!page.data.features.security || $user.admin)} {/if} {#if page.data.features.upload_firmware && (!page.data.features.security || $user.admin)} {/if}
================================================ FILE: interface/src/routes/system/update/+page.ts ================================================ import type { PageLoad } from './$types'; export const load = (async () => { return { title: 'Firmware Update' }; }) satisfies PageLoad; ================================================ FILE: interface/src/routes/system/update/GithubFirmwareManager.svelte ================================================ {#snippet icon()} {/snippet} {#snippet title()} Github Firmware Manager {/snippet} {#await getGithubAPI()} {:then githubReleases}
Current Firmware Version: v{page.data.features.firmware_version}
{#each githubReleases as release} {/each}
Release Exp. Install
{release.name} {#if release.prerelease} {/if} {#if compareVersions(page.data.features.firmware_version, release.tag_name) != 0} {/if}
{:catch error}
Please connect to a network with internet access to perform a firmware update.
{/await}
================================================ FILE: interface/src/routes/system/update/UploadFirmware.svelte ================================================ {#snippet icon()} {/snippet} {#snippet title()} Upload Firmware {/snippet}
Uploading a new firmware (.bin) file will replace the existing firmware. You may upload a (.md5) file first to verify the uploaded firmware.
{#if md5StatusType}
{#if md5StatusType === 'success'} {:else} {/if}
{md5StatusMessage} {#if md5StatusType === 'success'} Upload a .bin file to flash the firmware {/if}
{/if} {#if fileValidationError}
{fileValidationError}
{/if}
================================================ FILE: interface/src/routes/user/+page.svelte ================================================ {#if $user.admin}
{#snippet icon()} {/snippet} {#snippet title()} Manage Users {/snippet} {#await getSecuritySettings()} {:then nothing}
{#each securitySettings.users as user, index} {/each}
Username Admin Edit
{user.username} {#if user.admin} {/if}
Security Settings
The JWT secret is used to sign authentication tokens. If you modify the JWT Secret, all users will be signed out.
{/await}
{:else} {goto('/')} {/if} ================================================ FILE: interface/src/routes/user/+page.ts ================================================ import type { PageLoad } from './$types'; export const load = (async () => { return { title: 'Users' }; }) satisfies PageLoad; ================================================ FILE: interface/src/routes/user/EditUser.svelte ================================================ {#if isOpen} {/if} ================================================ FILE: interface/src/routes/wifi/+page.ts ================================================ import type { PageLoad } from './$types'; import { goto } from '$app/navigation'; export const load = (async () => { goto('/'); return; }) satisfies PageLoad; ================================================ FILE: interface/src/routes/wifi/ap/+page.svelte ================================================
================================================ FILE: interface/src/routes/wifi/ap/+page.ts ================================================ import type { PageLoad } from './$types'; export const load = (async () => { return { title: 'Access Point' }; }) satisfies PageLoad; ================================================ FILE: interface/src/routes/wifi/ap/Accesspoint.svelte ================================================ {#snippet icon()} {/snippet} {#snippet title()} Access Point {/snippet}
{#await getAPStatus()} {:then nothing}
Status
{apStatusDescription[apStatus.status].description}
IP Address
{apStatus.ip_address}
MAC Address
{apStatus.mac_address}
AP Clients
{apStatus.station_num}
{/await}
{#if !page.data.features.security || $user.admin}
Change AP Settings
{#await getAPSettings()} {:then nothing}
{/await}
{/if}
================================================ FILE: interface/src/routes/wifi/sta/+page.svelte ================================================
================================================ FILE: interface/src/routes/wifi/sta/+page.ts ================================================ import type { PageLoad } from './$types'; export const load = (async () => { return { title: 'WiFi Station' }; }) satisfies PageLoad; ================================================ FILE: interface/src/routes/wifi/sta/EditNetwork.svelte ================================================ {#if isOpen} {/if} ================================================ FILE: interface/src/routes/wifi/sta/Scan.svelte ================================================ {#if isOpen} {/if} ================================================ FILE: interface/src/routes/wifi/sta/Wifi.svelte ================================================ {#snippet icon()} {/snippet} {#snippet title()} WiFi Connection {/snippet} {#await getWifiData()} {:then nothing}
Status
{wifiStatus.status === 3 ? 'Connected' : 'Inactive'}
{#if wifiStatus.status === 3}
SSID
{wifiStatus.ssid}
IP Address
{wifiStatus.local_ip}
RSSI
{wifiStatus.rssi} dBm
{/if}
{#if showWifiDetails}
MAC Address
{wifiStatus.mac_address}
Channel
{wifiStatus.channel}
Gateway IP
{wifiStatus.gateway_ip}
Subnet Mask
{wifiStatus.subnet_mask}
DNS
{wifiStatus.dns_ip_1}
{/if}
{#if !page.data.features.security || $user.admin} {#snippet icon()} {/snippet} {#snippet title()} Settings & Networks {/snippet}
{#if formErrorhostname}
{/if}
{#if wifiSettings.wifi_networks.length === 0}
No WiFi networks configured yet.
Scan for available networks or add one manually.
{:else} {#snippet children({ item: network, index }: { item: any; index: number })}
{network.ssid}
{#if network.static_ip_config} {:else} {/if}
{/snippet}
{/if}
{#if wifiSettings.connection_mode === 2 && wifiSettings.wifi_networks.length > 1}
{/if}
{/if} {/await}
================================================ FILE: interface/static/manifest.json ================================================ { "name": "ESP32 SvelteKit", "icons": [ { "src": "/favicon.png", "sizes": "48x48 72x72 96x96 128x128 256x256" } ], "start_url": "/", "display": "fullscreen", "orientation": "any" } ================================================ FILE: interface/svelte.config.js ================================================ import adapter from '@sveltejs/adapter-static'; import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; /** @type {import('@sveltejs/kit').Config} */ const config = { // Consult https://kit.svelte.dev/docs/integrations#preprocessors // for more information about preprocessors preprocess: vitePreprocess(), kit: { adapter: adapter({ pages: 'build', assets: 'build', fallback: 'index.html', precompress: false, strict: true }), alias: { $src: './src' }, output: { bundleStrategy: 'single' } } }; export default config; ================================================ FILE: interface/tsconfig.json ================================================ { "extends": "./.svelte-kit/tsconfig.json", "compilerOptions": { "allowJs": true, "checkJs": true, "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "resolveJsonModule": true, "skipLibCheck": true, "sourceMap": true, "strict": true } // Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias // // If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes // from the referenced tsconfig.json - TypeScript does not merge them in } ================================================ FILE: interface/vite-plugin-littlefs.ts ================================================ import type { UserConfig, Plugin } from 'vite'; export default function viteLittleFS(): Plugin[] { return [ { name: 'vite-plugin-littlefs', enforce: 'post', apply: 'build', async config(config, _configEnv) { const { assetFileNames, chunkFileNames, entryFileNames } = config.build?.rollupOptions?.output; // Handle Server-build + Client Assets config.build.rollupOptions.output = { ...config.build?.rollupOptions?.output, assetFileNames: assetFileNames.replace('.[hash]', '') } // Handle Client-build if (config.build?.rollupOptions?.output.chunkFileNames.includes('hash')) { config.build.rollupOptions.output = { ...config.build?.rollupOptions?.output, chunkFileNames: chunkFileNames.replace('.[hash]', ''), entryFileNames: entryFileNames.replace('.[hash]', ''), } } } } ] } ================================================ FILE: interface/vite.config.ts ================================================ import { sveltekit } from '@sveltejs/kit/vite'; import type { UserConfig } from 'vite'; import Icons from 'unplugin-icons/vite'; import viteLittleFS from './vite-plugin-littlefs'; import tailwindcss from '@tailwindcss/vite'; const config: UserConfig = { plugins: [ sveltekit(), Icons({ compiler: 'svelte' }), tailwindcss(), // Shorten file names for LittleFS 32 char limit viteLittleFS() ], server: { proxy: { // Proxying REST: http://localhost:5173/rest/bar -> http://192.168.1.83/rest/bar '/rest': { target: 'http://192.168.1.111', changeOrigin: true }, // Proxying websockets ws://localhost:5173/ws -> ws://192.168.1.83/ws '/ws': { target: 'ws://192.168.1.111', changeOrigin: true, ws: true } } }, build: { minify: 'terser', sourcemap: false, rollupOptions: { output: { manualChunks(id) { if (id.includes('node_modules')) return 'vendor'; } } }, cssCodeSplit: true } }; export default config; ================================================ FILE: lib/PsychicHttp/.gitignore ================================================ **.vscode **.pio **.DS_Store .pioenvs .clang_complete .gcc-flags.json # Compiled Object files *.slo *.lo *.o *.obj # Precompiled Headers *.gch *.pch # Compiled Dynamic libraries *.so *.dylib *.dll # Fortran module files *.mod # Compiled Static libraries *.lai *.la *.a *.lib # Executables *.exe *.out *.app # Visual Studio/VisualMicro stuff Visual\ Micro *.sdf *.opensdf *.suo .pioenvs .piolibdeps .pio .vscode/c_cpp_properties.json .vscode/launch.json .vscode/settings.json .vscode/.browse.c_cpp.db* .vscode/ipch /psychic-http-loadtest.log /psychic-websocket-loadtest.log examples/platformio/lib/PsychicHttp benchmark/.~lock.comparison.ods# benchmark/psychic-http-loadtest.log .$request flow.drawio.bkp .$request flow.drawio.dtmp benchmark/package-lock.json benchmark/node_modules src/secret.h benchmark/psychichttp/src/_secret.h benchmark/psychichttps/src/_secret.h examples/platformio/src/_secret.h examples/arduino/src/_secret.h src/cookie.txt examples/websockets/lib/PsychicHttp examples/websockets/src/_secret.h /build ================================================ FILE: lib/PsychicHttp/CHANGELOG.md ================================================ # v1.2.1 * Fix bug with missing include preventing the HTTPS server from compiling. # v1.2 * Added TemplatePrinter from https://github.com/Chris--A/PsychicHttp/tree/templatePrint * Support using as ESP IDF component * Optional using https server in ESP IDF * Fixed bug with headers * Add ESP IDF example + CI script * Added Arduino Captive Portal example and OTAUpdate from @06GitHub * HTTPS fix for ESP-IDF v5.0.2+ from @06GitHub * lots of bugfixes from @mathieucarbou Thanks to @Chris--A, @06GitHub, and @dzungpv for your contributions. # v1.1 * Changed the internal structure to support request handlers on endpoints and generic requests that do not match an endpoint * websockets, uploads, etc should now create an appropriate handler and attach to an endpoint with the server.on() syntax * Added PsychicClient to abstract away some of the internals of ESP-IDF sockets + add convenience * onOpen and onClose callbacks have changed as a result * Added support for EventSource / SSE * Added support for multipart file uploads * changed getParam() to return a PsychicWebParameter in line with ESPAsyncWebserver * Renamed various classes / files: * PsychicHttpFileResponse -> PsychicFileResponse * PsychicHttpServerEndpoint -> PsychicEndpoint * PsychicHttpServerRequest -> PsychicRequest * PsychicHttpServerResponse -> PsychicResponse * PsychicHttpWebsocket.h -> PsychicWebSocket.h * Websocket => WebSocket * Quite a few bugfixes from the community. Thank you @glennsky, @gb88, @KastanEr, @kstam, and @zekageri ================================================ FILE: lib/PsychicHttp/LICENSE ================================================ Copyright (c) 2024 Jeremy Poulter, Zachary Smith, and Mathieu Carbou Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: lib/PsychicHttp/README.md ================================================ # PsychicHttp - HTTP on your ESP 🧙🔮 PsychicHttp is a webserver library for ESP32 + Arduino framework which uses the [ESP-IDF HTTP Server](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/protocols/esp_http_server.html) library under the hood. It is written in a similar style to the [Arduino WebServer](https://github.com/espressif/arduino-esp32/tree/master/libraries/WebServer), [ESPAsyncWebServer](https://github.com/me-no-dev/ESPAsyncWebServer), and [ArduinoMongoose](https://github.com/jeremypoulter/ArduinoMongoose) libraries to make writing code simple and porting from those other libraries straightforward. # Features * Asynchronous approach (server runs in its own FreeRTOS thread) * Handles all HTTP methods with lots of convenience functions: * GET/POST parameters * get/set headers * get/set cookies * basic key/value session data storage * authentication (basic and digest mode) * HTTPS / SSL support * Static fileserving (SPIFFS, LittleFS, etc.) * Chunked response serving for large files * File uploads (Basic + Multipart) * Websocket support with onOpen, onFrame, and onClose callbacks * EventSource / SSE support with onOpen, and onClose callbacks * Request filters, including Client vs AP mode (ON_STA_FILTER / ON_AP_FILTER) * TemplatePrinter class for dynamic variables at runtime ## Differences from ESPAsyncWebserver * No templating system (anyone actually use this?) * No url rewriting (but you can use request->redirect) # Usage ## Installation ### Platformio [PlatformIO](http://platformio.org) is an open source ecosystem for IoT development. Add "PsychicHttp" to project using [Project Configuration File `platformio.ini`](http://docs.platformio.org/page/projectconf.html) and [lib_deps](http://docs.platformio.org/page/projectconf/section_env_library.html#lib-deps) option: ```ini [env:myboard] platform = espressif... board = ... framework = arduino # using the latest stable version lib_deps = hoeken/PsychicHttp # or using GIT Url (the latest development version) lib_deps = https://github.com/hoeken/PsychicHttp ``` ### Installation - Arduino Open *Tools -> Manage Libraries...* and search for PsychicHttp. # Principles of Operation ## Things to Note * PsychicHttp is a fully asynchronous server and as such does not run on the loop thread. * You should not use yield or delay or any function that uses them inside the callbacks. * The server is smart enough to know when to close the connection and free resources. * You can not send more than one response to a single request. ## PsychicHttp * Listens for connections. * Wraps the incoming request into PsychicRequest. * Keeps track of clients + calls optional callbacks on client open and close. * Find the appropriate handler (if any) for a request and pass it on. ## Request Life Cycle * TCP connection is received by the server. * HTTP request is wrapped inside ```PsychicRequest``` object + TCP Connection wrapped inside PsychicConnection object. * When the request head is received, the server goes through all ```PsychicEndpoints``` and finds one that matches the url + method. * ```handler->filter()``` and ```handler->canHandle()``` are called on the handler to verify the handler should process the request. * ```handler->needsAuthentication()``` is called and sends an authorization response if required. * ```handler->handleRequest()``` is called to actually process the HTTP request. * If the handler cannot process the request, the server will loop through any global handlers and call that handler if it passes filter(), canHandle(), and needsAuthentication(). * If no global handlers are called, the server.defaultEndpoint handler will be called. * Each handler is responsible for processing the request and sending a response. * When the response is sent, the client is closed and freed from the memory. * Unless its a special handler like websockets or eventsource. ![Flowchart of Request Lifecycle](/assets/request-flow.svg) ### Handlers * ```PsychicHandler``` is used for processing and responding to specific HTTP requests. * ```PsychicHandler``` instances can be attached to any endpoint or as global handlers. * Setting a ```Filter``` to the ```PsychicHandler``` controls when to apply the handler, decision can be based on request method, url, request host/port/target host, the request client's localIP or remoteIP. * Two filter callbacks are provided: ```ON_AP_FILTER``` to execute the rewrite when request is made to the AP interface, ```ON_STA_FILTER``` to execute the rewrite when request is made to the STA interface. * The ```canHandle``` method is used for handler specific control on whether the requests can be handled. Decision can be based on request method, request url, request host/port/target host. * Depending on how the handler is implemented, it may provide callbacks for adding your own custom processing code to the handler. * Global ```Handlers``` are evaluated in the order they are attached to the server. The ```canHandle``` is called only if the ```Filter``` that was set to the ```Handler``` return true. * The first global ```Handler``` that can handle the request is selected, no further processing of handlers is called. ![Flowchart of Request Lifecycle](/assets/handler-callbacks.svg) ### Responses and how do they work * The ```PsychicResponse``` objects are used to send the response data back to the client. * Typically the response should be fully generated and sent from the callback. * It may be possible to generate the response outside the callback, but it will be difficult. * The exceptions are websockets + eventsource where the response is sent, but the connection is maintained and new data can be sent/received outside the handler. # Porting From ESPAsyncWebserver If you have existing code using ESPAsyncWebserver, you will feel right at home with PsychicHttp. Even if internally it is much different, the external interface is very similar. Some things are mostly cosmetic, like different class names and callback definitions. A few things might require a bit more in-depth approach. If you're porting your code and run into issues that aren't covered here, please post and issue. ## Globals Stuff * Change your #include to ```#include ``` * Change your server instance: ```PsychicHttpServer server;``` * Define websocket handler if you have one: ```PsychicWebSocketHandler websocketHandler;``` * Define eventsource if you have one: ```PsychicEventSource eventSource;``` ## setup() Stuff * no more server.begin(), call server.listen(80), before you add your handlers * server has a configurable limit on .on() endpoints. change it with ```server.config.max_uri_handlers = 20;``` as needed. * check your callback function definitions: * AsyncWebServerRequest -> PsychicRequest * no more onBody() event * for small bodies (server.maxRequestBodySize, default 16k) it will be automatically loaded and accessed by request->body() * for large bodies, use an upload handler and onUpload() * websocket callbacks are much different (and simpler!) * websocket / eventsource handlers get attached to url in server.on("/url", &handler) instead of passing url to handler constructor. * eventsource callbacks are onOpen and onClose now. * HTTP_ANY is not supported by ESP-IDF, so we can't use it either. * NO server.onFileUpload(onUpload); (you could attach an UploadHandler to the default endpoint i guess?) * NO server.onRequestBody(onBody); (same) ## Requests / Responses * request->send is now request->reply() * if you create a response, call response->send() directly, not request->send(reply) * request->headers() is not supported by ESP-IDF, you have to just check for the header you need. * No AsyncCallbackJsonWebHandler (for now... can add if needed) * No request->beginResponse(). Instanciate a PsychicResponse instead: ```PsychicResponse response(request);``` * No PROGMEM suppport (its not relevant to ESP32: https://esp32.com/viewtopic.php?t=20595) * No Stream response support just yet # Usage ## Create the Server Here is an example of the typical server setup: ```cpp #include PsychicHttpServer server; void setup() { //optional low level setup server config stuff here. //server.config is an ESP-IDF httpd_config struct //see: https://docs.espressif.com/projects/esp-idf/en/v4.4.6/esp32/api-reference/protocols/esp_http_server.html#_CPPv412httpd_config //increase maximum number of uri endpoint handlers (.on() calls) server.config.max_uri_handlers = 20; //connect to wifi //start the server listening on port 80 (standard HTTP port) server.listen(80); //call server methods to attach endpoints and handlers server.on(...); server.serveStatic(...); server.attachHandler(...); } ``` ## Add Handlers One major difference from ESPAsyncWebserver is that handlers can be attached to a specific url (endpoint) or as a global handler. The reason for this, is that attaching to a specific URL is more efficient and makes for cleaner code. ### Endpoint Handlers An endpoint is basically just the URL path (eg. /path/to/file) without any query string. The ```server.on(...)``` function is a convenience function for creating endpoints and attaching a handler to them. There are two main styles: attaching a basic ```WebRequest``` handler and attaching an external handler. ```cpp //creates a basic PsychicWebHandler that calls the request_callback callback server.on("/url", HTTP_GET, request_callback); //same as above, but defaults to HTTP_GET server.on("/url", request_callback); //attaches a websocket handler to /ws PsychicWebSocketHandler websocketHandler; server.on("/ws", &websocketHandler); ``` The ```server.on(...)``` returns a pointer to the endpoint, which can be used to call various functions like ```setHandler()```, ```setFilter()```, and ```setAuthentication()```. ```cpp //respond to /url only from requests to the AP server.on("/url", HTTP_GET, request_callback)->setFilter(ON_AP_FILTER); //require authentication on /url server.on("/url", HTTP_GET, request_callback)->setAuthentication("user", "pass"); //attach websocket handler to /ws PsychicWebSocketHandler websocketHandler; server.on("/ws")->attachHandler(&websocketHandler); ``` ### Basic Requests The ```PsychicWebHandler``` class is for handling standard web requests. It provides a single callback: ```onRequest()```. This callback is called when the handler receives a valid HTTP request. One major difference from ESPAsyncWebserver is that this callback needs to return an esp_err_t variable to let the server know the result of processing the request. The ```response->reply()``` and ```request->send()``` functions will return this. It is a good habit to return the result of these functions as sending the response will close the connection. The function definition for the onRequest callback is: ```cpp esp_err_t function_name(PsychicRequest *request); ``` Here is a simple example that sends back the client's IP on the URL /ip ```cpp server.on("/ip", [](PsychicRequest *request) { String output = "Your IP is: " + request->client()->remoteIP().toString(); return request->reply(output.c_str()); }); ``` ### Uploads The ```PsychicUploadHandler``` class is for handling uploads, both large POST bodies and multipart encoded forms. It provides two callbacks: ```onUpload()``` and ```onRequest()```. ```onUpload(...)``` is called when there is new data. This function may be called multiple times so that you can process the data in chunks. The function definition for the onUpload callback is: ```cpp esp_err_t function_name(PsychicRequest *request, const String& filename, uint64_t index, uint8_t *data, size_t len, bool final); ``` * request is a pointer to the Request object * filename is the name of the uploaded file * index is the overall byte position of the current data * data is a pointer to the data buffer * len is the length of the data buffer * final is a flag to tell if its the last chunk of data ```onRequest(...)``` is called after the successful handling of the upload. Its definition and usage is the same as the basic request example as above. #### Basic Upload (file is the entire POST body) It's worth noting that there is no standard way of passing in a filename for this method, so the handler attempts to guess the filename with the following methods: * Checking the Content-Disposition header * Checking the _filename query parameter (eg. /upload?filename=filename.txt becomes filename.txt) * Checking the url and taking the last part as filename (eg. /upload/filename.txt becomes filename.txt). You must set a wildcard url for this to work as in the example below. ```cpp //handle a very basic upload as post body PsychicUploadHandler *uploadHandler = new PsychicUploadHandler(); uploadHandler->onUpload([](PsychicRequest *request, const String& filename, uint64_t index, uint8_t *data, size_t len, bool last) { File file; String path = "/www/" + filename; Serial.printf("Writing %d/%d bytes to: %s\n", (int)index+(int)len, request->contentLength(), path.c_str()); if (last) Serial.printf("%s is finished. Total bytes: %d\n", path.c_str(), (int)index+(int)len); //our first call? if (!index) file = LittleFS.open(path, FILE_WRITE); else file = LittleFS.open(path, FILE_APPEND); if(!file) { Serial.println("Failed to open file"); return ESP_FAIL; } if(!file.write(data, len)) { Serial.println("Write failed"); return ESP_FAIL; } return ESP_OK; }); //gets called after upload has been handled uploadHandler->onRequest([](PsychicRequest *request) { String url = "/" + request->getFilename(); String output = "" + url + ""; return request->reply(output.c_str()); }); //wildcard basic file upload - POST to /upload/filename.ext server.on("/upload/*", HTTP_POST, uploadHandler); ``` #### Multipart Upload Very similar to the basic upload, with 2 key differences: * multipart requests don't know the total size of the file until after it has been fully processed. You can get a rough idea with request->contentLength(), but that is the length of the entire multipart encoded request. * you can access form variables, including multipart file infor (name + size) in the onRequest handler using request->getParam() ```cpp //a little bit more complicated multipart form PsychicUploadHandler *multipartHandler = new PsychicUploadHandler(); multipartHandler->onUpload([](PsychicRequest *request, const String& filename, uint64_t index, uint8_t *data, size_t len, bool last) { File file; String path = "/www/" + filename; //some progress over serial. Serial.printf("Writing %d bytes to: %s\n", (int)len, path.c_str()); if (last) Serial.printf("%s is finished. Total bytes: %d\n", path.c_str(), (int)index+(int)len); //our first call? if (!index) file = LittleFS.open(path, FILE_WRITE); else file = LittleFS.open(path, FILE_APPEND); if(!file) { Serial.println("Failed to open file"); return ESP_FAIL; } if(!file.write(data, len)) { Serial.println("Write failed"); return ESP_FAIL; } return ESP_OK; }); //gets called after upload has been handled multipartHandler->onRequest([](PsychicRequest *request) { PsychicWebParameter *file = request->getParam("file_upload"); String url = "/" + file->value(); String output; output += "" + url + "
\n"; output += "Bytes: " + String(file->size()) + "
\n"; output += "Param 1: " + request->getParam("param1")->value() + "
\n"; output += "Param 2: " + request->getParam("param2")->value() + "
\n"; return request->reply(output.c_str()); }); //upload to /multipart url server.on("/multipart", HTTP_POST, multipartHandler); ``` ### Static File Serving The ```PsychicStaticFileHandler``` is a special handler that does not provide any callbacks. It is used to serve a file or files from a specific directory in a filesystem to a directory on the webserver. The syntax is exactly the same as ESPAsyncWebserver. Anything that is derived from the ```FS``` class should work (eg. SPIFFS, LittleFS, SD, etc) A couple important notes: * If it finds a file with an extra .gz extension, it will serve it as gzip encoded (eg: /targetfile.ext -> {targetfile.ext}.gz) * If the file is larger than FILE_CHUNK_SIZE (default 8kb) then it will send it as a chunked response. * It will detect most basic filetypes and automatically set the appropriate Content-Type The ```server.serveStatic()``` function handles creating the handler and assigning it to the server: ```cpp //serve static files from LittleFS/www on / only to clients on same wifi network //this is where our /index.html file lives server.serveStatic("/", LittleFS, "/www/")->setFilter(ON_STA_FILTER); //serve static files from LittleFS/www-ap on / only to clients on SoftAP //this is where our /index.html file lives server.serveStatic("/", LittleFS, "/www-ap/")->setFilter(ON_AP_FILTER); //serve static files from LittleFS/img on /img //it's more efficient to serve everything from a single www directory, but this is also possible. server.serveStatic("/img", LittleFS, "/img/"); //you can also serve single files server.serveStatic("/myfile.txt", LittleFS, "/custom.txt"); ``` You could also theoretically use the file response directly: ```cpp server.on("/ip", [](PsychicRequest *request) { String filename = "/path/to/file"; PsychicFileResponse response(request, LittleFS, filename); return response.send(); }); PsychicFileResponse(PsychicRequest *request, FS &fs, const String& path) ``` ### Websockets The ```PsychicWebSocketHandler``` class is for handling WebSocket connections. It provides 3 callbacks: ```onOpen(...)``` is called when a new WebSocket client connects. ```onFrame(...)``` is called when a new WebSocket frame has arrived. ```onClose(...)``` is called when a new WebSocket client disconnects. Here are the callback definitions: ```cpp void open_function(PsychicWebSocketClient *client); esp_err_t frame_function(PsychicWebSocketRequest *request, httpd_ws_frame *frame); void close_function(PsychicWebSocketClient *client); ``` WebSockets were the main reason for starting PsychicHttp, so they are well tested. They are also much simplified from the ESPAsyncWebserver style. You do not need to worry about error handling, partial frame assembly, PONG messages, etc. The onFrame() function is called when a complete frame has been received, and can handle frames up to the entire available heap size. Here is a basic example of using WebSockets: ```cpp //create our handler... note this should be located as a global or somewhere it wont go out of scope and be destroyed. PsychicWebSocketHandler websocketHandler(); websocketHandler.onOpen([](PsychicWebSocketClient *client) { Serial.printf("[socket] connection #%u connected from %s\n", client->socket(), client->remoteIP().toString()); client->sendMessage("Hello!"); }); websocketHandler.onFrame([](PsychicWebSocketRequest *request, httpd_ws_frame *frame) { Serial.printf("[socket] #%d sent: %s\n", request->client()->socket(), (char *)frame->payload); return request->reply(frame); }); websocketHandler.onClose([](PsychicWebSocketClient *client) { Serial.printf("[socket] connection #%u closed from %s\n", client->socket(), client->remoteIP().toString()); }); //attach the handler to /ws. You can then connect to ws://ip.address/ws server.on("/ws", &websocketHandler); ``` The onFrame() callback has 2 parameters: * ```PsychicWebSocketRequest *request``` a special request with helper functions for replying in websocket format. * ```httpd_ws_frame *frame``` ESP-IDF websocket struct. The important struct members we care about are: * ```uint8_t *payload; /*!< Pre-allocated data buffer */``` * ```size_t len; /*!< Length of the WebSocket data */``` For sending data on the websocket connection, there are 3 methods: * ```request->reply()``` - only available in the onFrame() callback context. * ```webSocketHandler.sendAll()``` - can be used anywhere to send websocket messages to all connected clients. * ```client->send()``` - can be used anywhere* to send a websocket message to a specific client All of the above functions either accept simple ```char *``` string of you can construct your own httpd_ws_frame. *Special Note:* Do not hold on to the ```PsychicWebSocketClient``` for sending messages to clients outside the callbacks. That pointer is destroyed when a client disconnects. Instead, store the ```int client->socket()```. Then when you want to send a message, use this code: ```cpp //make sure our client is still connected. PsychicWebSocketClient *client = websocketHandler.getClient(socket); if (client != NULL) client->send("Your Message") ``` ### EventSource / SSE The ```PsychicEventSource``` class is for handling EventSource / SSE connections. It provides 2 callbacks: ```onOpen(...)``` is called when a new EventSource client connects. ```onClose(...)``` is called when a new EventSource client disconnects. Here are the callback definitions: ```cpp void open_function(PsychicEventSourceClient *client); void close_function(PsychicEventSourceClient *client); ``` Here is a basic example of using PsychicEventSource: ```cpp //create our handler... note this should be located as a global or somewhere it wont go out of scope and be destroyed. PsychicEventSource eventSource; eventSource.onOpen([](PsychicEventSourceClient *client) { Serial.printf("[eventsource] connection #%u connected from %s\n", client->socket(), client->remoteIP().toString()); client->send("Hello user!", NULL, millis(), 1000); }); eventSource.onClose([](PsychicEventSourceClient *client) { Serial.printf("[eventsource] connection #%u closed from %s\n", client->socket(), client->remoteIP().toString()); }); //attach the handler to /events server.on("/events", &eventSource); ``` For sending data on the EventSource connection, there are 2 methods: * ```eventSource.send()``` - can be used anywhere to send events to all connected clients. * ```client->send()``` - can be used anywhere* to send events to a specific client All of the above functions accept a simple ```char *``` message, and optionally: ```char *``` event name, id, and reconnect time. *Special Note:* Do not hold on to the ```PsychicEventSourceClient``` for sending messages to clients outside the callbacks. That pointer is destroyed when a client disconnects. Instead, store the ```int client->socket()```. Then when you want to send a message, use this code: ```cpp //make sure our client is still connected. PsychicEventSourceClient *client = eventSource.getClient(socket); if (client != NULL) client->send("Your Event") ``` ### HTTPS / SSL PsychicHttp supports HTTPS / SSL out of the box, however there are some limitations (see performance below). Enabling it also increases the code size by about 100kb. To use HTTPS, you need to modify your setup like so: ```cpp #include #include PsychicHttpsServer server; server.listen(443, server_cert, server_key); ``` ```server_cert``` and ```server_key``` are both ```const char *``` parameters which contain the server certificate and private key, respectively. To generate your own key and self signed certificate, you can use the command below: ``` openssl req -x509 -newkey rsa:4096 -nodes -keyout server.key -out server.crt -sha256 -days 365 ``` Including the ```PsychicHttpsServer.h``` also defines ```PSY_ENABLE_SSL``` which you can use in your code to allow enabling / disabling calls in your code based on if the HTTPS server is available: ```cpp //our main server object #ifdef PSY_ENABLE_SSL PsychicHttpsServer server; #else PsychicHttpServer server; #endif ``` Last, but not least, you can create a separate HTTP server on port 80 that redirects all requests to the HTTPS server: ```cpp //this creates a 2nd server listening on port 80 and redirects all requests HTTPS PsychicHttpServer *redirectServer = new PsychicHttpServer(); redirectServer->config.ctrl_port = 20420; // just a random port different from the default one redirectServer->listen(80); redirectServer->onNotFound([](PsychicRequest *request) { String url = "https://" + request->host() + request->url(); return request->redirect(url.c_str()); }); ``` # TemplatePrinter **This is not specific to PsychicHttp, and it works with any `Print` object. You could for example, template data out to `File`, `Serial`, etc...**. The template engine is a `Print` interface and can be printed to directly, however, if you are just templating a few short strings, I'd probably just use `response.printf()` instead. **Its benefit will be seen when templating large inputs such as files.** One benefit may be **templating a **JSON** file avoiding the need to use ArduinoJson.** Before closing the underlying `Print`/`Stream` that this writes to, it must be flushed as small amounts of data can be buffered. A convenience method to take care of this is shows in `example 3`. The header file is not currently added to `PsychicHttp.h` and users will have to add it manually: ```C++ #include ``` ## Template parameter definition: - Must start and end with a preset delimiter, the default is `%` - Can only contain `a-z`, `A-Z`, `0-9`, and `_` - Maximum length of 63 characters (buffer is 64 including `null`). - A parameter must not be zero length (not including delimiters). - Spaces or any other character do not match as a parameter, and will be output as is. - Valid examples - `%MY_PARAM%` - `%SOME1%` - **Invalid** examples - `%MY PARAM%` - `%SOME1 %` - `%UNFINISHED` - `%%` ## Template processing A function or lambda is used to receive the parameter replacement. ```C++ bool templateHandler(Print &output, const char *param){ //... } [](Print &output, const char *param){ //... } ``` Parameters: - `Print &output` - the underlying `Print`, print the results of templating to this. - `const char *param` - a string containing the current parameter. The handler must return a `bool`. - `true`: the parameter was handled, continue as normal. - `false`: the input detected as a parameter is not, print literal. See output in **example 1** regarding the effects of returning `true` or `false`. ## Template input handler This is not needed unless using the static convenience function `TemplatePrinter::start()`. See **example 3**. ```C++ bool inputHandler(TemplatePrinter &printer){ //... } [](TemplatePrinter &printer){ //... } ``` Parameters: - `TemplatePrinter &printer` - The template engine, print your template text to this for processing. ## Example 1 - Simple use with `PsychicStreamResponse`: This example highlights its most basic usage. ```C++ // Function to handle parameter requests. bool templateHandler(Print &output, const char *param){ if(strcmp(param, "FREE_HEAP") == 0){ output.print((double)ESP.getFreeHeap() / 1024.0, 2); }else if(strcmp(param, "MIN_FREE_HEAP") == 0){ output.print((double)ESP.getMinFreeHeap() / 1024.0, 2); }else if(strcmp(param, "MAX_ALLOC_HEAP") == 0){ output.print((double)ESP.getMaxAllocHeap() / 1024.0, 2); }else if(strcmp(param, "HEAP_SIZE") == 0){ output.print((double)ESP.getHeapSize() / 1024.0, 2); }else{ return false; } output.print("Kb"); return true; } // Example serving a request server.on("/template", [](PsychicRequest *request) { PsychicStreamResponse response(request, "text/plain"); response.beginSend(); TemplatePrinter printer(response, templateHandler); printer.println("My ESP has %FREE_HEAP% left. Its lifetime minimum heap is %MIN_FREE_HEAP%."); printer.println("The maximum allocation size is %MAX_ALLOC_HEAP%, and its total size is %HEAP_SIZE%."); printer.println("This is an unhandled parameter: %UNHANDLED_PARAM% and this is an invalid param %INVALID PARAM%."); printer.println("This line finished with %UNFIN"); printer.flush(); return response.endSend(); }); ``` The output for example looks like: ``` My ESP has 170.92Kb left. Its lifetime minimum heap is 169.83Kb. The maximum allocation size is 107.99Kb, and its total size is 284.19Kb. This is an unhandled parameter: %UNHANDLED_PARAM% and this is an invalid param %INVALID PARAM%. This line finished with %UNFIN ``` ## Example 2 - Templating a file ```C++ server.on("/home", [](PsychicRequest *request) { PsychicStreamResponse response(request, "text/html"); File file = SD.open("/www/index.html"); response.beginSend(); TemplatePrinter printer(response, templateHandler); printer.copyFrom(file); printer.flush(); file.close(); return response.endSend(); }); ``` ## Example 3 - Using the `TemplatePrinter::start` method. This static method allows an RAII approach, allowing you to template a stream, etc... without needing a `flush()`. The function call is laid out as: ```C++ TemplatePrinter::start(host_stream, template_handler, input_handler); ``` \*these examples use the `templateHandler` function defined in example 1. ### Serve a file like example 2 ```C++ server.on("/home", [](PsychicRequest *request) { PsychicStreamResponse response(request, "text/html"); File file = SD.open("/www/index.html"); response.beginSend(); TemplatePrinter::start(response, templateHandler, [&file](TemplatePrinter &printer){ printer.copyFrom(file); }); file.close(); return response.endSend(); }); ``` ### Template a string like example 1 ```C++ server.on("/template2", [](PsychicRequest *request) { PsychicStreamResponse response(request, "text/plain"); response.beginSend(); TemplatePrinter::start(response, templateHandler, [](TemplatePrinter &printer){ printer.println("My ESP has %FREE_HEAP% left. Its lifetime minimum heap is %MIN_FREE_HEAP%."); printer.println("The maximum allocation size is %MAX_ALLOC_HEAP%, and its total size is %HEAP_SIZE%."); printer.println("This is an unhandled parameter: %UNHANDLED_PARAM% and this is an invalid param %INVALID PARAM%."); }); return response.endSend(); }); ``` # Performance In order to really see the differences between libraries, I created some basic benchmark firmwares for PsychicHttp, ESPAsyncWebserver, and ArduinoMongoose. I then ran the loadtest-http.sh and loadtest-websocket.sh scripts against each firmware to get some real numbers on the performance of each server library. All of the code and results are available in the /benchmark folder. If you want to see the collated data and graphs, there is a [LibreOffice spreadsheet](/benchmark/comparison.ods). ![Performance graph](/benchmark/performance.png) ![Latency graph](/benchmark/latency.png) ## HTTPS / SSL Yes, PsychicHttp supports SSL out of the box, but there are a few caveats: * Due to memory limitations, it can only handle 2 connections at a time. Each SSL connection takes about 45k ram, and a blank PsychicHttp sketch has about 150k ram free. * Speed and latency are still pretty good (see graph above) but the SSH handshake seems to take 1500ms. With websockets or browser its not an issue since the connection is kept alive, but if you are loading requests in another way it will be a bit slow * Unless you want to expose your ESP to the internet, you are limited to self signed keys and the annoying browser security warnings that come with them. ## Analysis The results clearly show some of the reasons for writing PsychicHttp: ESPAsyncWebserver crashes under heavy load on each test, across the board in a 60s test. That means in normal usage, you're just rolling the dice with how long it will go until it crashes. Every other number is moot, IMHO. ArduinoMongoose doesn't crash under heavy load, but it does bog down with extremely high latency (15s) for web requests and appears to not even respond at the highest loadings as the loadtest script crashes instead. The code itself doesnt crash, so bonus points there. After the high load, it does go back to serving normally. One area ArduinoMongoose does shine, is in websockets where its performance is almost 2x the performance of PsychicHttp. Both in requests per second and latency. Clearly an area of improvement for PsychicHttp. PsychicHttp has good performance across the board. No crashes and continously responds during each test. It is a clear winner in requests per second when serving files from memory, dynamic JSON, and has consistent performance when serving files from LittleFS. The only real downside is the lower performance of the websockets with a single connection handling 38rps, and maxing out at 120rps across multiple connections. ## Takeaways With all due respect to @me-no-dev who has done some amazing work in the open source community, I cannot recommend anyone use the ESPAsyncWebserver for anything other than simple projects that don't need to be reliable. Even then, PsychicHttp has taken the arcane api of the ESP-IDF web server library and made it nice and friendly to use with a very similar API to ESPAsyncWebserver. Also, ESPAsyncWebserver is more or less abandoned, with 150 open issues, 77 pending pull requests, and the last commit in over 2 years. ArduinoMongoose is a good alternative, although the latency issues when it gets fully loaded can be very annoying. I believe it is also cross platform to other microcontrollers as well, but I haven't tested that. The other issue here is that it is based on an old version of a modified Mongoose library that will be difficult to update as it is a major revision behind and several security updates behind as well. Big thanks to @jeremypoulter though as PsychicHttp is a fork of ArduinoMongoose so it's built on strong bones. # Roadmap ## v1.2: ESPAsyncWebserver Parity Change: Modify the request handling to bring initail url matching and filtering into PsychicHttpServer itself. Benefits: * Fix a bug with filter() where endpoint is matched, but filter fails and it doesn't continue matching further endpoints (checks are in different codebases) * HTTP_ANY support * unlimited endpoints * we would use a List to store endpoints * dont have to pre-declare config.max_uri_handlers; * much more flexibility for future Issues * it would log a warning on every request as if its a 404. (httpd_uri.c:298) * req->user_ctx is not passed in. (httpd_uri.c:309) * but... user_ctx is something we could store in the psychicendpoint data * Websocket support assumes an endpoint with matching url / method (httpd_uri.c:312) * we could copy and bring this code into our own internal request processor * would need to manually maintain more code (~100 lines?) and be more prone to esp-idf http_server updates causing problems. How to implement * set config.max_uri_handlers = 1; * possibly do not register any uri_handlers (looks like it would be fastest way to exit httpd_find_uri_handler (httpd_uri.c:94)) * looks like 404 is set by default, so should work. * modify PsychicEndpoint to store the stuff we would pass to http_server * create a new function handleRequest() before PsychicHttpServer::defaultNotFoundHandler to process incoming requests. * bring in code from PsychicHttpServer::notFoundHandler * add new code to loop over endpoints to call match and filter * bring code from esp-idf library * templating system * regex url matching * rewrite urls? * What else are we missing? ## Longterm Wants * investigate websocket performance gap * support for esp-idf framework * support for arduino 3.0 framework * Enable worker based multithreading with esp-idf v5.x * 100-continue support? If anyone wants to take a crack at implementing any of the above features I am more than happy to accept pull requests. ================================================ FILE: lib/PsychicHttp/RELEASE.md ================================================ * Update CHANGELOG * Bump version in library.json * Bump version in library.properties * Make new release + tag * this will get pulled in automatically by Arduino Library Indexer * run ```pio pkg publish``` to publish to Platform.io ================================================ FILE: lib/PsychicHttp/library.json ================================================ { "name": "PsychicHttp", "version": "1.2.1", "description": "Arduino style wrapper around ESP-IDF HTTP library. HTTP server with SSL + websockets. Works on esp32 and probably esp8266", "keywords": "network,http,https,tcp,ssl,tls,websocket,espasyncwebserver", "repository": { "type": "git", "url": "https://github.com/hoeken/PsychicHttp" }, "authors": [ { "name": "Zach Hoeken", "email": "hoeken@gmail.com", "maintainer": true } ], "license" : "MIT", "examples": [ { "name": "platformio", "base": "examples/platformio", "files": [ "src/main.cpp" ] } ], "frameworks": "arduino", "platforms": "espressif32", "dependencies": [ { "owner": "bblanchon", "name": "ArduinoJson", "version": "^7.0.4" }, { "owner": "plageoj", "name" : "UrlEncode", "version" : "^1.0.1" } ], "export": { "include": [ "examples/platformio", "src", "library.json", "library.properties", "LICENSE", "README.md" ] } } ================================================ FILE: lib/PsychicHttp/request flow.drawio ================================================ 7Vxbd5s4EP41Pmf3wTkgAcaPza3Zbq/bbNM+yiAbNhi5ICd2f/0KIxmQFIypsZ1jpw+1hBCS5pv5ZgaJHryaLt4maBZ8ID6OesDwFz143QPANIDD/stqlnnNwIJ5xSQJfd6oqPga/sLiTl47D32cVhpSQiIazqqVHolj7NFKHUoS8lxtNiZR9akzNMFKxVcPRWrtQ+jTIK91waCov8PhJBBPNp1hfmWKRGM+kzRAPnkuVcGbHrxKCKH5r+niCkfZ4ol1efhr+RC9f3TevvuS/kT/Xv59//FbP+/sdptb1lNIcExbd+0/B97S/uJ9MrxvX76P0/f9+Gff5MvwhKI5XzA+WboUK5iQeezjrBezBy+fg5DirzPkZVefGWZYXUCnEb+8XiSDFcYkphwRbL3ZRXZbGE9Y0c6uhlF0RSKSrB4Dx3b2j99Vqs//srtpQh5x6Yqz+mNXGq4PX8cnnFC8KKGDr9dbTKaYJkvWRFwVIObYN21efi6QZA95XVBCkevwSsTRO1n3XUiI/eBC0gvsevkufbie3t/Yd9blDfz0bvHQ70NzG4EZVeH8hyldcoGgOSWsiiQ0IBMSo+g9ITPeriQ3Myvj2H+TqSIrjyLiPeZVt2E29NUzWIm3d9eCEtqmoCJCIxxdIu9xshqoEGhMYpx15TP15XMpBndT1LKHsYX8nnV2YYvij/VAWOF6USktRWkR0tJtrPSDDy/7XdyUFcQ9KUUJFXPnI9wObSmZJx6uUUEuP/agCaZ1kueQyhaoFrwJjhANn6r2TwdEfutnErKJrEEPbFgBPRyCahf5jPhdZYOzoSPbkDrKp6x0tNKL9XwaqYpWAODkNaU9UrXtoIpUbTtn10BtajHrRl2Cwd39/WdW8w/+Occp/T2+KwOAzfFyEqE0XRuPWulK/Ocj7I49Lc95Lh6Nu+Q5t6qpQGhqiedMoOE5awc0p52CpQjtB3MiT0x92xLdjtXeaaj2ptlQ7znq+sYFgIZbQV7f5N53WxITTch4nOJ6foKGdVB+shWMfyQKxDej5FUrQTdQ3YhA4c8b+wObVTWxljHYK9gcBWw3sT/jY/yAqBdkELpVTWxApqN52iLwu0XTMMpme4ejJ0xDD2noEkXhJGYFj8kfJ3o0rYNGpyjdr9DLaEINI8dj4Glp1HdGjt1puDiUPGdnoNKooQsXu6JRU40WP6dLLwi9OxT7EVvxs/MjOz+2uUfnRxvpaaR2it5Pi3B9/x6TXoCamH5XLpMNoC25TPtjMcuQWAxILNY2N2ANm9EhwydalpqtGCzVTErQrmSSLRfUj0um6Wp79iMfQVturoVLSd9XjJyxHnAiBqDLEbPUzoSuoOqgaWaH41Ga/ScM+Zm7f4sFZP9sr9ytR4WauLjGYzSPMrgWztvJ87cle12udWE3ZHC7K9mp+YvTi+0KMq5QccHMOyHjjXlzoUdHGBRam4LCpnQKZTo1O4su9Wus5jLOHuur8lib5vZbeKyOpST5Duix2m1VTNJVW3Z9d+Sx2rIqH6XHqqaTPuJnVnGV7+IISax1SA/jnBwyJSS/WXEbJhdAZ26luuMjxQmb0QWJP81wnAkRRdGImcFjkZ9vY9e3dPJzwQh2ugMEwqrpAoODJ4eGivxUx7KgRS9b9dCriqbKw4K2zBJpFRS2iba69O0205bm3VQt6jfSVnlnj0as9m8y1xpWktEWsNqalVw5ISN11LHjB9QgtUQBzJREJH3hxcLJc4Fra1IMe+UCoIapQZ5OYmSwEp2af1qTxQvXBXnUef8nwx6Sb+ZCt2lqQnZTdydzNVQ7Xf4AmrCnVlOOlD9Mw2ob1khGadgwEb8rAhG7GktwvA3jMA2OxXyMXQ/rCWPk2pa9PSjbE8YQNCSMzpxPCGoIg0cPPaC8o0hn2AvHzIoAwzvTw4v0MBCm+HDyVd25kyAH7cZstyE3CKU4Fm4wq6hybPNiWP5rSRTWVt3ujja0smmA0y6Tzes3HK9ub2ibHHV7vapNIZcVq+5kROcHHuTMrt0yGJc7GkCwV6VQXSnGdRQnf/yZ0fI5Bte4VPY+87H6E3iK0DwU55s6znJ7UW4OPLTcVE+YcUnAph16iJ5FVyO6g6ucmvVK8qNAbwoJhiTOZHgc0sMmi1IGOukNnQFE+4xRtNKzzD1K70TzV03PjtYh/kgjlIHV0uFSAmi5o44dLleBYp4N4ScLzwZEY/4HB2du9QVqgtMZiVN8kTLLcZaaRmpu00MR3fnJanRzULu/r+1adfZ8o90fHrfdbxtoy9sdlY52tRdLvPYRzg//FMJL45LbD7bcuzXY8d4tvSKpkcvpKpKhKlLtEY1j1ST56HJTTbLEkQaxed6W7PeONMmxqs8RX815aVxyewjr28vnfKT2HWnSkb0tOagmNd6Of9ya5LTXJAmBg272B8uaIcqvW5PUlIw4p0zprFf6VotxGzFlkrWMebW0qldVl5m/Vin717xKOcSW+cihh6I3/MI09P3VGxed21/VXuVzZ8q30PiIre10r7nbDiTh6T7kAsUOj7I2we3ddlYsvn2XA6H4giC8+R8=7Vtbc5s4FP41ntk+tGMQAvyYOLdNp9NOvTttn3ZkkDGNQA7It/z6FUayBcK3xNhMA34I5+iCdL5P5xwJ0gH9aHGfoMn4C/Ux6Zhdf9EBNx3TNLqmzf9kmmWucSyQK4Ik9EWljWIQvmDZUminoY/TQkVGKWHhpKj0aBxjjxV0KEnovFhtREnxqRMUYE0x8BDRtT9Cn41zrWs6G/0DDoOxfLJh9/KSCMnKYibpGPl0rqjAbQf0E0pZfhct+phkxpN2ue69/J493t0Yzy/92Xf/3v3nKviYd3Z3TJP1FBIcs9N2beZdzxCZCnuJubKlNGBCp7GPs06MDriej0OGBxPkZaVzThmuG7OIiOK1jbpcGNGYCUJwc/NC3iyMAy7CrDQkpE8JTVaPASOY/UQrRZ9fWWuW0CeslNiri5dEdIaGq+FmQ0hwGr6oMmWIKTInOFZl7IeqKHioaA60vkBphhOGFwr3BBr3mEaYJUteRZTyueVNxMoCUBBtvuEpsIVurHDUcoQSibURrPve4M9vBAWOoENPo8MPPHxAsU9w8jZiKFwwuE2uA4LSVPAkR1auTp1GRaL4CLsjr5IQnouHozoRc7sFxCwANcQMswqxugCTA1AQE3Clq2HxUZndPiJkiLynVIOQz5uVFnDBqDGNcQkBoUIkDGIuetzEnBvgOrNiyN3ulSiIQt/PHlNJjA11yn4CVjoRMWKrNmANWFyKbsVS7Dk6sOAEwBqfH8jEnz7+9yv4m4HH5+gruhe+XMWVxt/x8xSn7K8PjVmKELu+VbUUXXMIVr65LsQsGcDlUrQOXIpmXYgZGmIaTDj2r7KUJls3mdFDr4hMcVlwiyXLn6rwKxM+QSneLNTCm6WUFiH7KYMbv1dacWnTKBNkm+NgSuk08fD+OMJQEmC2w2YCC+wXcjgddAVUWIGp1CWYIBbOiplfFdDiCd9oyKercKrk3iEsdpHPW7RSU61yR3axI2Bbn3rqVew2N5PW7YqFayO8nph6jseD+oB6T5i1oX1baLfNM4b2SthARQT4OsFx6/4r3L/dvbT7tyrguktQhFu8qvA6NHOuDS89caZxn9C0xasSL/vSeNnvM73aFdH3pldWs9IroxhiofHa9Ao4uzuqOaFymkLF42i1ly6gWXTpljIy60R0sctp/Ra6cADRUqk2ySqkh/NbDnjruMr1jUJ9fpOP4KTcdf9Q7sJ3wl2zodx1zsBd/XT63wmhyG93sdt2sevIeLFdrORJe5B5YKYNL3+Q+U5PMnf5nL3xR/K8KQGodJQJwYmOMi3rNUeZbw1HcviHhiMIzxCODLPCteURqfVsVZ7t4md0hn5IdyHPdpzN93sfs1nep3sq71Pe6dvnSX+P9jfn2LoZ+pHl7YzzZ5DHsKY4nOZkv845P8+ohkw/tWxf4mwNEM6h79zqCxD68Uj7VmAHYBd/K2Dq28s/JKLbjY7ozqs/jQBbKFRzRHfgcRHdAWeI6GZjdtqnZq/7TthbTmybwt63HcdycfNZe159888B4PZ/ ================================================ FILE: lib/PsychicHttp/src/ChunkPrinter.cpp ================================================ #include "ChunkPrinter.h" ChunkPrinter::ChunkPrinter(PsychicResponse *response, uint8_t *buffer, size_t len) : _response(response), _buffer(buffer), _length(len), _pos(0) {} ChunkPrinter::~ChunkPrinter() { flush(); } size_t ChunkPrinter::write(uint8_t c) { esp_err_t err; //if we're full, send a chunk if (_pos == _length) { _pos = 0; err = _response->sendChunk(_buffer, _length); if (err != ESP_OK) return 0; } _buffer[_pos] = c; _pos++; return 1; } size_t ChunkPrinter::write(const uint8_t *buffer, size_t size) { size_t written = 0; while (written < size) { size_t space = _length - _pos; size_t blockSize = std::min(space, size - written); memcpy(_buffer + _pos, buffer + written, blockSize); _pos += blockSize; if (_pos == _length) { _pos = 0; if (_response->sendChunk(_buffer, _length) != ESP_OK) return written; } written += blockSize; //Update if sent correctly. } return written; } void ChunkPrinter::flush() { if (_pos) { _response->sendChunk(_buffer, _pos); _pos = 0; } } size_t ChunkPrinter::copyFrom(Stream &stream) { size_t count = 0; while (stream.available()){ if (_pos == _length) { _response->sendChunk(_buffer, _length); _pos = 0; } size_t readBytes = stream.readBytes(_buffer + _pos, _length - _pos); _pos += readBytes; count += readBytes; } return count; } ================================================ FILE: lib/PsychicHttp/src/ChunkPrinter.h ================================================ #ifndef ChunkPrinter_h #define ChunkPrinter_h #include "PsychicResponse.h" #include class ChunkPrinter : public Print { private: PsychicResponse *_response; uint8_t *_buffer; size_t _length; size_t _pos; public: ChunkPrinter(PsychicResponse *response, uint8_t *buffer, size_t len); ~ChunkPrinter(); size_t write(uint8_t c) override; size_t write(const uint8_t *buffer, size_t size) override; size_t copyFrom(Stream &stream); void flush() override; }; #endif ================================================ FILE: lib/PsychicHttp/src/PsychicClient.cpp ================================================ #include "PsychicClient.h" #include "PsychicHttpServer.h" #include PsychicClient::PsychicClient(httpd_handle_t server, int socket) : _server(server), _socket(socket), _friend(NULL), isNew(false) {} PsychicClient::~PsychicClient() { } httpd_handle_t PsychicClient::server() { return _server; } int PsychicClient::socket() { return _socket; } // I'm not sure this is entirely safe to call. I was having issues with race conditions when highly loaded using this. esp_err_t PsychicClient::close() { esp_err_t err = httpd_sess_trigger_close(_server, _socket); //PsychicHttpServer::closeCallback(_server, _socket); // call this immediately so the client is taken off the list. return err; } IPAddress PsychicClient::localIP() { IPAddress address(0,0,0,0); char ipstr[INET6_ADDRSTRLEN]; struct sockaddr_in6 addr; // esp_http_server uses IPv6 addressing socklen_t addr_size = sizeof(addr); if (getsockname(_socket, (struct sockaddr *)&addr, &addr_size) < 0) { ESP_LOGE(PH_TAG, "Error getting client IP"); return address; } // Convert to IPv4 string inet_ntop(AF_INET, &addr.sin6_addr.un.u32_addr[3], ipstr, sizeof(ipstr)); //ESP_LOGD(PH_TAG, "Client Local IP => %s", ipstr); address.fromString(ipstr); return address; } IPAddress PsychicClient::remoteIP() { IPAddress address(0,0,0,0); char ipstr[INET6_ADDRSTRLEN]; struct sockaddr_in6 addr; // esp_http_server uses IPv6 addressing socklen_t addr_size = sizeof(addr); if (getpeername(_socket, (struct sockaddr *)&addr, &addr_size) < 0) { ESP_LOGE(PH_TAG, "Error getting client IP"); return address; } // Convert to IPv4 string inet_ntop(AF_INET, &addr.sin6_addr.un.u32_addr[3], ipstr, sizeof(ipstr)); //ESP_LOGD(PH_TAG, "Client Remote IP => %s", ipstr); address.fromString(ipstr); return address; } ================================================ FILE: lib/PsychicHttp/src/PsychicClient.h ================================================ #ifndef PsychicClient_h #define PsychicClient_h #include "PsychicCore.h" /* * PsychicClient :: Generic wrapper around the ESP-IDF socket */ class PsychicClient { protected: httpd_handle_t _server; int _socket; public: PsychicClient(httpd_handle_t server, int socket); ~PsychicClient(); //no idea if this is the right way to do it or not, but lets see. //pointer to our derived class (eg. PsychicWebSocketConnection) void *_friend; bool isNew = false; bool operator==(PsychicClient& rhs) const { return _socket == rhs.socket(); } httpd_handle_t server(); int socket(); esp_err_t close(); IPAddress localIP(); IPAddress remoteIP(); }; #endif ================================================ FILE: lib/PsychicHttp/src/PsychicCore.h ================================================ #ifndef PsychicCore_h #define PsychicCore_h #define PH_TAG "🔮" // version numbers #define PSYCHIC_HTTP_VERSION_MAJOR 1 #define PSYCHIC_HTTP_VERSION_MINOR 1 #define PSYCHIC_HTTP_VERSION_PATCH 0 #ifndef MAX_COOKIE_SIZE #define MAX_COOKIE_SIZE 512 #endif #ifndef FILE_CHUNK_SIZE #define FILE_CHUNK_SIZE 8 * 1024 #endif #ifndef STREAM_CHUNK_SIZE #define STREAM_CHUNK_SIZE 1024 #endif #ifndef MAX_UPLOAD_SIZE #define MAX_UPLOAD_SIZE (2048 * 1024) // 2MB #endif #ifndef MAX_REQUEST_BODY_SIZE #define MAX_REQUEST_BODY_SIZE (16 * 1024) // 16K #endif #ifdef ARDUINO #include #endif #include #include #include #include #include "esp_random.h" #include "MD5Builder.h" #include #include "FS.h" #include enum HTTPAuthMethod { BASIC_AUTH, DIGEST_AUTH }; String urlDecode(const char *encoded); class PsychicHttpServer; class PsychicRequest; class PsychicWebSocketRequest; class PsychicClient; // filter function definition typedef std::function PsychicRequestFilterFunction; // client connect callback typedef std::function PsychicClientCallback; // callback definitions typedef std::function PsychicHttpRequestCallback; typedef std::function PsychicJsonRequestCallback; struct HTTPHeader { char *field; char *value; }; class DefaultHeaders { std::list _headers; public: DefaultHeaders() {} void addHeader(const String &field, const String &value) { addHeader(field.c_str(), value.c_str()); } void addHeader(const char *field, const char *value) { HTTPHeader header; // these are just going to stick around forever. header.field = (char *)malloc(strlen(field) + 1); header.value = (char *)malloc(strlen(value) + 1); strlcpy(header.field, field, strlen(field) + 1); strlcpy(header.value, value, strlen(value) + 1); _headers.push_back(header); } const std::list &getHeaders() { return _headers; } // delete the copy constructor, singleton class DefaultHeaders(DefaultHeaders const &) = delete; DefaultHeaders &operator=(DefaultHeaders const &) = delete; // single static class interface static DefaultHeaders &Instance() { static DefaultHeaders instance; return instance; } }; #endif // PsychicCore_h ================================================ FILE: lib/PsychicHttp/src/PsychicEndpoint.cpp ================================================ #include "PsychicEndpoint.h" #include "PsychicHttpServer.h" PsychicEndpoint::PsychicEndpoint() : _server(NULL), _uri(""), _method(HTTP_GET), _handler(NULL) { } PsychicEndpoint::PsychicEndpoint(PsychicHttpServer *server, http_method method, const char * uri) : _server(server), _uri(uri), _method(method), _handler(NULL) { } PsychicEndpoint * PsychicEndpoint::setHandler(PsychicHandler *handler) { //clean up old / default handler if (_handler != NULL) delete _handler; //get our new pointer _handler = handler; //keep a pointer to the server _handler->_server = _server; return this; } PsychicHandler * PsychicEndpoint::handler() { return _handler; } String PsychicEndpoint::uri() { return _uri; } esp_err_t PsychicEndpoint::requestCallback(httpd_req_t *req) { PsychicEndpoint *self = (PsychicEndpoint *)req->user_ctx; PsychicHandler *handler = self->handler(); PsychicRequest request(self->_server, req); //make sure we have a handler if (handler != NULL) { if (handler->filter(&request) && handler->canHandle(&request)) { //check our credentials if (handler->needsAuthentication(&request)) return handler->authenticate(&request); //pass it to our handler return handler->handleRequest(&request); } //pass it to our generic handlers else return PsychicHttpServer::notFoundHandler(req, HTTPD_500_INTERNAL_SERVER_ERROR); } else return request.reply(500, "text/html", "No handler registered."); } PsychicEndpoint* PsychicEndpoint::setFilter(PsychicRequestFilterFunction fn) { _handler->setFilter(fn); return this; } PsychicEndpoint* PsychicEndpoint::setAuthentication(const char *username, const char *password, HTTPAuthMethod method, const char *realm, const char *authFailMsg) { _handler->setAuthentication(username, password, method, realm, authFailMsg); return this; }; ================================================ FILE: lib/PsychicHttp/src/PsychicEndpoint.h ================================================ #ifndef PsychicEndpoint_h #define PsychicEndpoint_h #include "PsychicCore.h" class PsychicHandler; class PsychicEndpoint { friend PsychicHttpServer; private: PsychicHttpServer *_server; String _uri; http_method _method; PsychicHandler *_handler; public: PsychicEndpoint(); PsychicEndpoint(PsychicHttpServer *server, http_method method, const char * uri); PsychicEndpoint *setHandler(PsychicHandler *handler); PsychicHandler *handler(); PsychicEndpoint* setFilter(PsychicRequestFilterFunction fn); PsychicEndpoint* setAuthentication(const char *username, const char *password, HTTPAuthMethod method = BASIC_AUTH, const char *realm = "", const char *authFailMsg = ""); String uri(); static esp_err_t requestCallback(httpd_req_t *req); }; #endif // PsychicEndpoint_h ================================================ FILE: lib/PsychicHttp/src/PsychicEventSource.cpp ================================================ /* Asynchronous WebServer library for Espressif MCUs Copyright (c) 2016 Hristo Gochkov. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "PsychicEventSource.h" /*****************************************/ // PsychicEventSource - Handler /*****************************************/ PsychicEventSource::PsychicEventSource() : PsychicHandler(), _onOpen(NULL), _onClose(NULL) {} PsychicEventSource::~PsychicEventSource() { } PsychicEventSourceClient * PsychicEventSource::getClient(int socket) { PsychicClient *client = PsychicHandler::getClient(socket); if (client == NULL) return NULL; return (PsychicEventSourceClient *)client->_friend; } PsychicEventSourceClient * PsychicEventSource::getClient(PsychicClient *client) { return getClient(client->socket()); } esp_err_t PsychicEventSource::handleRequest(PsychicRequest *request) { //start our open ended HTTP response PsychicEventSourceResponse response(request); esp_err_t err = response.send(); //lookup our client PsychicClient *client = checkForNewClient(request->client()); if (client->isNew) { //did we get our last id? if(request->hasHeader("Last-Event-ID")) { PsychicEventSourceClient *buddy = getClient(client); buddy->_lastId = atoi(request->header("Last-Event-ID").c_str()); } //let our handler know. openCallback(client); } return err; } PsychicEventSource * PsychicEventSource::onOpen(PsychicEventSourceClientCallback fn) { _onOpen = fn; return this; } PsychicEventSource * PsychicEventSource::onClose(PsychicEventSourceClientCallback fn) { _onClose = fn; return this; } void PsychicEventSource::addClient(PsychicClient *client) { client->_friend = new PsychicEventSourceClient(client); PsychicHandler::addClient(client); } void PsychicEventSource::removeClient(PsychicClient *client) { PsychicHandler::removeClient(client); delete (PsychicEventSourceClient*)client->_friend; client->_friend = NULL; } void PsychicEventSource::openCallback(PsychicClient *client) { PsychicEventSourceClient *buddy = getClient(client); if (buddy == NULL) { return; } if (_onOpen != NULL) _onOpen(buddy); } void PsychicEventSource::closeCallback(PsychicClient *client) { PsychicEventSourceClient *buddy = getClient(client); if (buddy == NULL) { return; } if (_onClose != NULL) _onClose(getClient(buddy)); } void PsychicEventSource::send(const char *message, const char *event, uint32_t id, uint32_t reconnect) { String ev = generateEventMessage(message, event, id, reconnect); for(PsychicClient *c : _clients) { ((PsychicEventSourceClient*)c->_friend)->sendEvent(ev.c_str()); } } /*****************************************/ // PsychicEventSourceClient /*****************************************/ PsychicEventSourceClient::PsychicEventSourceClient(PsychicClient *client) : PsychicClient(client->server(), client->socket()), _lastId(0) { } PsychicEventSourceClient::~PsychicEventSourceClient(){ } void PsychicEventSourceClient::send(const char *message, const char *event, uint32_t id, uint32_t reconnect){ String ev = generateEventMessage(message, event, id, reconnect); sendEvent(ev.c_str()); } void PsychicEventSourceClient::sendEvent(const char *event) { int result; do { result = httpd_socket_send(this->server(), this->socket(), event, strlen(event), 0); } while (result == HTTPD_SOCK_ERR_TIMEOUT); //if (result < 0) //error log here } /*****************************************/ // PsychicEventSourceResponse /*****************************************/ PsychicEventSourceResponse::PsychicEventSourceResponse(PsychicRequest *request) : PsychicResponse(request) { } esp_err_t PsychicEventSourceResponse::send() { //build our main header String out = String(); out.concat("HTTP/1.1 200 OK\r\n"); out.concat("Content-Type: text/event-stream\r\n"); out.concat("Cache-Control: no-cache\r\n"); out.concat("Connection: keep-alive\r\n"); //get our global headers out of the way first for (HTTPHeader header : DefaultHeaders::Instance().getHeaders()) out.concat(String(header.field) + ": " + String(header.value) + "\r\n"); //separator out.concat("\r\n"); int result; do { result = httpd_send(_request->request(), out.c_str(), out.length()); } while (result == HTTPD_SOCK_ERR_TIMEOUT); if (result < 0) ESP_LOGE(PH_TAG, "EventSource send failed with %s", esp_err_to_name(result)); if (result > 0) return ESP_OK; else return ESP_ERR_HTTPD_RESP_SEND; } /*****************************************/ // Event Message Generator /*****************************************/ String generateEventMessage(const char *message, const char *event, uint32_t id, uint32_t reconnect) { String ev = ""; if(reconnect){ ev += "retry: "; ev += String(reconnect); ev += "\r\n"; } if(id){ ev += "id: "; ev += String(id); ev += "\r\n"; } if(event != NULL){ ev += "event: "; ev += String(event); ev += "\r\n"; } if(message != NULL){ ev += "data: "; ev += String(message); ev += "\r\n"; } ev += "\r\n"; return ev; } ================================================ FILE: lib/PsychicHttp/src/PsychicEventSource.h ================================================ /* Asynchronous WebServer library for Espressif MCUs Copyright (c) 2016 Hristo Gochkov. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef PsychicEventSource_H_ #define PsychicEventSource_H_ #include "PsychicCore.h" #include "PsychicHandler.h" #include "PsychicClient.h" #include "PsychicResponse.h" class PsychicEventSource; class PsychicEventSourceResponse; class PsychicEventSourceClient; class PsychicResponse; typedef std::function PsychicEventSourceClientCallback; class PsychicEventSourceClient : public PsychicClient { friend PsychicEventSource; protected: uint32_t _lastId; public: PsychicEventSourceClient(PsychicClient *client); ~PsychicEventSourceClient(); uint32_t lastId() const { return _lastId; } void send(const char *message, const char *event=NULL, uint32_t id=0, uint32_t reconnect=0); void sendEvent(const char *event); }; class PsychicEventSource : public PsychicHandler { private: PsychicEventSourceClientCallback _onOpen; PsychicEventSourceClientCallback _onClose; public: PsychicEventSource(); ~PsychicEventSource(); PsychicEventSourceClient * getClient(int socket) override; PsychicEventSourceClient * getClient(PsychicClient *client) override; void addClient(PsychicClient *client) override; void removeClient(PsychicClient *client) override; void openCallback(PsychicClient *client) override; void closeCallback(PsychicClient *client) override; PsychicEventSource *onOpen(PsychicEventSourceClientCallback fn); PsychicEventSource *onClose(PsychicEventSourceClientCallback fn); esp_err_t handleRequest(PsychicRequest *request) override final; void send(const char *message, const char *event=NULL, uint32_t id=0, uint32_t reconnect=0); }; class PsychicEventSourceResponse: public PsychicResponse { public: PsychicEventSourceResponse(PsychicRequest *request); virtual esp_err_t send() override; }; String generateEventMessage(const char *message, const char *event, uint32_t id, uint32_t reconnect); #endif /* PsychicEventSource_H_ */ ================================================ FILE: lib/PsychicHttp/src/PsychicFileResponse.cpp ================================================ #include "PsychicFileResponse.h" #include "PsychicResponse.h" #include "PsychicRequest.h" PsychicFileResponse::PsychicFileResponse(PsychicRequest *request, FS &fs, const String& path, const String& contentType, bool download) : PsychicResponse(request) { //_code = 200; String _path(path); if(!download && !fs.exists(_path) && fs.exists(_path+".gz")){ _path = _path+".gz"; addHeader("Content-Encoding", "gzip"); } _content = fs.open(_path, "r"); _contentLength = _content.size(); if(contentType == "") _setContentType(path); else setContentType(contentType.c_str()); int filenameStart = path.lastIndexOf('/') + 1; char buf[26+path.length()-filenameStart]; char* filename = (char*)path.c_str() + filenameStart; if(download) { // set filename and force download snprintf(buf, sizeof (buf), "attachment; filename=\"%s\"", filename); } else { // set filename and force rendering snprintf(buf, sizeof (buf), "inline; filename=\"%s\"", filename); } addHeader("Content-Disposition", buf); } PsychicFileResponse::PsychicFileResponse(PsychicRequest *request, File content, const String& path, const String& contentType, bool download) : PsychicResponse(request) { String _path(path); if(!download && String(content.name()).endsWith(".gz") && !path.endsWith(".gz")){ addHeader("Content-Encoding", "gzip"); } _content = content; _contentLength = _content.size(); if(contentType == "") _setContentType(path); else setContentType(contentType.c_str()); int filenameStart = path.lastIndexOf('/') + 1; char buf[26+path.length()-filenameStart]; char* filename = (char*)path.c_str() + filenameStart; if(download) { snprintf(buf, sizeof (buf), "attachment; filename=\"%s\"", filename); } else { snprintf(buf, sizeof (buf), "inline; filename=\"%s\"", filename); } addHeader("Content-Disposition", buf); } PsychicFileResponse::~PsychicFileResponse() { if(_content) _content.close(); } void PsychicFileResponse::_setContentType(const String& path){ const char *_contentType; if (path.endsWith(".html")) _contentType = "text/html"; else if (path.endsWith(".htm")) _contentType = "text/html"; else if (path.endsWith(".css")) _contentType = "text/css"; else if (path.endsWith(".json")) _contentType = "application/json"; else if (path.endsWith(".js")) _contentType = "application/javascript"; else if (path.endsWith(".png")) _contentType = "image/png"; else if (path.endsWith(".gif")) _contentType = "image/gif"; else if (path.endsWith(".jpg")) _contentType = "image/jpeg"; else if (path.endsWith(".ico")) _contentType = "image/x-icon"; else if (path.endsWith(".svg")) _contentType = "image/svg+xml"; else if (path.endsWith(".eot")) _contentType = "font/eot"; else if (path.endsWith(".woff")) _contentType = "font/woff"; else if (path.endsWith(".woff2")) _contentType = "font/woff2"; else if (path.endsWith(".ttf")) _contentType = "font/ttf"; else if (path.endsWith(".xml")) _contentType = "text/xml"; else if (path.endsWith(".pdf")) _contentType = "application/pdf"; else if (path.endsWith(".zip")) _contentType = "application/zip"; else if(path.endsWith(".gz")) _contentType = "application/x-gzip"; else _contentType = "text/plain"; setContentType(_contentType); } esp_err_t PsychicFileResponse::send() { esp_err_t err = ESP_OK; //just send small files directly size_t size = getContentLength(); if (size < FILE_CHUNK_SIZE) { uint8_t *buffer = (uint8_t *)malloc(size); if (buffer == NULL) { /* Respond with 500 Internal Server Error */ httpd_resp_send_err(this->_request->request(), HTTPD_500_INTERNAL_SERVER_ERROR, "Unable to allocate memory."); return ESP_FAIL; } size_t readSize = _content.readBytes((char *)buffer, size); this->setContent(buffer, readSize); err = PsychicResponse::send(); free(buffer); } else { /* Retrieve the pointer to scratch buffer for temporary storage */ char *chunk = (char *)malloc(FILE_CHUNK_SIZE); if (chunk == NULL) { /* Respond with 500 Internal Server Error */ httpd_resp_send_err(this->_request->request(), HTTPD_500_INTERNAL_SERVER_ERROR, "Unable to allocate memory."); return ESP_FAIL; } this->sendHeaders(); size_t chunksize; do { /* Read file in chunks into the scratch buffer */ chunksize = _content.readBytes(chunk, FILE_CHUNK_SIZE); if (chunksize > 0) { err = this->sendChunk((uint8_t *)chunk, chunksize); if (err != ESP_OK) break; } /* Keep looping till the whole file is sent */ } while (chunksize != 0); //keep track of our memory free(chunk); if (err == ESP_OK) { ESP_LOGD(PH_TAG, "File sending complete"); this->finishChunking(); } } return err; } ================================================ FILE: lib/PsychicHttp/src/PsychicFileResponse.h ================================================ #ifndef PsychicFileResponse_h #define PsychicFileResponse_h #include "PsychicCore.h" #include "PsychicResponse.h" class PsychicRequest; class PsychicFileResponse: public PsychicResponse { using File = fs::File; using FS = fs::FS; private: File _content; void _setContentType(const String& path); public: PsychicFileResponse(PsychicRequest *request, FS &fs, const String& path, const String& contentType=String(), bool download=false); PsychicFileResponse(PsychicRequest *request, File content, const String& path, const String& contentType=String(), bool download=false); ~PsychicFileResponse(); esp_err_t send(); }; #endif // PsychicFileResponse_h ================================================ FILE: lib/PsychicHttp/src/PsychicHandler.cpp ================================================ #include "PsychicHandler.h" PsychicHandler::PsychicHandler() : _filter(NULL), _server(NULL), _username(""), _password(""), _method(DIGEST_AUTH), _realm(""), _authFailMsg(""), _subprotocol("") {} PsychicHandler::~PsychicHandler() { // actual PsychicClient deletion handled by PsychicServer // for (PsychicClient *client : _clients) // delete(client); _clients.clear(); } PsychicHandler* PsychicHandler::setFilter(PsychicRequestFilterFunction fn) { _filter = fn; return this; } bool PsychicHandler::filter(PsychicRequest *request){ return _filter == NULL || _filter(request); } void PsychicHandler::setSubprotocol(const String& subprotocol) { this->_subprotocol = subprotocol; } const char* PsychicHandler::getSubprotocol() const { return _subprotocol.c_str(); } PsychicHandler* PsychicHandler::setAuthentication(const char *username, const char *password, HTTPAuthMethod method, const char *realm, const char *authFailMsg) { _username = String(username); _password = String(password); _method = method; _realm = String(realm); _authFailMsg = String(authFailMsg); return this; }; bool PsychicHandler::needsAuthentication(PsychicRequest *request) { return (_username != "" && _password != "") && !request->authenticate(_username.c_str(), _password.c_str()); } esp_err_t PsychicHandler::authenticate(PsychicRequest *request) { return request->requestAuthentication(_method, _realm.c_str(), _authFailMsg.c_str()); } PsychicClient * PsychicHandler::checkForNewClient(PsychicClient *client) { PsychicClient *c = PsychicHandler::getClient(client); if (c == NULL) { c = client; addClient(c); c->isNew = true; } else c->isNew = false; return c; } void PsychicHandler::checkForClosedClient(PsychicClient *client) { if (hasClient(client)) { closeCallback(client); removeClient(client); } } void PsychicHandler::addClient(PsychicClient *client) { _clients.push_back(client); } void PsychicHandler::removeClient(PsychicClient *client) { _clients.remove(client); } PsychicClient * PsychicHandler::getClient(int socket) { //make sure the server has it too. if (!_server->hasClient(socket)) return NULL; //what about us? for (PsychicClient *client : _clients) if (client->socket() == socket) return client; //nothing found. return NULL; } PsychicClient * PsychicHandler::getClient(PsychicClient *client) { return PsychicHandler::getClient(client->socket()); } bool PsychicHandler::hasClient(PsychicClient *socket) { return PsychicHandler::getClient(socket) != NULL; } const std::list& PsychicHandler::getClientList() { return _clients; } ================================================ FILE: lib/PsychicHttp/src/PsychicHandler.h ================================================ #ifndef PsychicHandler_h #define PsychicHandler_h #include "PsychicCore.h" #include "PsychicRequest.h" class PsychicEndpoint; class PsychicHttpServer; /* * HANDLER :: Can be attached to any endpoint or as a generic request handler. */ class PsychicHandler { friend PsychicEndpoint; protected: PsychicRequestFilterFunction _filter; PsychicHttpServer *_server; String _username; String _password; HTTPAuthMethod _method; String _realm; String _authFailMsg; String _subprotocol; std::list _clients; public: PsychicHandler(); virtual ~PsychicHandler(); PsychicHandler* setFilter(PsychicRequestFilterFunction fn); bool filter(PsychicRequest *request); PsychicHandler* setAuthentication(const char *username, const char *password, HTTPAuthMethod method = BASIC_AUTH, const char *realm = "", const char *authFailMsg = ""); bool needsAuthentication(PsychicRequest *request); esp_err_t authenticate(PsychicRequest *request); virtual bool isWebSocket() { return false; }; void setSubprotocol(const String& subprotocol); const char* getSubprotocol() const; PsychicClient * checkForNewClient(PsychicClient *client); void checkForClosedClient(PsychicClient *client); virtual void addClient(PsychicClient *client); virtual void removeClient(PsychicClient *client); virtual PsychicClient * getClient(int socket); virtual PsychicClient * getClient(PsychicClient *client); virtual void openCallback(PsychicClient *client) {}; virtual void closeCallback(PsychicClient *client) {}; bool hasClient(PsychicClient *client); int count() { return _clients.size(); }; const std::list& getClientList(); //derived classes must implement these functions virtual bool canHandle(PsychicRequest *request) { return true; }; virtual esp_err_t handleRequest(PsychicRequest *request) = 0; }; #endif ================================================ FILE: lib/PsychicHttp/src/PsychicHttp.h ================================================ #ifndef PsychicHttp_h #define PsychicHttp_h #include #include "PsychicHttpServer.h" #include "PsychicRequest.h" #include "PsychicResponse.h" #include "PsychicEndpoint.h" #include "PsychicHandler.h" #include "PsychicStaticFileHandler.h" #include "PsychicFileResponse.h" #include "PsychicStreamResponse.h" #include "PsychicUploadHandler.h" #include "PsychicWebSocket.h" #include "PsychicEventSource.h" #include "PsychicJson.h" #endif /* PsychicHttp_h */ ================================================ FILE: lib/PsychicHttp/src/PsychicHttpServer.cpp ================================================ #include "PsychicHttpServer.h" #include "PsychicEndpoint.h" #include "PsychicHandler.h" #include "PsychicWebHandler.h" #include "PsychicStaticFileHandler.h" #include "PsychicWebSocket.h" #include "PsychicJson.h" #include "WiFi.h" PsychicHttpServer::PsychicHttpServer() : _onOpen(NULL), _onClose(NULL) { maxRequestBodySize = MAX_REQUEST_BODY_SIZE; maxUploadSize = MAX_UPLOAD_SIZE; defaultEndpoint = new PsychicEndpoint(this, HTTP_GET, ""); onNotFound(PsychicHttpServer::defaultNotFoundHandler); //for a regular server config = HTTPD_DEFAULT_CONFIG(); config.open_fn = PsychicHttpServer::openCallback; config.close_fn = PsychicHttpServer::closeCallback; config.uri_match_fn = httpd_uri_match_wildcard; config.global_user_ctx = this; config.global_user_ctx_free_fn = destroy; config.max_uri_handlers = 20; } PsychicHttpServer::~PsychicHttpServer() { for (auto *client : _clients) delete(client); _clients.clear(); for (auto *endpoint : _endpoints) delete(endpoint); _endpoints.clear(); for (auto *handler : _handlers) delete(handler); _handlers.clear(); delete defaultEndpoint; } void PsychicHttpServer::destroy(void *ctx) { // do not release any resource for PsychicHttpServer in order to be able to restart it after stopping } esp_err_t PsychicHttpServer::listen(uint16_t port) { this->_use_ssl = false; this->config.server_port = port; return this->_start(); } esp_err_t PsychicHttpServer::_start() { esp_err_t ret; //fire it up. ret = _startServer(); if (ret != ESP_OK) { ESP_LOGE(PH_TAG, "Server start failed (%s)", esp_err_to_name(ret)); return ret; } // Register handler ret = httpd_register_err_handler(server, HTTPD_404_NOT_FOUND, PsychicHttpServer::notFoundHandler); if (ret != ESP_OK) ESP_LOGE(PH_TAG, "Add 404 handler failed (%s)", esp_err_to_name(ret)); return ret; } esp_err_t PsychicHttpServer::_startServer() { return httpd_start(&this->server, &this->config); } void PsychicHttpServer::stop() { httpd_stop(this->server); } PsychicHandler& PsychicHttpServer::addHandler(PsychicHandler* handler){ _handlers.push_back(handler); return *handler; } void PsychicHttpServer::removeHandler(PsychicHandler *handler){ _handlers.remove(handler); } PsychicEndpoint* PsychicHttpServer::on(const char* uri) { return on(uri, HTTP_GET); } PsychicEndpoint* PsychicHttpServer::on(const char* uri, http_method method) { PsychicWebHandler *handler = new PsychicWebHandler(); return on(uri, method, handler); } PsychicEndpoint* PsychicHttpServer::on(const char* uri, PsychicHandler *handler) { return on(uri, HTTP_GET, handler); } PsychicEndpoint* PsychicHttpServer::on(const char* uri, http_method method, PsychicHandler *handler) { //make our endpoint PsychicEndpoint *endpoint = new PsychicEndpoint(this, method, uri); //set our handler endpoint->setHandler(handler); // URI handler structure httpd_uri_t my_uri { .uri = uri, .method = method, .handler = PsychicEndpoint::requestCallback, .user_ctx = endpoint, .is_websocket = handler->isWebSocket(), .supported_subprotocol = handler->getSubprotocol() }; // Register endpoint with ESP-IDF server esp_err_t ret = httpd_register_uri_handler(this->server, &my_uri); if (ret != ESP_OK) ESP_LOGE(PH_TAG, "Add endpoint failed (%s)", esp_err_to_name(ret)); //save it for later _endpoints.push_back(endpoint); return endpoint; } PsychicEndpoint* PsychicHttpServer::on(const char* uri, PsychicHttpRequestCallback fn) { return on(uri, HTTP_GET, fn); } PsychicEndpoint* PsychicHttpServer::on(const char* uri, http_method method, PsychicHttpRequestCallback fn) { //these basic requests need a basic web handler PsychicWebHandler *handler = new PsychicWebHandler(); handler->onRequest(fn); return on(uri, method, handler); } PsychicEndpoint* PsychicHttpServer::on(const char* uri, PsychicJsonRequestCallback fn) { return on(uri, HTTP_GET, fn); } PsychicEndpoint* PsychicHttpServer::on(const char* uri, http_method method, PsychicJsonRequestCallback fn) { //these basic requests need a basic web handler PsychicJsonHandler *handler = new PsychicJsonHandler(); handler->onRequest(fn); return on(uri, method, handler); } void PsychicHttpServer::onNotFound(PsychicHttpRequestCallback fn) { PsychicWebHandler *handler = new PsychicWebHandler(); handler->onRequest(fn == nullptr ? PsychicHttpServer::defaultNotFoundHandler : fn); this->defaultEndpoint->setHandler(handler); } esp_err_t PsychicHttpServer::notFoundHandler(httpd_req_t *req, httpd_err_code_t err) { PsychicHttpServer *server = (PsychicHttpServer*)httpd_get_global_user_ctx(req->handle); PsychicRequest request(server, req); //loop through our global handlers and see if anyone wants it for(auto *handler: server->_handlers) { //are we capable of handling this? if (handler->filter(&request) && handler->canHandle(&request)) { //check our credentials if (handler->needsAuthentication(&request)) return handler->authenticate(&request); else return handler->handleRequest(&request); } } //nothing found, give it to our defaultEndpoint PsychicHandler *handler = server->defaultEndpoint->handler(); if (handler->filter(&request) && handler->canHandle(&request)) return handler->handleRequest(&request); //not sure how we got this far. return ESP_ERR_HTTPD_INVALID_REQ; } esp_err_t PsychicHttpServer::defaultNotFoundHandler(PsychicRequest *request) { request->reply(404, "text/html", "That URI does not exist."); return ESP_OK; } void PsychicHttpServer::onOpen(PsychicClientCallback handler) { this->_onOpen = handler; } esp_err_t PsychicHttpServer::openCallback(httpd_handle_t hd, int sockfd) { ESP_LOGD(PH_TAG, "New client connected %d", sockfd); //get our global server reference PsychicHttpServer *server = (PsychicHttpServer*)httpd_get_global_user_ctx(hd); //lookup our client PsychicClient *client = server->getClient(sockfd); if (client == NULL) { client = new PsychicClient(hd, sockfd); server->addClient(client); } //user callback if (server->_onOpen != NULL) server->_onOpen(client); return ESP_OK; } void PsychicHttpServer::onClose(PsychicClientCallback handler) { this->_onClose = handler; } void PsychicHttpServer::closeCallback(httpd_handle_t hd, int sockfd) { ESP_LOGD(PH_TAG, "Client disconnected %d", sockfd); PsychicHttpServer *server = (PsychicHttpServer*)httpd_get_global_user_ctx(hd); //lookup our client PsychicClient *client = server->getClient(sockfd); if (client != NULL) { //give our handlers a chance to handle a disconnect first for (PsychicEndpoint * endpoint : server->_endpoints) { PsychicHandler *handler = endpoint->handler(); handler->checkForClosedClient(client); } //do we have a callback attached? if (server->_onClose != NULL) server->_onClose(client); //remove it from our list server->removeClient(client); } else ESP_LOGE(PH_TAG, "No client record %d", sockfd); //finally close it out. close(sockfd); } PsychicStaticFileHandler* PsychicHttpServer::serveStatic(const char* uri, fs::FS& fs, const char* path, const char* cache_control) { PsychicStaticFileHandler* handler = new PsychicStaticFileHandler(uri, fs, path, cache_control); this->addHandler(handler); return handler; } void PsychicHttpServer::addClient(PsychicClient *client) { _clients.push_back(client); } void PsychicHttpServer::removeClient(PsychicClient *client) { _clients.remove(client); delete client; } PsychicClient * PsychicHttpServer::getClient(int socket) { for (PsychicClient * client : _clients) if (client->socket() == socket) return client; return NULL; } PsychicClient * PsychicHttpServer::getClient(httpd_req_t *req) { return getClient(httpd_req_to_sockfd(req)); } bool PsychicHttpServer::hasClient(int socket) { return getClient(socket) != NULL; } const std::list& PsychicHttpServer::getClientList() { return _clients; } bool ON_STA_FILTER(PsychicRequest *request) { return WiFi.localIP() == request->client()->localIP(); } bool ON_AP_FILTER(PsychicRequest *request) { return WiFi.softAPIP() == request->client()->localIP(); } String urlDecode(const char* encoded) { size_t length = strlen(encoded); char* decoded = (char*)malloc(length + 1); if (!decoded) { return ""; } size_t i, j = 0; for (i = 0; i < length; ++i) { if (encoded[i] == '%' && isxdigit(encoded[i + 1]) && isxdigit(encoded[i + 2])) { // Valid percent-encoded sequence int hex; sscanf(encoded + i + 1, "%2x", &hex); decoded[j++] = (char)hex; i += 2; // Skip the two hexadecimal characters } else if (encoded[i] == '+') { // Convert '+' to space decoded[j++] = ' '; } else { // Copy other characters as they are decoded[j++] = encoded[i]; } } decoded[j] = '\0'; // Null-terminate the decoded string String output(decoded); free(decoded); return output; } ================================================ FILE: lib/PsychicHttp/src/PsychicHttpServer.h ================================================ #ifndef PsychicHttpServer_h #define PsychicHttpServer_h #include "PsychicCore.h" #include "PsychicClient.h" #include "PsychicHandler.h" class PsychicEndpoint; class PsychicHandler; class PsychicStaticFileHandler; class PsychicHttpServer { protected: bool _use_ssl = false; std::list _endpoints; std::list _handlers; std::list _clients; PsychicClientCallback _onOpen; PsychicClientCallback _onClose; esp_err_t _start(); virtual esp_err_t _startServer(); public: PsychicHttpServer(); virtual ~PsychicHttpServer(); //esp-idf specific stuff httpd_handle_t server; httpd_config_t config; //some limits on what we will accept unsigned long maxUploadSize; unsigned long maxRequestBodySize; PsychicEndpoint *defaultEndpoint; static void destroy(void *ctx); esp_err_t listen(uint16_t port); virtual void stop(); PsychicHandler& addHandler(PsychicHandler* handler); void removeHandler(PsychicHandler* handler); void addClient(PsychicClient *client); void removeClient(PsychicClient *client); PsychicClient* getClient(int socket); PsychicClient* getClient(httpd_req_t *req); bool hasClient(int socket); int count() { return _clients.size(); }; const std::list& getClientList(); PsychicEndpoint* on(const char* uri); PsychicEndpoint* on(const char* uri, http_method method); PsychicEndpoint* on(const char* uri, PsychicHandler *handler); PsychicEndpoint* on(const char* uri, http_method method, PsychicHandler *handler); PsychicEndpoint* on(const char* uri, PsychicHttpRequestCallback onRequest); PsychicEndpoint* on(const char* uri, http_method method, PsychicHttpRequestCallback onRequest); PsychicEndpoint* on(const char* uri, PsychicJsonRequestCallback onRequest); PsychicEndpoint* on(const char* uri, http_method method, PsychicJsonRequestCallback onRequest); static esp_err_t notFoundHandler(httpd_req_t *req, httpd_err_code_t err); static esp_err_t defaultNotFoundHandler(PsychicRequest *request); void onNotFound(PsychicHttpRequestCallback fn); void onOpen(PsychicClientCallback handler); void onClose(PsychicClientCallback handler); static esp_err_t openCallback(httpd_handle_t hd, int sockfd); static void closeCallback(httpd_handle_t hd, int sockfd); PsychicStaticFileHandler* serveStatic(const char* uri, fs::FS& fs, const char* path, const char* cache_control = NULL); }; bool ON_STA_FILTER(PsychicRequest *request); bool ON_AP_FILTER(PsychicRequest *request); #endif // PsychicHttpServer_h ================================================ FILE: lib/PsychicHttp/src/PsychicHttpsServer.cpp ================================================ #include "PsychicHttpsServer.h" #ifdef CONFIG_ESP_HTTPS_SERVER_ENABLE PsychicHttpsServer::PsychicHttpsServer() : PsychicHttpServer() { //for a SSL server ssl_config = HTTPD_SSL_CONFIG_DEFAULT(); ssl_config.httpd.open_fn = PsychicHttpServer::openCallback; ssl_config.httpd.close_fn = PsychicHttpServer::closeCallback; ssl_config.httpd.uri_match_fn = httpd_uri_match_wildcard; ssl_config.httpd.global_user_ctx = this; ssl_config.httpd.global_user_ctx_free_fn = destroy; ssl_config.httpd.max_uri_handlers = 20; // each SSL connection takes about 45kb of heap // a barebones sketch with PsychicHttp has ~150kb of heap available // if we set it higher than 2 and use all the connections, we get lots of memory errors. // not to mention there is no heap left over for the program itself. ssl_config.httpd.max_open_sockets = 2; } PsychicHttpsServer::~PsychicHttpsServer() {} esp_err_t PsychicHttpsServer::listen(uint16_t port, const char *cert, const char *private_key) { this->_use_ssl = true; this->ssl_config.port_secure = port; #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 2) this->ssl_config.servercert = (uint8_t *)cert; this->ssl_config.servercert_len = strlen(cert)+1; #else this->ssl_config.cacert_pem = (uint8_t *)cert; this->ssl_config.cacert_len = strlen(cert)+1; #endif this->ssl_config.prvtkey_pem = (uint8_t *)private_key; this->ssl_config.prvtkey_len = strlen(private_key)+1; return this->_start(); } esp_err_t PsychicHttpsServer::_startServer() { if (this->_use_ssl) return httpd_ssl_start(&this->server, &this->ssl_config); else return httpd_start(&this->server, &this->config); } void PsychicHttpsServer::stop() { if (this->_use_ssl) httpd_ssl_stop(this->server); else httpd_stop(this->server); } #endif // CONFIG_ESP_HTTPS_SERVER_ENABLE ================================================ FILE: lib/PsychicHttp/src/PsychicHttpsServer.h ================================================ #ifndef PsychicHttpsServer_h #define PsychicHttpsServer_h #include #ifdef CONFIG_ESP_HTTPS_SERVER_ENABLE #include "PsychicCore.h" #include "PsychicHttpServer.h" #include #if !CONFIG_HTTPD_WS_SUPPORT #error PsychicHttpsServer cannot be used unless HTTPD_WS_SUPPORT is enabled in esp-http-server component configuration #endif #define PSY_ENABLE_SSL //you can use this define in your code to enable/disable these features class PsychicHttpsServer : public PsychicHttpServer { protected: bool _use_ssl = false; public: PsychicHttpsServer(); ~PsychicHttpsServer(); httpd_ssl_config_t ssl_config; using PsychicHttpServer::listen; //keep the regular version esp_err_t listen(uint16_t port, const char *cert, const char *private_key); virtual esp_err_t _startServer() override final; virtual void stop() override final; }; #endif // PsychicHttpsServer_h #else #error ESP-IDF https server support not enabled. #endif // CONFIG_ESP_HTTPS_SERVER_ENABLE ================================================ FILE: lib/PsychicHttp/src/PsychicJson.cpp ================================================ #include "PsychicJson.h" #ifdef ARDUINOJSON_6_COMPATIBILITY PsychicJsonResponse::PsychicJsonResponse(PsychicRequest *request, bool isArray, size_t maxJsonBufferSize) : PsychicResponse(request), _jsonBuffer(maxJsonBufferSize) { setContentType(JSON_MIMETYPE); if (isArray) _root = _jsonBuffer.createNestedArray(); else _root = _jsonBuffer.createNestedObject(); } #else PsychicJsonResponse::PsychicJsonResponse(PsychicRequest *request, bool isArray) : PsychicResponse(request) { setContentType(JSON_MIMETYPE); if (isArray) _root = _jsonBuffer.add(); else _root = _jsonBuffer.add(); } #endif JsonVariant &PsychicJsonResponse::getRoot() { return _root; } size_t PsychicJsonResponse::getLength() { return measureJson(_root); } esp_err_t PsychicJsonResponse::send() { esp_err_t err = ESP_OK; size_t length = getLength(); size_t buffer_size; char *buffer; //how big of a buffer do we want? if (length < JSON_BUFFER_SIZE) buffer_size = length+1; else buffer_size = JSON_BUFFER_SIZE; buffer = (char *)malloc(buffer_size); if (buffer == NULL) { httpd_resp_send_err(this->_request->request(), HTTPD_500_INTERNAL_SERVER_ERROR, "Unable to allocate memory."); return ESP_FAIL; } //send it in one shot or no? if (length < JSON_BUFFER_SIZE) { serializeJson(_root, buffer, buffer_size); this->setContent((uint8_t *)buffer, length); this->setContentType(JSON_MIMETYPE); err = PsychicResponse::send(); } else { //helper class that acts as a stream to print chunked responses ChunkPrinter dest(this, (uint8_t *)buffer, buffer_size); //keep our headers this->sendHeaders(); serializeJson(_root, dest); //send the last bits dest.flush(); //done with our chunked response too err = this->finishChunking(); } //let the buffer go free(buffer); return err; } #ifdef ARDUINOJSON_6_COMPATIBILITY PsychicJsonHandler::PsychicJsonHandler(size_t maxJsonBufferSize) : _onRequest(NULL), _maxJsonBufferSize(maxJsonBufferSize) {}; PsychicJsonHandler::PsychicJsonHandler(PsychicJsonRequestCallback onRequest, size_t maxJsonBufferSize) : _onRequest(onRequest), _maxJsonBufferSize(maxJsonBufferSize) {} #else PsychicJsonHandler::PsychicJsonHandler() : _onRequest(NULL) {}; PsychicJsonHandler::PsychicJsonHandler(PsychicJsonRequestCallback onRequest) : _onRequest(onRequest) {} #endif void PsychicJsonHandler::onRequest(PsychicJsonRequestCallback fn) { _onRequest = fn; } esp_err_t PsychicJsonHandler::handleRequest(PsychicRequest *request) { //process basic stuff PsychicWebHandler::handleRequest(request); if (_onRequest) { #ifdef ARDUINOJSON_6_COMPATIBILITY DynamicJsonDocument jsonBuffer(this->_maxJsonBufferSize); DeserializationError error = deserializeJson(jsonBuffer, request->body()); if (error) return request->reply(400); JsonVariant json = jsonBuffer.as(); #else JsonDocument jsonBuffer; DeserializationError error = deserializeJson(jsonBuffer, request->body()); if (error) return request->reply(400); JsonVariant json = jsonBuffer.as(); #endif return _onRequest(request, json); } else return request->reply(500); } ================================================ FILE: lib/PsychicHttp/src/PsychicJson.h ================================================ // PsychicJson.h /* Async Response to use with ArduinoJson and AsyncWebServer Written by Andrew Melvin (SticilFace) with help from me-no-dev and BBlanchon. Ported to PsychicHttp by Zach Hoeken */ #ifndef PSYCHIC_JSON_H_ #define PSYCHIC_JSON_H_ #include "PsychicRequest.h" #include "PsychicWebHandler.h" #include "ChunkPrinter.h" #include #if ARDUINOJSON_VERSION_MAJOR == 6 #define ARDUINOJSON_6_COMPATIBILITY #ifndef DYNAMIC_JSON_DOCUMENT_SIZE #define DYNAMIC_JSON_DOCUMENT_SIZE 4096 #endif #endif #ifndef JSON_BUFFER_SIZE #define JSON_BUFFER_SIZE 4*1024 #endif constexpr const char *JSON_MIMETYPE = "application/json"; /* * Json Response * */ class PsychicJsonResponse : public PsychicResponse { protected: #ifdef ARDUINOJSON_5_COMPATIBILITY DynamicJsonBuffer _jsonBuffer; #elif ARDUINOJSON_VERSION_MAJOR == 6 DynamicJsonDocument _jsonBuffer; #else JsonDocument _jsonBuffer; #endif JsonVariant _root; size_t _contentLength; public: #ifdef ARDUINOJSON_5_COMPATIBILITY PsychicJsonResponse(PsychicRequest *request, bool isArray = false); #elif ARDUINOJSON_VERSION_MAJOR == 6 PsychicJsonResponse(PsychicRequest *request, bool isArray = false, size_t maxJsonBufferSize = DYNAMIC_JSON_DOCUMENT_SIZE); #else PsychicJsonResponse(PsychicRequest *request, bool isArray = false); #endif ~PsychicJsonResponse() {} JsonVariant &getRoot(); size_t getLength(); virtual esp_err_t send() override; }; class PsychicJsonHandler : public PsychicWebHandler { protected: PsychicJsonRequestCallback _onRequest; #if ARDUINOJSON_VERSION_MAJOR == 6 const size_t _maxJsonBufferSize = DYNAMIC_JSON_DOCUMENT_SIZE; #endif public: #ifdef ARDUINOJSON_5_COMPATIBILITY PsychicJsonHandler(); PsychicJsonHandler(PsychicJsonRequestCallback onRequest); #elif ARDUINOJSON_VERSION_MAJOR == 6 PsychicJsonHandler(size_t maxJsonBufferSize = DYNAMIC_JSON_DOCUMENT_SIZE); PsychicJsonHandler(PsychicJsonRequestCallback onRequest, size_t maxJsonBufferSize = DYNAMIC_JSON_DOCUMENT_SIZE); #else PsychicJsonHandler(); PsychicJsonHandler(PsychicJsonRequestCallback onRequest); #endif void onRequest(PsychicJsonRequestCallback fn); virtual esp_err_t handleRequest(PsychicRequest *request) override; }; #endif ================================================ FILE: lib/PsychicHttp/src/PsychicRequest.cpp ================================================ #include "PsychicRequest.h" #include "http_status.h" #include "PsychicHttpServer.h" PsychicRequest::PsychicRequest(PsychicHttpServer *server, httpd_req_t *req) : _server(server), _req(req), _method(HTTP_GET), _query(""), _body(""), _tempObject(NULL) { // load up our client. this->_client = server->getClient(req); // handle our session data if (req->sess_ctx != NULL) this->_session = (SessionData *)req->sess_ctx; else { this->_session = new SessionData(); req->sess_ctx = this->_session; } // callback for freeing the session later req->free_ctx = this->freeSession; // load up some data this->_uri = String(this->_req->uri); } PsychicRequest::~PsychicRequest() { // temorary user object if (_tempObject != NULL) free(_tempObject); // our web parameters for (auto *param : _params) delete (param); _params.clear(); } void PsychicRequest::freeSession(void *ctx) { if (ctx != NULL) { SessionData *session = (SessionData *)ctx; delete session; } } PsychicHttpServer *PsychicRequest::server() { return _server; } httpd_req_t *PsychicRequest::request() { return _req; } PsychicClient *PsychicRequest::client() { return _client; } const String PsychicRequest::getFilename() { // parse the content-disposition header if (this->hasHeader("Content-Disposition")) { ContentDisposition cd = this->getContentDisposition(); if (cd.filename != "") return cd.filename; } // fall back to passed in query string PsychicWebParameter *param = getParam("_filename"); if (param != NULL) return param->name(); // fall back to parsing it from url (useful for wildcard uploads) String uri = this->uri(); int filenameStart = uri.lastIndexOf('/') + 1; String filename = uri.substring(filenameStart); if (filename != "") return filename; // finally, unknown. ESP_LOGE(PH_TAG, "Did not get a valid filename from the upload."); return "unknown.txt"; } const ContentDisposition PsychicRequest::getContentDisposition() { ContentDisposition cd; String header = this->header("Content-Disposition"); int start; int end; if (header.indexOf("form-data") == 0) cd.disposition = FORM_DATA; else if (header.indexOf("attachment") == 0) cd.disposition = ATTACHMENT; else if (header.indexOf("inline") == 0) cd.disposition = INLINE; else cd.disposition = NONE; start = header.indexOf("filename="); if (start) { end = header.indexOf('"', start + 10); cd.filename = header.substring(start + 10, end - 1); } start = header.indexOf("name="); if (start) { end = header.indexOf('"', start + 6); cd.name = header.substring(start + 6, end - 1); } return cd; } esp_err_t PsychicRequest::loadBody() { esp_err_t err = ESP_OK; this->_body = String(); size_t remaining = this->_req->content_len; size_t actuallyReceived = 0; char *buf = (char *)malloc(remaining + 1); if (buf == NULL) { ESP_LOGE(PH_TAG, "Failed to allocate memory for body"); return ESP_FAIL; } while (remaining > 0) { int received = httpd_req_recv(this->_req, buf + actuallyReceived, remaining); if (received == HTTPD_SOCK_ERR_TIMEOUT) { continue; } else if (received == HTTPD_SOCK_ERR_FAIL) { ESP_LOGE(PH_TAG, "Failed to receive data."); err = ESP_FAIL; break; } remaining -= received; actuallyReceived += received; } buf[actuallyReceived] = '\0'; this->_body = String(buf); free(buf); return err; } http_method PsychicRequest::method() { return (http_method)this->_req->method; } const String PsychicRequest::methodStr() { return String(http_method_str((http_method)this->_req->method)); } const String PsychicRequest::path() { int index = _uri.indexOf("?"); if (index == -1) return _uri; else return _uri.substring(0, index); } const String &PsychicRequest::uri() { return this->_uri; } const String &PsychicRequest::query() { return this->_query; } // no way to get list of headers yet.... // int PsychicRequest::headers() // { // } const String PsychicRequest::header(const char *name) { size_t header_len = httpd_req_get_hdr_value_len(this->_req, name); // if we've got one, allocated it and load it if (header_len) { char header[header_len + 1]; httpd_req_get_hdr_value_str(this->_req, name, header, sizeof(header)); return String(header); } else return ""; } bool PsychicRequest::hasHeader(const char *name) { return httpd_req_get_hdr_value_len(this->_req, name) > 0; } const String PsychicRequest::host() { return this->header("Host"); } const String PsychicRequest::contentType() { return header("Content-Type"); } size_t PsychicRequest::contentLength() { return this->_req->content_len; } const String &PsychicRequest::body() { return this->_body; } bool PsychicRequest::isMultipart() { const String &type = this->contentType(); return (this->contentType().indexOf("multipart/form-data") >= 0); } esp_err_t PsychicRequest::redirect(const char *url) { PsychicResponse response(this); response.setCode(301); response.addHeader("Location", url); return response.send(); } bool PsychicRequest::hasCookie(const char *key) { char cookie[MAX_COOKIE_SIZE]; size_t cookieSize = MAX_COOKIE_SIZE; esp_err_t err = httpd_req_get_cookie_val(this->_req, key, cookie, &cookieSize); // did we get anything? if (err == ESP_OK) return true; else if (err == ESP_ERR_HTTPD_RESULT_TRUNC) ESP_LOGE(PH_TAG, "cookie too large (%d bytes).\n", cookieSize); return false; } const String PsychicRequest::getCookie(const char *key) { char cookie[MAX_COOKIE_SIZE]; size_t cookieSize = MAX_COOKIE_SIZE; esp_err_t err = httpd_req_get_cookie_val(this->_req, key, cookie, &cookieSize); // did we get anything? if (err == ESP_OK) return String(cookie); else return ""; } void PsychicRequest::loadParams() { // did we get a query string? size_t query_len = httpd_req_get_url_query_len(_req); if (query_len) { char query[query_len + 1]; httpd_req_get_url_query_str(_req, query, sizeof(query)); _query.clear(); _query.concat(query); // parse them. _addParams(_query, false); } // did we get form data as body? if (this->method() == HTTP_POST && this->contentType().startsWith("application/x-www-form-urlencoded")) { _addParams(_body, true); } } void PsychicRequest::_addParams(const String ¶ms, bool post) { size_t start = 0; while (start < params.length()) { int end = params.indexOf('&', start); if (end < 0) end = params.length(); int equal = params.indexOf('=', start); if (equal < 0 || equal > end) equal = end; String name = params.substring(start, equal); String value = equal + 1 < end ? params.substring(equal + 1, end) : String(); addParam(name, value, true, post); start = end + 1; } } PsychicWebParameter *PsychicRequest::addParam(const String &name, const String &value, bool decode, bool post) { if (decode) return addParam(new PsychicWebParameter(urlDecode(name.c_str()), urlDecode(value.c_str()), post)); else return addParam(new PsychicWebParameter(name, value, post)); } PsychicWebParameter *PsychicRequest::addParam(PsychicWebParameter *param) { // ESP_LOGD(PH_TAG, "Adding param: '%s' = '%s'", param->name().c_str(), param->value().c_str()); _params.push_back(param); return param; } bool PsychicRequest::hasParam(const char *key) { return getParam(key) != NULL; } PsychicWebParameter *PsychicRequest::getParam(const char *key) { for (auto *param : _params) if (param->name().equals(key)) return param; return NULL; } bool PsychicRequest::hasSessionKey(const String &key) { return this->_session->find(key) != this->_session->end(); } const String PsychicRequest::getSessionKey(const String &key) { auto it = this->_session->find(key); if (it != this->_session->end()) return it->second; else return ""; } void PsychicRequest::setSessionKey(const String &key, const String &value) { this->_session->insert(std::pair(key, value)); } static const String md5str(const String &in) { MD5Builder md5 = MD5Builder(); md5.begin(); md5.add(in); md5.calculate(); return md5.toString(); } bool PsychicRequest::authenticate(const char *username, const char *password) { if (hasHeader("Authorization")) { String authReq = header("Authorization"); if (authReq.startsWith("Basic")) { authReq = authReq.substring(6); authReq.trim(); char toencodeLen = strlen(username) + strlen(password) + 1; char *toencode = new char[toencodeLen + 1]; if (toencode == NULL) { authReq = ""; return false; } char *encoded = new char[base64_encode_expected_len(toencodeLen) + 1]; if (encoded == NULL) { authReq = ""; delete[] toencode; return false; } sprintf(toencode, "%s:%s", username, password); if (base64_encode_chars(toencode, toencodeLen, encoded) > 0 && authReq.equalsConstantTime(encoded)) { authReq = ""; delete[] toencode; delete[] encoded; return true; } delete[] toencode; delete[] encoded; } else if (authReq.startsWith(F("Digest"))) { authReq = authReq.substring(7); String _username = _extractParam(authReq, F("username=\""), '\"'); if (!_username.length() || _username != String(username)) { authReq = ""; return false; } // extracting required parameters for RFC 2069 simpler Digest String _realm = _extractParam(authReq, F("realm=\""), '\"'); String _nonce = _extractParam(authReq, F("nonce=\""), '\"'); String _uri = _extractParam(authReq, F("uri=\""), '\"'); String _resp = _extractParam(authReq, F("response=\""), '\"'); String _opaque = _extractParam(authReq, F("opaque=\""), '\"'); if ((!_realm.length()) || (!_nonce.length()) || (!_uri.length()) || (!_resp.length()) || (!_opaque.length())) { authReq = ""; return false; } if ((_opaque != this->getSessionKey("opaque")) || (_nonce != this->getSessionKey("nonce")) || (_realm != this->getSessionKey("realm"))) { authReq = ""; return false; } // parameters for the RFC 2617 newer Digest String _nc, _cnonce; if (authReq.indexOf("qop=auth") != -1 || authReq.indexOf("qop=\"auth\"") != -1) { _nc = _extractParam(authReq, F("nc="), ','); _cnonce = _extractParam(authReq, F("cnonce=\""), '\"'); } String _H1 = md5str(String(username) + ':' + _realm + ':' + String(password)); // ESP_LOGD(PH_TAG, "Hash of user:realm:pass=%s", _H1.c_str()); String _H2 = ""; if (_method == HTTP_GET) { _H2 = md5str(String(F("GET:")) + _uri); } else if (_method == HTTP_POST) { _H2 = md5str(String(F("POST:")) + _uri); } else if (_method == HTTP_PUT) { _H2 = md5str(String(F("PUT:")) + _uri); } else if (_method == HTTP_DELETE) { _H2 = md5str(String(F("DELETE:")) + _uri); } else { _H2 = md5str(String(F("GET:")) + _uri); } // ESP_LOGD(PH_TAG, "Hash of GET:uri=%s", _H2.c_str()); String _responsecheck = ""; if (authReq.indexOf("qop=auth") != -1 || authReq.indexOf("qop=\"auth\"") != -1) { _responsecheck = md5str(_H1 + ':' + _nonce + ':' + _nc + ':' + _cnonce + F(":auth:") + _H2); } else { _responsecheck = md5str(_H1 + ':' + _nonce + ':' + _H2); } // ESP_LOGD(PH_TAG, "The Proper response=%s", _responsecheck.c_str()); if (_resp == _responsecheck) { authReq = ""; return true; } } authReq = ""; } return false; } const String PsychicRequest::_extractParam(const String &authReq, const String ¶m, const char delimit) { int _begin = authReq.indexOf(param); if (_begin == -1) return ""; return authReq.substring(_begin + param.length(), authReq.indexOf(delimit, _begin + param.length())); } const String PsychicRequest::_getRandomHexString() { char buffer[33]; // buffer to hold 32 Hex Digit + /0 int i; for (i = 0; i < 4; i++) { sprintf(buffer + (i * 8), "%08lx", (unsigned long int)esp_random()); } return String(buffer); } esp_err_t PsychicRequest::requestAuthentication(HTTPAuthMethod mode, const char *realm, const char *authFailMsg) { // what is thy realm, sire? if (!strcmp(realm, "")) this->setSessionKey("realm", "Login Required"); else this->setSessionKey("realm", realm); PsychicResponse response(this); String authStr; // what kind of auth? if (mode == BASIC_AUTH) { authStr = "Basic realm=\"" + this->getSessionKey("realm") + "\""; response.addHeader("WWW-Authenticate", authStr.c_str()); } else { // only make new ones if we havent sent them yet if (this->getSessionKey("nonce").isEmpty()) this->setSessionKey("nonce", _getRandomHexString()); if (this->getSessionKey("opaque").isEmpty()) this->setSessionKey("opaque", _getRandomHexString()); authStr = "Digest realm=\"" + this->getSessionKey("realm") + "\", qop=\"auth\", nonce=\"" + this->getSessionKey("nonce") + "\", opaque=\"" + this->getSessionKey("opaque") + "\""; response.addHeader("WWW-Authenticate", authStr.c_str()); } response.setCode(401); response.setContentType("text/html"); response.setContent(authStr.c_str()); return response.send(); } esp_err_t PsychicRequest::reply(int code) { PsychicResponse response(this); response.setCode(code); response.setContentType("text/plain"); response.setContent(http_status_reason(code)); return response.send(); } esp_err_t PsychicRequest::reply(const char *content) { PsychicResponse response(this); response.setCode(200); response.setContentType("text/html"); response.setContent(content); return response.send(); } esp_err_t PsychicRequest::reply(int code, const char *contentType, const char *content) { PsychicResponse response(this); response.setCode(code); response.setContentType(contentType); response.setContent(content); return response.send(); } ================================================ FILE: lib/PsychicHttp/src/PsychicRequest.h ================================================ #ifndef PsychicRequest_h #define PsychicRequest_h #include "PsychicCore.h" #include "PsychicHttpServer.h" #include "PsychicClient.h" #include "PsychicWebParameter.h" #include "PsychicResponse.h" typedef std::map SessionData; enum Disposition { NONE, INLINE, ATTACHMENT, FORM_DATA}; struct ContentDisposition { Disposition disposition; String filename; String name; }; class PsychicRequest { friend PsychicHttpServer; protected: PsychicHttpServer *_server; httpd_req_t *_req; SessionData *_session; PsychicClient *_client; http_method _method; String _uri; String _query; String _body; std::list _params; void _addParams(const String& params, bool post); void _parseGETParams(); void _parsePOSTParams(); const String _extractParam(const String& authReq, const String& param, const char delimit); const String _getRandomHexString(); public: PsychicRequest(PsychicHttpServer *server, httpd_req_t *req); virtual ~PsychicRequest(); void *_tempObject; PsychicHttpServer * server(); httpd_req_t * request(); virtual PsychicClient * client(); bool isMultipart(); esp_err_t loadBody(); const String header(const char *name); bool hasHeader(const char *name); static void freeSession(void *ctx); bool hasSessionKey(const String& key); const String getSessionKey(const String& key); void setSessionKey(const String& key, const String& value); bool hasCookie(const char * key); const String getCookie(const char * key); http_method method(); // returns the HTTP method used as enum value (eg. HTTP_GET) const String methodStr(); // returns the HTTP method used as a string (eg. "GET") const String path(); // returns the request path (eg /page?foo=bar returns "/page") const String& uri(); // returns the full request uri (eg /page?foo=bar) const String& query(); // returns the request query data (eg /page?foo=bar returns "foo=bar") const String host(); // returns the requested host (request to http://psychic.local/foo will return "psychic.local") const String contentType(); // returns the Content-Type header value size_t contentLength(); // returns the Content-Length header value const String& body(); // returns the body of the request const ContentDisposition getContentDisposition(); const String& queryString() { return query(); } //compatability function. same as query() const String& url() { return uri(); } //compatability function. same as uri() void loadParams(); PsychicWebParameter * addParam(PsychicWebParameter *param); PsychicWebParameter * addParam(const String &name, const String &value, bool decode = true, bool post = false); bool hasParam(const char *key); PsychicWebParameter * getParam(const char *name); const String getFilename(); bool authenticate(const char * username, const char * password); esp_err_t requestAuthentication(HTTPAuthMethod mode, const char* realm, const char* authFailMsg); esp_err_t redirect(const char *url); esp_err_t reply(int code); esp_err_t reply(const char *content); esp_err_t reply(int code, const char *contentType, const char *content); }; #endif // PsychicRequest_h ================================================ FILE: lib/PsychicHttp/src/PsychicResponse.cpp ================================================ #include "PsychicResponse.h" #include "PsychicRequest.h" #include PsychicResponse::PsychicResponse(PsychicRequest *request) : _request(request), _code(200), _status(""), _contentLength(0), _body("") { } PsychicResponse::~PsychicResponse() { //clean up our header variables. we have to do this on desctruct since httpd_resp_send doesn't store copies for (HTTPHeader header : _headers) { free(header.field); free(header.value); } _headers.clear(); } void PsychicResponse::addHeader(const char *field, const char *value) { //these get freed after send by the destructor HTTPHeader header; header.field =(char *)malloc(strlen(field)+1); header.value = (char *)malloc(strlen(value)+1); strlcpy(header.field, field, strlen(field)+1); strlcpy(header.value, value, strlen(value)+1); _headers.push_back(header); } void PsychicResponse::setCookie(const char *name, const char *value, unsigned long secondsFromNow, const char *extras) { time_t now = time(nullptr); String output; output = urlEncode(name) + "=" + urlEncode(value); //if current time isn't modern, default to using max age if (now < 1700000000) output += "; Max-Age=" + String(secondsFromNow); //otherwise, set an expiration date else { time_t expirationTimestamp = now + secondsFromNow; // Convert the expiration timestamp to a formatted string for the "expires" attribute struct tm* tmInfo = gmtime(&expirationTimestamp); char expires[30]; strftime(expires, sizeof(expires), "%a, %d %b %Y %H:%M:%S GMT", tmInfo); output += "; Expires=" + String(expires); } //did we get any extras? if (strlen(extras)) output += "; " + String(extras); //okay, add it in. addHeader("Set-Cookie", output.c_str()); } void PsychicResponse::setCode(int code) { _code = code; } void PsychicResponse::setContentType(const char *contentType) { httpd_resp_set_type(_request->request(), contentType); } void PsychicResponse::setContent(const char *content) { _body = content; setContentLength(strlen(content)); } void PsychicResponse::setContent(const uint8_t *content, size_t len) { _body = (char *)content; setContentLength(len); } const char * PsychicResponse::getContent() { return _body; } size_t PsychicResponse::getContentLength() { return _contentLength; } esp_err_t PsychicResponse::send() { //esp-idf makes you set the whole status. sprintf(_status, "%u %s", _code, http_status_reason(_code)); httpd_resp_set_status(_request->request(), _status); //our headers too this->sendHeaders(); //now send it off esp_err_t err = httpd_resp_send(_request->request(), getContent(), getContentLength()); //did something happen? if (err != ESP_OK) ESP_LOGE(PH_TAG, "Send response failed (%s)", esp_err_to_name(err)); return err; } void PsychicResponse::sendHeaders() { //get our global headers out of the way first for (HTTPHeader header : DefaultHeaders::Instance().getHeaders()) httpd_resp_set_hdr(_request->request(), header.field, header.value); //now do our individual headers for (HTTPHeader header : _headers) httpd_resp_set_hdr(this->_request->request(), header.field, header.value); // DO NOT RELEASE HEADERS HERE... released in the PsychicResponse destructor after they have been sent. // httpd_resp_set_hdr just passes on the pointer, but its needed after this call. // clean up our header variables after send // for (HTTPHeader header : _headers) // { // free(header.field); // free(header.value); // } // _headers.clear(); } esp_err_t PsychicResponse::sendChunk(uint8_t *chunk, size_t chunksize) { /* Send the buffer contents as HTTP response chunk */ esp_err_t err = httpd_resp_send_chunk(this->_request->request(), (char *)chunk, chunksize); if (err != ESP_OK) { ESP_LOGE(PH_TAG, "File sending failed (%s)", esp_err_to_name(err)); /* Abort sending file */ httpd_resp_sendstr_chunk(this->_request->request(), NULL); /* Respond with 500 Internal Server Error */ httpd_resp_send_err(this->_request->request(), HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to send file"); } return err; } esp_err_t PsychicResponse::finishChunking() { /* Respond with an empty chunk to signal HTTP response completion */ return httpd_resp_send_chunk(this->_request->request(), NULL, 0); } ================================================ FILE: lib/PsychicHttp/src/PsychicResponse.h ================================================ #ifndef PsychicResponse_h #define PsychicResponse_h #include "PsychicCore.h" #include "time.h" class PsychicRequest; class PsychicResponse { protected: PsychicRequest *_request; int _code; char _status[60]; std::list _headers; int64_t _contentLength; const char * _body; public: PsychicResponse(PsychicRequest *request); virtual ~PsychicResponse(); void setCode(int code); void setContentType(const char *contentType); void setContentLength(int64_t contentLength) { _contentLength = contentLength; } int64_t getContentLength(int64_t contentLength) { return _contentLength; } void addHeader(const char *field, const char *value); void setCookie(const char *key, const char *value, unsigned long max_age = 60*60*24*30, const char *extras = ""); void setContent(const char *content); void setContent(const uint8_t *content, size_t len); const char * getContent(); size_t getContentLength(); virtual esp_err_t send(); void sendHeaders(); esp_err_t sendChunk(uint8_t *chunk, size_t chunksize); esp_err_t finishChunking(); }; #endif // PsychicResponse_h ================================================ FILE: lib/PsychicHttp/src/PsychicStaticFileHander.cpp ================================================ #include "PsychicStaticFileHandler.h" /*************************************/ /* PsychicStaticFileHandler */ /*************************************/ PsychicStaticFileHandler::PsychicStaticFileHandler(const char *uri, FS &fs, const char *path, const char *cache_control) : _fs(fs), _uri(uri), _path(path), _default_file("index.html"), _cache_control(cache_control), _last_modified("") { // Ensure leading '/' if (_uri.length() == 0 || _uri[0] != '/') _uri = "/" + _uri; if (_path.length() == 0 || _path[0] != '/') _path = "/" + _path; // If path ends with '/' we assume a hint that this is a directory to improve performance. // However - if it does not end with '/' we, can't assume a file, path can still be a directory. _isDir = _path[_path.length() - 1] == '/'; // Remove the trailing '/' so we can handle default file // Notice that root will be "" not "/" if (_uri[_uri.length() - 1] == '/') _uri = _uri.substring(0, _uri.length() - 1); if (_path[_path.length() - 1] == '/') _path = _path.substring(0, _path.length() - 1); // Reset stats _gzipFirst = false; _gzipStats = 0xF8; } PsychicStaticFileHandler &PsychicStaticFileHandler::setIsDir(bool isDir) { _isDir = isDir; return *this; } PsychicStaticFileHandler &PsychicStaticFileHandler::setDefaultFile(const char *filename) { _default_file = String(filename); return *this; } PsychicStaticFileHandler &PsychicStaticFileHandler::setCacheControl(const char *cache_control) { _cache_control = String(cache_control); return *this; } PsychicStaticFileHandler &PsychicStaticFileHandler::setLastModified(const char *last_modified) { _last_modified = String(last_modified); return *this; } PsychicStaticFileHandler &PsychicStaticFileHandler::setLastModified(struct tm *last_modified) { char result[30]; strftime(result, 30, "%a, %d %b %Y %H:%M:%S %Z", last_modified); return setLastModified((const char *)result); } bool PsychicStaticFileHandler::canHandle(PsychicRequest *request) { if (request->method() != HTTP_GET || !request->uri().startsWith(_uri)) return false; if (_getFile(request)) return true; return false; } bool PsychicStaticFileHandler::_getFile(PsychicRequest *request) { // Remove the found uri String path = request->uri().substring(_uri.length()); // We can skip the file check and look for default if request is to the root of a directory or that request path ends with '/' bool canSkipFileCheck = (_isDir && path.length() == 0) || (path.length() && path[path.length() - 1] == '/'); path = _path + path; // Do we have a file or .gz file if (!canSkipFileCheck && _fileExists(path)) return true; // Can't handle if not default file if (_default_file.length() == 0) return false; // Try to add default file, ensure there is a trailing '/' ot the path. if (path.length() == 0 || path[path.length() - 1] != '/') path += "/"; path += _default_file; return _fileExists(path); } #define FILE_IS_REAL(f) (f == true && !f.isDirectory()) bool PsychicStaticFileHandler::_fileExists(const String &path) { bool fileFound = false; bool gzipFound = false; String gzip = path + ".gz"; if (_gzipFirst) { _file = _fs.open(gzip, "r"); gzipFound = FILE_IS_REAL(_file); if (!gzipFound) { _file = _fs.open(path, "r"); fileFound = FILE_IS_REAL(_file); } } else { _file = _fs.open(path, "r"); fileFound = FILE_IS_REAL(_file); if (!fileFound) { _file = _fs.open(gzip, "r"); gzipFound = FILE_IS_REAL(_file); } } bool found = fileFound || gzipFound; if (found) { _filename = path; // Calculate gzip statistic _gzipStats = (_gzipStats << 1) + (gzipFound ? 1 : 0); if (_gzipStats == 0x00) _gzipFirst = false; // All files are not gzip else if (_gzipStats == 0xFF) _gzipFirst = true; // All files are gzip else _gzipFirst = _countBits(_gzipStats) > 4; // IF we have more gzip files - try gzip first } return found; } uint8_t PsychicStaticFileHandler::_countBits(const uint8_t value) const { uint8_t w = value; uint8_t n; for (n = 0; w != 0; n++) w &= w - 1; return n; } esp_err_t PsychicStaticFileHandler::handleRequest(PsychicRequest *request) { if (_file == true) { // is it not modified? String etag = String(_file.size()); if (_last_modified.length() && _last_modified == request->header("If-Modified-Since")) { _file.close(); request->reply(304); // Not modified } // does our Etag match? else if (_cache_control.length() && request->hasHeader("If-None-Match") && request->header("If-None-Match").equals(etag)) { _file.close(); PsychicResponse response(request); response.addHeader("Cache-Control", _cache_control.c_str()); response.addHeader("ETag", etag.c_str()); response.setCode(304); response.send(); } // nope, send them the full file. else { PsychicFileResponse response(request, _fs, _filename); if (_last_modified.length()) response.addHeader("Last-Modified", _last_modified.c_str()); if (_cache_control.length()) { response.addHeader("Cache-Control", _cache_control.c_str()); response.addHeader("ETag", etag.c_str()); } _file.close(); return response.send(); } } else { return request->reply(404); } return ESP_OK; } ================================================ FILE: lib/PsychicHttp/src/PsychicStaticFileHandler.h ================================================ #ifndef PsychicStaticFileHandler_h #define PsychicStaticFileHandler_h #include "PsychicCore.h" #include "PsychicWebHandler.h" #include "PsychicRequest.h" #include "PsychicResponse.h" #include "PsychicFileResponse.h" class PsychicStaticFileHandler : public PsychicWebHandler { using File = fs::File; using FS = fs::FS; private: bool _getFile(PsychicRequest *request); bool _fileExists(const String& path); uint8_t _countBits(const uint8_t value) const; protected: FS _fs; File _file; String _filename; String _uri; String _path; String _default_file; String _cache_control; String _last_modified; bool _isDir; bool _gzipFirst; uint8_t _gzipStats; public: PsychicStaticFileHandler(const char* uri, FS& fs, const char* path, const char* cache_control); bool canHandle(PsychicRequest *request) override; esp_err_t handleRequest(PsychicRequest *request) override; PsychicStaticFileHandler& setIsDir(bool isDir); PsychicStaticFileHandler& setDefaultFile(const char* filename); PsychicStaticFileHandler& setCacheControl(const char* cache_control); PsychicStaticFileHandler& setLastModified(const char* last_modified); PsychicStaticFileHandler& setLastModified(struct tm* last_modified); //PsychicStaticFileHandler& setTemplateProcessor(AwsTemplateProcessor newCallback) {_callback = newCallback; return *this;} }; #endif /* PsychicHttp_h */ ================================================ FILE: lib/PsychicHttp/src/PsychicStreamResponse.cpp ================================================ #include "PsychicStreamResponse.h" #include "PsychicResponse.h" #include "PsychicRequest.h" PsychicStreamResponse::PsychicStreamResponse(PsychicRequest *request, const String& contentType) : PsychicResponse(request), _buffer(NULL) { setContentType(contentType.c_str()); addHeader("Content-Disposition", "inline"); } PsychicStreamResponse::PsychicStreamResponse(PsychicRequest *request, const String& contentType, const String& name) : PsychicResponse(request), _buffer(NULL) { setContentType(contentType.c_str()); char buf[26+name.length()]; snprintf(buf, sizeof (buf), "attachment; filename=\"%s\"", name.c_str()); addHeader("Content-Disposition", buf); } PsychicStreamResponse::~PsychicStreamResponse() { endSend(); } esp_err_t PsychicStreamResponse::beginSend() { if(_buffer) return ESP_OK; //Buffer to hold ChunkPrinter and stream buffer. Using placement new will keep us at a single allocation. _buffer = (uint8_t*)malloc(STREAM_CHUNK_SIZE + sizeof(ChunkPrinter)); if(!_buffer) { /* Respond with 500 Internal Server Error */ httpd_resp_send_err(_request->request(), HTTPD_500_INTERNAL_SERVER_ERROR, "Unable to allocate memory."); return ESP_FAIL; } _printer = new (_buffer) ChunkPrinter(this, _buffer + sizeof(ChunkPrinter), STREAM_CHUNK_SIZE); sendHeaders(); return ESP_OK; } esp_err_t PsychicStreamResponse::endSend() { esp_err_t err = ESP_OK; if(!_buffer) err = ESP_FAIL; else { _printer->~ChunkPrinter(); //flushed on destruct err = finishChunking(); free(_buffer); _buffer = NULL; } return err; } void PsychicStreamResponse::flush() { if(_buffer) _printer->flush(); } size_t PsychicStreamResponse::write(uint8_t data) { return _buffer ? _printer->write(data) : 0; } size_t PsychicStreamResponse::write(const uint8_t *buffer, size_t size) { return _buffer ? _printer->write(buffer, size) : 0; } size_t PsychicStreamResponse::copyFrom(Stream &stream) { if(_buffer) return _printer->copyFrom(stream); return 0; } ================================================ FILE: lib/PsychicHttp/src/PsychicStreamResponse.h ================================================ #ifndef PsychicStreamResponse_h #define PsychicStreamResponse_h #include "PsychicCore.h" #include "PsychicResponse.h" #include "ChunkPrinter.h" class PsychicRequest; class PsychicStreamResponse : public PsychicResponse, public Print { private: ChunkPrinter *_printer; uint8_t *_buffer; public: PsychicStreamResponse(PsychicRequest *request, const String& contentType); PsychicStreamResponse(PsychicRequest *request, const String& contentType, const String& name); //Download ~PsychicStreamResponse(); esp_err_t beginSend(); esp_err_t endSend(); void flush() override; size_t write(uint8_t data) override; size_t write(const uint8_t *buffer, size_t size) override; size_t copyFrom(Stream &stream); using Print::write; }; #endif // PsychicStreamResponse_h ================================================ FILE: lib/PsychicHttp/src/PsychicUploadHandler.cpp ================================================ #include "PsychicUploadHandler.h" PsychicUploadHandler::PsychicUploadHandler() : PsychicWebHandler(), _temp(), _parsedLength(0), _multiParseState(EXPECT_BOUNDARY), _boundaryPosition(0), _itemStartIndex(0), _itemSize(0), _itemName(), _itemFilename(), _itemType(), _itemValue(), _itemBuffer(0), _itemBufferIndex(0), _itemIsFile(false) { } PsychicUploadHandler::~PsychicUploadHandler() {} bool PsychicUploadHandler::canHandle(PsychicRequest *request) { return true; } esp_err_t PsychicUploadHandler::handleRequest(PsychicRequest *request) { esp_err_t err = ESP_OK; // save it for later (multipart) _request = request; _parsedLength = 0; /* File cannot be larger than a limit */ if (request->contentLength() > request->server()->maxUploadSize) { ESP_LOGE(PH_TAG, "File too large : %d bytes", request->contentLength()); /* Respond with 400 Bad Request */ char error[50]; sprintf(error, "File size must be less than %lu bytes!", request->server()->maxUploadSize); httpd_resp_send_err(request->request(), HTTPD_400_BAD_REQUEST, error); /* Return failure to close underlying connection else the incoming file content will keep the socket busy */ return ESP_FAIL; } // we might want to access some of these params request->loadParams(); // TODO: support for the 100 header. not sure if we can do it. // if (request->header("Expect").equals("100-continue")) // { // char response[] = "100 Continue"; // httpd_socket_send(self->server, httpd_req_to_sockfd(req), response, strlen(response), 0); // } // 2 types of upload requests if (request->isMultipart()) err = _multipartUploadHandler(request); else err = _basicUploadHandler(request); // we can also call onRequest for some final processing and response if (err == ESP_OK) { if (_requestCallback != NULL) err = _requestCallback(request); else err = request->reply("Upload Successful."); } else request->reply(500, "text/html", "Error processing upload."); return err; } esp_err_t PsychicUploadHandler::_basicUploadHandler(PsychicRequest *request) { esp_err_t err = ESP_OK; String filename = request->getFilename(); /* Retrieve the pointer to scratch buffer for temporary storage */ char *buf = (char *)malloc(FILE_CHUNK_SIZE); int received; unsigned long index = 0; /* Content length of the request gives the size of the file being uploaded */ int remaining = request->contentLength(); while (remaining > 0) { // ESP_LOGD(PH_TAG, "Remaining size : %d", remaining); /* Receive the file part by part into a buffer */ if ((received = httpd_req_recv(request->request(), buf, min(remaining, FILE_CHUNK_SIZE))) <= 0) { /* Retry if timeout occurred */ if (received == HTTPD_SOCK_ERR_TIMEOUT) continue; // bail if we got an error else if (received == HTTPD_SOCK_ERR_FAIL) { ESP_LOGE(PH_TAG, "Socket error"); err = ESP_FAIL; break; } } // call our upload callback here. if (_uploadCallback != NULL) { err = _uploadCallback(request, filename, index, (uint8_t *)buf, received, (remaining - received == 0)); if (err != ESP_OK) break; } else { ESP_LOGE(PH_TAG, "No upload callback specified!"); err = ESP_FAIL; break; } /* Keep track of remaining size of the file left to be uploaded */ remaining -= received; index += received; } // dont forget to free our buffer free(buf); return err; } esp_err_t PsychicUploadHandler::_multipartUploadHandler(PsychicRequest *request) { esp_err_t err = ESP_OK; String value = request->header("Content-Type"); if (value.startsWith("multipart/")) { _boundary = value.substring(value.indexOf('=') + 1); _boundary.replace("\"", ""); } else { ESP_LOGE(PH_TAG, "No multipart boundary found."); return request->reply(400, "text/html", "No multipart boundary found."); } char *buf = (char *)malloc(FILE_CHUNK_SIZE); int received; unsigned long index = 0; /* Content length of the request gives the size of the file being uploaded */ int remaining = request->contentLength(); while (remaining > 0) { // ESP_LOGD(PH_TAG, "Remaining size : %d", remaining); /* Receive the file part by part into a buffer */ if ((received = httpd_req_recv(request->request(), buf, min(remaining, FILE_CHUNK_SIZE))) <= 0) { /* Retry if timeout occurred */ if (received == HTTPD_SOCK_ERR_TIMEOUT) continue; // bail if we got an error else if (received == HTTPD_SOCK_ERR_FAIL) { ESP_LOGE(PH_TAG, "Socket error"); err = ESP_FAIL; break; } } // parse it 1 byte at a time. for (int i = 0; i < received; i++) { /* Keep track of remaining size of the file left to be uploaded */ remaining--; index++; // send it to our parser _parseMultipartPostByte(buf[i], !remaining); _parsedLength++; } } // dont forget to free our buffer free(buf); return err; } PsychicUploadHandler *PsychicUploadHandler::onUpload(PsychicUploadCallback fn) { _uploadCallback = fn; return this; } void PsychicUploadHandler::_handleUploadByte(uint8_t data, bool last) { _itemBuffer[_itemBufferIndex++] = data; if (last || _itemBufferIndex == FILE_CHUNK_SIZE) { if (_uploadCallback) _uploadCallback(_request, _itemFilename, _itemSize - _itemBufferIndex, _itemBuffer, _itemBufferIndex, last); _itemBufferIndex = 0; } } #define itemWriteByte(b) \ do \ { \ _itemSize++; \ if (_itemIsFile) \ _handleUploadByte(b, last); \ else \ _itemValue += (char)(b); \ } while (0) void PsychicUploadHandler::_parseMultipartPostByte(uint8_t data, bool last) { if (_multiParseState == PARSE_ERROR) { // not sure we can end up with an error during buffer fill, but jsut to be safe if (_itemBuffer != NULL) { free(_itemBuffer); _itemBuffer = NULL; } return; } if (!_parsedLength) { _multiParseState = EXPECT_BOUNDARY; _temp = String(); _itemName = String(); _itemFilename = String(); _itemType = String(); } if (_multiParseState == WAIT_FOR_RETURN1) { if (data != '\r') { itemWriteByte(data); } else { _multiParseState = EXPECT_FEED1; } } else if (_multiParseState == EXPECT_BOUNDARY) { if (_parsedLength < 2 && data != '-') { ESP_LOGE(PH_TAG, "Multipart: No boundary"); _multiParseState = PARSE_ERROR; return; } else if (_parsedLength - 2 < _boundary.length() && _boundary.c_str()[_parsedLength - 2] != data) { ESP_LOGE(PH_TAG, "Multipart: Multipart malformed"); _multiParseState = PARSE_ERROR; return; } else if (_parsedLength - 2 == _boundary.length() && data != '\r') { ESP_LOGE(PH_TAG, "Multipart: Multipart missing carriage return"); _multiParseState = PARSE_ERROR; return; } else if (_parsedLength - 3 == _boundary.length()) { if (data != '\n') { ESP_LOGE(PH_TAG, "Multipart: Multipart missing newline"); _multiParseState = PARSE_ERROR; return; } _multiParseState = PARSE_HEADERS; _itemIsFile = false; } } else if (_multiParseState == PARSE_HEADERS) { if ((char)data != '\r' && (char)data != '\n') _temp += (char)data; if ((char)data == '\n') { if (_temp.length()) { if (_temp.length() > 12 && _temp.substring(0, 12).equalsIgnoreCase("Content-Type")) { _itemType = _temp.substring(14); _itemIsFile = true; } else if (_temp.length() > 19 && _temp.substring(0, 19).equalsIgnoreCase("Content-Disposition")) { _temp = _temp.substring(_temp.indexOf(';') + 2); while (_temp.indexOf(';') > 0) { String name = _temp.substring(0, _temp.indexOf('=')); String nameVal = _temp.substring(_temp.indexOf('=') + 2, _temp.indexOf(';') - 1); if (name == "name") { _itemName = nameVal; } else if (name == "filename") { _itemFilename = nameVal; _itemIsFile = true; } _temp = _temp.substring(_temp.indexOf(';') + 2); } String name = _temp.substring(0, _temp.indexOf('=')); String nameVal = _temp.substring(_temp.indexOf('=') + 2, _temp.length() - 1); if (name == "name") { _itemName = nameVal; } else if (name == "filename") { _itemFilename = nameVal; _itemIsFile = true; } } _temp = String(); } else { _multiParseState = WAIT_FOR_RETURN1; // value starts from here _itemSize = 0; _itemStartIndex = _parsedLength; _itemValue = String(); if (_itemIsFile) { if (_itemBuffer) free(_itemBuffer); _itemBuffer = (uint8_t *)malloc(FILE_CHUNK_SIZE); if (_itemBuffer == NULL) { ESP_LOGE(PH_TAG, "Multipart: Failed to allocate buffer"); _multiParseState = PARSE_ERROR; return; } _itemBufferIndex = 0; } } } } else if (_multiParseState == EXPECT_FEED1) { if (data != '\n') { _multiParseState = WAIT_FOR_RETURN1; itemWriteByte('\r'); _parseMultipartPostByte(data, last); } else { _multiParseState = EXPECT_DASH1; } } else if (_multiParseState == EXPECT_DASH1) { if (data != '-') { _multiParseState = WAIT_FOR_RETURN1; itemWriteByte('\r'); itemWriteByte('\n'); _parseMultipartPostByte(data, last); } else { _multiParseState = EXPECT_DASH2; } } else if (_multiParseState == EXPECT_DASH2) { if (data != '-') { _multiParseState = WAIT_FOR_RETURN1; itemWriteByte('\r'); itemWriteByte('\n'); itemWriteByte('-'); _parseMultipartPostByte(data, last); } else { _multiParseState = BOUNDARY_OR_DATA; _boundaryPosition = 0; } } else if (_multiParseState == BOUNDARY_OR_DATA) { if (_boundaryPosition < _boundary.length() && _boundary.c_str()[_boundaryPosition] != data) { _multiParseState = WAIT_FOR_RETURN1; itemWriteByte('\r'); itemWriteByte('\n'); itemWriteByte('-'); itemWriteByte('-'); uint8_t i; for (i = 0; i < _boundaryPosition; i++) itemWriteByte(_boundary.c_str()[i]); _parseMultipartPostByte(data, last); } else if (_boundaryPosition == _boundary.length() - 1) { _multiParseState = DASH3_OR_RETURN2; if (!_itemIsFile) { _request->addParam(_itemName, _itemValue); //_addParam(new AsyncWebParameter(_itemName, _itemValue, true)); } else { if (_itemSize) { if (_uploadCallback) _uploadCallback(_request, _itemFilename, _itemSize - _itemBufferIndex, _itemBuffer, _itemBufferIndex, true); _itemBufferIndex = 0; _request->addParam(new PsychicWebParameter(_itemName, _itemFilename, true, true, _itemSize)); } free(_itemBuffer); _itemBuffer = NULL; } } else { _boundaryPosition++; } } else if (_multiParseState == DASH3_OR_RETURN2) { if (data == '-' && (_request->contentLength() - _parsedLength - 4) != 0) { ESP_LOGE(PH_TAG, "ERROR: The parser got to the end of the POST but is expecting more bytes!"); _multiParseState = PARSE_ERROR; return; } if (data == '\r') { _multiParseState = EXPECT_FEED2; } else if (data == '-' && _request->contentLength() == (_parsedLength + 4)) { _multiParseState = PARSING_FINISHED; } else { _multiParseState = WAIT_FOR_RETURN1; itemWriteByte('\r'); itemWriteByte('\n'); itemWriteByte('-'); itemWriteByte('-'); uint8_t i; for (i = 0; i < _boundary.length(); i++) itemWriteByte(_boundary.c_str()[i]); _parseMultipartPostByte(data, last); } } else if (_multiParseState == EXPECT_FEED2) { if (data == '\n') { _multiParseState = PARSE_HEADERS; _itemIsFile = false; } else { _multiParseState = WAIT_FOR_RETURN1; itemWriteByte('\r'); itemWriteByte('\n'); itemWriteByte('-'); itemWriteByte('-'); uint8_t i; for (i = 0; i < _boundary.length(); i++) itemWriteByte(_boundary.c_str()[i]); itemWriteByte('\r'); _parseMultipartPostByte(data, last); } } } ================================================ FILE: lib/PsychicHttp/src/PsychicUploadHandler.h ================================================ #ifndef PsychicUploadHandler_h #define PsychicUploadHandler_h #include "PsychicCore.h" #include "PsychicHttpServer.h" #include "PsychicRequest.h" #include "PsychicWebHandler.h" #include "PsychicWebParameter.h" //callback definitions typedef std::function PsychicUploadCallback; /* * HANDLER :: Can be attached to any endpoint or as a generic request handler. */ class PsychicUploadHandler : public PsychicWebHandler { protected: PsychicUploadCallback _uploadCallback; PsychicRequest *_request; String _temp; size_t _parsedLength; uint8_t _multiParseState; String _boundary; uint8_t _boundaryPosition; size_t _itemStartIndex; size_t _itemSize; String _itemName; String _itemFilename; String _itemType; String _itemValue; uint8_t *_itemBuffer; size_t _itemBufferIndex; bool _itemIsFile; esp_err_t _basicUploadHandler(PsychicRequest *request); esp_err_t _multipartUploadHandler(PsychicRequest *request); void _handleUploadByte(uint8_t data, bool last); void _parseMultipartPostByte(uint8_t data, bool last); public: PsychicUploadHandler(); ~PsychicUploadHandler(); bool canHandle(PsychicRequest *request) override; esp_err_t handleRequest(PsychicRequest *request) override; PsychicUploadHandler * onUpload(PsychicUploadCallback fn); }; enum { EXPECT_BOUNDARY, PARSE_HEADERS, WAIT_FOR_RETURN1, EXPECT_FEED1, EXPECT_DASH1, EXPECT_DASH2, BOUNDARY_OR_DATA, DASH3_OR_RETURN2, EXPECT_FEED2, PARSING_FINISHED, PARSE_ERROR }; #endif // PsychicUploadHandler_h ================================================ FILE: lib/PsychicHttp/src/PsychicWebHandler.cpp ================================================ #include "PsychicWebHandler.h" PsychicWebHandler::PsychicWebHandler() : PsychicHandler(), _requestCallback(NULL), _onOpen(NULL), _onClose(NULL) {} PsychicWebHandler::~PsychicWebHandler() {} bool PsychicWebHandler::canHandle(PsychicRequest *request) { return true; } esp_err_t PsychicWebHandler::handleRequest(PsychicRequest *request) { //lookup our client PsychicClient *client = checkForNewClient(request->client()); if (client->isNew) openCallback(client); /* Request body cannot be larger than a limit */ if (request->contentLength() > request->server()->maxRequestBodySize) { ESP_LOGE(PH_TAG, "Request body too large : %d bytes", request->contentLength()); /* Respond with 400 Bad Request */ char error[60]; sprintf(error, "Request body must be less than %lu bytes!", request->server()->maxRequestBodySize); httpd_resp_send_err(request->request(), HTTPD_400_BAD_REQUEST, error); /* Return failure to close underlying connection else the incoming file content will keep the socket busy */ return ESP_FAIL; } //get our body loaded up. esp_err_t err = request->loadBody(); if (err != ESP_OK) return err; //load our params in. request->loadParams(); //okay, pass on to our callback. if (this->_requestCallback != NULL) err = this->_requestCallback(request); return err; } PsychicWebHandler * PsychicWebHandler::onRequest(PsychicHttpRequestCallback fn) { _requestCallback = fn; return this; } void PsychicWebHandler::openCallback(PsychicClient *client) { if (_onOpen != NULL) _onOpen(client); } void PsychicWebHandler::closeCallback(PsychicClient *client) { if (_onClose != NULL) _onClose(getClient(client)); } PsychicWebHandler * PsychicWebHandler::onOpen(PsychicClientCallback fn) { _onOpen = fn; return this; } PsychicWebHandler * PsychicWebHandler::onClose(PsychicClientCallback fn) { _onClose = fn; return this; } ================================================ FILE: lib/PsychicHttp/src/PsychicWebHandler.h ================================================ #ifndef PsychicWebHandler_h #define PsychicWebHandler_h // #include "PsychicCore.h" // #include "PsychicHttpServer.h" // #include "PsychicRequest.h" #include "PsychicHandler.h" /* * HANDLER :: Can be attached to any endpoint or as a generic request handler. */ class PsychicWebHandler : public PsychicHandler { protected: PsychicHttpRequestCallback _requestCallback; PsychicClientCallback _onOpen; PsychicClientCallback _onClose; public: PsychicWebHandler(); ~PsychicWebHandler(); virtual bool canHandle(PsychicRequest *request) override; virtual esp_err_t handleRequest(PsychicRequest *request) override; PsychicWebHandler * onRequest(PsychicHttpRequestCallback fn); virtual void openCallback(PsychicClient *client); virtual void closeCallback(PsychicClient *client); PsychicWebHandler *onOpen(PsychicClientCallback fn); PsychicWebHandler *onClose(PsychicClientCallback fn); }; #endif ================================================ FILE: lib/PsychicHttp/src/PsychicWebParameter.h ================================================ #ifndef PsychicWebParameter_h #define PsychicWebParameter_h /* * PARAMETER :: Chainable object to hold GET/POST and FILE parameters * */ class PsychicWebParameter { private: String _name; String _value; size_t _size; bool _isForm; bool _isFile; public: PsychicWebParameter(const String& name, const String& value, bool form=false, bool file=false, size_t size=0): _name(name), _value(value), _size(size), _isForm(form), _isFile(file){} const String& name() const { return _name; } const String& value() const { return _value; } size_t size() const { return _size; } bool isPost() const { return _isForm; } bool isFile() const { return _isFile; } }; #endif //PsychicWebParameter_h ================================================ FILE: lib/PsychicHttp/src/PsychicWebSocket.cpp ================================================ #include "PsychicWebSocket.h" /*************************************/ /* PsychicWebSocketRequest */ /*************************************/ PsychicWebSocketRequest::PsychicWebSocketRequest(PsychicRequest *req) : PsychicRequest(req->server(), req->request()), _client(req->client()) { } PsychicWebSocketRequest::~PsychicWebSocketRequest() { } PsychicWebSocketClient * PsychicWebSocketRequest::client() { return &_client; } esp_err_t PsychicWebSocketRequest::reply(httpd_ws_frame_t * ws_pkt) { return httpd_ws_send_frame(this->_req, ws_pkt); } esp_err_t PsychicWebSocketRequest::reply(httpd_ws_type_t op, const void *data, size_t len) { httpd_ws_frame_t ws_pkt; memset(&ws_pkt, 0, sizeof(httpd_ws_frame_t)); ws_pkt.payload = (uint8_t*)data; ws_pkt.len = len; ws_pkt.type = op; return this->reply(&ws_pkt); } esp_err_t PsychicWebSocketRequest::reply(const char *buf) { return this->reply(HTTPD_WS_TYPE_TEXT, buf, strlen(buf)); } /*************************************/ /* PsychicWebSocketClient */ /*************************************/ PsychicWebSocketClient::PsychicWebSocketClient(PsychicClient *client) : PsychicClient(client->server(), client->socket()) { } PsychicWebSocketClient::~PsychicWebSocketClient() { } esp_err_t PsychicWebSocketClient::sendMessage(httpd_ws_frame_t * ws_pkt) { return httpd_ws_send_frame_async(this->server(), this->socket(), ws_pkt); } esp_err_t PsychicWebSocketClient::sendMessage(httpd_ws_type_t op, const void *data, size_t len) { httpd_ws_frame_t ws_pkt; memset(&ws_pkt, 0, sizeof(httpd_ws_frame_t)); ws_pkt.payload = (uint8_t*)data; ws_pkt.len = len; ws_pkt.type = op; return this->sendMessage(&ws_pkt); } esp_err_t PsychicWebSocketClient::sendMessage(const char *buf) { return this->sendMessage(HTTPD_WS_TYPE_TEXT, buf, strlen(buf)); } PsychicWebSocketHandler::PsychicWebSocketHandler() : PsychicHandler(), _onOpen(NULL), _onFrame(NULL), _onClose(NULL) { } PsychicWebSocketHandler::~PsychicWebSocketHandler() { } PsychicWebSocketClient * PsychicWebSocketHandler::getClient(int socket) { PsychicClient *client = PsychicHandler::getClient(socket); if (client == NULL) return NULL; if (client->_friend == NULL) { return NULL; } return (PsychicWebSocketClient *)client->_friend; } PsychicWebSocketClient * PsychicWebSocketHandler::getClient(PsychicClient *client) { return getClient(client->socket()); } void PsychicWebSocketHandler::addClient(PsychicClient *client) { client->_friend = new PsychicWebSocketClient(client); PsychicHandler::addClient(client); } void PsychicWebSocketHandler::removeClient(PsychicClient *client) { PsychicHandler::removeClient(client); delete (PsychicWebSocketClient*)client->_friend; client->_friend = NULL; } void PsychicWebSocketHandler::openCallback(PsychicClient *client) { PsychicWebSocketClient *buddy = getClient(client); if (buddy == NULL) { return; } if (_onOpen != NULL) _onOpen(getClient(buddy)); } void PsychicWebSocketHandler::closeCallback(PsychicClient *client) { PsychicWebSocketClient *buddy = getClient(client); if (buddy == NULL) { return; } if (_onClose != NULL) _onClose(getClient(buddy)); } bool PsychicWebSocketHandler::isWebSocket() { return true; } esp_err_t PsychicWebSocketHandler::handleRequest(PsychicRequest *request) { //lookup our client PsychicClient *client = checkForNewClient(request->client()); // beginning of the ws URI handler and our onConnect hook if (request->method() == HTTP_GET) { if (client->isNew) openCallback(client); return ESP_OK; } //prep our request PsychicWebSocketRequest wsRequest(request); //init our memory for storing the packet httpd_ws_frame_t ws_pkt; memset(&ws_pkt, 0, sizeof(httpd_ws_frame_t)); ws_pkt.type = HTTPD_WS_TYPE_TEXT; uint8_t *buf = NULL; /* Set max_len = 0 to get the frame len */ esp_err_t ret = httpd_ws_recv_frame(wsRequest.request(), &ws_pkt, 0); if (ret != ESP_OK) { ESP_LOGE(PH_TAG, "httpd_ws_recv_frame failed to get frame len with %s", esp_err_to_name(ret)); return ret; } //okay, now try to load the packet //ESP_LOGD(PH_TAG, "frame len is %d", ws_pkt.len); if (ws_pkt.len) { /* ws_pkt.len + 1 is for NULL termination as we are expecting a string */ buf = (uint8_t*) calloc(1, ws_pkt.len + 1); if (buf == NULL) { ESP_LOGE(PH_TAG, "Failed to calloc memory for buf"); return ESP_ERR_NO_MEM; } ws_pkt.payload = buf; /* Set max_len = ws_pkt.len to get the frame payload */ ret = httpd_ws_recv_frame(wsRequest.request(), &ws_pkt, ws_pkt.len); if (ret != ESP_OK) { ESP_LOGE(PH_TAG, "httpd_ws_recv_frame failed with %s", esp_err_to_name(ret)); free(buf); return ret; } //ESP_LOGD(PH_TAG, "Got packet with message: %s", ws_pkt.payload); } // Text messages are our payload. if (ws_pkt.type == HTTPD_WS_TYPE_TEXT || ws_pkt.type == HTTPD_WS_TYPE_BINARY) { if (this->_onFrame != NULL) ret = this->_onFrame(&wsRequest, &ws_pkt); } //logging housekeeping if (ret != ESP_OK) ESP_LOGE(PH_TAG, "httpd_ws_send_frame failed with %s", esp_err_to_name(ret)); // ESP_LOGD(PH_TAG, "ws_handler: httpd_handle_t=%p, sockfd=%d, client_info:%d", // request->server(), // httpd_req_to_sockfd(request->request()), // httpd_ws_get_fd_info(request->server()->server, httpd_req_to_sockfd(request->request()))); //dont forget to release our buffer memory free(buf); return ret; } PsychicWebSocketHandler * PsychicWebSocketHandler::onOpen(PsychicWebSocketClientCallback fn) { _onOpen = fn; return this; } PsychicWebSocketHandler * PsychicWebSocketHandler::onFrame(PsychicWebSocketFrameCallback fn) { _onFrame = fn; return this; } PsychicWebSocketHandler * PsychicWebSocketHandler::onClose(PsychicWebSocketClientCallback fn) { _onClose = fn; return this; } void PsychicWebSocketHandler::sendAll(httpd_ws_frame_t * ws_pkt) { for (PsychicClient *client : _clients) { //ESP_LOGD(PH_TAG, "Active client (fd=%d) -> sending async message", client->socket()); if (client->_friend == NULL) { return; } if (((PsychicWebSocketClient*)client->_friend)->sendMessage(ws_pkt) != ESP_OK) break; } } void PsychicWebSocketHandler::sendAll(httpd_ws_type_t op, const void *data, size_t len) { httpd_ws_frame_t ws_pkt; memset(&ws_pkt, 0, sizeof(httpd_ws_frame_t)); ws_pkt.payload = (uint8_t*)data; ws_pkt.len = len; ws_pkt.type = op; this->sendAll(&ws_pkt); } void PsychicWebSocketHandler::sendAll(const char *buf) { this->sendAll(HTTPD_WS_TYPE_TEXT, buf, strlen(buf)); } ================================================ FILE: lib/PsychicHttp/src/PsychicWebSocket.h ================================================ #ifndef PsychicWebSocket_h #define PsychicWebSocket_h #include "PsychicCore.h" #include "PsychicRequest.h" class PsychicWebSocketRequest; class PsychicWebSocketClient; //callback function definitions typedef std::function PsychicWebSocketClientCallback; typedef std::function PsychicWebSocketFrameCallback; class PsychicWebSocketClient : public PsychicClient { public: PsychicWebSocketClient(PsychicClient *client); ~PsychicWebSocketClient(); esp_err_t sendMessage(httpd_ws_frame_t * ws_pkt); esp_err_t sendMessage(httpd_ws_type_t op, const void *data, size_t len); esp_err_t sendMessage(const char *buf); }; class PsychicWebSocketRequest : public PsychicRequest { private: PsychicWebSocketClient _client; public: PsychicWebSocketRequest(PsychicRequest *req); virtual ~PsychicWebSocketRequest(); PsychicWebSocketClient * client() override; esp_err_t reply(httpd_ws_frame_t * ws_pkt); esp_err_t reply(httpd_ws_type_t op, const void *data, size_t len); esp_err_t reply(const char *buf); }; class PsychicWebSocketHandler : public PsychicHandler { protected: PsychicWebSocketClientCallback _onOpen; PsychicWebSocketFrameCallback _onFrame; PsychicWebSocketClientCallback _onClose; public: PsychicWebSocketHandler(); ~PsychicWebSocketHandler(); PsychicWebSocketClient * getClient(int socket) override; PsychicWebSocketClient * getClient(PsychicClient *client) override; void addClient(PsychicClient *client) override; void removeClient(PsychicClient *client) override; void openCallback(PsychicClient *client) override; void closeCallback(PsychicClient *client) override; bool isWebSocket() override final; esp_err_t handleRequest(PsychicRequest *request) override; PsychicWebSocketHandler *onOpen(PsychicWebSocketClientCallback fn); PsychicWebSocketHandler *onFrame(PsychicWebSocketFrameCallback fn); PsychicWebSocketHandler *onClose(PsychicWebSocketClientCallback fn); void sendAll(httpd_ws_frame_t * ws_pkt); void sendAll(httpd_ws_type_t op, const void *data, size_t len); void sendAll(const char *buf); }; #endif // PsychicWebSocket_h ================================================ FILE: lib/PsychicHttp/src/TemplatePrinter.cpp ================================================ /************************************************************ TemplatePrinter Class A basic templating engine for a stream of text. This wraps the Arduino Print interface and writes to any Print interface. Written by Christopher Andrews (https://github.com/Chris--A) ************************************************************/ #include "TemplatePrinter.h" void TemplatePrinter::resetParam(bool flush){ if(flush && _inParam){ _stream.write(_delimiter); if(_paramPos) _stream.print(_paramBuffer); } memset(_paramBuffer, 0, sizeof(_paramBuffer)); _paramPos = 0; _inParam = false; } void TemplatePrinter::flush(){ resetParam(true); _stream.flush(); } size_t TemplatePrinter::write(uint8_t data){ if(data == _delimiter){ // End of parameter, send to callback if(_inParam){ // On false, return the parameter place holder as is: not a parameter // Bug fix: ignore parameters that are zero length. if(!_paramPos || !_cb(_stream, _paramBuffer)){ resetParam(true); _stream.write(data); }else{ resetParam(false); } // Start collecting parameter }else{ _inParam = true; } }else{ // Are we collecting if(_inParam){ // Is param still valid if(isalnum(data) || data == '_'){ // Total param len must be 63, 1 for null. if(_paramPos < sizeof(_paramBuffer) - 1){ _paramBuffer[_paramPos++] = data; // Not a valid param }else{ resetParam(true); } }else{ resetParam(true); _stream.write(data); } // Just output }else{ _stream.write(data); } } return 1; } size_t TemplatePrinter::copyFrom(Stream &stream){ size_t count = 0; while(stream.available()) count += this->write(stream.read()); return count; } ================================================ FILE: lib/PsychicHttp/src/TemplatePrinter.h ================================================ #ifndef TemplatePrinter_h #define TemplatePrinter_h #include "PsychicCore.h" #include /************************************************************ TemplatePrinter Class A basic templating engine for a stream of text. This wraps the Arduino Print interface and writes to any Print interface. Written by Christopher Andrews (https://github.com/Chris--A) ************************************************************/ class TemplatePrinter; typedef std::function TemplateCallback; typedef std::function TemplateSourceCallback; class TemplatePrinter : public Print{ private: bool _inParam; char _paramBuffer[64]; uint8_t _paramPos; Print &_stream; TemplateCallback _cb; char _delimiter; void resetParam(bool flush); public: using Print::write; static void start(Print &stream, TemplateCallback cb, TemplateSourceCallback entry){ TemplatePrinter printer(stream, cb); entry(printer); } TemplatePrinter(Print &stream, TemplateCallback cb, const char delimeter = '%') : _stream(stream), _cb(cb), _delimiter(delimeter) { resetParam(false); } ~TemplatePrinter(){ flush(); } void flush() override; size_t write(uint8_t data) override; size_t copyFrom(Stream &stream); }; #endif ================================================ FILE: lib/PsychicHttp/src/http_status.cpp ================================================ #include "http_status.h" bool http_informational(int code) { return code >= 100 && code < 200; } bool http_success(int code) { return code >= 200 && code < 300; } bool http_redirection(int code) { return code >= 300 && code < 400; } bool http_client_error(int code) { return code >= 400 && code < 500; } bool http_server_error(int code) { return code >= 500 && code < 600; } bool http_failure(int code) { return code >= 400 && code < 600; } const char *http_status_group(int code) { if (http_informational(code)) return "Informational"; if (http_success(code)) return "Success"; if (http_redirection(code)) return "Redirection"; if (http_client_error(code)) return "Client Error"; if (http_server_error(code)) return "Server Error"; return "Unknown"; } const char *http_status_reason(int code) { switch (code) { /*####### 1xx - Informational #######*/ case 100: return "Continue"; case 101: return "Switching Protocols"; case 102: return "Processing"; case 103: return "Early Hints"; /*####### 2xx - Successful #######*/ case 200: return "OK"; case 201: return "Created"; case 202: return "Accepted"; case 203: return "Non-Authoritative Information"; case 204: return "No Content"; case 205: return "Reset Content"; case 206: return "Partial Content"; case 207: return "Multi-Status"; case 208: return "Already Reported"; case 226: return "IM Used"; /*####### 3xx - Redirection #######*/ case 300: return "Multiple Choices"; case 301: return "Moved Permanently"; case 302: return "Found"; case 303: return "See Other"; case 304: return "Not Modified"; case 305: return "Use Proxy"; case 307: return "Temporary Redirect"; case 308: return "Permanent Redirect"; /*####### 4xx - Client Error #######*/ case 400: return "Bad Request"; case 401: return "Unauthorized"; case 402: return "Payment Required"; case 403: return "Forbidden"; case 404: return "Not Found"; case 405: return "Method Not Allowed"; case 406: return "Not Acceptable"; case 407: return "Proxy Authentication Required"; case 408: return "Request Timeout"; case 409: return "Conflict"; case 410: return "Gone"; case 411: return "Length Required"; case 412: return "Precondition Failed"; case 413: return "Content Too Large"; case 414: return "URI Too Long"; case 415: return "Unsupported Media Type"; case 416: return "Range Not Satisfiable"; case 417: return "Expectation Failed"; case 418: return "I'm a teapot"; case 421: return "Misdirected Request"; case 422: return "Unprocessable Content"; case 423: return "Locked"; case 424: return "Failed Dependency"; case 425: return "Too Early"; case 426: return "Upgrade Required"; case 428: return "Precondition Required"; case 429: return "Too Many Requests"; case 431: return "Request Header Fields Too Large"; case 451: return "Unavailable For Legal Reasons"; /*####### 5xx - Server Error #######*/ case 500: return "Internal Server Error"; case 501: return "Not Implemented"; case 502: return "Bad Gateway"; case 503: return "Service Unavailable"; case 504: return "Gateway Timeout"; case 505: return "HTTP Version Not Supported"; case 506: return "Variant Also Negotiates"; case 507: return "Insufficient Storage"; case 508: return "Loop Detected"; case 510: return "Not Extended"; case 511: return "Network Authentication Required"; default: return "Unknown"; } } ================================================ FILE: lib/PsychicHttp/src/http_status.h ================================================ #ifndef MICRO_HTTP_STATUS_H #define MICRO_HTTP_STATUS_H #include bool http_informational(int code); bool http_success(int code); bool http_redirection(int code); bool http_client_error(int code); bool http_server_error(int code); bool http_failure(int code); const char *http_status_group(int code); const char *http_status_reason(int code); #endif // MICRO_HTTP_STATUS_H ================================================ FILE: lib/framework/APSettingsService.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include APSettingsService::APSettingsService(PsychicHttpServer *server, FS *fs, SecurityManager *securityManager) : _server(server), _securityManager(securityManager), _httpEndpoint(APSettings::read, APSettings::update, this, server, AP_SETTINGS_SERVICE_PATH, securityManager), _fsPersistence(APSettings::read, APSettings::update, this, fs, AP_SETTINGS_FILE), _dnsServer(nullptr), _lastManaged(0), _reconfigureAp(false) { addUpdateHandler([&](const String &originId) { reconfigureAP(); }, false); } void APSettingsService::begin() { _httpEndpoint.begin(); _fsPersistence.readFromFS(); reconfigureAP(); } void APSettingsService::reconfigureAP() { _lastManaged = millis() - MANAGE_NETWORK_DELAY; _reconfigureAp = true; _recoveryMode = false; } void APSettingsService::recoveryMode() { #ifdef SERIAL_INFO Serial.println("Recovery Mode needed"); #endif _lastManaged = millis() - MANAGE_NETWORK_DELAY; _recoveryMode = true; _reconfigureAp = true; } void APSettingsService::loop() { unsigned long currentMillis = millis(); unsigned long manageElapsed = (unsigned long)(currentMillis - _lastManaged); if (manageElapsed >= MANAGE_NETWORK_DELAY) { _lastManaged = currentMillis; manageAP(); } handleDNS(); } void APSettingsService::manageAP() { WiFiMode_t currentWiFiMode = WiFi.getMode(); if (_state.provisionMode == AP_MODE_ALWAYS || (_state.provisionMode == AP_MODE_DISCONNECTED && WiFi.status() != WL_CONNECTED) || _recoveryMode) { if (_reconfigureAp || currentWiFiMode == WIFI_OFF || currentWiFiMode == WIFI_STA) { startAP(); } } else if ((currentWiFiMode == WIFI_AP || currentWiFiMode == WIFI_AP_STA) && (_reconfigureAp || !WiFi.softAPgetStationNum())) { stopAP(); } _reconfigureAp = false; } void APSettingsService::startAP() { #ifdef SERIAL_INFO Serial.println("Starting software access point"); #endif WiFi.softAPConfig(_state.localIP, _state.gatewayIP, _state.subnetMask); WiFi.softAP(_state.ssid.c_str(), _state.password.c_str(), _state.channel, _state.ssidHidden, _state.maxClients); #if CONFIG_IDF_TARGET_ESP32C3 WiFi.setTxPower(WIFI_POWER_8_5dBm); // https://www.wemos.cc/en/latest/c3/c3_mini_1_0_0.html#about-wifi #endif if (!_dnsServer) { IPAddress apIp = WiFi.softAPIP(); #ifdef SERIAL_INFO Serial.print("Starting captive portal on "); Serial.println(apIp); #endif _dnsServer = new DNSServer; _dnsServer->start(DNS_PORT, "*", apIp); } } void APSettingsService::stopAP() { if (_dnsServer) { #ifdef SERIAL_INFO Serial.println("Stopping captive portal"); #endif _dnsServer->stop(); delete _dnsServer; _dnsServer = nullptr; } #ifdef SERIAL_INFO Serial.println("Stopping software access point"); #endif WiFi.softAPdisconnect(true); } void APSettingsService::handleDNS() { if (_dnsServer) { _dnsServer->processNextRequest(); } } APNetworkStatus APSettingsService::getAPNetworkStatus() { WiFiMode_t currentWiFiMode = WiFi.getMode(); bool apActive = currentWiFiMode == WIFI_AP || currentWiFiMode == WIFI_AP_STA; if (apActive && _state.provisionMode != AP_MODE_ALWAYS && WiFi.status() == WL_CONNECTED) { return APNetworkStatus::LINGERING; } return apActive ? APNetworkStatus::ACTIVE : APNetworkStatus::INACTIVE; } ================================================ FILE: lib/framework/APSettingsService.h ================================================ #ifndef APSettingsConfig_h #define APSettingsConfig_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #include #include #include #ifndef FACTORY_AP_PROVISION_MODE #define FACTORY_AP_PROVISION_MODE AP_MODE_DISCONNECTED #endif #ifndef FACTORY_AP_SSID #define FACTORY_AP_SSID "ESP32-SvelteKit-#{unique_id}" #endif #ifndef FACTORY_AP_PASSWORD #define FACTORY_AP_PASSWORD "esp-sveltekit" #endif #ifndef FACTORY_AP_LOCAL_IP #define FACTORY_AP_LOCAL_IP "192.168.4.1" #endif #ifndef FACTORY_AP_GATEWAY_IP #define FACTORY_AP_GATEWAY_IP "192.168.4.1" #endif #ifndef FACTORY_AP_SUBNET_MASK #define FACTORY_AP_SUBNET_MASK "255.255.255.0" #endif #ifndef FACTORY_AP_CHANNEL #define FACTORY_AP_CHANNEL 1 #endif #ifndef FACTORY_AP_SSID_HIDDEN #define FACTORY_AP_SSID_HIDDEN false #endif #ifndef FACTORY_AP_MAX_CLIENTS #define FACTORY_AP_MAX_CLIENTS 4 #endif #define AP_SETTINGS_FILE "/config/apSettings.json" #define AP_SETTINGS_SERVICE_PATH "/rest/apSettings" #define AP_MODE_ALWAYS 0 #define AP_MODE_DISCONNECTED 1 #define AP_MODE_NEVER 2 #define MANAGE_NETWORK_DELAY 10000 #define DNS_PORT 53 enum APNetworkStatus { ACTIVE = 0, INACTIVE, LINGERING }; class APSettings { public: uint8_t provisionMode; String ssid; String password; uint8_t channel; bool ssidHidden; uint8_t maxClients; IPAddress localIP; IPAddress gatewayIP; IPAddress subnetMask; bool operator==(const APSettings &settings) const { return provisionMode == settings.provisionMode && ssid == settings.ssid && password == settings.password && channel == settings.channel && ssidHidden == settings.ssidHidden && maxClients == settings.maxClients && localIP == settings.localIP && gatewayIP == settings.gatewayIP && subnetMask == settings.subnetMask; } static void read(APSettings &settings, JsonObject &root) { root["provision_mode"] = settings.provisionMode; root["ssid"] = settings.ssid; root["password"] = settings.password; root["channel"] = settings.channel; root["ssid_hidden"] = settings.ssidHidden; root["max_clients"] = settings.maxClients; root["local_ip"] = settings.localIP.toString(); root["gateway_ip"] = settings.gatewayIP.toString(); root["subnet_mask"] = settings.subnetMask.toString(); } static StateUpdateResult update(JsonObject &root, APSettings &settings, const String &originId) { APSettings newSettings = {}; newSettings.provisionMode = root["provision_mode"] | FACTORY_AP_PROVISION_MODE; switch (settings.provisionMode) { case AP_MODE_ALWAYS: case AP_MODE_DISCONNECTED: case AP_MODE_NEVER: break; default: newSettings.provisionMode = AP_MODE_DISCONNECTED; } newSettings.ssid = root["ssid"] | SettingValue::format(FACTORY_AP_SSID); newSettings.password = root["password"] | FACTORY_AP_PASSWORD; newSettings.channel = root["channel"] | FACTORY_AP_CHANNEL; newSettings.ssidHidden = root["ssid_hidden"] | FACTORY_AP_SSID_HIDDEN; newSettings.maxClients = root["max_clients"] | FACTORY_AP_MAX_CLIENTS; JsonUtils::readIPStr(root, "local_ip", newSettings.localIP, FACTORY_AP_LOCAL_IP); JsonUtils::readIPStr(root, "gateway_ip", newSettings.gatewayIP, FACTORY_AP_GATEWAY_IP); JsonUtils::readIPStr(root, "subnet_mask", newSettings.subnetMask, FACTORY_AP_SUBNET_MASK); if (newSettings == settings) { return StateUpdateResult::UNCHANGED; } settings = newSettings; return StateUpdateResult::CHANGED; } }; class APSettingsService : public StatefulService { public: APSettingsService(PsychicHttpServer *server, FS *fs, SecurityManager *securityManager); void begin(); void loop(); APNetworkStatus getAPNetworkStatus(); void recoveryMode(); private: PsychicHttpServer *_server; SecurityManager *_securityManager; HttpEndpoint _httpEndpoint; FSPersistence _fsPersistence; // for the captive portal DNSServer *_dnsServer; // for the mangement delay loop volatile unsigned long _lastManaged; volatile boolean _reconfigureAp; volatile boolean _recoveryMode = false; void reconfigureAP(); void manageAP(); void startAP(); void stopAP(); void handleDNS(); }; #endif // end APSettingsConfig_h ================================================ FILE: lib/framework/APStatus.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include APStatus::APStatus(PsychicHttpServer *server, SecurityManager *securityManager, APSettingsService *apSettingsService) : _server(server), _securityManager(securityManager), _apSettingsService(apSettingsService) { } void APStatus::begin() { _server->on(AP_STATUS_SERVICE_PATH, HTTP_GET, _securityManager->wrapRequest(std::bind(&APStatus::apStatus, this, std::placeholders::_1), AuthenticationPredicates::IS_AUTHENTICATED)); ESP_LOGV(SVK_TAG, "Registered GET endpoint: %s", AP_STATUS_SERVICE_PATH); } esp_err_t APStatus::apStatus(PsychicRequest *request) { PsychicJsonResponse response = PsychicJsonResponse(request, false); JsonObject root = response.getRoot(); root["status"] = _apSettingsService->getAPNetworkStatus(); root["ip_address"] = WiFi.softAPIP().toString(); root["mac_address"] = WiFi.softAPmacAddress(); root["station_num"] = WiFi.softAPgetStationNum(); return response.send(); } bool APStatus::isActive() { return _apSettingsService->getAPNetworkStatus() == APNetworkStatus::ACTIVE ? true : false; } ================================================ FILE: lib/framework/APStatus.h ================================================ #ifndef APStatus_h #define APStatus_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #include #include #define AP_STATUS_SERVICE_PATH "/rest/apStatus" class APStatus { public: APStatus(PsychicHttpServer *server, SecurityManager *securityManager, APSettingsService *apSettingsService); void begin(); bool isActive(); private: PsychicHttpServer *_server; SecurityManager *_securityManager; APSettingsService *_apSettingsService; esp_err_t apStatus(PsychicRequest *request); }; #endif // end APStatus_h ================================================ FILE: lib/framework/AnalyticsService.h ================================================ #pragma once /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #define MAX_ESP_ANALYTICS_SIZE 1024 #define EVENT_ANALYTICS "analytics" #define ANALYTICS_INTERVAL 2000 class AnalyticsService { public: AnalyticsService(EventSocket *socket) : _socket(socket) {}; void begin() { _socket->registerEvent(EVENT_ANALYTICS); } void loop() { if (millis() - lastMillis > ANALYTICS_INTERVAL) { lastMillis = millis(); JsonDocument doc; doc["uptime"] = millis() / 1000; doc["free_heap"] = ESP.getFreeHeap(); doc["used_heap"] = ESP.getHeapSize() - ESP.getFreeHeap(); doc["total_heap"] = ESP.getHeapSize(); doc["min_free_heap"] = ESP.getMinFreeHeap(); doc["max_alloc_heap"] = ESP.getMaxAllocHeap(); doc["fs_used"] = ESPFS.usedBytes(); doc["fs_total"] = ESPFS.totalBytes(); doc["core_temp"] = temperatureRead(); if (psramFound()) { doc["free_psram"] = ESP.getFreePsram(); doc["used_psram"] = ESP.getPsramSize() - ESP.getFreePsram(); doc["psram_size"] = ESP.getPsramSize(); } JsonObject jsonObject = doc.as(); _socket->emitEvent(EVENT_ANALYTICS, jsonObject); } }; protected: EventSocket *_socket; unsigned long lastMillis = 0; }; ================================================ FILE: lib/framework/ArduinoJsonJWT.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include "ArduinoJsonJWT.h" ArduinoJsonJWT::ArduinoJsonJWT(String secret) : _secret(secret) { } void ArduinoJsonJWT::setSecret(String secret) { _secret = secret; } String ArduinoJsonJWT::getSecret() { return _secret; } /* * ESP32 uses mbedtls, * * Both come with decent HMAC implmentations supporting sha256, as well as others. * * No need to pull in additional crypto libraries - lets use what we already have. */ String ArduinoJsonJWT::sign(String &payload) { unsigned char hmacResult[32]; { mbedtls_md_context_t ctx; mbedtls_md_type_t md_type = MBEDTLS_MD_SHA256; mbedtls_md_init(&ctx); mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(md_type), 1); mbedtls_md_hmac_starts(&ctx, (unsigned char *)_secret.c_str(), _secret.length()); mbedtls_md_hmac_update(&ctx, (unsigned char *)payload.c_str(), payload.length()); mbedtls_md_hmac_finish(&ctx, hmacResult); mbedtls_md_free(&ctx); } return encode((char *)hmacResult, 32); } String ArduinoJsonJWT::buildJWT(JsonObject &payload) { // serialize, then encode payload String jwt; serializeJson(payload, jwt); jwt = encode(jwt.c_str(), jwt.length()); // add the header to payload jwt = JWT_HEADER + '.' + jwt; // add signature jwt += '.' + sign(jwt); return jwt; } void ArduinoJsonJWT::parseJWT(String jwt, JsonDocument &jsonDocument) { // clear json document before we begin, jsonDocument wil be null on failure jsonDocument.clear(); // must have the correct header and delimiter if (!jwt.startsWith(JWT_HEADER) || jwt.indexOf('.') != JWT_HEADER_SIZE) { return; } // check there is a signature delimieter int signatureDelimiterIndex = jwt.lastIndexOf('.'); if (signatureDelimiterIndex == JWT_HEADER_SIZE) { return; } // check the signature is valid String signature = jwt.substring(signatureDelimiterIndex + 1); jwt = jwt.substring(0, signatureDelimiterIndex); if (sign(jwt) != signature) { return; } // decode payload jwt = jwt.substring(JWT_HEADER_SIZE + 1); jwt = decode(jwt); // parse payload, clearing json document after failure DeserializationError error = deserializeJson(jsonDocument, jwt); if (error != DeserializationError::Ok || !jsonDocument.is()) { jsonDocument.clear(); } } String ArduinoJsonJWT::encode(const char *cstr, int inputLen) { // prepare encoder base64_encodestate _state; base64_init_encodestate(&_state); size_t encodedLength = base64_encode_expected_len(inputLen) + 1; // prepare buffer of correct length, returning an empty string on failure char *buffer = (char *)malloc(encodedLength * sizeof(char)); if (buffer == nullptr) { return ""; } // encode to buffer int len = base64_encode_block(cstr, inputLen, &buffer[0], &_state); len += base64_encode_blockend(&buffer[len], &_state); buffer[len] = 0; // convert to arduino string, freeing buffer String value = String(buffer); free(buffer); buffer = nullptr; // remove padding and convert to URL safe form while (value.length() > 0 && value.charAt(value.length() - 1) == '=') { value.remove(value.length() - 1); } value.replace('+', '-'); value.replace('/', '_'); // return as string return value; } String ArduinoJsonJWT::decode(String value) { // convert to standard base64 value.replace('-', '+'); value.replace('_', '/'); // prepare buffer of correct length char buffer[base64_decode_expected_len(value.length()) + 1]; // decode int len = base64_decode_chars(value.c_str(), value.length(), &buffer[0]); buffer[len] = 0; // return as string return String(buffer); } ================================================ FILE: lib/framework/ArduinoJsonJWT.h ================================================ #ifndef ArduinoJsonJWT_H #define ArduinoJsonJWT_H /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #include class ArduinoJsonJWT { private: String _secret; const String JWT_HEADER = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"; const int JWT_HEADER_SIZE = JWT_HEADER.length(); String sign(String &value); static String encode(const char *cstr, int len); static String decode(String value); public: ArduinoJsonJWT(String secret); void setSecret(String secret); String getSecret(); String buildJWT(JsonObject &payload); void parseJWT(String jwt, JsonDocument &jsonDocument); }; #endif ================================================ FILE: lib/framework/AuthenticationService.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #if FT_ENABLED(FT_SECURITY) AuthenticationService::AuthenticationService(PsychicHttpServer *server, SecurityManager *securityManager) : _server(server), _securityManager(securityManager) { } void AuthenticationService::begin() { // Signs in a user if the username and password match. Provides a JWT to be used in the Authorization header in subsequent requests _server->on(SIGN_IN_PATH, HTTP_POST, [this](PsychicRequest *request, JsonVariant &json) { if (json.is()) { String username = json["username"]; String password = json["password"]; Authentication authentication = _securityManager->authenticate(username, password); if (authentication.authenticated) { PsychicJsonResponse response = PsychicJsonResponse(request, false); JsonObject root = response.getRoot(); root["access_token"] = _securityManager->generateJWT(authentication.user); return response.send(); } } return request->reply(401); }); ESP_LOGV(SVK_TAG, "Registered POST endpoint: %s", SIGN_IN_PATH); // Verifies that the request supplied a valid JWT _server->on(VERIFY_AUTHORIZATION_PATH, HTTP_GET, [this](PsychicRequest *request) { Authentication authentication = _securityManager->authenticateRequest(request); return request->reply(authentication.authenticated ? 200 : 401); }); ESP_LOGV(SVK_TAG, "Registered GET endpoint: %s", VERIFY_AUTHORIZATION_PATH); } #endif // end FT_ENABLED(FT_SECURITY) ================================================ FILE: lib/framework/AuthenticationService.h ================================================ #ifndef AuthenticationService_H_ #define AuthenticationService_H_ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #define VERIFY_AUTHORIZATION_PATH "/rest/verifyAuthorization" #define SIGN_IN_PATH "/rest/signIn" #if FT_ENABLED(FT_SECURITY) class AuthenticationService { public: AuthenticationService(PsychicHttpServer *server, SecurityManager *securityManager); void begin(); private: SecurityManager *_securityManager; PsychicHttpServer *_server; }; #endif // end FT_ENABLED(FT_SECURITY) #endif // end SecurityManager_h ================================================ FILE: lib/framework/BatteryService.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include BatteryService::BatteryService(EventSocket *socket) : _socket(socket) { } void BatteryService::updateSOC(float stateOfCharge) { _lastSOC = (int)round(stateOfCharge); batteryEvent(); } void BatteryService::setCharging(boolean isCharging) { _isCharging = isCharging; batteryEvent(); } boolean BatteryService::isCharging() { return _isCharging; } int BatteryService::getSOC() { return _lastSOC; } void BatteryService::begin() { _socket->registerEvent(EVENT_BATTERY); } void BatteryService::batteryEvent() { JsonDocument doc; doc["soc"] = _lastSOC; doc["charging"] = _isCharging; JsonObject jsonObject = doc.as(); _socket->emitEvent(EVENT_BATTERY, jsonObject); } ================================================ FILE: lib/framework/BatteryService.h ================================================ #pragma once /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #define EVENT_BATTERY "battery" class BatteryService { public: BatteryService(EventSocket *socket); void begin(); void updateSOC(float stateOfCharge); void setCharging(boolean isCharging); boolean isCharging(); int getSOC(); private: EventSocket *_socket; int _lastSOC = 100; boolean _isCharging = false; void batteryEvent(); }; ================================================ FILE: lib/framework/CoreDump.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include "esp_core_dump.h" #include "esp_partition.h" #include "esp_flash.h" #define MIN(a, b) ({ __typeof__ (a) _a = (a); __typeof__ (b) _b = (b); _a < _b ? _a : _b; }) CoreDump::CoreDump(PsychicHttpServer *server, SecurityManager *securityManager) : _server(server), _securityManager(securityManager) { } void CoreDump::begin() { _server->on(CORE_DUMP_SERVICE_PATH, HTTP_GET, _securityManager->wrapRequest(std::bind(&CoreDump::coreDump, this, std::placeholders::_1), AuthenticationPredicates::IS_AUTHENTICATED)); ESP_LOGV("CoreDump", "Registered GET endpoint: %s", CORE_DUMP_SERVICE_PATH); } esp_err_t CoreDump::coreDump(PsychicRequest *request) { size_t coredump_addr; size_t coredump_size; esp_err_t err = esp_core_dump_image_get(&coredump_addr, &coredump_size); if (err != ESP_OK) { request->reply(500, "application/json", "{\"status\":\"error\",\"message\":\"core dump not available\"}"); return err; } size_t const chunk_len = 3 * 16; // must be multiple of 3 size_t const b64_len = chunk_len / 3 * 4 + 4; uint8_t *const chunk = (uint8_t *)malloc(chunk_len); char *const b64 = (char *)malloc(b64_len); assert(chunk && b64); /*if (write_cfg->start) { if ((err = write_cfg->start(write_cfg->priv)) != ESP_OK) { return err; } }*/ ESP_LOGI(SVK_TAG, "Coredump is %u bytes", coredump_size); httpd_resp_set_status(request->request(), "200 OK"); PsychicResponse response(request); response.setCode(200); response.setContentType("application/octet-stream"); response.sendHeaders(); for (size_t offset = 0; offset < coredump_size; offset += chunk_len) { uint const read_len = MIN(chunk_len, coredump_size - offset); if (esp_flash_read(esp_flash_default_chip, chunk, coredump_addr + offset, read_len)) { ESP_LOGE(SVK_TAG, "Coredump read failed"); break; } err = response.sendChunk(chunk, read_len); if (err != ESP_OK) { break; } } free(chunk); free(b64); err = response.finishChunking(); /*uint32_t sec_num = coredump_size / SPI_FLASH_SEC_SIZE; if (coredump_size % SPI_FLASH_SEC_SIZE) { sec_num++; } err = esp_flash_erase_region(esp_flash_default_chip, coredump_addr, sec_num * SPI_FLASH_SEC_SIZE); if (err != ESP_OK) { ESP_LOGE(SVK_TAG, "Failed to erase coredump (%d)!", err); }*/ return err; } ================================================ FILE: lib/framework/CoreDump.h ================================================ #ifndef CoreDump_h #define CoreDump_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #include #define CORE_DUMP_SERVICE_PATH "/rest/coreDump" class CoreDump { public: CoreDump(PsychicHttpServer *server, SecurityManager *securityManager); void begin(); private: PsychicHttpServer *_server; SecurityManager *_securityManager; esp_err_t coreDump(PsychicRequest *request); }; #endif // end CoreDump_h ================================================ FILE: lib/framework/DownloadFirmwareService.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include extern const uint8_t rootca_crt_bundle_start[] asm("_binary_src_certs_x509_crt_bundle_bin_start"); extern const uint8_t rootca_crt_bundle_end[] asm("_binary_src_certs_x509_crt_bundle_bin_end"); /** * This is github-io.pem */ const char *githubCACertificate = "-----BEGIN CERTIFICATE-----\n" "MIIGEzCCA/ugAwIBAgIQfVtRJrR2uhHbdBYLvFMNpzANBgkqhkiG9w0BAQwFADCB\n" "iDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0pl\n" "cnNleSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNV\n" "BAMTJVVTRVJUcnVzdCBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTgx\n" "MTAyMDAwMDAwWhcNMzAxMjMxMjM1OTU5WjCBjzELMAkGA1UEBhMCR0IxGzAZBgNV\n" "BAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEYMBYGA1UE\n" "ChMPU2VjdGlnbyBMaW1pdGVkMTcwNQYDVQQDEy5TZWN0aWdvIFJTQSBEb21haW4g\n" "VmFsaWRhdGlvbiBTZWN1cmUgU2VydmVyIENBMIIBIjANBgkqhkiG9w0BAQEFAAOC\n" "AQ8AMIIBCgKCAQEA1nMz1tc8INAA0hdFuNY+B6I/x0HuMjDJsGz99J/LEpgPLT+N\n" "TQEMgg8Xf2Iu6bhIefsWg06t1zIlk7cHv7lQP6lMw0Aq6Tn/2YHKHxYyQdqAJrkj\n" "eocgHuP/IJo8lURvh3UGkEC0MpMWCRAIIz7S3YcPb11RFGoKacVPAXJpz9OTTG0E\n" "oKMbgn6xmrntxZ7FN3ifmgg0+1YuWMQJDgZkW7w33PGfKGioVrCSo1yfu4iYCBsk\n" "Haswha6vsC6eep3BwEIc4gLw6uBK0u+QDrTBQBbwb4VCSmT3pDCg/r8uoydajotY\n" "uK3DGReEY+1vVv2Dy2A0xHS+5p3b4eTlygxfFQIDAQABo4IBbjCCAWowHwYDVR0j\n" "BBgwFoAUU3m/WqorSs9UgOHYm8Cd8rIDZsswHQYDVR0OBBYEFI2MXsRUrYrhd+mb\n" "+ZsF4bgBjWHhMA4GA1UdDwEB/wQEAwIBhjASBgNVHRMBAf8ECDAGAQH/AgEAMB0G\n" "A1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAbBgNVHSAEFDASMAYGBFUdIAAw\n" "CAYGZ4EMAQIBMFAGA1UdHwRJMEcwRaBDoEGGP2h0dHA6Ly9jcmwudXNlcnRydXN0\n" "LmNvbS9VU0VSVHJ1c3RSU0FDZXJ0aWZpY2F0aW9uQXV0aG9yaXR5LmNybDB2Bggr\n" "BgEFBQcBAQRqMGgwPwYIKwYBBQUHMAKGM2h0dHA6Ly9jcnQudXNlcnRydXN0LmNv\n" "bS9VU0VSVHJ1c3RSU0FBZGRUcnVzdENBLmNydDAlBggrBgEFBQcwAYYZaHR0cDov\n" "L29jc3AudXNlcnRydXN0LmNvbTANBgkqhkiG9w0BAQwFAAOCAgEAMr9hvQ5Iw0/H\n" "ukdN+Jx4GQHcEx2Ab/zDcLRSmjEzmldS+zGea6TvVKqJjUAXaPgREHzSyrHxVYbH\n" "7rM2kYb2OVG/Rr8PoLq0935JxCo2F57kaDl6r5ROVm+yezu/Coa9zcV3HAO4OLGi\n" "H19+24rcRki2aArPsrW04jTkZ6k4Zgle0rj8nSg6F0AnwnJOKf0hPHzPE/uWLMUx\n" "RP0T7dWbqWlod3zu4f+k+TY4CFM5ooQ0nBnzvg6s1SQ36yOoeNDT5++SR2RiOSLv\n" "xvcRviKFxmZEJCaOEDKNyJOuB56DPi/Z+fVGjmO+wea03KbNIaiGCpXZLoUmGv38\n" "sbZXQm2V0TP2ORQGgkE49Y9Y3IBbpNV9lXj9p5v//cWoaasm56ekBYdbqbe4oyAL\n" "l6lFhd2zi+WJN44pDfwGF/Y4QA5C5BIG+3vzxhFoYt/jmPQT2BVPi7Fp2RBgvGQq\n" "6jG35LWjOhSbJuMLe/0CjraZwTiXWTb2qHSihrZe68Zk6s+go/lunrotEbaGmAhY\n" "LcmsJWTyXnW0OMGuf1pGg+pRyrbxmRE1a6Vqe8YAsOf4vmSyrcjC8azjUeqkk+B5\n" "yOGBQMkKW+ESPMFgKuOXwIlCypTPRpgSabuY0MLTDXJLR27lk8QyKGOHQ+SwMj4K\n" "00u/I5sUKUErmgQfky3xxzlIPK1aEn8=\n" "-----END CERTIFICATE-----\n"; static EventSocket *_socket = nullptr; static int previousProgress = 0; static String *otaURL = nullptr; JsonDocument doc; void update_started() { String output; doc["status"] = "preparing"; doc["progress"] = 0; doc["bytes_written"] = 0; doc["total_bytes"] = 0; JsonObject jsonObject = doc.as(); _socket->emitEvent(EVENT_OTA_UPDATE, jsonObject); ESP_LOGI(SVK_TAG, "HTTP Update started"); #ifdef SERIAL_INFO Serial.println("HTTP Update started"); #endif } void update_progress(int currentBytes, int totalBytes) { doc["status"] = "progress"; int progress = ((currentBytes * 100) / totalBytes); if (progress > previousProgress) { doc["progress"] = progress; doc["bytes_written"] = currentBytes; doc["total_bytes"] = totalBytes; JsonObject jsonObject = doc.as(); _socket->emitEvent(EVENT_OTA_UPDATE, jsonObject); ESP_LOGV(SVK_TAG, "HTTP update process at %d of %d bytes... (%d %%)", currentBytes, totalBytes, progress); } previousProgress = progress; } void update_finished() { String output; doc["status"] = "finished"; doc["progress"] = 100; // Keep the last known bytes_written and total_bytes from progress JsonObject jsonObject = doc.as(); _socket->emitEvent(EVENT_OTA_UPDATE, jsonObject); ESP_LOGI(SVK_TAG, "HTTP Update successful - Restarting"); #ifdef SERIAL_INFO Serial.println("HTTP Update successful - Restarting"); #endif vTaskDelay(250 / portTICK_PERIOD_MS); } void updateTask(void *param) { String url = *((String *)param); delete (String *)param; // Clean up the allocated memory WiFiClientSecure client; #ifndef DOWNLOAD_OTA_SKIP_CERT_VERIFY #if ESP_ARDUINO_VERSION_MAJOR == 3 client.setCACertBundle(rootca_crt_bundle_start, rootca_crt_bundle_end - rootca_crt_bundle_start); #else client.setCACertBundle(rootca_crt_bundle_start); #endif #else ESP_LOGW(SVK_TAG, "Skipping SSL certificate verification for OTA update!"); client.setInsecure(); #endif client.setTimeout(12000); httpUpdate.setFollowRedirects(HTTPC_FORCE_FOLLOW_REDIRECTS); httpUpdate.rebootOnUpdate(true); String output; httpUpdate.onStart(update_started); httpUpdate.onProgress(update_progress); httpUpdate.onEnd(update_finished); t_httpUpdate_return ret = httpUpdate.update(client, url.c_str()); JsonObject jsonObject; // Reduce task priority to allow other tasks to run vTaskPrioritySet(NULL, tskIDLE_PRIORITY + 1); bool _emitEvent = false; switch (ret) { case HTTP_UPDATE_FAILED: doc["status"] = "error"; doc["error"] = httpUpdate.getLastErrorString().c_str(); _emitEvent = true; ESP_LOGE(SVK_TAG, "HTTP Update failed with error (%d): %s", httpUpdate.getLastError(), httpUpdate.getLastErrorString().c_str()); #ifdef SERIAL_INFO Serial.printf("HTTP Update failed with error (%d): %s\n", httpUpdate.getLastError(), httpUpdate.getLastErrorString().c_str()); #endif break; case HTTP_UPDATE_NO_UPDATES: doc["status"] = "error"; doc["error"] = "Update failed, has same firmware version"; _emitEvent = true; ESP_LOGE(SVK_TAG, "HTTP Update failed, has same firmware version"); #ifdef SERIAL_INFO Serial.println("HTTP Update failed, has same firmware version"); #endif break; } if (_emitEvent) { jsonObject = doc.as(); _socket->emitEvent(EVENT_OTA_UPDATE, jsonObject); } // delay to allow the event to be sent out vTaskDelay(100 / portTICK_PERIOD_MS); vTaskDelete(NULL); } DownloadFirmwareService::DownloadFirmwareService(PsychicHttpServer *server, SecurityManager *securityManager, EventSocket *socket) : _server(server), _securityManager(securityManager), _socket(socket) { } void DownloadFirmwareService::begin() { ::_socket = _socket; if (!_socket->isEventValid(EVENT_OTA_UPDATE)) { _socket->registerEvent(EVENT_OTA_UPDATE); } _server->on(GITHUB_FIRMWARE_PATH, HTTP_POST, _securityManager->wrapCallback( std::bind(&DownloadFirmwareService::downloadUpdate, this, std::placeholders::_1, std::placeholders::_2), AuthenticationPredicates::IS_ADMIN)); ESP_LOGV(SVK_TAG, "Registered POST endpoint: %s", GITHUB_FIRMWARE_PATH); } esp_err_t DownloadFirmwareService::downloadUpdate(PsychicRequest *request, JsonVariant &json) { if (!json.is()) { return request->reply(400); } String downloadURL = json["download_url"]; ESP_LOGI(SVK_TAG, "Starting OTA from: %s", downloadURL.c_str()); #ifdef SERIAL_INFO Serial.println("Starting OTA from: " + downloadURL); #endif doc["status"] = "preparing"; doc["progress"] = 0; doc["bytes_written"] = 0; doc["total_bytes"] = 0; doc["error"] = ""; JsonObject jsonObject = doc.as(); _socket->emitEvent(EVENT_OTA_UPDATE, jsonObject); // Allocate memory for the URL on the heap String *urlPtr = new String(downloadURL); if (xTaskCreatePinnedToCore( &updateTask, // Function that should be called "Update", // Name of the task (for debugging) OTA_TASK_STACK_SIZE, // Stack size (bytes) urlPtr, // Pass reference to this class instance (configMAX_PRIORITIES - 1), // Pretty high task priority NULL, // Task handle 1 // Have it on application core ) != pdPASS) { delete urlPtr; // Clean up if task creation fails ESP_LOGE(SVK_TAG, "Couldn't create download OTA task"); #ifdef SERIAL_INFO Serial.println("Couldn't create download OTA task"); #endif return request->reply(500); } return request->reply(200); } ================================================ FILE: lib/framework/DownloadFirmwareService.h ================================================ #pragma once /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #include #include #include #include #include #define GITHUB_FIRMWARE_PATH "/rest/downloadUpdate" #define OTA_TASK_STACK_SIZE 9216 class DownloadFirmwareService { public: DownloadFirmwareService(PsychicHttpServer *server, SecurityManager *securityManager, EventSocket *socket); void begin(); private: SecurityManager *_securityManager; PsychicHttpServer *_server; EventSocket *_socket; esp_err_t downloadUpdate(PsychicRequest *request, JsonVariant &json); }; ================================================ FILE: lib/framework/ESP32SvelteKit.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include ESP32SvelteKit::ESP32SvelteKit(PsychicHttpServer *server, unsigned int numberEndpoints) : _server(server), _numberEndpoints(numberEndpoints), _featureService(server, &_socket), _securitySettingsService(server, &ESPFS), _wifiSettingsService(server, &ESPFS, &_securitySettingsService, &_socket), _wifiScanner(server, &_securitySettingsService), _wifiStatus(server, &_securitySettingsService), _apSettingsService(server, &ESPFS, &_securitySettingsService), _apStatus(server, &_securitySettingsService, &_apSettingsService), #if FT_ENABLED(FT_ETHERNET) _ethernetSettingsService(server, &ESPFS, &_securitySettingsService, &_socket), _ethernetStatus(server, &_securitySettingsService), #endif _socket(server, &_securitySettingsService, AuthenticationPredicates::IS_AUTHENTICATED), _notificationService(&_socket), #if FT_ENABLED(FT_NTP) _ntpSettingsService(server, &ESPFS, &_securitySettingsService), _ntpStatus(server, &_securitySettingsService), #endif #if FT_ENABLED(FT_UPLOAD_FIRMWARE) _uploadFirmwareService(server, &_securitySettingsService, &_socket), #endif #if FT_ENABLED(FT_DOWNLOAD_FIRMWARE) _downloadFirmwareService(server, &_securitySettingsService, &_socket), #endif #if FT_ENABLED(FT_MQTT) _mqttSettingsService(server, &ESPFS, &_securitySettingsService), _mqttStatus(server, &_mqttSettingsService, &_securitySettingsService), #endif #if FT_ENABLED(FT_SECURITY) _authenticationService(server, &_securitySettingsService), #endif #if FT_ENABLED(FT_SLEEP) _sleepService(server, &_securitySettingsService), #endif #if FT_ENABLED(FT_BATTERY) _batteryService(&_socket), #endif #if FT_ENABLED(FT_ANALYTICS) _analyticsService(&_socket), #endif _restartService(server, &_securitySettingsService), _factoryResetService(server, &ESPFS, &_securitySettingsService), #if FT_ENABLED(FT_COREDUMP) _coreDump(server, &_securitySettingsService), #endif _systemStatus(server, &_securitySettingsService) { } void ESP32SvelteKit::begin() { ESP_LOGV(SVK_TAG, "Loading settings from files system"); ESPFS.begin(true); #if FT_ENABLED(FT_ETHERNET) _ethernetSettingsService.initEthernet(); #endif _wifiSettingsService.initWiFi(); // SvelteKit uses a lot of handlers, so we need to increase the max_uri_handlers // WWWData has 77 Endpoints, Framework has 27, and Lighstate Demo has 4 _server->config.max_uri_handlers = _numberEndpoints; _server->listen(80); #ifdef EMBED_WWW // Serve static resources from PROGMEM ESP_LOGV(SVK_TAG, "Registering routes from PROGMEM static resources"); WWWData::registerRoutes( [&](const String &uri, const String &contentType, const uint8_t *content, size_t len) { PsychicHttpRequestCallback requestHandler = [contentType, content, len](PsychicRequest *request) { PsychicResponse response(request); response.setCode(200); response.setContentType(contentType.c_str()); response.addHeader("Content-Encoding", "gzip"); response.addHeader("Cache-Control", "public, immutable, max-age=31536000"); response.setContent(content, len); return response.send(); }; PsychicWebHandler *handler = new PsychicWebHandler(); handler->onRequest(requestHandler); _server->on(uri.c_str(), HTTP_GET, handler); // Set default end-point for all non matching requests // this is easier than using webServer.onNotFound() if (uri.equals("/index.html")) { _server->defaultEndpoint->setHandler(handler); } }); #else // Serve static resources from /www/ ESP_LOGV(SVK_TAG, "Registering routes from FS /www/ static resources"); _server->serveStatic("/_app/", ESPFS, "/www/_app/"); _server->serveStatic("/favicon.png", ESPFS, "/www/favicon.png"); // Serving all other get requests with "/www/index.htm" _server->onNotFound([](PsychicRequest *request) { if (request->method() == HTTP_GET) { PsychicFileResponse response(request, ESPFS, "/www/index.html", "text/html"); return response.send(); // String url = "http://" + request->host() + "/index.html"; // request->redirect(url.c_str()); } }); #endif // Serve static resources from /config/ if set by platformio.ini #if SERVE_CONFIG_FILES _server->serveStatic("/config/", ESPFS, "/config/"); #endif #if defined(ENABLE_CORS) ESP_LOGV(SVK_TAG, "Enabling CORS headers"); DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", CORS_ORIGIN); DefaultHeaders::Instance().addHeader("Access-Control-Allow-Headers", "Accept, Content-Type, Authorization"); DefaultHeaders::Instance().addHeader("Access-Control-Allow-Credentials", "true"); #endif ESP_LOGV(SVK_TAG, "Starting MDNS"); MDNS.begin(_wifiSettingsService.getHostname().c_str()); MDNS.setInstanceName(_appName); MDNS.addService("http", "tcp", 80); MDNS.addService("ws", "tcp", 80); MDNS.addServiceTxt("http", "tcp", "Firmware Version", APP_VERSION); #ifdef SERIAL_INFO Serial.printf("Running Firmware Version: %s\n", APP_VERSION); #endif // Start the services _apStatus.begin(); _socket.begin(); _notificationService.begin(); _apSettingsService.begin(); _factoryResetService.begin(); _featureService.begin(); _restartService.begin(); _systemStatus.begin(); _wifiSettingsService.begin(); _wifiScanner.begin(); _wifiStatus.begin(); #if FT_ENABLED(FT_ETHERNET) _ethernetSettingsService.begin(); _ethernetStatus.begin(); #endif #if FT_ENABLED(FT_COREDUMP) _coreDump.begin(); #endif #if FT_ENABLED(FT_UPLOAD_FIRMWARE) _uploadFirmwareService.begin(); #endif #if FT_ENABLED(FT_DOWNLOAD_FIRMWARE) _downloadFirmwareService.begin(); #endif #if FT_ENABLED(FT_NTP) _ntpSettingsService.begin(); _ntpStatus.begin(); #endif #if FT_ENABLED(FT_MQTT) _mqttSettingsService.begin(); _mqttStatus.begin(); #endif #if FT_ENABLED(FT_SECURITY) _authenticationService.begin(); _securitySettingsService.begin(); #endif #if FT_ENABLED(FT_SLEEP) _sleepService.begin(); _sleepService.attachOnSleepCallback([&]() { ESP_LOGI(SVK_TAG, "Attempting to stop server"); for (auto client : _server->getClientList()) { client->close(); } vTaskDelete(_loopTaskHandle); ESP_LOGI(SVK_TAG, "Server stopped"); }); #if FT_ENABLED(FT_MQTT) _sleepService.attachOnSleepCallback([&]() { _mqttSettingsService.disconnect(); }); #endif #endif #if FT_ENABLED(FT_BATTERY) _batteryService.begin(); #endif #if FT_ENABLED(FT_ANALYTICS) _analyticsService.begin(); #endif // Start the loop task ESP_LOGV(SVK_TAG, "Starting loop task"); xTaskCreatePinnedToCore( this->_loopImpl, // Function that should be called "ESP32 SvelteKit Loop", // Name of the task (for debugging) 4096, // Stack size (bytes) this, // Pass reference to this class instance (tskIDLE_PRIORITY + 2), // task priority &_loopTaskHandle, // Task handle ESP32SVELTEKIT_RUNNING_CORE // Pin to application core ); } void ESP32SvelteKit::_loop() { TickType_t xLastWakeTime = xTaskGetTickCount(); bool wifi = false; bool ap = false; bool event = false; bool mqtt = false; #if FT_ENABLED(FT_ETHERNET) bool eth = false; #endif bool wifi_eth_combined = false; while (1) { _wifiSettingsService.loop(); // 30 seconds _apSettingsService.loop(); // 10 seconds #if FT_ENABLED(FT_MQTT) _mqttSettingsService.loop(); // 5 seconds #endif #if FT_ENABLED(FT_ANALYTICS) _analyticsService.loop(); #endif #if FT_ENABLED(FT_ETHERNET) _ethernetSettingsService.loop(); eth = _ethernetStatus.isConnected(); if (eth) { wifi_eth_combined = true; } #endif // Query the connectivity status wifi = _wifiStatus.isConnected(); if (wifi) { wifi_eth_combined = true; } ap = _apStatus.isActive(); event = _socket.getConnectedClients() > 0; #if FT_ENABLED(FT_MQTT) mqtt = _mqttStatus.isConnected(); #endif // Update the system status if (wifi_eth_combined && mqtt) { _connectionStatus = ConnectionStatus::STA_MQTT; } else if (wifi_eth_combined) { _connectionStatus = event ? ConnectionStatus::STA_CONNECTED : ConnectionStatus::STA; } else if (ap) { _connectionStatus = event ? ConnectionStatus::AP_CONNECTED : ConnectionStatus::AP; } else { _connectionStatus = ConnectionStatus::OFFLINE; } // iterate over all loop functions for (auto &function : _loopFunctions) { function(); } #ifdef TELEPLOT_TASKS static int lastTime = 0; if (millis() - lastTime > 1000) { lastTime = millis(); Serial.printf(">ESP32SveltekitTask:%i:%i\n", millis(), uxTaskGetStackHighWaterMark(NULL)); } #endif vTaskDelayUntil(&xLastWakeTime, ESP32SVELTEKIT_LOOP_INTERVAL / portTICK_PERIOD_MS); } } ================================================ FILE: lib/framework/ESP32SvelteKit.h ================================================ #ifndef ESP32SvelteKit_h #define ESP32SvelteKit_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef EMBED_WWW #include #endif #ifndef CORS_ORIGIN #define CORS_ORIGIN "*" #endif #ifndef APP_VERSION #define APP_VERSION "demo" #endif #ifndef APP_NAME #define APP_NAME "ESP32 SvelteKit Demo" #endif #ifndef ESP32SVELTEKIT_RUNNING_CORE #define ESP32SVELTEKIT_RUNNING_CORE -1 #endif #ifndef ESP32SVELTEKIT_LOOP_INTERVAL #define ESP32SVELTEKIT_LOOP_INTERVAL 10 #endif // define callback function to include into the main loop typedef std::function loopCallback; // enum for connection status enum class ConnectionStatus { OFFLINE, AP, AP_CONNECTED, STA, STA_CONNECTED, STA_MQTT }; class ESP32SvelteKit { public: ESP32SvelteKit(PsychicHttpServer *server, unsigned int numberEndpoints = 115); void begin(); ConnectionStatus getConnectionStatus() { return _connectionStatus; } FS *getFS() { return &ESPFS; } PsychicHttpServer *getServer() { return _server; } SecurityManager *getSecurityManager() { return &_securitySettingsService; } EventSocket *getSocket() { return &_socket; } #if FT_ENABLED(FT_SECURITY) SecuritySettingsService *getSecuritySettingsService() { return &_securitySettingsService; } #endif WiFiSettingsService *getWiFiSettingsService() { return &_wifiSettingsService; } APSettingsService *getAPSettingsService() { return &_apSettingsService; } NotificationService *getNotificationService() { return &_notificationService; } #if FT_ENABLED(FT_NTP) NTPSettingsService *getNTPSettingsService() { return &_ntpSettingsService; } #endif #if FT_ENABLED(FT_MQTT) MqttSettingsService *getMqttSettingsService() { return &_mqttSettingsService; } PsychicMqttClient *getMqttClient() { return _mqttSettingsService.getMqttClient(); } #endif #if FT_ENABLED(FT_SLEEP) SleepService *getSleepService() { return &_sleepService; } #endif #if FT_ENABLED(FT_BATTERY) BatteryService *getBatteryService() { return &_batteryService; } #endif FeaturesService *getFeatureService() { return &_featureService; } RestartService *getRestartService() { return &_restartService; } void factoryReset() { _factoryResetService.factoryReset(); } void setMDNSAppName(String name) { _appName = name; } void recoveryMode() { _apSettingsService.recoveryMode(); } void addLoopFunction(loopCallback function) { _loopFunctions.push_back(function); } private: PsychicHttpServer *_server; TaskHandle_t _loopTaskHandle; unsigned int _numberEndpoints; FeaturesService _featureService; SecuritySettingsService _securitySettingsService; WiFiSettingsService _wifiSettingsService; WiFiScanner _wifiScanner; WiFiStatus _wifiStatus; APSettingsService _apSettingsService; APStatus _apStatus; #if FT_ENABLED(FT_ETHERNET) EthernetSettingsService _ethernetSettingsService; EthernetStatus _ethernetStatus; #endif EventSocket _socket; NotificationService _notificationService; #if FT_ENABLED(FT_NTP) NTPSettingsService _ntpSettingsService; NTPStatus _ntpStatus; #endif #if FT_ENABLED(FT_UPLOAD_FIRMWARE) UploadFirmwareService _uploadFirmwareService; #endif #if FT_ENABLED(FT_DOWNLOAD_FIRMWARE) DownloadFirmwareService _downloadFirmwareService; #endif #if FT_ENABLED(FT_MQTT) MqttSettingsService _mqttSettingsService; MqttStatus _mqttStatus; #endif #if FT_ENABLED(FT_SECURITY) AuthenticationService _authenticationService; #endif #if FT_ENABLED(FT_SLEEP) SleepService _sleepService; #endif #if FT_ENABLED(FT_BATTERY) BatteryService _batteryService; #endif #if FT_ENABLED(FT_ANALYTICS) AnalyticsService _analyticsService; #endif #if FT_ENABLED(FT_COREDUMP) CoreDump _coreDump; #endif RestartService _restartService; FactoryResetService _factoryResetService; SystemStatus _systemStatus; String _appName = APP_NAME; protected: static void _loopImpl(void *_this) { static_cast(_this)->_loop(); } void _loop(); std::vector _loopFunctions; // Connectivity status ConnectionStatus _connectionStatus = ConnectionStatus::OFFLINE; }; #endif ================================================ FILE: lib/framework/ESPFS.h ================================================ #ifndef ESPFS_H_ #define ESPFS_H_ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #define ESPFS LittleFS #endif ================================================ FILE: lib/framework/EthernetSettingsService.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #if FT_ENABLED(FT_ETHERNET) EthernetSettingsService::EthernetSettingsService(PsychicHttpServer *server, FS *fs, SecurityManager *securityManager, EventSocket *socket) : _server(server), _securityManager(securityManager), _httpEndpoint(EthernetSettings::read, EthernetSettings::update, this, server, ETHERNET_SETTINGS_SERVICE_PATH, securityManager, AuthenticationPredicates::IS_ADMIN), _fsPersistence(EthernetSettings::read, EthernetSettings::update, this, fs, ETHERNET_SETTINGS_FILE), _socket(socket) { addUpdateHandler([&](const String &originId) { reconfigureEthernet(); }, false); } void EthernetSettingsService::initEthernet() { // make sure the interface is stopped before continuing and initializing ETH.end(); _fsPersistence.readFromFS(); configureNetwork(_state.ethernetSettings); } void EthernetSettingsService::begin() { _socket->registerEvent(EVENT_ETHERNET); _httpEndpoint.begin(); } void EthernetSettingsService::loop() { unsigned long currentMillis = millis(); if (!_lastEthernetUpdate || (unsigned long)(currentMillis - _lastEthernetUpdate) >= ETHERNET_EVENT_DELAY) { _lastEthernetUpdate = currentMillis; updateEthernet(); } } String EthernetSettingsService::getHostname() { return _state.hostname; } String EthernetSettingsService::getIP() { if (ETH.connected()) { return ETH.localIP().toString(); } return "Not connected"; } void EthernetSettingsService::configureNetwork(ethernet_settings_t &network) { // set hostname before IP configuration starts ETH.setHostname(_state.hostname.c_str()); if (network.staticIPConfig) { // configure for static IP ETH.config(network.localIP, network.gatewayIP, network.subnetMask, network.dnsIP1, network.dnsIP2); } else { // configure for DHCP ETH.config(INADDR_NONE, INADDR_NONE, INADDR_NONE); } // (re)start ethernet #if CONFIG_IDF_TARGET_ESP32 // ESP32 chips with built-in ethernet MAC/PHY ETH.begin(); #else // For SPI based ethernet modules like W5500, ENC28J60 etc. SPI.begin(ETH_SPI_SCK, ETH_SPI_MISO, ETH_SPI_MOSI); ETH.begin(ETH_PHY_TYPE, ETH_PHY_ADDR, ETH_PHY_CS, ETH_PHY_IRQ, ETH_PHY_RST, SPI); #endif // set hostname (again) after (re)starting ethernet due to a bug in the ESP-IDF implementation ETH.setHostname(_state.hostname.c_str()); } void EthernetSettingsService::reconfigureEthernet() { configureNetwork(_state.ethernetSettings); } void EthernetSettingsService::updateEthernet() { JsonDocument doc; doc["connected"] = ETH.connected(); JsonObject jsonObject = doc.as(); _socket->emitEvent(EVENT_ETHERNET, jsonObject); } #endif // end FT_ENABLED(FT_ETHERNET) ================================================ FILE: lib/framework/EthernetSettingsService.h ================================================ #ifndef EthernetSettingsService_h #define EthernetSettingsService_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #include #include #include #include #include #include #include #ifndef FACTORY_ETHERNET_HOSTNAME #define FACTORY_ETHERNET_HOSTNAME "#{platform}-#{unique_id}" #endif #define ETHERNET_EVENT_DELAY 500 #define ETHERNET_SETTINGS_FILE "/config/ethernetSettings.json" #define ETHERNET_SETTINGS_SERVICE_PATH "/rest/ethernetSettings" #define EVENT_ETHERNET "ethernet" #if FT_ENABLED(FT_ETHERNET) // Struct defining the ethernet settings typedef struct { bool staticIPConfig; IPAddress localIP; IPAddress gatewayIP; IPAddress subnetMask; IPAddress dnsIP1; IPAddress dnsIP2; bool available; } ethernet_settings_t; class EthernetSettings { public: // core ethernet configuration String hostname; ethernet_settings_t ethernetSettings; static void read(EthernetSettings &settings, JsonObject &root) { root["hostname"] = settings.hostname; root["static_ip_config"] = settings.ethernetSettings.staticIPConfig; JsonUtils::writeIP(root, "local_ip", settings.ethernetSettings.localIP); JsonUtils::writeIP(root, "gateway_ip", settings.ethernetSettings.gatewayIP); JsonUtils::writeIP(root, "subnet_mask", settings.ethernetSettings.subnetMask); JsonUtils::writeIP(root, "dns_ip_1", settings.ethernetSettings.dnsIP1); JsonUtils::writeIP(root, "dns_ip_2", settings.ethernetSettings.dnsIP2); ESP_LOGV(SVK_TAG, "Ethernet Settings read"); } static StateUpdateResult update(JsonObject &root, EthernetSettings &settings, const String &originId) { settings.hostname = root["hostname"] | SettingValue::format(FACTORY_ETHERNET_HOSTNAME); settings.ethernetSettings.staticIPConfig = root["static_ip_config"] | false; JsonUtils::readIP(root, "local_ip", settings.ethernetSettings.localIP); JsonUtils::readIP(root, "gateway_ip", settings.ethernetSettings.gatewayIP); JsonUtils::readIP(root, "subnet_mask", settings.ethernetSettings.subnetMask); JsonUtils::readIP(root, "dns_ip_1", settings.ethernetSettings.dnsIP1); JsonUtils::readIP(root, "dns_ip_2", settings.ethernetSettings.dnsIP2); // Swap around the dns servers if 2 is populated but 1 is not if (IPUtils::isNotSet(settings.ethernetSettings.dnsIP1) && IPUtils::isSet(settings.ethernetSettings.dnsIP2)) { settings.ethernetSettings.dnsIP1 = settings.ethernetSettings.dnsIP2; settings.ethernetSettings.dnsIP2 = INADDR_NONE; } // Turning off static ip config if we don't meet the minimum requirements // of ipAddress and subnet. This may change to static ip only // as sensible defaults can be assumed for gateway and subnet if (settings.ethernetSettings.staticIPConfig && (IPUtils::isNotSet(settings.ethernetSettings.localIP) || IPUtils::isNotSet(settings.ethernetSettings.subnetMask))) { settings.ethernetSettings.staticIPConfig = false; } ESP_LOGV(SVK_TAG, "Ethernet Settings updated"); return StateUpdateResult::CHANGED; }; }; class EthernetSettingsService : public StatefulService { public: EthernetSettingsService(PsychicHttpServer *server, FS *fs, SecurityManager *securityManager, EventSocket *socket); void initEthernet(); void begin(); void loop(); String getHostname(); String getIP(); private: PsychicHttpServer *_server; SecurityManager *_securityManager; HttpEndpoint _httpEndpoint; FSPersistence _fsPersistence; EventSocket *_socket; unsigned long _lastEthernetUpdate; void configureNetwork(ethernet_settings_t &network); void reconfigureEthernet(); void updateEthernet(); }; #endif // end FT_ENABLED(FT_ETHERNET) #endif // end EthernetSettingsService_h ================================================ FILE: lib/framework/EthernetStatus.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #if FT_ENABLED(FT_ETHERNET) EthernetStatus::EthernetStatus(PsychicHttpServer *server, SecurityManager *securityManager) : _server(server), _securityManager(securityManager) { } void EthernetStatus::begin() { _server->on(ETHERNET_STATUS_SERVICE_PATH, HTTP_GET, _securityManager->wrapRequest(std::bind(&EthernetStatus::ethernetStatus, this, std::placeholders::_1), AuthenticationPredicates::IS_AUTHENTICATED)); ESP_LOGV(SVK_TAG, "Registered GET endpoint: %s", ETHERNET_STATUS_SERVICE_PATH); // arduino also uses WiFi events for Ethernet WiFi.onEvent(onConnected, WiFiEvent_t::ARDUINO_EVENT_ETH_CONNECTED); WiFi.onEvent(onDisconnected, WiFiEvent_t::ARDUINO_EVENT_ETH_DISCONNECTED); WiFi.onEvent(onGotIP, WiFiEvent_t::ARDUINO_EVENT_ETH_GOT_IP); } void EthernetStatus::onConnected(WiFiEvent_t event, WiFiEventInfo_t info) { ESP_LOGI(SVK_TAG, "Ethernet Connected."); #ifdef SERIAL_INFO Serial.println("Ethernet Connected."); #endif } void EthernetStatus::onDisconnected(WiFiEvent_t event, WiFiEventInfo_t info) { ESP_LOGI(SVK_TAG, "Ethernet Disconnected."); #ifdef SERIAL_INFO Serial.print("Ethernet Disconnected."); #endif } void EthernetStatus::onGotIP(WiFiEvent_t event, WiFiEventInfo_t info) { ESP_LOGI(SVK_TAG, "Ethernet Got IP. localIP=%s, hostName=%s", ETH.localIP().toString().c_str(), ETH.getHostname()); #ifdef SERIAL_INFO Serial.printf("Ethernet Got IP. localIP=%s, hostName=%s\r\n", ETH.localIP().toString().c_str(), ETH.getHostname()); #endif } esp_err_t EthernetStatus::ethernetStatus(PsychicRequest *request) { PsychicJsonResponse response = PsychicJsonResponse(request, false); JsonObject root = response.getRoot(); bool isConnected = ETH.connected(); root["connected"] = isConnected; if (isConnected) { root["local_ip"] = ETH.localIP().toString(); root["mac_address"] = ETH.macAddress(); root["subnet_mask"] = ETH.subnetMask().toString(); root["gateway_ip"] = ETH.gatewayIP().toString(); IPAddress dnsIP1 = ETH.dnsIP(0); IPAddress dnsIP2 = ETH.dnsIP(1); if (IPUtils::isSet(dnsIP1)) { root["dns_ip_1"] = dnsIP1.toString(); } if (IPUtils::isSet(dnsIP2)) { root["dns_ip_2"] = dnsIP2.toString(); } root["link_speed"] = ETH.linkSpeed(); } return response.send(); } bool EthernetStatus::isConnected() { return ETH.connected(); } #endif // end FT_ENABLED(FT_ETHERNET) ================================================ FILE: lib/framework/EthernetStatus.h ================================================ #ifndef EthernetStatus_h #define EthernetStatus_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #include #include #define ETHERNET_STATUS_SERVICE_PATH "/rest/ethernetStatus" #if FT_ENABLED(FT_ETHERNET) class EthernetStatus { public: EthernetStatus(PsychicHttpServer *server, SecurityManager *securityManager); void begin(); bool isConnected(); private: PsychicHttpServer *_server; SecurityManager *_securityManager; // static functions for logging Ethernet events to the UART // they are using the same signature as WiFi events static void onConnected(WiFiEvent_t event, WiFiEventInfo_t info); static void onDisconnected(WiFiEvent_t event, WiFiEventInfo_t info); static void onGotIP(WiFiEvent_t event, WiFiEventInfo_t info); esp_err_t ethernetStatus(PsychicRequest *request); }; #endif // end FT_ENABLED(FT_ETHERNET) #endif // end EthernetStatus_h ================================================ FILE: lib/framework/EventEndpoint.h ================================================ #ifndef EventEndpoint_h #define EventEndpoint_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include template class EventEndpoint { public: EventEndpoint(JsonStateReader stateReader, JsonStateUpdater stateUpdater, StatefulService *statefulService, EventSocket *socket, const char *event) : _stateReader(stateReader), _stateUpdater(stateUpdater), _statefulService(statefulService), _socket(socket), _event(event) { _statefulService->addUpdateHandler([&](const String &originId) { syncState(originId); }, false); } void begin() { _socket->registerEvent(_event); _socket->onEvent(_event, std::bind(&EventEndpoint::updateState, this, std::placeholders::_1, std::placeholders::_2)); _socket->onSubscribe(_event, [&](const String &originId) { syncState(originId, true); }); } private: JsonStateReader _stateReader; JsonStateUpdater _stateUpdater; StatefulService *_statefulService; EventSocket *_socket; const char *_event; void updateState(JsonObject &root, int originId) { _statefulService->update(root, _stateUpdater, String(originId)); } void syncState(const String &originId, bool sync = false) { JsonDocument jsonDocument; JsonObject root = jsonDocument.to(); _statefulService->read(root, _stateReader); JsonObject jsonObject = jsonDocument.as(); _socket->emitEvent(_event, jsonObject, originId.c_str(), sync); } }; #endif ================================================ FILE: lib/framework/EventSocket.cpp ================================================ #include SemaphoreHandle_t clientSubscriptionsMutex = xSemaphoreCreateMutex(); EventSocket::EventSocket(PsychicHttpServer *server, SecurityManager *securityManager, AuthenticationPredicate authenticationPredicate) : _server(server), _securityManager(securityManager), _authenticationPredicate(authenticationPredicate) { } void EventSocket::begin() { _socket.setFilter(_securityManager->filterRequest(_authenticationPredicate)); _socket.onOpen((std::bind(&EventSocket::onWSOpen, this, std::placeholders::_1))); _socket.onClose(std::bind(&EventSocket::onWSClose, this, std::placeholders::_1)); _socket.onFrame(std::bind(&EventSocket::onFrame, this, std::placeholders::_1, std::placeholders::_2)); _server->on(EVENT_SERVICE_PATH, &_socket); ESP_LOGV(SVK_TAG, "Registered event socket endpoint: %s", EVENT_SERVICE_PATH); } void EventSocket::registerEvent(String event) { if (!isEventValid(event)) { ESP_LOGD(SVK_TAG, "Registering event: %s", event.c_str()); events.push_back(event); } else { ESP_LOGW(SVK_TAG, "Event already registered: %s", event.c_str()); } } void EventSocket::onWSOpen(PsychicWebSocketClient *client) { ESP_LOGI(SVK_TAG, "ws[%s][%u] connect", client->remoteIP().toString().c_str(), client->socket()); } void EventSocket::onWSClose(PsychicWebSocketClient *client) { xSemaphoreTake(clientSubscriptionsMutex, portMAX_DELAY); for (auto &event_subscriptions : client_subscriptions) { event_subscriptions.second.remove(client->socket()); } xSemaphoreGive(clientSubscriptionsMutex); ESP_LOGI(SVK_TAG, "ws[%s][%u] disconnect", client->remoteIP().toString().c_str(), client->socket()); } esp_err_t EventSocket::onFrame(PsychicWebSocketRequest *request, httpd_ws_frame *frame) { ESP_LOGV(SVK_TAG, "ws[%s][%u] opcode[%d]", request->client()->remoteIP().toString().c_str(), request->client()->socket(), frame->type); JsonDocument doc; #if FT_ENABLED(EVENT_USE_JSON) if (frame->type == HTTPD_WS_TYPE_TEXT) { ESP_LOGV(SVK_TAG, "ws[%s][%u] request: %s", request->client()->remoteIP().toString().c_str(), request->client()->socket(), (char *)frame->payload); DeserializationError error = deserializeJson(doc, (char *)frame->payload, frame->len); #else if (frame->type == HTTPD_WS_TYPE_BINARY) { ESP_LOGV(SVK_TAG, "ws[%s][%u] request: %s", request->client()->remoteIP().toString().c_str(), request->client()->socket(), (char *)frame->payload); DeserializationError error = deserializeMsgPack(doc, (char *)frame->payload, frame->len); #endif if (!error && doc.is()) { String event = doc["event"]; if (event == "subscribe") { // only subscribe to events that are registered if (isEventValid(doc["data"].as())) { client_subscriptions[doc["data"]].push_back(request->client()->socket()); handleSubscribeCallbacks(doc["data"], String(request->client()->socket())); } else { ESP_LOGW(SVK_TAG, "Client tried to subscribe to unregistered event: %s", doc["data"].as().c_str()); } } else if (event == "unsubscribe") { client_subscriptions[doc["data"]].remove(request->client()->socket()); } else { JsonObject jsonObject = doc["data"].as(); handleEventCallbacks(event, jsonObject, request->client()->socket()); } return ESP_OK; } ESP_LOGW(SVK_TAG, "Error[%d] parsing JSON: %s", error, (char *)frame->payload); } return ESP_OK; } void EventSocket::emitEvent(String event, JsonObject &jsonObject, const char *originId, bool onlyToSameOrigin) { // Only process valid events if (!isEventValid(String(event))) { ESP_LOGW(SVK_TAG, "Method tried to emit unregistered event: %s", event); return; } int originSubscriptionId = originId[0] ? atoi(originId) : -1; xSemaphoreTake(clientSubscriptionsMutex, portMAX_DELAY); auto &subscriptions = client_subscriptions[event]; if (subscriptions.empty()) { xSemaphoreGive(clientSubscriptionsMutex); return; } JsonDocument doc; doc["event"] = event; doc["data"] = jsonObject; #if FT_ENABLED(EVENT_USE_JSON) size_t len = measureJson(doc); #else size_t len = measureMsgPack(doc); #endif char *output = new char[len + 1]; #if FT_ENABLED(EVENT_USE_JSON) serializeJson(doc, output, len + 1); #else serializeMsgPack(doc, output, len); #endif // null terminate the string output[len] = '\0'; // if onlyToSameOrigin == true, send the message back to the origin if (onlyToSameOrigin && originSubscriptionId > 0) { auto *client = _socket.getClient(originSubscriptionId); if (client) { ESP_LOGV(SVK_TAG, "Emitting event: %s to %s[%u], Message[%d]: %s", event, client->remoteIP().toString().c_str(), client->socket(), len, output); #if FT_ENABLED(EVENT_USE_JSON) client->sendMessage(HTTPD_WS_TYPE_TEXT, output, len); #else client->sendMessage(HTTPD_WS_TYPE_BINARY, output, len); #endif } } else { // else send the message to all other clients for (int subscription : client_subscriptions[event]) { if (subscription == originSubscriptionId) continue; auto *client = _socket.getClient(subscription); if (!client) { subscriptions.remove(subscription); continue; } ESP_LOGV(SVK_TAG, "Emitting event: %s to %s[%u], Message[%d]: %s", event, client->remoteIP().toString().c_str(), client->socket(), len, output); #if FT_ENABLED(EVENT_USE_JSON) client->sendMessage(HTTPD_WS_TYPE_TEXT, output, len); #else client->sendMessage(HTTPD_WS_TYPE_BINARY, output, len); #endif } } delete[] output; xSemaphoreGive(clientSubscriptionsMutex); } void EventSocket::handleEventCallbacks(String event, JsonObject &jsonObject, int originId) { for (auto &callback : event_callbacks[event]) { callback(jsonObject, originId); } } void EventSocket::handleSubscribeCallbacks(String event, const String &originId) { for (auto &callback : subscribe_callbacks[event]) { callback(originId); } } void EventSocket::onEvent(String event, EventCallback callback) { if (!isEventValid(event)) { ESP_LOGW(SVK_TAG, "Method tried to register unregistered event: %s", event.c_str()); return; } event_callbacks[event].push_back(callback); } void EventSocket::onSubscribe(String event, SubscribeCallback callback) { if (!isEventValid(event)) { ESP_LOGW(SVK_TAG, "Method tried to subscribe to unregistered event: %s", event.c_str()); return; } subscribe_callbacks[event].push_back(callback); ESP_LOGI(SVK_TAG, "onSubscribe for event: %s", event.c_str()); } bool EventSocket::isEventValid(String event) { return std::find(events.begin(), events.end(), event) != events.end(); } unsigned int EventSocket::getConnectedClients() { return (unsigned int)_socket.getClientList().size(); } ================================================ FILE: lib/framework/EventSocket.h ================================================ #ifndef Socket_h #define Socket_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #include #include #define EVENT_SERVICE_PATH "/ws/events" typedef std::function EventCallback; typedef std::function SubscribeCallback; class EventSocket { public: EventSocket(PsychicHttpServer *server, SecurityManager *_securityManager, AuthenticationPredicate authenticationPredicate = AuthenticationPredicates::IS_AUTHENTICATED); void begin(); void registerEvent(String event); void onEvent(String event, EventCallback callback); void onSubscribe(String event, SubscribeCallback callback); void emitEvent(String event, JsonObject &jsonObject, const char *originId = "", bool onlyToSameOrigin = false); // if onlyToSameOrigin == true, the message will be sent to the originId only, otherwise it will be broadcasted to all clients except the originId bool isEventValid(String event); unsigned int getConnectedClients(); private: PsychicHttpServer *_server; PsychicWebSocketHandler _socket; SecurityManager *_securityManager; AuthenticationPredicate _authenticationPredicate; std::vector events; std::map> client_subscriptions; std::map> event_callbacks; std::map> subscribe_callbacks; void handleEventCallbacks(String event, JsonObject &jsonObject, int originId); void handleSubscribeCallbacks(String event, const String &originId); void onWSOpen(PsychicWebSocketClient *client); void onWSClose(PsychicWebSocketClient *client); esp_err_t onFrame(PsychicWebSocketRequest *request, httpd_ws_frame *frame); }; #endif ================================================ FILE: lib/framework/FSPersistence.h ================================================ #ifndef FSPersistence_h #define FSPersistence_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include template class FSPersistence { public: FSPersistence(JsonStateReader stateReader, JsonStateUpdater stateUpdater, StatefulService *statefulService, FS *fs, const char *filePath) : _stateReader(stateReader), _stateUpdater(stateUpdater), _statefulService(statefulService), _fs(fs), _filePath(filePath), _updateHandlerId(0) { enableUpdateHandler(); } void readFromFS() { File settingsFile = _fs->open(_filePath, "r"); if (settingsFile) { JsonDocument jsonDocument; DeserializationError error = deserializeJson(jsonDocument, settingsFile); if (error == DeserializationError::Ok && jsonDocument.is()) { JsonObject jsonObject = jsonDocument.as(); _statefulService->updateWithoutPropagation(jsonObject, _stateUpdater, _filePath); settingsFile.close(); return; } settingsFile.close(); } // If we reach here we have not been successful in loading the config and hard-coded defaults are now applied. // The settings are then written back to the file system so the defaults persist between resets. This last step is // required as in some cases defaults contain randomly generated values which would otherwise be modified on reset. applyDefaults(); writeToFS(); } bool writeToFS() { // create and populate a new json object JsonDocument jsonDocument; JsonObject jsonObject = jsonDocument.to(); _statefulService->read(jsonObject, _stateReader); // make directories if required mkdirs(); // serialize it to filesystem File settingsFile = _fs->open(_filePath, "w"); // failed to open file, return false if (!settingsFile) { return false; } // serialize the data to the file serializeJson(jsonDocument, settingsFile); settingsFile.close(); return true; } void disableUpdateHandler() { if (_updateHandlerId) { _statefulService->removeUpdateHandler(_updateHandlerId); _updateHandlerId = 0; } } void enableUpdateHandler() { if (!_updateHandlerId) { _updateHandlerId = _statefulService->addUpdateHandler([&](const String &originId) { writeToFS(); }); } } private: JsonStateReader _stateReader; JsonStateUpdater _stateUpdater; StatefulService *_statefulService; FS *_fs; const char *_filePath; update_handler_id_t _updateHandlerId; // We assume we have a _filePath with format "/directory1/directory2/filename" // We create a directory for each missing parent void mkdirs() { String path(_filePath); int index = 0; while ((index = path.indexOf('/', index + 1)) != -1) { String segment = path.substring(0, index); if (!_fs->exists(segment)) { _fs->mkdir(segment); } } } protected: // We assume the updater supplies sensible defaults if an empty object // is supplied, this virtual function allows that to be changed. virtual void applyDefaults() { JsonDocument jsonDocument; JsonObject jsonObject = jsonDocument.as(); _statefulService->updateWithoutPropagation(jsonObject, _stateUpdater, _filePath); } }; #endif // end FSPersistence ================================================ FILE: lib/framework/FactoryResetService.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include using namespace std::placeholders; FactoryResetService::FactoryResetService(PsychicHttpServer *server, FS *fs, SecurityManager *securityManager) : _server(server), fs(fs), _securityManager(securityManager) { } void FactoryResetService::begin() { _server->on(FACTORY_RESET_SERVICE_PATH, HTTP_POST, _securityManager->wrapRequest(std::bind(&FactoryResetService::handleRequest, this, _1), AuthenticationPredicates::IS_ADMIN)); ESP_LOGV(SVK_TAG, "Registered POST endpoint: %s", FACTORY_RESET_SERVICE_PATH); } esp_err_t FactoryResetService::handleRequest(PsychicRequest *request) { request->reply(200); factoryReset(); return ESP_OK; } /** * Delete function assumes that all files are stored flat, within the config directory. */ void FactoryResetService::factoryReset() { File root = fs->open(FS_CONFIG_DIRECTORY); File file; while (file = root.openNextFile()) { String path = file.path(); file.close(); fs->remove(path); } RestartService::restartNow(); } ================================================ FILE: lib/framework/FactoryResetService.h ================================================ #ifndef FactoryResetService_h #define FactoryResetService_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #include #define FS_CONFIG_DIRECTORY "/config" #define FACTORY_RESET_SERVICE_PATH "/rest/factoryReset" class FactoryResetService { FS *fs; public: FactoryResetService(PsychicHttpServer *server, FS *fs, SecurityManager *securityManager); void begin(); void factoryReset(); private: PsychicHttpServer *_server; SecurityManager *_securityManager; esp_err_t handleRequest(PsychicRequest *request); }; #endif // end FactoryResetService_h ================================================ FILE: lib/framework/Features.h ================================================ #ifndef Features_h #define Features_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #define FT_ENABLED(feature) feature // security feature on by default #ifndef FT_SECURITY #define FT_SECURITY 1 #endif // mqtt feature on by default #ifndef FT_MQTT #define FT_MQTT 1 #endif // ntp feature on by default #ifndef FT_NTP #define FT_NTP 1 #endif // upload firmware feature off by default #ifndef FT_UPLOAD_FIRMWARE #define FT_UPLOAD_FIRMWARE 0 #endif // download firmware feature off by default #ifndef FT_DOWNLOAD_FIRMWARE #define FT_DOWNLOAD_FIRMWARE 0 #endif // ESP32 sleep states off by default #ifndef FT_SLEEP #define FT_SLEEP 0 #endif // ESP32 battery state off by default #ifndef FT_BATTERY #define FT_BATTERY 0 #endif // ESP32 analytics on by default #ifndef FT_ANALYTICS #define FT_ANALYTICS 1 #endif // Use JSON for events. Default, use MessagePack for events #ifndef EVENT_USE_JSON #define EVENT_USE_JSON 0 #endif // Endpoint for Core Dump, off by default #ifndef FT_COREDUMP #define FT_COREDUMP 0 #endif // Ethernet feature off by default #ifndef FT_ETHERNET #define FT_ETHERNET 0 #endif #endif ================================================ FILE: lib/framework/FeaturesService.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include FeaturesService::FeaturesService(PsychicHttpServer *server, EventSocket *eventsocket) : _server(server), _socket(eventsocket) { } void FeaturesService::begin() { _server->on(FEATURES_SERVICE_PATH, HTTP_GET, [&](PsychicRequest *request) { PsychicJsonResponse response = PsychicJsonResponse(request, false); JsonObject root = response.getRoot(); createJSON(root); return response.send(); }); ESP_LOGV(SVK_TAG, "Registered GET endpoint: %s", FEATURES_SERVICE_PATH); _socket->registerEvent(FEATURES_SERVICE_EVENT); _socket->onSubscribe(FEATURES_SERVICE_EVENT, [&](const String &originId) { ESP_LOGV(SVK_TAG, "Sending features to %s", originId.c_str()); JsonDocument doc; JsonObject root = doc.as(); createJSON(root); _socket->emitEvent(FEATURES_SERVICE_EVENT, root); }); } void FeaturesService::addFeature(String feature, bool enabled) { UserFeature newFeature; newFeature.feature = feature; newFeature.enabled = enabled; bool featureExists = false; // Check if the feature already exists for (auto &existingFeature : userFeatures) { if (existingFeature.feature == feature) { // Update the existing feature existingFeature.enabled = enabled; featureExists = true; break; } } if (!featureExists) { // If the feature does not exist, add it userFeatures.push_back(newFeature); } JsonDocument doc; JsonObject root = doc.as(); createJSON(root); _socket->emitEvent(FEATURES_SERVICE_EVENT, root); } void FeaturesService::createJSON(JsonObject &root) { #if FT_ENABLED(FT_SECURITY) root["security"] = true; #else root["security"] = false; #endif #if FT_ENABLED(FT_MQTT) root["mqtt"] = true; #else root["mqtt"] = false; #endif #if FT_ENABLED(FT_NTP) root["ntp"] = true; #else root["ntp"] = false; #endif #if FT_ENABLED(FT_UPLOAD_FIRMWARE) root["upload_firmware"] = true; #else root["upload_firmware"] = false; #endif #if FT_ENABLED(FT_DOWNLOAD_FIRMWARE) root["download_firmware"] = true; #else root["download_firmware"] = false; #endif #if FT_ENABLED(FT_SLEEP) root["sleep"] = true; #else root["sleep"] = false; #endif #if FT_ENABLED(FT_BATTERY) root["battery"] = true; #else root["battery"] = false; #endif #if FT_ENABLED(FT_ANALYTICS) root["analytics"] = true; #else root["analytics"] = false; #endif #if FT_ENABLED(FT_COREDUMP) root["coredump"] = true; #else root["coredump"] = false; #endif #if FT_ENABLED(EVENT_USE_JSON) root["event_use_json"] = true; #else root["event_use_json"] = false; #endif #if FT_ENABLED(FT_ETHERNET) root["ethernet"] = true; #else root["ethernet"] = false; #endif root["firmware_version"] = APP_VERSION; root["firmware_name"] = APP_NAME; root["firmware_built_target"] = BUILD_TARGET; // Iterate over user features for (auto &element : userFeatures) { root[element.feature.c_str()] = element.enabled; } } ================================================ FILE: lib/framework/FeaturesService.h ================================================ #ifndef FeaturesService_h #define FeaturesService_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #include #include #define FEATURES_SERVICE_PATH "/rest/features" #define FEATURES_SERVICE_EVENT "features" typedef struct { String feature; bool enabled; } UserFeature; class FeaturesService { public: FeaturesService(PsychicHttpServer *server, EventSocket *socket); void begin(); void addFeature(String feature, bool enabled); private: PsychicHttpServer *_server; EventSocket *_socket; std::vector userFeatures; void createJSON(JsonObject &root); }; #endif ================================================ FILE: lib/framework/FirmwareUpdateEvents.h ================================================ #ifndef FirmwareUpdateEvents_h #define FirmwareUpdateEvents_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2025 hmbacher * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ /** * WebSocket event name for OTA firmware updates * Used by both UploadFirmwareService and DownloadFirmwareService */ #define EVENT_OTA_UPDATE "otastatus" /** * Event JSON Structure: * * { * "status": string, // Current update status * "progress": number, // Progress percentage (0-100) * "bytes_written": number, // Optional: Bytes written so far * "total_bytes": number, // Optional: Total bytes to write * "error": string // Optional: Error message if status is "error" * } * * Status Values: * - "none" : Frontend-only initial state, no update in progress (never sent by backend) * - "preparing" : Update started, preparing to receive data * - "progress" : Update in progress, progress field contains percentage * - "finished" : Update completed successfully, device will restart * - "error" : Update failed, error field contains error message * * Example Events: * * Preparing: * {"status":"preparing","progress":0} * * Progress: * {"status":"progress","progress":45,"bytes_written":102400,"total_bytes":227328} * * Finished: * {"status":"finished","progress":100} * * Error: * {"status":"error","error":"Firmware update failed"} */ #endif ================================================ FILE: lib/framework/HttpEndpoint.h ================================================ #ifndef HttpEndpoint_h #define HttpEndpoint_h #include #include #include #include #define HTTP_ENDPOINT_ORIGIN_ID "http" #define HTTPS_ENDPOINT_ORIGIN_ID "https" using namespace std::placeholders; // for `_1` etc template class HttpEndpoint { protected: JsonStateReader _stateReader; JsonStateUpdater _stateUpdater; StatefulService *_statefulService; SecurityManager *_securityManager; AuthenticationPredicate _authenticationPredicate; PsychicHttpServer *_server; const char *_servicePath; public: HttpEndpoint(JsonStateReader stateReader, JsonStateUpdater stateUpdater, StatefulService *statefulService, PsychicHttpServer *server, const char *servicePath, SecurityManager *securityManager, AuthenticationPredicate authenticationPredicate = AuthenticationPredicates::IS_ADMIN) : _stateReader(stateReader), _stateUpdater(stateUpdater), _statefulService(statefulService), _server(server), _servicePath(servicePath), _securityManager(securityManager), _authenticationPredicate(authenticationPredicate) { } // register the web server on() endpoints void begin() { // OPTIONS (for CORS preflight) #ifdef ENABLE_CORS _server->on(_servicePath, HTTP_OPTIONS, _securityManager->wrapRequest( [this](PsychicRequest *request) { return request->reply(200); }, AuthenticationPredicates::IS_AUTHENTICATED)); #endif // GET _server->on(_servicePath, HTTP_GET, _securityManager->wrapRequest( [this](PsychicRequest *request) { PsychicJsonResponse response = PsychicJsonResponse(request, false); JsonObject jsonObject = response.getRoot(); _statefulService->read(jsonObject, _stateReader); return response.send(); }, _authenticationPredicate)); ESP_LOGV(SVK_TAG, "Registered GET endpoint: %s", _servicePath); // POST _server->on(_servicePath, HTTP_POST, _securityManager->wrapCallback( [this](PsychicRequest *request, JsonVariant &json) { if (!json.is()) { return request->reply(400); } JsonObject jsonObject = json.as(); StateUpdateResult outcome = _statefulService->updateWithoutPropagation(jsonObject, _stateUpdater, _servicePath); if (outcome == StateUpdateResult::ERROR) { return request->reply(400); } else if ((outcome == StateUpdateResult::CHANGED)) { // persist the changes to the FS _statefulService->callUpdateHandlers(HTTP_ENDPOINT_ORIGIN_ID); } PsychicJsonResponse response = PsychicJsonResponse(request, false); jsonObject = response.getRoot(); _statefulService->read(jsonObject, _stateReader); return response.send(); }, _authenticationPredicate)); ESP_LOGV(SVK_TAG, "Registered POST endpoint: %s", _servicePath); } }; #endif ================================================ FILE: lib/framework/IPUtils.h ================================================ #ifndef IPUtils_h #define IPUtils_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include const IPAddress IP_NOT_SET = IPAddress(INADDR_NONE); class IPUtils { public: static bool isSet(const IPAddress &ip) { return ip != IP_NOT_SET; } static bool isNotSet(const IPAddress &ip) { return ip == IP_NOT_SET; } }; #endif // end IPUtils_h ================================================ FILE: lib/framework/JsonUtils.h ================================================ #ifndef JsonUtils_h #define JsonUtils_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include class JsonUtils { public: static void readIPStr(JsonObject &root, const String &key, IPAddress &ip, const String &def) { IPAddress defaultIp = {}; if (!defaultIp.fromString(def)) { defaultIp = INADDR_NONE; } readIP(root, key, ip, defaultIp); } static void readIP(JsonObject &root, const String &key, IPAddress &ip, const IPAddress &defaultIp = INADDR_NONE) { if (!root[key].is() || !ip.fromString(root[key].as())) { ip = defaultIp; } } static void writeIP(JsonObject &root, const String &key, const IPAddress &ip) { if (IPUtils::isSet(ip)) { root[key] = ip.toString(); } } }; #endif // end JsonUtils ================================================ FILE: lib/framework/LICENSE ================================================ ESP32-SvelteKit is distributed with two licenses for different sections of the code. The back end code inherits the GNU LESSER GENERAL PUBLIC LICENSE Version 3 and is therefore distributed said license. The front end code is distributed under the MIT License. GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. ================================================ FILE: lib/framework/MqttEndpoint.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include std::vector MqttCommitHandler::_instances; TimerHandle_t MqttCommitHandler::_sendTimer = nullptr; uint32_t MqttCommitHandler::_timerIntervalMs = FACTORY_MQTT_MIN_MESSAGE_INTERVAL_MS; // default ================================================ FILE: lib/framework/MqttEndpoint.h ================================================ #ifndef MqttEndpoint_h #define MqttEndpoint_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #define MQTT_ORIGIN_ID "mqtt" // Commit interface, needed to ensure that the MqttEndpoint can be used in a commit pattern without template class MqttCommitHandler { public: MqttCommitHandler() { if (_instances.size() == 0) { _sendTimer = xTimerCreate("MqttSendTimer", pdMS_TO_TICKS(500), pdTRUE, nullptr, commitPending); setTimerInterval(_timerIntervalMs); } _instances.push_back(this); } virtual void commit() {}; virtual ~MqttCommitHandler() = default; static void setTimerInterval(uint32_t intervalMs) { _timerIntervalMs = intervalMs; if (_sendTimer) { if (intervalMs == 0) { xTimerStop(_sendTimer, 0); // Disable timer (no throttling) } else { xTimerChangePeriod(_sendTimer, pdMS_TO_TICKS(intervalMs), 0); // Update interval xTimerStart(_sendTimer, 0); } } } static uint32_t getTimerInterval() { return _timerIntervalMs; } protected: static std::vector _instances; static void commitPending(TimerHandle_t xTimer) { ESP_LOGV(SVK_TAG, "Publishing pending MQTT messages"); for (auto instance : _instances) { instance->commit(); } } static TimerHandle_t _sendTimer; static uint32_t _timerIntervalMs; }; template class MqttEndpoint : public MqttCommitHandler { public: MqttEndpoint(JsonStateReader stateReader, JsonStateUpdater stateUpdater, StatefulService *statefulService, PsychicMqttClient *mqttClient, const String &pubTopic = "", const String &subTopic = "", int QoS = 0, bool retain = false) : _stateReader(stateReader), _stateUpdater(stateUpdater), _statefulService(statefulService), _mqttClient(mqttClient), _pubTopic(pubTopic), _subTopic(subTopic), _qos(QoS), _retain(retain), _pendingCommit(false) { _statefulService->addUpdateHandler([&](const String &originId) { publish(); }, false); _mqttClient->onConnect(std::bind(&MqttEndpoint::onConnect, this)); _mqttClient->onMessage(std::bind(&MqttEndpoint::onMqttMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5)); } void configureTopics(const String &pubTopic, const String &subTopic) { setSubTopic(subTopic); setPubTopic(pubTopic); } void setSubTopic(const String &subTopic) { if (!_subTopic.equals(subTopic)) { // unsubscribe from the existing topic if one was set if (_subTopic.length() > 0) { _mqttClient->unsubscribe(_subTopic.c_str()); } // set the new topic and re-configure the subscription _subTopic = subTopic; subscribe(); } } void setPubTopic(const String &pubTopic) { _pubTopic = pubTopic; publish(); } void setRetain(const bool retain) { _retain = retain; publish(); } void commit() override { if (!_pendingCommit) { return; // nothing to do } if (_pubTopic.length() > 0 && _mqttClient->connected()) { // serialize to json doc JsonDocument json; JsonObject jsonObject = json.to(); _statefulService->read(jsonObject, _stateReader); // serialize to string String payload; serializeJson(json, payload); // publish the payload _mqttClient->publish(_pubTopic.c_str(), _qos, _retain, payload.c_str(), 0, false); } _pendingCommit = false; } void publish() { _pendingCommit = true; if (MqttCommitHandler::getTimerInterval() == 0) { commit(); // No throttling—send immediately } } PsychicMqttClient *getMqttClient() { return _mqttClient; } protected: StatefulService *_statefulService; PsychicMqttClient *_mqttClient; JsonStateUpdater _stateUpdater; JsonStateReader _stateReader; String _subTopic; String _pubTopic; int _qos; bool _retain; bool _pendingCommit; void onMqttMessage(char *topic, char *payload, int retain, int qos, bool dup) { // we only care about the topic we are watching in this class if (strcmp(_subTopic.c_str(), topic)) { return; } // deserialize from string JsonDocument json; DeserializationError error = deserializeJson(json, payload); if (!error && json.is()) { JsonObject jsonObject = json.as(); _statefulService->update(jsonObject, _stateUpdater, MQTT_ORIGIN_ID); } } void onConnect() { subscribe(); publish(); } void subscribe() { if (_subTopic.length() > 0) { _mqttClient->subscribe(_subTopic.c_str(), 2); } } }; #endif // end MqttEndpoint ================================================ FILE: lib/framework/MqttSettingsService.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include /** * Load the root certificate bundle embedded by the build process */ extern const uint8_t rootca_crt_bundle_start[] asm("_binary_src_certs_x509_crt_bundle_bin_start"); extern const uint8_t rootca_crt_bundle_end[] asm("_binary_src_certs_x509_crt_bundle_bin_end"); /** * Retains a copy of the cstr provided in the pointer provided using dynamic allocation. * * Frees the pointer before allocation and leaves it as nullptr if cstr == nullptr. */ static char *retainCstr(const char *cstr, char **ptr) { // free up previously retained value if exists free(*ptr); *ptr = nullptr; // dynamically allocate and copy cstr (if non null) if (cstr != nullptr) { *ptr = (char *)malloc(strlen(cstr) + 1); strcpy(*ptr, cstr); } // return reference to pointer for convenience return *ptr; } MqttSettingsService::MqttSettingsService(PsychicHttpServer *server, FS *fs, SecurityManager *securityManager) : _server(server), _securityManager(securityManager), _httpEndpoint(MqttSettings::read, MqttSettings::update, this, server, MQTT_SETTINGS_SERVICE_PATH, securityManager), _fsPersistence(MqttSettings::read, MqttSettings::update, this, fs, MQTT_SETTINGS_FILE), _retainedHost(nullptr), _retainedClientId(nullptr), _retainedUsername(nullptr), _retainedPassword(nullptr), _reconfigureMqtt(false), _mqttClient(), _lastError("None") { String status_topic = SettingValue::format(FACTORY_MQTT_STATUS_TOPIC); retainCstr(status_topic.c_str(), &_retainedWillTopic); addUpdateHandler([&](const String &originId) { onConfigUpdated(); }, false); #if ESP_ARDUINO_VERSION_MAJOR == 3 _mqttClient.setCACertBundle(rootca_crt_bundle_start, rootca_crt_bundle_end - rootca_crt_bundle_start); #else _mqttClient.setCACertBundle(rootca_crt_bundle_start); #endif } MqttSettingsService::~MqttSettingsService() { } void MqttSettingsService::begin() { WiFi.onEvent( std::bind(&MqttSettingsService::onStationModeDisconnected, this, std::placeholders::_1, std::placeholders::_2), WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_DISCONNECTED); WiFi.onEvent(std::bind(&MqttSettingsService::onStationModeGotIP, this, std::placeholders::_1, std::placeholders::_2), WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_GOT_IP); _mqttClient.onConnect(std::bind(&MqttSettingsService::onMqttConnect, this, std::placeholders::_1)); _mqttClient.onDisconnect(std::bind(&MqttSettingsService::onMqttDisconnect, this, std::placeholders::_1)); _mqttClient.onError(std::bind(&MqttSettingsService::onMqttError, this, std::placeholders::_1)); _httpEndpoint.begin(); _fsPersistence.readFromFS(); } void MqttSettingsService::loop() { if (_reconfigureMqtt) { // reconfigure MQTT client configureMqtt(); // clear the reconnection flags _reconfigureMqtt = false; } } bool MqttSettingsService::isEnabled() { return _state.enabled; } bool MqttSettingsService::isConnected() { return _mqttClient.connected(); } const char *MqttSettingsService::getClientId() { // return _mqttClient.getClientId(); return _state.clientId.c_str(); } PsychicMqttClient *MqttSettingsService::getMqttClient() { return &_mqttClient; } String MqttSettingsService::getLastError() { return _lastError; } void MqttSettingsService::onMqttConnect(bool sessionPresent) { #if ESP_IDF_VERSION_MAJOR == 5 String uri = _mqttClient.getMqttConfig()->broker.address.uri; #else String uri = _mqttClient.getMqttConfig()->uri; #endif ESP_LOGI(SVK_TAG, "Connected to MQTT: %s", uri.c_str()); #ifdef SERIAL_INFO Serial.printf("Connected to MQTT: %s\n", uri.c_str()); #endif _lastError = "None"; // publish status message _mqttClient.publish(_retainedWillTopic, 1, true, "online"); } void MqttSettingsService::onMqttDisconnect(bool sessionPresent) { ESP_LOGI(SVK_TAG, "Disconnected from MQTT."); #ifdef SERIAL_INFO Serial.println("Disconnected from MQTT."); #endif } void MqttSettingsService::onMqttError(esp_mqtt_error_codes_t error) { if (error.error_type == MQTT_ERROR_TYPE_TCP_TRANSPORT) { _lastError = strerror(error.esp_transport_sock_errno); ESP_LOGE(SVK_TAG, "MQTT TCP error: %s", _lastError.c_str()); } } void MqttSettingsService::onConfigUpdated() { _reconfigureMqtt = true; } void MqttSettingsService::onStationModeGotIP(WiFiEvent_t event, WiFiEventInfo_t info) { if (_state.enabled) { ESP_LOGI(SVK_TAG, "WiFi connection established, starting MQTT client."); onConfigUpdated(); } } void MqttSettingsService::onStationModeDisconnected(WiFiEvent_t event, WiFiEventInfo_t info) { if (_state.enabled) { ESP_LOGI(SVK_TAG, "WiFi connection dropped, stopping MQTT client."); onConfigUpdated(); } } void MqttSettingsService::configureMqtt() { disconnect(); // only connect if WiFi is connected and MQTT is enabled if (_state.enabled && WiFi.isConnected()) { #ifdef SERIAL_INFO Serial.println("Connecting to MQTT..."); #endif _mqttClient.setServer(retainCstr(_state.uri.c_str(), &_retainedHost)); if (_state.username.length() > 0) { _mqttClient.setCredentials( retainCstr(_state.username.c_str(), &_retainedUsername), retainCstr(_state.password.length() > 0 ? _state.password.c_str() : nullptr, &_retainedPassword)); } else { _mqttClient.setCredentials(retainCstr(nullptr, &_retainedUsername), retainCstr(nullptr, &_retainedPassword)); } _mqttClient.setClientId(retainCstr(_state.clientId.c_str(), &_retainedClientId)); _mqttClient.setKeepAlive(_state.keepAlive); _mqttClient.setWill(_retainedWillTopic, 1, true, _retainedWillPayload); _mqttClient.setCleanSession(_state.cleanSession); _mqttClient.connect(); MqttCommitHandler::setTimerInterval(_state.messageIntervalMs); } } void MqttSettingsService::setStatusTopic(String statusTopic) { // check if the status topic is different from the current one if (statusTopic.equals(_retainedWillTopic)) { return; // no change } // copy the new status topic to the retained pointer retainCstr(statusTopic.c_str(), &_retainedWillTopic); // update the state _reconfigureMqtt = true; // mark for reconfiguration ESP_LOGI(SVK_TAG, "Status topic updated to: %s", _retainedWillTopic); } String MqttSettingsService::getStatusTopic() { return String(_retainedWillTopic); } void MqttSettingsService::disconnect() { // disable MQTT message commit timer, if disconnected MqttCommitHandler::setTimerInterval(0); // disconnect if currently connected if (_mqttClient.connected()) { ESP_LOGI(SVK_TAG, "Disconnecting from MQTT client."); _mqttClient.publish(_retainedWillTopic, 1, true, "offline", 0, false); _mqttClient.disconnect(); } } ================================================ FILE: lib/framework/MqttSettingsService.h ================================================ #ifndef MqttSettingsService_h #define MqttSettingsService_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #include #include #include #ifndef FACTORY_MQTT_ENABLED #define FACTORY_MQTT_ENABLED false #endif #ifndef FACTORY_MQTT_HOST #define FACTORY_MQTT_HOST "test.mosquitto.org" #endif #ifndef FACTORY_MQTT_PORT #define FACTORY_MQTT_PORT 1883 #endif #ifndef FACTORY_MQTT_USERNAME #define FACTORY_MQTT_USERNAME "" #endif #ifndef FACTORY_MQTT_PASSWORD #define FACTORY_MQTT_PASSWORD "" #endif #ifndef FACTORY_MQTT_CLIENT_ID #define FACTORY_MQTT_CLIENT_ID "#{platform}-#{unique_id}" #endif #ifndef FACTORY_MQTT_STATUS_TOPIC #define FACTORY_MQTT_STATUS_TOPIC "#{platform}/#{unique_id}/status" #endif #ifndef FACTORY_MQTT_KEEP_ALIVE #define FACTORY_MQTT_KEEP_ALIVE 16 #endif #ifndef FACTORY_MQTT_CLEAN_SESSION #define FACTORY_MQTT_CLEAN_SESSION true #endif #ifndef FACTORY_MQTT_MAX_TOPIC_LENGTH #define FACTORY_MQTT_MAX_TOPIC_LENGTH 128 #endif #ifndef FACTORY_MQTT_MIN_MESSAGE_INTERVAL_MS #define FACTORY_MQTT_MIN_MESSAGE_INTERVAL_MS 500 #endif #define MQTT_SETTINGS_FILE "/config/mqttSettings.json" #define MQTT_SETTINGS_SERVICE_PATH "/rest/mqttSettings" #define MQTT_RECONNECTION_DELAY 5000 class MqttSettings { public: // host and port - if enabled bool enabled; String uri; // username and password String username; String password; // client id settings String clientId; // connection settings uint16_t keepAlive; bool cleanSession; // Publish rate limiting uint32_t messageIntervalMs; static void read(MqttSettings &settings, JsonObject &root) { root["enabled"] = settings.enabled; root["uri"] = settings.uri; root["username"] = settings.username; root["password"] = settings.password; root["client_id"] = settings.clientId; root["keep_alive"] = settings.keepAlive; root["clean_session"] = settings.cleanSession; root["message_interval_ms"] = settings.messageIntervalMs; } static StateUpdateResult update(JsonObject &root, MqttSettings &settings, const String &originId) { settings.enabled = root["enabled"] | FACTORY_MQTT_ENABLED; settings.uri = root["uri"] | FACTORY_MQTT_URI; settings.username = root["username"] | SettingValue::format(FACTORY_MQTT_USERNAME); settings.password = root["password"] | FACTORY_MQTT_PASSWORD; settings.clientId = root["client_id"] | SettingValue::format(FACTORY_MQTT_CLIENT_ID); settings.keepAlive = root["keep_alive"] | FACTORY_MQTT_KEEP_ALIVE; settings.cleanSession = root["clean_session"] | FACTORY_MQTT_CLEAN_SESSION; settings.messageIntervalMs = root["message_interval_ms"] | FACTORY_MQTT_MIN_MESSAGE_INTERVAL_MS; return StateUpdateResult::CHANGED; } }; class MqttSettingsService : public StatefulService { public: MqttSettingsService(PsychicHttpServer *server, FS *fs, SecurityManager *securityManager); ~MqttSettingsService(); void begin(); void loop(); bool isEnabled(); bool isConnected(); const char *getClientId(); String getLastError(); void setStatusTopic(String statusTopic); String getStatusTopic(); PsychicMqttClient *getMqttClient(); void disconnect(); protected: void onConfigUpdated(); private: PsychicHttpServer *_server; SecurityManager *_securityManager; HttpEndpoint _httpEndpoint; FSPersistence _fsPersistence; // Pointers to hold retained copies of the mqtt client connection strings. // This is required as AsyncMqttClient holds references to the supplied connection strings. char *_retainedHost; char *_retainedClientId; char *_retainedUsername; char *_retainedPassword; char *_retainedWillTopic = nullptr; const char *_retainedWillPayload = "offline"; // variable to help manage connection bool _reconfigureMqtt; String _lastError; // the MQTT client instance PsychicMqttClient _mqttClient; void onStationModeGotIP(WiFiEvent_t event, WiFiEventInfo_t info); void onStationModeDisconnected(WiFiEvent_t event, WiFiEventInfo_t info); void onMqttConnect(bool sessionPresent); void onMqttDisconnect(bool sessionPresent); void onMqttError(esp_mqtt_error_codes_t error); void configureMqtt(); }; #endif // end MqttSettingsService_h ================================================ FILE: lib/framework/MqttStatus.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include MqttStatus::MqttStatus(PsychicHttpServer *server, MqttSettingsService *mqttSettingsService, SecurityManager *securityManager) : _server(server), _securityManager(securityManager), _mqttSettingsService(mqttSettingsService) { } void MqttStatus::begin() { _server->on(MQTT_STATUS_SERVICE_PATH, HTTP_GET, _securityManager->wrapRequest(std::bind(&MqttStatus::mqttStatus, this, std::placeholders::_1), AuthenticationPredicates::IS_AUTHENTICATED)); ESP_LOGV(SVK_TAG, "Registered GET endpoint: %s", MQTT_STATUS_SERVICE_PATH); } esp_err_t MqttStatus::mqttStatus(PsychicRequest *request) { PsychicJsonResponse response = PsychicJsonResponse(request, false); JsonObject root = response.getRoot(); root["enabled"] = _mqttSettingsService->isEnabled(); root["connected"] = _mqttSettingsService->isConnected(); root["client_id"] = _mqttSettingsService->getClientId(); root["last_error"] = _mqttSettingsService->getLastError(); return response.send(); } bool MqttStatus::isConnected() { return _mqttSettingsService->isConnected(); } ================================================ FILE: lib/framework/MqttStatus.h ================================================ #ifndef MqttStatus_h #define MqttStatus_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #include #define MQTT_STATUS_SERVICE_PATH "/rest/mqttStatus" class MqttStatus { public: MqttStatus(PsychicHttpServer *server, MqttSettingsService *mqttSettingsService, SecurityManager *securityManager); void begin(); bool isConnected(); private: PsychicHttpServer *_server; SecurityManager *_securityManager; MqttSettingsService *_mqttSettingsService; esp_err_t mqttStatus(PsychicRequest *request); }; #endif // end MqttStatus_h ================================================ FILE: lib/framework/NTPSettingsService.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #if FT_ENABLED(FT_ETHERNET) #include #endif NTPSettingsService::NTPSettingsService(PsychicHttpServer *server, FS *fs, SecurityManager *securityManager) : _server(server), _securityManager(securityManager), _httpEndpoint(NTPSettings::read, NTPSettings::update, this, server, NTP_SETTINGS_SERVICE_PATH, securityManager), _fsPersistence(NTPSettings::read, NTPSettings::update, this, fs, NTP_SETTINGS_FILE) { addUpdateHandler([&](const String &originId) { configureNTP(); }, false); } void NTPSettingsService::begin() { WiFi.onEvent( std::bind(&NTPSettingsService::onNetworkDisconnected, this, std::placeholders::_1, std::placeholders::_2), WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_DISCONNECTED); WiFi.onEvent(std::bind(&NTPSettingsService::onNetworkGotIP, this, std::placeholders::_1, std::placeholders::_2), WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_GOT_IP); #if FT_ENABLED(FT_ETHERNET) WiFi.onEvent( std::bind(&NTPSettingsService::onNetworkDisconnected, this, std::placeholders::_1, std::placeholders::_2), WiFiEvent_t::ARDUINO_EVENT_ETH_DISCONNECTED); WiFi.onEvent(std::bind(&NTPSettingsService::onNetworkGotIP, this, std::placeholders::_1, std::placeholders::_2), WiFiEvent_t::ARDUINO_EVENT_ETH_GOT_IP); #endif _httpEndpoint.begin(); _server->on(TIME_PATH, HTTP_POST, _securityManager->wrapCallback( std::bind(&NTPSettingsService::configureTime, this, std::placeholders::_1, std::placeholders::_2), AuthenticationPredicates::IS_ADMIN)); ESP_LOGV(SVK_TAG, "Registered POST endpoint: %s", TIME_PATH); _fsPersistence.readFromFS(); configureNTP(); } void NTPSettingsService::onNetworkGotIP(WiFiEvent_t event, WiFiEventInfo_t info) { #ifdef SERIAL_INFO Serial.println(F("Got IP address, starting NTP Synchronization")); #endif configureNTP(); } void NTPSettingsService::onNetworkDisconnected(WiFiEvent_t event, WiFiEventInfo_t info) { #ifdef SERIAL_INFO Serial.println(F("Network connection dropped, stopping NTP.")); #endif configureNTP(); } void NTPSettingsService::configureNTP() { bool networkConnected = WiFi.isConnected(); #if FT_ENABLED(FT_ETHERNET) networkConnected = networkConnected || ETH.connected(); #endif if (networkConnected && _state.enabled) { #ifdef SERIAL_INFO Serial.println(F("Starting NTP...")); #endif configTzTime(_state.tzFormat.c_str(), _state.server.c_str()); } else { #ifdef CONFIG_LWIP_TCPIP_CORE_LOCKING if (!sys_thread_tcpip(LWIP_CORE_LOCK_QUERY_HOLDER)) { LOCK_TCPIP_CORE(); } #endif setenv("TZ", _state.tzFormat.c_str(), 1); tzset(); sntp_stop(); #ifdef CONFIG_LWIP_TCPIP_CORE_LOCKING if (sys_thread_tcpip(LWIP_CORE_LOCK_QUERY_HOLDER)) { UNLOCK_TCPIP_CORE(); } #endif } } esp_err_t NTPSettingsService::configureTime(PsychicRequest *request, JsonVariant &json) { if (!sntp_enabled() && json.is()) { struct tm tm = {0}; String timeLocal = json["local_time"]; char *s = strptime(timeLocal.c_str(), "%Y-%m-%dT%H:%M:%S", &tm); if (s != nullptr) { time_t time = mktime(&tm); struct timeval now = {.tv_sec = time}; settimeofday(&now, nullptr); return request->reply(200); } } return request->reply(400); } ================================================ FILE: lib/framework/NTPSettingsService.h ================================================ #ifndef NTPSettingsService_h #define NTPSettingsService_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #include #ifdef CONFIG_LWIP_TCPIP_CORE_LOCKING #include "lwip/priv/tcpip_priv.h" #endif #ifndef FACTORY_NTP_ENABLED #define FACTORY_NTP_ENABLED true #endif #ifndef FACTORY_NTP_TIME_ZONE_LABEL #define FACTORY_NTP_TIME_ZONE_LABEL "Europe/London" #endif #ifndef FACTORY_NTP_TIME_ZONE_FORMAT #define FACTORY_NTP_TIME_ZONE_FORMAT "GMT0BST,M3.5.0/1,M10.5.0" #endif #ifndef FACTORY_NTP_SERVER #define FACTORY_NTP_SERVER "time.google.com" #endif #define NTP_SETTINGS_FILE "/config/ntpSettings.json" #define NTP_SETTINGS_SERVICE_PATH "/rest/ntpSettings" #define TIME_PATH "/rest/time" class NTPSettings { public: bool enabled; String tzLabel; String tzFormat; String server; static void read(NTPSettings &settings, JsonObject &root) { root["enabled"] = settings.enabled; root["server"] = settings.server; root["tz_label"] = settings.tzLabel; root["tz_format"] = settings.tzFormat; } static StateUpdateResult update(JsonObject &root, NTPSettings &settings, const String &originId) { settings.enabled = root["enabled"] | FACTORY_NTP_ENABLED; settings.server = root["server"] | FACTORY_NTP_SERVER; settings.tzLabel = root["tz_label"] | FACTORY_NTP_TIME_ZONE_LABEL; settings.tzFormat = root["tz_format"] | FACTORY_NTP_TIME_ZONE_FORMAT; return StateUpdateResult::CHANGED; } }; class NTPSettingsService : public StatefulService { public: NTPSettingsService(PsychicHttpServer *server, FS *fs, SecurityManager *securityManager); void begin(); private: PsychicHttpServer *_server; SecurityManager *_securityManager; HttpEndpoint _httpEndpoint; FSPersistence _fsPersistence; void onNetworkGotIP(WiFiEvent_t event, WiFiEventInfo_t info); void onNetworkDisconnected(WiFiEvent_t event, WiFiEventInfo_t info); void configureNTP(); esp_err_t configureTime(PsychicRequest *request, JsonVariant &json); }; #endif // end NTPSettingsService_h ================================================ FILE: lib/framework/NTPStatus.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include NTPStatus::NTPStatus(PsychicHttpServer *server, SecurityManager *securityManager) : _server(server), _securityManager(securityManager) { } void NTPStatus::begin() { _server->on(NTP_STATUS_SERVICE_PATH, HTTP_GET, _securityManager->wrapRequest(std::bind(&NTPStatus::ntpStatus, this, std::placeholders::_1), AuthenticationPredicates::IS_AUTHENTICATED)); ESP_LOGV(SVK_TAG, "Registered GET endpoint: %s", NTP_STATUS_SERVICE_PATH); } /* * Formats the time using the format provided. * * Uses a 25 byte buffer, large enough to fit an ISO time string with offset. */ String formatTime(tm *time, const char *format) { char time_string[25]; strftime(time_string, 25, format, time); return String(time_string); } String toUTCTimeString(tm *time) { return formatTime(time, "%FT%TZ"); } String toLocalTimeString(tm *time) { return formatTime(time, "%FT%T"); } esp_err_t NTPStatus::ntpStatus(PsychicRequest *request) { PsychicJsonResponse response = PsychicJsonResponse(request, false); JsonObject root = response.getRoot(); // grab the current instant in unix seconds time_t now = time(nullptr); // only provide enabled/disabled status for now root["status"] = sntp_enabled() ? 1 : 0; // the current time in UTC root["utc_time"] = toUTCTimeString(gmtime(&now)); // local time with offset root["local_time"] = toLocalTimeString(localtime(&now)); // the sntp server name root["server"] = sntp_getservername(0); // device uptime in seconds root["uptime"] = millis() / 1000; return response.send(); } ================================================ FILE: lib/framework/NTPStatus.h ================================================ #ifndef NTPStatus_h #define NTPStatus_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #include #include #define NTP_STATUS_SERVICE_PATH "/rest/ntpStatus" class NTPStatus { public: NTPStatus(PsychicHttpServer *server, SecurityManager *securityManager); void begin(); private: PsychicHttpServer *_server; SecurityManager *_securityManager; esp_err_t ntpStatus(PsychicRequest *request); }; #endif // end NTPStatus_h ================================================ FILE: lib/framework/NotificationService.cpp ================================================ #include // array translating pushType into strings const char *pushTypeStrings[] = {"error", "warning", "info", "success"}; NotificationService::NotificationService(EventSocket *eventSocket) : _eventSocket(eventSocket) { } void NotificationService::begin() { _eventSocket->registerEvent(NOTIFICATION_EVENT); } void NotificationService::pushNotification(String message, pushType event) { JsonDocument doc; doc["type"] = pushTypeStrings[event]; doc["message"] = message; JsonObject jsonObject = doc.as(); _eventSocket->emitEvent(NOTIFICATION_EVENT, jsonObject); } ================================================ FILE: lib/framework/NotificationService.h ================================================ #ifndef NotificationService_h #define NotificationService_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #define NOTIFICATION_EVENT "notification" enum pushType { PUSHERROR, PUSHWARNING, PUSHINFO, PUSHSUCCESS }; class NotificationService { public: NotificationService(EventSocket *eventSocket); void begin(); void pushNotification(String message, pushType event); private: EventSocket *_eventSocket; }; #endif // NotificationService_h ================================================ FILE: lib/framework/RestartService.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include RestartService::RestartService(PsychicHttpServer *server, SecurityManager *securityManager) : _server(server), _securityManager(securityManager) { } void RestartService::begin() { _server->on(RESTART_SERVICE_PATH, HTTP_POST, _securityManager->wrapRequest(std::bind(&RestartService::restart, this, std::placeholders::_1), AuthenticationPredicates::IS_ADMIN)); ESP_LOGV(SVK_TAG, "Registered POST endpoint: %s", RESTART_SERVICE_PATH); } esp_err_t RestartService::restart(PsychicRequest *request) { request->reply(200); restartNow(); return ESP_OK; } ================================================ FILE: lib/framework/RestartService.h ================================================ #ifndef RestartService_h #define RestartService_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #define RESTART_SERVICE_PATH "/rest/restart" class RestartService { public: RestartService(PsychicHttpServer *server, SecurityManager *securityManager); void begin(); static void restartNow() { delay(250); MDNS.end(); delay(100); WiFi.disconnect(true); delay(200); ESP.restart(); } private: PsychicHttpServer *_server; SecurityManager *_securityManager; esp_err_t restart(PsychicRequest *request); }; #endif // end RestartService_h ================================================ FILE: lib/framework/SecurityManager.h ================================================ #ifndef SecurityManager_h #define SecurityManager_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #define SVK_TAG "🐼" #define ACCESS_TOKEN_PARAMATER "access_token" #define AUTHORIZATION_HEADER "Authorization" #define AUTHORIZATION_HEADER_PREFIX "Bearer " #define AUTHORIZATION_HEADER_PREFIX_LEN 7 class User { public: String username; String password; bool admin; public: User(String username, String password, bool admin) : username(username), password(password), admin(admin) { } }; class Authentication { public: User *user; boolean authenticated; public: Authentication(User &user) : user(new User(user)), authenticated(true) { } Authentication() : user(nullptr), authenticated(false) { } ~Authentication() { delete (user); } }; typedef std::function AuthenticationPredicate; class AuthenticationPredicates { public: static bool NONE_REQUIRED(Authentication &authentication) { return true; }; static bool IS_AUTHENTICATED(Authentication &authentication) { return authentication.authenticated; }; static bool IS_ADMIN(Authentication &authentication) { return authentication.authenticated && authentication.user->admin; }; }; class SecurityManager { public: #if FT_ENABLED(FT_SECURITY) /* * Authenticate, returning the user if found */ virtual Authentication authenticate(const String &username, const String &password) = 0; /* * Generate a JWT for the user provided */ virtual String generateJWT(User *user) = 0; #endif /* * Check the request header for the Authorization token */ virtual Authentication authenticateRequest(PsychicRequest *request) = 0; /** * Filter a request with the provided predicate, only returning true if the predicate matches. */ virtual PsychicRequestFilterFunction filterRequest(AuthenticationPredicate predicate) = 0; /** * Wrap the provided request to provide validation against an AuthenticationPredicate. */ virtual PsychicHttpRequestCallback wrapRequest(PsychicHttpRequestCallback onRequest, AuthenticationPredicate predicate) = 0; /** * Wrap the provided json request callback to provide validation against an AuthenticationPredicate. */ virtual PsychicJsonRequestCallback wrapCallback(PsychicJsonRequestCallback onRequest, AuthenticationPredicate predicate) = 0; }; #endif // end SecurityManager_h ================================================ FILE: lib/framework/SecuritySettingsService.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #if FT_ENABLED(FT_SECURITY) SecuritySettingsService::SecuritySettingsService(PsychicHttpServer *server, FS *fs) : _server(server), _httpEndpoint(SecuritySettings::read, SecuritySettings::update, this, server, SECURITY_SETTINGS_PATH, this), _fsPersistence(SecuritySettings::read, SecuritySettings::update, this, fs, SECURITY_SETTINGS_FILE), _jwtHandler(FACTORY_JWT_SECRET) { addUpdateHandler([&](const String &originId) { configureJWTHandler(); }, false); } void SecuritySettingsService::begin() { _server->on(GENERATE_TOKEN_PATH, HTTP_GET, wrapRequest(std::bind(&SecuritySettingsService::generateToken, this, std::placeholders::_1), AuthenticationPredicates::IS_ADMIN)); ESP_LOGV(SVK_TAG, "Registered GET endpoint: %s", GENERATE_TOKEN_PATH); _httpEndpoint.begin(); _fsPersistence.readFromFS(); configureJWTHandler(); } Authentication SecuritySettingsService::authenticateRequest(PsychicRequest *request) { // Load the parameters from the request, as they are only loaded later with the regular handler if (request->hasHeader(AUTHORIZATION_HEADER)) { auto value = request->header(AUTHORIZATION_HEADER); // ESP_LOGV(SVK_TAG, "Authorization header: %s", value.c_str()); if (value.startsWith(AUTHORIZATION_HEADER_PREFIX)) { value = value.substring(AUTHORIZATION_HEADER_PREFIX_LEN); return authenticateJWT(value); } } else if (request->hasParam(ACCESS_TOKEN_PARAMATER)) { String value = request->getParam(ACCESS_TOKEN_PARAMATER)->value(); // ESP_LOGV(SVK_TAG, "Access token parameter: %s", value.c_str()); return authenticateJWT(value); } return Authentication(); } void SecuritySettingsService::configureJWTHandler() { _jwtHandler.setSecret(_state.jwtSecret); } Authentication SecuritySettingsService::authenticateJWT(String &jwt) { JsonDocument payloadDocument; _jwtHandler.parseJWT(jwt, payloadDocument); if (payloadDocument.is()) { JsonObject parsedPayload = payloadDocument.as(); String username = parsedPayload["username"]; for (User _user : _state.users) { if (_user.username == username && validatePayload(parsedPayload, &_user)) { return Authentication(_user); } } } return Authentication(); } Authentication SecuritySettingsService::authenticate(const String &username, const String &password) { for (User _user : _state.users) { if (_user.username == username && _user.password == password) { return Authentication(_user); } } return Authentication(); } inline void populateJWTPayload(JsonObject &payload, User *user) { payload["username"] = user->username; payload["admin"] = user->admin; } boolean SecuritySettingsService::validatePayload(JsonObject &parsedPayload, User *user) { JsonDocument jsonDocument; JsonObject payload = jsonDocument.to(); populateJWTPayload(payload, user); return payload == parsedPayload; } String SecuritySettingsService::generateJWT(User *user) { JsonDocument jsonDocument; JsonObject payload = jsonDocument.to(); populateJWTPayload(payload, user); return _jwtHandler.buildJWT(payload); } PsychicRequestFilterFunction SecuritySettingsService::filterRequest(AuthenticationPredicate predicate) { return [this, predicate](PsychicRequest *request) { // ESP_LOGV(SVK_TAG, "Authenticating filter request: %s", request->uri().c_str()); // ESP_LOGV(SVK_TAG, "Request Method: %s", request->methodStr().c_str()); // TODO: This is a hack to allow bogus websocket filter requests to pass through // This is a temporary fix until the PsychicHttp websocket handler is fixed to not send a bogus filter request // Check if we have a bogus filter request and return true if (request->uri().isEmpty() && request->method() == HTTP_DELETE) { // ESP_LOGV(SVK_TAG, "Bogus filter request - allowing"); return true; } else request->loadParams(); Authentication authentication = authenticateRequest(request); bool result = predicate(authentication); // ESP_LOGV(SVK_TAG, "Filter Request %s", result ? "allowed" : "denied"); return result; }; } PsychicHttpRequestCallback SecuritySettingsService::wrapRequest(PsychicHttpRequestCallback onRequest, AuthenticationPredicate predicate) { return [this, onRequest, predicate](PsychicRequest *request) { Authentication authentication = authenticateRequest(request); if (!predicate(authentication)) { return request->reply(401); } return onRequest(request); }; } PsychicJsonRequestCallback SecuritySettingsService::wrapCallback(PsychicJsonRequestCallback onRequest, AuthenticationPredicate predicate) { return [this, onRequest, predicate](PsychicRequest *request, JsonVariant &json) { Authentication authentication = authenticateRequest(request); if (!predicate(authentication)) { return request->reply(401); } return onRequest(request, json); }; } esp_err_t SecuritySettingsService::generateToken(PsychicRequest *request) { String usernameParam = request->getParam("username")->value(); for (User _user : _state.users) { if (_user.username == usernameParam) { PsychicJsonResponse response = PsychicJsonResponse(request, false); JsonObject root = response.getRoot(); root["token"] = generateJWT(&_user); return response.send(); } } return request->reply(401); } #else User ADMIN_USER = User(FACTORY_ADMIN_USERNAME, FACTORY_ADMIN_PASSWORD, true); SecuritySettingsService::SecuritySettingsService(PsychicHttpServer *server, FS *fs) : SecurityManager() { } SecuritySettingsService::~SecuritySettingsService() { } PsychicRequestFilterFunction SecuritySettingsService::filterRequest(AuthenticationPredicate predicate) { return [this, predicate](PsychicRequest *request) { // ESP_LOGV(SVK_TAG, "Security disabled - all requests are allowed"); return true; }; } // Return the admin user on all request - disabling security features Authentication SecuritySettingsService::authenticateRequest(PsychicRequest *request) { return Authentication(ADMIN_USER); } // Return the function unwrapped PsychicHttpRequestCallback SecuritySettingsService::wrapRequest(PsychicHttpRequestCallback onRequest, AuthenticationPredicate predicate) { return onRequest; } PsychicJsonRequestCallback SecuritySettingsService::wrapCallback(PsychicJsonRequestCallback onRequest, AuthenticationPredicate predicate) { return onRequest; } #endif ================================================ FILE: lib/framework/SecuritySettingsService.h ================================================ #ifndef SecuritySettingsService_h #define SecuritySettingsService_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #include #ifndef FACTORY_JWT_SECRET #define FACTORY_JWT_SECRET "#{random}-#{random}" #endif #ifndef FACTORY_ADMIN_USERNAME #define FACTORY_ADMIN_USERNAME "admin" #endif #ifndef FACTORY_ADMIN_PASSWORD #define FACTORY_ADMIN_PASSWORD "admin" #endif #ifndef FACTORY_GUEST_USERNAME #define FACTORY_GUEST_USERNAME "guest" #endif #ifndef FACTORY_GUEST_PASSWORD #define FACTORY_GUEST_PASSWORD "guest" #endif #define SECURITY_SETTINGS_FILE "/config/securitySettings.json" #define SECURITY_SETTINGS_PATH "/rest/securitySettings" #define GENERATE_TOKEN_PATH "/rest/generateToken" #if FT_ENABLED(FT_SECURITY) class SecuritySettings { public: String jwtSecret; std::list users; static void read(SecuritySettings &settings, JsonObject &root) { // secret root["jwt_secret"] = settings.jwtSecret; // users JsonArray users = root["users"].to(); for (User user : settings.users) { JsonObject userRoot = users.add(); userRoot["username"] = user.username; userRoot["password"] = user.password; userRoot["admin"] = user.admin; } } static StateUpdateResult update(JsonObject &root, SecuritySettings &settings, const String& originID) { // secret settings.jwtSecret = root["jwt_secret"] | SettingValue::format(FACTORY_JWT_SECRET); // users settings.users.clear(); if (root["users"].is()) { for (JsonVariant user : root["users"].as()) { settings.users.push_back(User(user["username"], user["password"], user["admin"])); } } else { settings.users.push_back(User(FACTORY_ADMIN_USERNAME, FACTORY_ADMIN_PASSWORD, true)); settings.users.push_back(User(FACTORY_GUEST_USERNAME, FACTORY_GUEST_PASSWORD, false)); } return StateUpdateResult::CHANGED; } }; class SecuritySettingsService : public StatefulService, public SecurityManager { public: SecuritySettingsService(PsychicHttpServer *server, FS *fs); void begin(); // Functions to implement SecurityManager Authentication authenticate(const String &username, const String &password); Authentication authenticateRequest(PsychicRequest *request); String generateJWT(User *user); PsychicRequestFilterFunction filterRequest(AuthenticationPredicate predicate); PsychicHttpRequestCallback wrapRequest(PsychicHttpRequestCallback onRequest, AuthenticationPredicate predicate); PsychicJsonRequestCallback wrapCallback(PsychicJsonRequestCallback onRequest, AuthenticationPredicate predicate); private: PsychicHttpServer *_server; HttpEndpoint _httpEndpoint; FSPersistence _fsPersistence; ArduinoJsonJWT _jwtHandler; esp_err_t generateToken(PsychicRequest *request); void configureJWTHandler(); /* * Lookup the user by JWT */ Authentication authenticateJWT(String &jwt); /* * Verify the payload is correct */ boolean validatePayload(JsonObject &parsedPayload, User *user); }; #else class SecuritySettingsService : public SecurityManager { public: SecuritySettingsService(PsychicHttpServer *server, FS *fs); ~SecuritySettingsService(); // minimal set of functions to support framework with security settings disabled Authentication authenticateRequest(PsychicRequest *request); PsychicRequestFilterFunction filterRequest(AuthenticationPredicate predicate); PsychicHttpRequestCallback wrapRequest(PsychicHttpRequestCallback onRequest, AuthenticationPredicate predicate); PsychicJsonRequestCallback wrapCallback(PsychicJsonRequestCallback onRequest, AuthenticationPredicate predicate); }; #endif // end FT_ENABLED(FT_SECURITY) #endif // end SecuritySettingsService_h ================================================ FILE: lib/framework/SettingValue.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include namespace SettingValue { const String PLATFORM = "esp32"; /** * Returns a new string after replacing each instance of the pattern with a value generated by calling the provided * callback. */ String replaceEach(String value, String pattern, String (*generateReplacement)()) { while (true) { int index = value.indexOf(pattern); if (index == -1) { break; } value = value.substring(0, index) + generateReplacement() + value.substring(index + pattern.length()); } return value; } /** * Generates a random number, encoded as a hex string. */ String getRandom() { return String(random(2147483647), HEX); } /** * Uses the station's MAC address to create a unique id for each device. */ String getUniqueId() { uint8_t mac[6]; esp_read_mac(mac, ESP_MAC_WIFI_STA); char macStr[13] = {0}; sprintf(macStr, "%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); return String(macStr); } String format(String value) { value = replaceEach(value, "#{random}", getRandom); value.replace("#{unique_id}", getUniqueId()); value.replace("#{platform}", PLATFORM); return value; } }; // end namespace SettingValue ================================================ FILE: lib/framework/SettingValue.h ================================================ #ifndef SettingValue_h #define SettingValue_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #if ESP_ARDUINO_VERSION_MAJOR == 3 #include #endif namespace SettingValue { String format(String value); }; #endif // end SettingValue ================================================ FILE: lib/framework/SleepService.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include // Definition of static member variables std::vector SleepService::_sleepCallbacks; u_int64_t _wakeUpPin = WAKEUP_PIN_NUMBER; bool _wakeUpSignal = WAKEUP_SIGNAL; pinTermination _wakeUpTermination = pinTermination::FLOATING; SleepService::SleepService(PsychicHttpServer *server, SecurityManager *securityManager) : _server(server), _securityManager(securityManager) { } void SleepService::begin() { // OPTIONS (for CORS preflight) #ifdef ENABLE_CORS _server->on(SLEEP_SERVICE_PATH, HTTP_OPTIONS, _securityManager->wrapRequest( [this](PsychicRequest *request) { return request->reply(200); }, AuthenticationPredicates::IS_AUTHENTICATED)); #endif _server->on(SLEEP_SERVICE_PATH, HTTP_POST, _securityManager->wrapRequest(std::bind(&SleepService::sleep, this, std::placeholders::_1), AuthenticationPredicates::IS_AUTHENTICATED)); ESP_LOGV(SVK_TAG, "Registered POST endpoint: %s", SLEEP_SERVICE_PATH); } esp_err_t SleepService::sleep(PsychicRequest *request) { request->reply(200); sleepNow(); return ESP_OK; } void SleepService::sleepNow() { #ifdef SERIAL_INFO Serial.println("Going into deep sleep now"); #endif ESP_LOGI(SVK_TAG, "Going into deep sleep now"); // Callback for main code sleep preparation for (auto callback : _sleepCallbacks) { callback(); } MDNS.end(); delay(100); WiFi.disconnect(true); delay(200); // set pin function of _wakeUpPin pinMode(_wakeUpPin, INPUT); ESP_LOGD(SVK_TAG, "Enabling GPIO wakeup on pin GPIO%d with level %d\n", _wakeUpPin, _wakeUpSignal); ESP_LOGD(SVK_TAG, "Current level on GPIO%d: %d\n", _wakeUpPin, digitalRead(_wakeUpPin)); // special treatment for ESP32-C3 / C6 because of the RISC-V architecture #if defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C6) esp_deep_sleep_enable_gpio_wakeup(BIT(_wakeUpPin), (esp_deepsleep_gpio_wake_up_mode_t)_wakeUpSignal); #else esp_sleep_enable_ext1_wakeup(BIT(_wakeUpPin), (esp_sleep_ext1_wakeup_mode_t)_wakeUpSignal); switch (_wakeUpTermination) { case pinTermination::PULL_DOWN: esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON); rtc_gpio_init((gpio_num_t)_wakeUpPin); rtc_gpio_pullup_dis((gpio_num_t)_wakeUpPin); rtc_gpio_pulldown_en((gpio_num_t)_wakeUpPin); break; case pinTermination::PULL_UP: esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON); rtc_gpio_init((gpio_num_t)_wakeUpPin); rtc_gpio_pullup_en((gpio_num_t)_wakeUpPin); rtc_gpio_pulldown_dis((gpio_num_t)_wakeUpPin); break; default: esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_AUTO); } #endif #ifdef SERIAL_INFO Serial.println("Good by!"); #endif esp_deep_sleep_start(); } void SleepService::setWakeUpPin(int pin, bool level, pinTermination termination) { _wakeUpPin = (u_int64_t)pin; _wakeUpSignal = level; _wakeUpTermination = termination; } ================================================ FILE: lib/framework/SleepService.h ================================================ #pragma once /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #include "driver/rtc_io.h" #include #define SLEEP_SERVICE_PATH "/rest/sleep" #ifndef WAKEUP_PIN_NUMBER #define WAKEUP_PIN_NUMBER 0 #endif #ifndef WAKEUP_SIGNAL #define WAKEUP_SIGNAL 0 #endif enum class pinTermination { FLOATING, PULL_UP, PULL_DOWN }; // typdef for sleep service callback typedef std::function sleepCallback; class SleepService { public: SleepService(PsychicHttpServer *server, SecurityManager *securityManager); void begin(); static void sleepNow(); void attachOnSleepCallback(sleepCallback callbackSleep) { _sleepCallbacks.push_back(callbackSleep); } void setWakeUpPin(int pin, bool level, pinTermination termination = pinTermination::FLOATING); private: PsychicHttpServer *_server; SecurityManager *_securityManager; esp_err_t sleep(PsychicRequest *request); protected: static std::vector _sleepCallbacks; }; ================================================ FILE: lib/framework/StatefulService.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include update_handler_id_t StateUpdateHandlerInfo::currentUpdatedHandlerId = 0; hook_handler_id_t StateHookHandlerInfo::currentHookHandlerId = 0; ================================================ FILE: lib/framework/StatefulService.h ================================================ #ifndef StatefulService_h #define StatefulService_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #include #include enum class StateUpdateResult { CHANGED = 0, // The update changed the state and propagation should take place if required UNCHANGED, // The state was unchanged, propagation should not take place ERROR // There was a problem updating the state, propagation should not take place }; template using JsonStateUpdater = std::function; template using JsonStateReader = std::function; typedef size_t update_handler_id_t; typedef size_t hook_handler_id_t; typedef std::function StateUpdateCallback; typedef std::function StateHookCallback; typedef struct StateUpdateHandlerInfo { static update_handler_id_t currentUpdatedHandlerId; update_handler_id_t _id; StateUpdateCallback _cb; bool _allowRemove; StateUpdateHandlerInfo(StateUpdateCallback cb, bool allowRemove) : _id(++currentUpdatedHandlerId), _cb(cb), _allowRemove(allowRemove) {}; } StateUpdateHandlerInfo_t; typedef struct StateHookHandlerInfo { static hook_handler_id_t currentHookHandlerId; hook_handler_id_t _id; StateHookCallback _cb; bool _allowRemove; StateHookHandlerInfo(StateHookCallback cb, bool allowRemove) : _id(++currentHookHandlerId), _cb(cb), _allowRemove(allowRemove) {}; } StateHookHandlerInfo_t; template class StatefulService { public: template StatefulService(Args &&...args) : _state(std::forward(args)...), _accessMutex(xSemaphoreCreateRecursiveMutex()) { } update_handler_id_t addUpdateHandler(StateUpdateCallback cb, bool allowRemove = true) { if (!cb) { return 0; } StateUpdateHandlerInfo_t updateHandler(cb, allowRemove); _updateHandlers.push_back(updateHandler); return updateHandler._id; } void removeUpdateHandler(update_handler_id_t id) { for (auto i = _updateHandlers.begin(); i != _updateHandlers.end();) { if ((*i)._allowRemove && (*i)._id == id) { i = _updateHandlers.erase(i); } else { ++i; } } } hook_handler_id_t addHookHandler(StateHookCallback cb, bool allowRemove = true) { if (!cb) { return 0; } StateHookHandlerInfo_t hookHandler(cb, allowRemove); _hookHandlers.push_back(hookHandler); return hookHandler._id; } void removeHookHandler(hook_handler_id_t id) { for (auto i = _hookHandlers.begin(); i != _hookHandlers.end();) { if ((*i)._allowRemove && (*i)._id == id) { i = _hookHandlers.erase(i); } else { ++i; } } } StateUpdateResult update(std::function stateUpdater, const String &originId) { beginTransaction(); StateUpdateResult result = stateUpdater(_state); endTransaction(); callHookHandlers(originId, result); if (result == StateUpdateResult::CHANGED) { callUpdateHandlers(originId); } return result; } StateUpdateResult updateWithoutPropagation(std::function stateUpdater, const String &originId) { beginTransaction(); StateUpdateResult result = stateUpdater(_state); endTransaction(); return result; } StateUpdateResult update(JsonObject &jsonObject, JsonStateUpdater stateUpdater, const String &originId) { beginTransaction(); StateUpdateResult result = stateUpdater(jsonObject, _state, originId); endTransaction(); callHookHandlers(originId, result); if (result == StateUpdateResult::CHANGED) { callUpdateHandlers(originId); } return result; } StateUpdateResult updateWithoutPropagation(JsonObject &jsonObject, JsonStateUpdater stateUpdater, const String &originId) { beginTransaction(); StateUpdateResult result = stateUpdater(jsonObject, _state, originId); endTransaction(); return result; } void read(std::function stateReader) { beginTransaction(); stateReader(_state); endTransaction(); } void read(JsonObject &jsonObject, JsonStateReader stateReader) { beginTransaction(); stateReader(_state, jsonObject); endTransaction(); } void callUpdateHandlers(const String &originId) { for (const StateUpdateHandlerInfo_t &updateHandler : _updateHandlers) { updateHandler._cb(originId); } } void callHookHandlers(const String &originId, StateUpdateResult &result) { for (const StateHookHandlerInfo_t &hookHandler : _hookHandlers) { hookHandler._cb(originId, result); } } protected: T _state; inline void beginTransaction() { xSemaphoreTakeRecursive(_accessMutex, portMAX_DELAY); } inline void endTransaction() { xSemaphoreGiveRecursive(_accessMutex); } private: SemaphoreHandle_t _accessMutex; std::list _updateHandlers; std::list _hookHandlers; }; #endif // end StatefulService_h ================================================ FILE: lib/framework/SystemStatus.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4 #include "esp32/rom/rtc.h" #define ESP_TARGET "ESP32"; #elif CONFIG_IDF_TARGET_ESP32S2 #include "esp32/rom/rtc.h" #define ESP_TARGET "ESP32-S2"; #elif CONFIG_IDF_TARGET_ESP32C3 #include "esp32c3/rom/rtc.h" #define ESP_TARGET "ESP32-C3"; #elif CONFIG_IDF_TARGET_ESP32S3 #include "esp32s3/rom/rtc.h" #define ESP_TARGET "ESP32-S3"; #elif CONFIG_IDF_TARGET_ESP32C6 #include "esp32c6/rom/rtc.h" #define ESP_TARGET "ESP32-C6"; #else #error Target CONFIG_IDF_TARGET is not supported #endif #ifndef ARDUINO_VERSION #ifndef STRINGIZE #define STRINGIZE(s) #s #endif #define ARDUINO_VERSION_STR(major, minor, patch) "v" STRINGIZE(major) "." STRINGIZE(minor) "." STRINGIZE(patch) #define ARDUINO_VERSION ARDUINO_VERSION_STR(ESP_ARDUINO_VERSION_MAJOR, ESP_ARDUINO_VERSION_MINOR, ESP_ARDUINO_VERSION_PATCH) #endif String verbosePrintResetReason(int reason) { switch (reason) { case ESP_RST_UNKNOWN: return ("Reset reason can not be determined"); break; case ESP_RST_POWERON: return ("Reset due to power-on event"); break; case ESP_RST_EXT: return ("Reset by external pin (not applicable for ESP32)"); break; case ESP_RST_SW: return ("Software reset via esp_restart"); break; case ESP_RST_PANIC: return ("Software reset due to exception/panic"); break; case ESP_RST_INT_WDT: return ("Reset (software or hardware) due to interrupt watchdog"); break; case ESP_RST_TASK_WDT: return ("Reset due to task watchdog"); break; case ESP_RST_WDT: return ("Reset due to other watchdogs"); break; case ESP_RST_DEEPSLEEP: return ("Reset after exiting deep sleep mode"); break; case ESP_RST_BROWNOUT: return ("Brownout reset (software or hardware)"); break; case ESP_RST_SDIO: return ("Reset over SDIO"); break; #ifdef ESP_RST_USB case ESP_RST_USB: return ("Reset by USB peripheral"); break; #endif #ifdef ESP_RST_JSVK_TAG case ESP_RST_JSVK_TAG: return ("Reset by JSVK_TAG"); break; #endif #ifdef ESP_RST_EFUSE case ESP_RST_EFUSE: return ("Reset due to efuse error"); break; #endif #ifdef ESP_RST_PWR_GLITCH case ESP_RST_PWR_GLITCH: return ("Reset due to power glitch detected"); break; #endif #ifdef ESP_RST_CPU_LOCKUP case ESP_RST_CPU_LOCKUP: return ("Reset due to CPU lock up (double exception)"); break; #endif default: char buffer[50]; snprintf(buffer, sizeof(buffer), "Unknown reset reason (%d)", reason); return String(buffer); break; } } SystemStatus::SystemStatus(PsychicHttpServer *server, SecurityManager *securityManager) : _server(server), _securityManager(securityManager) { } void SystemStatus::begin() { _server->on(SYSTEM_STATUS_SERVICE_PATH, HTTP_GET, _securityManager->wrapRequest(std::bind(&SystemStatus::systemStatus, this, std::placeholders::_1), AuthenticationPredicates::IS_AUTHENTICATED)); ESP_LOGV(SVK_TAG, "Registered GET endpoint: %s", SYSTEM_STATUS_SERVICE_PATH); } esp_err_t SystemStatus::systemStatus(PsychicRequest *request) { PsychicJsonResponse response = PsychicJsonResponse(request, false); JsonObject root = response.getRoot(); root["esp_platform"] = ESP_TARGET; root["firmware_version"] = APP_VERSION; root["max_alloc_heap"] = ESP.getMaxAllocHeap(); if (psramFound()) { root["free_psram"] = ESP.getFreePsram(); root["used_psram"] = ESP.getPsramSize() - ESP.getFreePsram(); root["psram_size"] = ESP.getPsramSize(); } root["cpu_freq_mhz"] = ESP.getCpuFreqMHz(); root["cpu_type"] = ESP.getChipModel(); root["cpu_rev"] = ESP.getChipRevision(); root["cpu_cores"] = ESP.getChipCores(); root["free_heap"] = ESP.getFreeHeap(); root["used_heap"] = ESP.getHeapSize() - ESP.getFreeHeap(); root["total_heap"] = ESP.getHeapSize(); root["min_free_heap"] = ESP.getMinFreeHeap(); root["sketch_size"] = ESP.getSketchSize(); root["free_sketch_space"] = ESP.getFreeSketchSpace(); root["sdk_version"] = ESP.getSdkVersion(); root["arduino_version"] = ARDUINO_VERSION; root["flash_chip_size"] = ESP.getFlashChipSize(); root["flash_chip_speed"] = ESP.getFlashChipSpeed(); root["fs_total"] = ESPFS.totalBytes(); root["fs_used"] = ESPFS.usedBytes(); root["core_temp"] = temperatureRead(); root["cpu_reset_reason"] = verbosePrintResetReason(esp_reset_reason()); root["uptime"] = millis() / 1000; return response.send(); } ================================================ FILE: lib/framework/SystemStatus.h ================================================ #ifndef SystemStatus_h #define SystemStatus_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #include #define SYSTEM_STATUS_SERVICE_PATH "/rest/systemStatus" class SystemStatus { public: SystemStatus(PsychicHttpServer *server, SecurityManager *securityManager); void begin(); private: PsychicHttpServer *_server; SecurityManager *_securityManager; esp_err_t systemStatus(PsychicRequest *request); }; #endif // end SystemStatus_h ================================================ FILE: lib/framework/UploadFirmwareService.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * Copyright (C) 2025 hmbacher * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #include #include using namespace std::placeholders; // for `_1` etc UploadFirmwareService::UploadFirmwareService(PsychicHttpServer *server, SecurityManager *securityManager, EventSocket *socket) : _server(server), _securityManager(securityManager), _socket(socket) { _md5[0] = '\0'; // Initialize MD5 buffer } void UploadFirmwareService::begin() { if (!_socket->isEventValid(EVENT_OTA_UPDATE)) { _socket->registerEvent(EVENT_OTA_UPDATE); } // Set PsychicHttp's limit to max to avoid connection reset on oversized files // We'll validate the size ourselves in handleUpload() to provide proper error handling _server->maxUploadSize = SIZE_MAX; _maxFirmwareSize = getMaxFirmwareSize(); // Setup progress callback for Update library Update.onProgress([this](size_t progress, size_t total) { if (_socket && total > 0) { int percentComplete = (progress * 100) / total; if (percentComplete > _previousProgress || progress == total) { JsonDocument doc; doc["status"] = "progress"; doc["progress"] = percentComplete; doc["bytes_written"] = progress; doc["total_bytes"] = total; JsonObject jsonObject = doc.as(); _socket->emitEvent(EVENT_OTA_UPDATE, jsonObject); ESP_LOGV(SVK_TAG, "Firmware upload process at %d of %d bytes... (%d %%)", progress, total, percentComplete); _previousProgress = percentComplete; } } }); PsychicUploadHandler *uploadHandler = new PsychicUploadHandler(); uploadHandler->onUpload(std::bind(&UploadFirmwareService::handleUpload, this, _1, _2, _3, _4, _5, _6)); uploadHandler->onRequest(std::bind(&UploadFirmwareService::uploadComplete, this, _1)); // gets called after upload has been handled uploadHandler->onClose(std::bind(&UploadFirmwareService::handleEarlyDisconnect, this)); // gets called if client disconnects _server->on(UPLOAD_FIRMWARE_PATH, HTTP_POST, uploadHandler); ESP_LOGV(SVK_TAG, "Registered POST endpoint: %s", UPLOAD_FIRMWARE_PATH); } size_t UploadFirmwareService::getMaxFirmwareSize() { const esp_partition_t* update_partition = esp_ota_get_next_update_partition(NULL); if (update_partition != NULL) { ESP_LOGI(SVK_TAG, "Max firmware size: %d bytes (from OTA partition)", update_partition->size); return update_partition->size; } // Fallback if partition query fails (should never happen) ESP_LOGW(SVK_TAG, "Could not determine OTA partition size, using fallback of 2MB"); return 2097152; // 2 MB fallback } bool UploadFirmwareService::validateChipType(uint8_t *data, size_t len) { if (len <= 12) { return false; // Not enough data to validate - firmware is invalid } // Check magic byte at offset 0 if (data[0] != ESP_MAGIC_BYTE) { return false; } // Check chip ID at offset 12 if (data[12] != ESP_CHIP_ID) { return false; } return true; } esp_err_t UploadFirmwareService::handleUpload(PsychicRequest *request, const String &filename, uint64_t index, uint8_t *data, size_t len, bool final) { // quit if not authorized Authentication authentication = _securityManager->authenticateRequest(request); if (!AuthenticationPredicates::IS_ADMIN(authentication)) { return handleError(request, 403, "Insufficient permissions to upload firmware"); } if (index == 0) // Are we at the start of a new upload? { // check details of the file, to see if its a valid bin or md5 file std::string fname(filename.c_str()); auto position = fname.find_last_of("."); // Check if extension exists to avoid undefined behavior if (position == std::string::npos) { return handleError(request, 406, "File has no extension"); } std::string extension = fname.substr(position + 1); size_t fsize = request->contentLength(); _fileType = ft_none; if (strcasecmp(extension.c_str(), "md5") == 0) // Are we processing an MD5 file? { _fileType = ft_md5; if (len == MD5_LENGTH) // This implicitely checks that fsize is also 32 { // Safe: _md5[MD5_LENGTH + 1] has space for 32 bytes + null terminator memcpy(_md5, data, MD5_LENGTH); _md5[MD5_LENGTH] = '\0'; return ESP_OK; // Finished processing MD5 file } else { _md5[0] = '\0'; // Clear any previously stored MD5 on invalid upload return handleError(request, 422, "MD5 must be exactly 32 bytes"); } } else if (strcasecmp(extension.c_str(), "bin") == 0) // Are we processing a firmware binary? { _fileType = ft_firmware; // Validate file size before processing if (fsize > _maxFirmwareSize) { char errorMsg[64]; snprintf(errorMsg, sizeof(errorMsg), "Firmware too large: %.2f MB (max: %.2f MB)", fsize / 1024.0 / 1024.0, _maxFirmwareSize / 1024.0 / 1024.0); return handleError(request, 413, errorMsg); } ESP_LOGI(SVK_TAG, "Starting firmware upload: %s (%d bytes)", filename.c_str(), fsize); #ifdef SERIAL_INFO Serial.printf("Starting firmware upload: %s (%d bytes)\n", filename.c_str(), fsize); #endif // Validate firmware header (magic byte and chip type) if (!validateChipType(data, len)) { return handleError(request, 503, "Wrong firmware for this device"); } if (Update.begin(fsize - sizeof(esp_image_header_t))) { // Emit preparing status after validation succeeds if (_socket) { JsonDocument doc; doc["status"] = "preparing"; doc["progress"] = 0; JsonObject jsonObject = doc.as(); _socket->emitEvent(EVENT_OTA_UPDATE, jsonObject); } if (strlen(_md5) == MD5_LENGTH) { Update.setMD5(_md5); ESP_LOGI(SVK_TAG, "MD5 hash for validation: %s", _md5); #ifdef SERIAL_INFO Serial.printf("MD5 hash for validation: %s\n", _md5); #endif _md5[0] = '\0'; // clear md5 after setting it in Arduino Updater } } else { return handleError(request, 507, "Insufficient storage space"); } } else // Are we processing an unsupported file type? { return handleError(request, 406, "File not a firmware binary or MD5 hash"); } } else // we are continuing an existing upload { // Resumable upload: verify that Update was already started if (_fileType == ft_none || !Update.isRunning()) { return handleError(request, 400, "Upload not initialized"); } } // if we haven't dealt with an error so far, continue with the firmware update if (!request->_tempObject) { if (_fileType == ft_firmware) { if (Update.write(data, len) != len) { Update.abort(); return handleError(request, 500, "Firmware write failed"); } if (final) { if (!Update.end(true)) { // Get specific error message from Update library (includes MD5 mismatch) String errorMsg = "Firmware update failed"; if (Update.hasError()) { errorMsg = Update.errorString(); } Update.abort(); return handleError(request, 500, errorMsg.c_str()); } } } } return ESP_OK; } esp_err_t UploadFirmwareService::uploadComplete(PsychicRequest *request) { // if we already handled an error in handleUpload, do nothing if (request->_tempObject) { return ESP_OK; } // if we completed uploading a md5 file create a JSON response if (_fileType == ft_md5) { if (strlen(_md5) == MD5_LENGTH) { PsychicJsonResponse response = PsychicJsonResponse(request, false); JsonObject root = response.getRoot(); root["md5"] = _md5; return response.send(); } return ESP_OK; } // if no error, send the success response if (_fileType == ft_firmware) { // Emit finished event if (_socket) { JsonDocument doc; doc["status"] = "finished"; doc["progress"] = 100; JsonObject jsonObject = doc.as(); _socket->emitEvent(EVENT_OTA_UPDATE, jsonObject); vTaskDelay(100 / portTICK_PERIOD_MS); // Give time for event to be sent } ESP_LOGI(SVK_TAG, "Firmware upload successful - Restarting"); #ifdef SERIAL_INFO Serial.println("Firmware upload successful - Restarting"); #endif // Reset progress tracker for next upload _previousProgress = 0; request->reply(200); RestartService::restartNow(); return ESP_OK; } // if updated has an error send 500 response and log on Serial if (Update.hasError()) { // Get specific error message from Update library String errorMsg = Update.errorString(); if (errorMsg.length() == 0) { errorMsg = "Unknown update error"; } // Reset progress tracker _previousProgress = 0; ESP_LOGE(SVK_TAG, "Update error: %s", errorMsg.c_str()); #ifdef SERIAL_INFO Update.printError(Serial); #endif Update.abort(); // handleError will emit the WebSocket event and send HTTP response return handleError(request, 500, errorMsg.c_str()); } return ESP_OK; } esp_err_t UploadFirmwareService::handleError(PsychicRequest *request, int code, const char *message) { // if we have had an error already, do nothing if (request->_tempObject) { return ESP_OK; } // Emit WebSocket error event for BIN files (skip for MD5 files) if (_fileType == ft_firmware && _socket && message) { JsonDocument doc; doc["status"] = "error"; doc["error"] = message; JsonObject jsonObject = doc.as(); _socket->emitEvent(EVENT_OTA_UPDATE, jsonObject); } // Log error if (message) { ESP_LOGE(SVK_TAG, "Firmware upload failed (%d): %s", code, message); #ifdef SERIAL_INFO Serial.printf("Firmware upload failed (%d): %s\n", code, message); #endif } else { ESP_LOGE(SVK_TAG, "Firmware upload failed with error code: %d", code); #ifdef SERIAL_INFO Serial.printf("Firmware upload failed with error code: %d\n", code); #endif } // Reset state to allow new upload attempts _fileType = ft_none; _previousProgress = 0; // Abort any ongoing Update to clear error state Update.abort(); // Mark this request as having encountered an error using _tempObject as a flag // (The pointer value itself is not used, only checked for NULL vs non-NULL) // The allocated memory is freed on request destruction (see PsychicRequest::~PsychicRequest()) request->_tempObject = malloc(sizeof(int)); return request->reply(code); } esp_err_t UploadFirmwareService::handleEarlyDisconnect() { // if updated has not ended on connection close, abort it if (!Update.end(true)) { ESP_LOGE(SVK_TAG, "Update error on early disconnect:"); #ifdef SERIAL_INFO Update.printError(Serial); #endif Update.abort(); return ESP_OK; } return ESP_OK; } ================================================ FILE: lib/framework/UploadFirmwareService.h ================================================ #ifndef UploadFirmwareService_h #define UploadFirmwareService_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * Copyright (C) 2025 hmbacher * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #include #include #include #include #define UPLOAD_FIRMWARE_PATH "/rest/uploadFirmware" // Firmware upload constants constexpr size_t MD5_LENGTH = 32; // MD5 hash length constexpr uint8_t ESP_MAGIC_BYTE = 0xE9; // ESP binary magic byte // ESP32 chip type identifiers (byte offset 12 in firmware) #if CONFIG_IDF_TARGET_ESP32 constexpr uint8_t ESP_CHIP_ID = 0; #elif CONFIG_IDF_TARGET_ESP32S2 constexpr uint8_t ESP_CHIP_ID = 2; #elif CONFIG_IDF_TARGET_ESP32C3 constexpr uint8_t ESP_CHIP_ID = 5; #elif CONFIG_IDF_TARGET_ESP32S3 constexpr uint8_t ESP_CHIP_ID = 9; #else #error "Unsupported ESP32 target" #endif enum FileType { ft_none = 0, ft_firmware = 1, ft_md5 = 2 }; /** * @brief Service for handling firmware uploads over HTTP with OTA support * * Supports chunked uploads of .bin firmware files and .md5 hash files for validation. * Emits real-time progress updates via WebSocket and validates chip compatibility. */ class UploadFirmwareService { public: /** * @brief Construct firmware upload service * @param server PsychicHttpServer instance for handling HTTP requests * @param securityManager Security manager for authentication * @param socket EventSocket for emitting real-time progress updates */ UploadFirmwareService(PsychicHttpServer *server, SecurityManager *securityManager, EventSocket *socket); /** * @brief Initialize the service and register HTTP endpoints * Sets up upload handlers and progress callbacks */ void begin(); private: PsychicHttpServer *_server; SecurityManager *_securityManager; EventSocket *_socket; // Upload state (per-instance to support concurrent uploads) char _md5[MD5_LENGTH + 1]; FileType _fileType = ft_none; int _previousProgress = 0; size_t _maxFirmwareSize = 0; /** * @brief Get maximum firmware size from OTA partition * @return Size of OTA partition in bytes, or 2MB fallback if not available */ size_t getMaxFirmwareSize(); /** * @brief Validate firmware chip type matches target device * @param data First chunk of firmware data * @param len Length of data chunk * @return true if magic byte and chip ID are valid, false otherwise */ bool validateChipType(uint8_t *data, size_t len); /** * @brief Handle incoming firmware upload chunks. Called once per chunk. * @param request HTTP request object * @param filename Uploaded file name * @param index Byte offset of this chunk (0 for first chunk) * @param data Chunk data buffer * @param len Chunk length in bytes * @param final true if this is the last chunk * @return ESP_OK on success, error code on failure */ esp_err_t handleUpload(PsychicRequest *request, const String &filename, uint64_t index, uint8_t *data, size_t len, bool final); /** * @brief Called after upload finished (i.e. all chunks received) * @param request HTTP request object * @return ESP_OK on success, error code on failure */ esp_err_t uploadComplete(PsychicRequest *request); /** * @brief Handle upload errors and emit error events * @param request HTTP request object * @param code HTTP status code to return * @param message Optional error message (default: nullptr) * @return ESP_OK (error already handled) */ esp_err_t handleError(PsychicRequest *request, int code, const char *message = nullptr); /** * @brief Handle client disconnection during upload * @return ESP_OK on successful cleanup */ esp_err_t handleEarlyDisconnect(); }; #endif // end UploadFirmwareService_h ================================================ FILE: lib/framework/WebSocketServer.h ================================================ #ifndef WebSocketServer_h #define WebSocketServer_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #define WEB_SOCKET_ORIGIN "wsserver" #define WEB_SOCKET_ORIGIN_CLIENT_ID_PREFIX "wsserver:" template class WebSocketServer { public: WebSocketServer(JsonStateReader stateReader, JsonStateUpdater stateUpdater, StatefulService *statefulService, PsychicHttpServer *server, const char *webSocketPath, SecurityManager *securityManager, AuthenticationPredicate authenticationPredicate = AuthenticationPredicates::IS_ADMIN) : _stateReader(stateReader), _stateUpdater(stateUpdater), _statefulService(statefulService), _server(server), _webSocketPath(webSocketPath), _authenticationPredicate(authenticationPredicate), _securityManager(securityManager) { _statefulService->addUpdateHandler( [&](const String &originId) { transmitData(nullptr, originId); }, false); } void begin() { _webSocket.setFilter(_securityManager->filterRequest(_authenticationPredicate)); _webSocket.onOpen(std::bind(&WebSocketServer::onWSOpen, this, std::placeholders::_1)); _webSocket.onClose(std::bind(&WebSocketServer::onWSClose, this, std::placeholders::_1)); _webSocket.onFrame(std::bind(&WebSocketServer::onWSFrame, this, std::placeholders::_1, std::placeholders::_2)); _server->on(_webSocketPath.c_str(), &_webSocket); ESP_LOGV(SVK_TAG, "Registered WebSocket handler: %s", _webSocketPath.c_str()); } void onWSOpen(PsychicWebSocketClient *client) { // when a client connects, we transmit it's id and the current payload transmitId(client); transmitData(client, WEB_SOCKET_ORIGIN); ESP_LOGI(SVK_TAG, "ws[%s][%u] connect", client->remoteIP().toString().c_str(), client->socket()); } void onWSClose(PsychicWebSocketClient *client) { ESP_LOGI(SVK_TAG, "ws[%s][%u] disconnect", client->remoteIP().toString().c_str(), client->socket()); } esp_err_t onWSFrame(PsychicWebSocketRequest *request, httpd_ws_frame *frame) { ESP_LOGV(SVK_TAG, "ws[%s][%u] opcode[%d]", request->client()->remoteIP().toString().c_str(), request->client()->socket(), frame->type); if (frame->type == HTTPD_WS_TYPE_TEXT) { ESP_LOGV(SVK_TAG, "ws[%s][%u] request: %s", request->client()->remoteIP().toString().c_str(), request->client()->socket(), (char *)frame->payload); JsonDocument jsonDocument; DeserializationError error = deserializeJson(jsonDocument, (char *)frame->payload, frame->len); if (!error && jsonDocument.is()) { JsonObject jsonObject = jsonDocument.as(); _statefulService->update(jsonObject, _stateUpdater, clientId(request->client())); return ESP_OK; } } return ESP_OK; } String clientId(PsychicWebSocketClient *client) { return WEB_SOCKET_ORIGIN_CLIENT_ID_PREFIX + String(client->socket()); } private: JsonStateReader _stateReader; JsonStateUpdater _stateUpdater; StatefulService *_statefulService; AuthenticationPredicate _authenticationPredicate; SecurityManager *_securityManager; PsychicHttpServer *_server; PsychicWebSocketHandler _webSocket; String _webSocketPath; void transmitId(PsychicWebSocketClient *client) { JsonDocument jsonDocument; JsonObject root = jsonDocument.to(); root["type"] = "id"; root["id"] = clientId(client); // serialize the json to a string String buffer; serializeJson(jsonDocument, buffer); client->sendMessage(buffer.c_str()); } /** * Broadcasts the payload to the destination, if provided. Otherwise broadcasts to all clients except the origin, if * specified. * * Original implementation sent clients their own IDs so they could ignore updates they initiated. This approach * simplifies the client and the server implementation but may not be sufficient for all use-cases. */ void transmitData(PsychicWebSocketClient *client, const String &originId) { JsonDocument jsonDocument; JsonObject root = jsonDocument.to(); String buffer; _statefulService->read(root, _stateReader); // serialize the json to a string serializeJson(jsonDocument, buffer); if (client) { client->sendMessage(buffer.c_str()); } else { _webSocket.sendAll(buffer.c_str()); } } }; #endif ================================================ FILE: lib/framework/WiFiScanner.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include WiFiScanner::WiFiScanner(PsychicHttpServer *server, SecurityManager *securityManager) : _server(server), _securityManager(securityManager) { } void WiFiScanner::begin() { _server->on(SCAN_NETWORKS_SERVICE_PATH, HTTP_GET, _securityManager->wrapRequest(std::bind(&WiFiScanner::scanNetworks, this, std::placeholders::_1), AuthenticationPredicates::IS_ADMIN)); ESP_LOGV(SVK_TAG, "Registered GET endpoint: %s", SCAN_NETWORKS_SERVICE_PATH); _server->on(LIST_NETWORKS_SERVICE_PATH, HTTP_GET, _securityManager->wrapRequest(std::bind(&WiFiScanner::listNetworks, this, std::placeholders::_1), AuthenticationPredicates::IS_ADMIN)); ESP_LOGV(SVK_TAG, "Registered GET endpoint: %s", LIST_NETWORKS_SERVICE_PATH); } esp_err_t WiFiScanner::scanNetworks(PsychicRequest *request) { if (WiFi.scanComplete() != -1) { WiFi.scanDelete(); WiFi.scanNetworks(true); } return request->reply(202); } esp_err_t WiFiScanner::listNetworks(PsychicRequest *request) { int numNetworks = WiFi.scanComplete(); if (numNetworks > -1) { PsychicJsonResponse response = PsychicJsonResponse(request, false); JsonObject root = response.getRoot(); JsonArray networks = root["networks"].to(); for (int i = 0; i < numNetworks; i++) { JsonObject network = networks.add(); network["rssi"] = WiFi.RSSI(i); network["ssid"] = WiFi.SSID(i); network["bssid"] = WiFi.BSSIDstr(i); network["channel"] = WiFi.channel(i); network["encryption_type"] = (uint8_t)WiFi.encryptionType(i); } return response.send(); } else if (numNetworks == -1) { return request->reply(202); } else { return scanNetworks(request); } } ================================================ FILE: lib/framework/WiFiScanner.h ================================================ #ifndef WiFiScanner_h #define WiFiScanner_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #define SCAN_NETWORKS_SERVICE_PATH "/rest/scanNetworks" #define LIST_NETWORKS_SERVICE_PATH "/rest/listNetworks" class WiFiScanner { public: WiFiScanner(PsychicHttpServer *server, SecurityManager *securityManager); void begin(); private: PsychicHttpServer *_server; SecurityManager *_securityManager; esp_err_t scanNetworks(PsychicRequest *request); esp_err_t listNetworks(PsychicRequest *request); }; #endif // end WiFiScanner_h ================================================ FILE: lib/framework/WiFiSettingsService.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include WiFiSettingsService::WiFiSettingsService(PsychicHttpServer *server, FS *fs, SecurityManager *securityManager, EventSocket *socket) : _server(server), _securityManager(securityManager), _httpEndpoint(WiFiSettings::read, WiFiSettings::update, this, server, WIFI_SETTINGS_SERVICE_PATH, securityManager, AuthenticationPredicates::IS_ADMIN), _fsPersistence(WiFiSettings::read, WiFiSettings::update, this, fs, WIFI_SETTINGS_FILE), _lastConnectionAttempt(0), _delayedReconnectTime(0), _delayedReconnectPending(false), _socket(socket) { addUpdateHandler([&](const String &originId) { delayedReconnect(); }, false); } void WiFiSettingsService::initWiFi() { WiFi.mode(WIFI_MODE_STA); // this is the default. // Disable WiFi config persistance and auto reconnect WiFi.persistent(false); WiFi.setAutoReconnect(false); WiFi.onEvent( std::bind(&WiFiSettingsService::onStationModeDisconnected, this, std::placeholders::_1, std::placeholders::_2), WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_DISCONNECTED); WiFi.onEvent(std::bind(&WiFiSettingsService::onStationModeStop, this, std::placeholders::_1, std::placeholders::_2), WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_STOP); _fsPersistence.readFromFS(); reconfigureWiFiConnection(); } void WiFiSettingsService::begin() { _socket->registerEvent(EVENT_RSSI); _socket->registerEvent(EVENT_RECONNECT); _httpEndpoint.begin(); } void WiFiSettingsService::delayedReconnect() { _delayedReconnectTime = millis() + DELAYED_RECONNECT_MS; _delayedReconnectPending = true; ESP_LOGI(SVK_TAG, "Delayed WiFi reconnection scheduled in %d ms", DELAYED_RECONNECT_MS); // Emit event to notify clients of impending reconnection JsonDocument doc; doc["delay_ms"] = DELAYED_RECONNECT_MS; JsonObject jsonObject = doc.as(); _socket->emitEvent(EVENT_RECONNECT, jsonObject); } void WiFiSettingsService::reconfigureWiFiConnection() { // reset last connection attempt to force loop to reconnect immediately _lastConnectionAttempt = 0; String connectionMode; switch (_state.staConnectionMode) { case (u_int8_t)STAConnectionMode::OFFLINE: connectionMode = "OFFLINE"; break; case (u_int8_t)STAConnectionMode::PRIORITY: connectionMode = "PRIORITY"; break; case (u_int8_t)STAConnectionMode::STRENGTH: connectionMode = "STRENGTH"; break; default: connectionMode = "UNKNOWN"; break; } ESP_LOGI(SVK_TAG, "Reconfiguring WiFi connection to: %s", connectionMode.c_str()); // disconnect and de-configure wifi if (WiFi.disconnect(true)) { _stopping = true; } } void WiFiSettingsService::loop() { unsigned long currentMillis = millis(); // Handle delayed reconnection if (_delayedReconnectPending && currentMillis >= _delayedReconnectTime) { _delayedReconnectPending = false; ESP_LOGI(SVK_TAG, "Executing delayed WiFi reconnection"); reconfigureWiFiConnection(); } if (!_lastConnectionAttempt || (unsigned long)(currentMillis - _lastConnectionAttempt) >= WIFI_RECONNECTION_DELAY) { _lastConnectionAttempt = currentMillis; manageSTA(); } if (!_lastRssiUpdate || (unsigned long)(currentMillis - _lastRssiUpdate) >= RSSI_EVENT_DELAY) { _lastRssiUpdate = currentMillis; updateRSSI(); } } String WiFiSettingsService::getHostname() { return _state.hostname; } String WiFiSettingsService::getIP() { if (WiFi.isConnected()) { return WiFi.localIP().toString(); } return "Not connected"; } void WiFiSettingsService::manageSTA() { // Abort if already connected, if we have no SSID, or are in offline mode if (WiFi.isConnected() || _state.wifiSettings.empty() || _state.staConnectionMode == (u_int8_t)STAConnectionMode::OFFLINE) { return; } else { #ifdef SERIAL_INFO Serial.println("Connecting to WiFi..."); #endif connectToWiFi(); } } void WiFiSettingsService::connectToWiFi() { // reset availability flag for all stored networks for (auto &network : _state.wifiSettings) { network.available = false; } // scanning for available networks int scanResult = WiFi.scanNetworks(); if (scanResult == WIFI_SCAN_FAILED) { ESP_LOGE(SVK_TAG, "WiFi scan failed."); } else if (scanResult == 0) { ESP_LOGW(SVK_TAG, "No networks found."); } else { ESP_LOGI(SVK_TAG, "%d networks found.", scanResult); // find the best network to connect wifi_settings_t *bestNetwork = NULL; int bestNetworkDb = FACTORY_WIFI_RSSI_THRESHOLD; for (int i = 0; i < scanResult; ++i) { String ssid_scan; int32_t rssi_scan; uint8_t sec_scan; uint8_t *BSSID_scan; int32_t chan_scan; WiFi.getNetworkInfo(i, ssid_scan, sec_scan, rssi_scan, BSSID_scan, chan_scan); ESP_LOGV(SVK_TAG, "SSID: %s, BSSID: " MACSTR ", RSSI: %d dbm, Channel: %d", ssid_scan.c_str(), MAC2STR(BSSID_scan), rssi_scan, chan_scan); for (auto &network : _state.wifiSettings) { if (ssid_scan.equals(network.ssid)) { // SSID match if (rssi_scan > bestNetworkDb) { // best network bestNetworkDb = rssi_scan; ESP_LOGV(SVK_TAG, "--> New best network SSID: %s, BSSID: " MACSTR "", ssid_scan.c_str(), MAC2STR(BSSID_scan)); network.available = true; network.channel = chan_scan; memcpy(network.bssid, BSSID_scan, 6); bestNetwork = &network; } else if (rssi_scan >= FACTORY_WIFI_RSSI_THRESHOLD && network.available == false) { // available network network.available = true; network.channel = chan_scan; memcpy(network.bssid, BSSID_scan, 6); } break; } } } // Connection mode PRIORITY: connect to the first available network if (_state.staConnectionMode == (u_int8_t)STAConnectionMode::PRIORITY) { for (auto &network : _state.wifiSettings) { if (network.available == true) { ESP_LOGI(SVK_TAG, "Connecting to first available network: %s", network.ssid.c_str()); configureNetwork(network); break; } } } // Connection mode STRENGTH: connect to the strongest network else if (_state.staConnectionMode == (u_int8_t)STAConnectionMode::STRENGTH) { if (bestNetwork) { ESP_LOGI(SVK_TAG, "Connecting to strongest network: %s, BSSID: " MACSTR " ", bestNetwork->ssid.c_str(), MAC2STR(bestNetwork->bssid)); configureNetwork(*bestNetwork); } else { ESP_LOGI(SVK_TAG, "No suitable network found."); } } // Connection mode OFFLINE: do not connect to any network else if (_state.staConnectionMode == (u_int8_t)STAConnectionMode::OFFLINE) { ESP_LOGI(SVK_TAG, "WiFi connection mode is OFFLINE, not connecting to any network."); } // Connection mode is unknown: do not connect to any network else { ESP_LOGE(SVK_TAG, "Unknown connection mode, not connecting to any network."); } // delete scan results WiFi.scanDelete(); } } void WiFiSettingsService::configureNetwork(wifi_settings_t &network) { if (network.staticIPConfig) { // configure for static IP WiFi.config(network.localIP, network.gatewayIP, network.subnetMask, network.dnsIP1, network.dnsIP2); } else { // configure for DHCP WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE); } WiFi.setHostname(_state.hostname.c_str()); // attempt to connect to the network WiFi.begin(network.ssid.c_str(), network.password.c_str(), network.channel, network.bssid); // WiFi.begin(network.ssid.c_str(), network.password.c_str()); #if CONFIG_IDF_TARGET_ESP32C3 WiFi.setTxPower(WIFI_POWER_8_5dBm); // https://www.wemos.cc/en/latest/c3/c3_mini_1_0_0.html#about-wifi #endif } void WiFiSettingsService::updateRSSI() { JsonDocument doc; doc["rssi"] = WiFi.RSSI(); doc["ssid"] = WiFi.isConnected() ? WiFi.SSID() : "disconnected"; JsonObject jsonObject = doc.as(); _socket->emitEvent(EVENT_RSSI, jsonObject); } void WiFiSettingsService::onStationModeDisconnected(WiFiEvent_t event, WiFiEventInfo_t info) { manageSTA(); } void WiFiSettingsService::onStationModeStop(WiFiEvent_t event, WiFiEventInfo_t info) { if (_stopping) { _lastConnectionAttempt = 0; _stopping = false; } } ================================================ FILE: lib/framework/WiFiSettingsService.h ================================================ #ifndef WiFiSettingsService_h #define WiFiSettingsService_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #include #include #include #include #include #include #include #ifndef FACTORY_WIFI_SSID #define FACTORY_WIFI_SSID "" #endif #ifndef FACTORY_WIFI_PASSWORD #define FACTORY_WIFI_PASSWORD "" #endif #ifndef FACTORY_WIFI_HOSTNAME #define FACTORY_WIFI_HOSTNAME "#{platform}-#{unique_id}" #endif #ifndef FACTORY_WIFI_RSSI_THRESHOLD #define FACTORY_WIFI_RSSI_THRESHOLD -80 #endif #define WIFI_SETTINGS_FILE "/config/wifiSettings.json" #define WIFI_SETTINGS_SERVICE_PATH "/rest/wifiSettings" #define WIFI_RECONNECTION_DELAY 1000 * 5 #define RSSI_EVENT_DELAY 500 #define DELAYED_RECONNECT_MS 1000 #define EVENT_RSSI "rssi" #define EVENT_RECONNECT "reconnect" // Struct defining the wifi settings typedef struct { String ssid; uint8_t bssid[6]; int32_t channel; String password; bool staticIPConfig; IPAddress localIP; IPAddress gatewayIP; IPAddress subnetMask; IPAddress dnsIP1; IPAddress dnsIP2; bool available; } wifi_settings_t; enum class STAConnectionMode { OFFLINE = 0, STRENGTH, PRIORITY }; class WiFiSettings { public: // core wifi configuration String hostname; u_int8_t staConnectionMode; std::vector wifiSettings; static void read(WiFiSettings &settings, JsonObject &root) { root["hostname"] = settings.hostname; root["connection_mode"] = settings.staConnectionMode; // create JSON array from root JsonArray wifiNetworks = root["wifi_networks"].to(); // iterate over the wifiSettings for (auto &wifi : settings.wifiSettings) { // create JSON object for each wifi network JsonObject wifiNetwork = wifiNetworks.add(); // add the ssid and password to the JSON object wifiNetwork["ssid"] = wifi.ssid; wifiNetwork["password"] = wifi.password; wifiNetwork["static_ip_config"] = wifi.staticIPConfig; // extended settings JsonUtils::writeIP(wifiNetwork, "local_ip", wifi.localIP); JsonUtils::writeIP(wifiNetwork, "gateway_ip", wifi.gatewayIP); JsonUtils::writeIP(wifiNetwork, "subnet_mask", wifi.subnetMask); JsonUtils::writeIP(wifiNetwork, "dns_ip_1", wifi.dnsIP1); JsonUtils::writeIP(wifiNetwork, "dns_ip_2", wifi.dnsIP2); } ESP_LOGV(SVK_TAG, "WiFi Settings read"); } static StateUpdateResult update(JsonObject &root, WiFiSettings &settings, const String &originId) { settings.hostname = root["hostname"] | SettingValue::format(FACTORY_WIFI_HOSTNAME); settings.staConnectionMode = root["connection_mode"] | 1; settings.wifiSettings.clear(); // create JSON array from root JsonArray wifiNetworks = root["wifi_networks"]; if (root["wifi_networks"].is()) { // iterate over the wifiSettings int i = 0; for (auto wifiNetwork : wifiNetworks) { // max 5 wifi networks if (i++ >= 5) { ESP_LOGE(SVK_TAG, "Too many wifi networks"); break; } // create JSON object for each wifi network JsonObject wifi = wifiNetwork.as(); // Check if SSID length is between 1 and 31 characters and password between 0 and 64 characters if (wifi["ssid"].as().length() < 1 || wifi["ssid"].as().length() > 31 || wifi["password"].as().length() > 64) { ESP_LOGE(SVK_TAG, "SSID or password length is invalid"); } else { // add the ssid and password to the JSON object wifi_settings_t wifiSettings; wifiSettings.ssid = wifi["ssid"].as(); wifiSettings.password = wifi["password"].as(); wifiSettings.staticIPConfig = wifi["static_ip_config"]; // extended settings JsonUtils::readIP(wifi, "local_ip", wifiSettings.localIP); JsonUtils::readIP(wifi, "gateway_ip", wifiSettings.gatewayIP); JsonUtils::readIP(wifi, "subnet_mask", wifiSettings.subnetMask); JsonUtils::readIP(wifi, "dns_ip_1", wifiSettings.dnsIP1); JsonUtils::readIP(wifi, "dns_ip_2", wifiSettings.dnsIP2); // Swap around the dns servers if 2 is populated but 1 is not if (IPUtils::isNotSet(wifiSettings.dnsIP1) && IPUtils::isSet(wifiSettings.dnsIP2)) { wifiSettings.dnsIP1 = wifiSettings.dnsIP2; wifiSettings.dnsIP2 = INADDR_NONE; } // Turning off static ip config if we don't meet the minimum requirements // of ipAddress, gateway and subnet. This may change to static ip only // as sensible defaults can be assumed for gateway and subnet if (wifiSettings.staticIPConfig && (IPUtils::isNotSet(wifiSettings.localIP) || IPUtils::isNotSet(wifiSettings.gatewayIP) || IPUtils::isNotSet(wifiSettings.subnetMask))) { wifiSettings.staticIPConfig = false; } // reset scan result wifiSettings.available = false; settings.wifiSettings.push_back(wifiSettings); // increment the wifi network index i++; } } } else { // populate with factory defaults if they are present if (String(FACTORY_WIFI_SSID).length() > 0) { settings.wifiSettings.push_back(wifi_settings_t{ .ssid = FACTORY_WIFI_SSID, .password = FACTORY_WIFI_PASSWORD, .staticIPConfig = false, .localIP = INADDR_NONE, .gatewayIP = INADDR_NONE, .subnetMask = INADDR_NONE, .dnsIP1 = INADDR_NONE, .dnsIP2 = INADDR_NONE, .available = false, }); } } ESP_LOGV(SVK_TAG, "WiFi Settings updated"); return StateUpdateResult::CHANGED; }; }; class WiFiSettingsService : public StatefulService { public: WiFiSettingsService(PsychicHttpServer *server, FS *fs, SecurityManager *securityManager, EventSocket *socket); void initWiFi(); void begin(); void loop(); void delayedReconnect(); String getHostname(); String getIP(); private: PsychicHttpServer *_server; SecurityManager *_securityManager; HttpEndpoint _httpEndpoint; FSPersistence _fsPersistence; EventSocket *_socket; unsigned long _lastConnectionAttempt; unsigned long _lastRssiUpdate; unsigned long _delayedReconnectTime; bool _delayedReconnectPending; bool _stopping; void onStationModeDisconnected(WiFiEvent_t event, WiFiEventInfo_t info); void onStationModeStop(WiFiEvent_t event, WiFiEventInfo_t info); void reconfigureWiFiConnection(); void manageSTA(); void connectToWiFi(); void configureNetwork(wifi_settings_t &network); void updateRSSI(); }; #endif // end WiFiSettingsService_h ================================================ FILE: lib/framework/WiFiStatus.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include WiFiStatus::WiFiStatus(PsychicHttpServer *server, SecurityManager *securityManager) : _server(server), _securityManager(securityManager) { } void WiFiStatus::begin() { _server->on(WIFI_STATUS_SERVICE_PATH, HTTP_GET, _securityManager->wrapRequest(std::bind(&WiFiStatus::wifiStatus, this, std::placeholders::_1), AuthenticationPredicates::IS_AUTHENTICATED)); ESP_LOGV(SVK_TAG, "Registered GET endpoint: %s", WIFI_STATUS_SERVICE_PATH); WiFi.onEvent(onStationModeConnected, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_CONNECTED); WiFi.onEvent(onStationModeDisconnected, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_DISCONNECTED); WiFi.onEvent(onStationModeGotIP, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_GOT_IP); } void WiFiStatus::onStationModeConnected(WiFiEvent_t event, WiFiEventInfo_t info) { ESP_LOGI(SVK_TAG, "WiFi Connected."); #ifdef SERIAL_INFO Serial.println("WiFi Connected."); #endif } void WiFiStatus::onStationModeDisconnected(WiFiEvent_t event, WiFiEventInfo_t info) { ESP_LOGI(SVK_TAG, "WiFi Disconnected. Reason code=%d", info.wifi_sta_disconnected.reason); #ifdef SERIAL_INFO Serial.print("WiFi Disconnected. Reason code="); Serial.println(info.wifi_sta_disconnected.reason); #endif } void WiFiStatus::onStationModeGotIP(WiFiEvent_t event, WiFiEventInfo_t info) { ESP_LOGI(SVK_TAG, "WiFi Got IP. localIP=%s, hostName=%s", WiFi.localIP().toString().c_str(), WiFi.getHostname()); #ifdef SERIAL_INFO Serial.printf("WiFi Got IP. localIP=%s, hostName=%s\r\n", WiFi.localIP().toString().c_str(), WiFi.getHostname()); #endif } esp_err_t WiFiStatus::wifiStatus(PsychicRequest *request) { PsychicJsonResponse response = PsychicJsonResponse(request, false); JsonObject root = response.getRoot(); wl_status_t status = WiFi.status(); root["status"] = (uint8_t)status; if (status == WL_CONNECTED) { root["local_ip"] = WiFi.localIP().toString(); root["mac_address"] = WiFi.macAddress(); root["rssi"] = WiFi.RSSI(); root["ssid"] = WiFi.SSID(); root["bssid"] = WiFi.BSSIDstr(); root["channel"] = WiFi.channel(); root["subnet_mask"] = WiFi.subnetMask().toString(); root["gateway_ip"] = WiFi.gatewayIP().toString(); IPAddress dnsIP1 = WiFi.dnsIP(0); IPAddress dnsIP2 = WiFi.dnsIP(1); if (IPUtils::isSet(dnsIP1)) { root["dns_ip_1"] = dnsIP1.toString(); } if (IPUtils::isSet(dnsIP2)) { root["dns_ip_2"] = dnsIP2.toString(); } } return response.send(); } bool WiFiStatus::isConnected() { return WiFi.status() == WL_CONNECTED; } ================================================ FILE: lib/framework/WiFiStatus.h ================================================ #ifndef WiFiStatus_h #define WiFiStatus_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #include #define WIFI_STATUS_SERVICE_PATH "/rest/wifiStatus" class WiFiStatus { public: WiFiStatus(PsychicHttpServer *server, SecurityManager *securityManager); void begin(); bool isConnected(); private: PsychicHttpServer *_server; SecurityManager *_securityManager; // static functions for logging WiFi events to the UART static void onStationModeConnected(WiFiEvent_t event, WiFiEventInfo_t info); static void onStationModeDisconnected(WiFiEvent_t event, WiFiEventInfo_t info); static void onStationModeGotIP(WiFiEvent_t event, WiFiEventInfo_t info); esp_err_t wifiStatus(PsychicRequest *request); }; #endif // end WiFiStatus_h ================================================ FILE: mkdocs.yml ================================================ site_name: ESP32 SvelteKit nav: - Home: index.md - "Build Tools": - gettingstarted.md - buildprocess.md - "Front End": - sveltekit.md - structure.md - stores.md - components.md - "Back End": - statefulservice.md - restfulapi.md site_author: elims site_description: >- A simple, secure and extensible framework for IoT projects on ESP32 platforms with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. # Repository repo_name: theelims/ESP32-sveltekit repo_url: https://github.com/theelims/ESP32-sveltekit theme: name: material logo: media/svelte-logo.png favicon: media/favicon.png icon: repo: fontawesome/brands/github palette: # Palette toggle for light mode - media: "(prefers-color-scheme: light)" scheme: default toggle: icon: material/weather-night name: Switch to dark mode primary: blue accent: blue # Palette toggle for dark mode - media: "(prefers-color-scheme: dark)" scheme: slate toggle: icon: material/weather-sunny name: Switch to light mode primary: indigo accent: indigo features: - navigation.instant - navigation.tracking - navigation.tabs - navigation.tabs.sticky - navigation.sections - navigation.expand - toc.follow - toc.integrate - navigation.top - content.code.copy markdown_extensions: - attr_list - md_in_html - tables - admonition - pymdownx.details - pymdownx.superfences: custom_fences: - name: mermaid class: mermaid format: !!python/name:pymdownx.superfences.fence_code_format - pymdownx.emoji: emoji_index: !!python/name:materialx.emoji.twemoji emoji_generator: !!python/name:materialx.emoji.to_svg extra: social: - icon: fontawesome/brands/github link: https://github.com/theelims/ - icon: fontawesome/brands/discord link: https://discord.gg/MTn9mVUG5n consent: title: Cookie consent description: >- We use cookies to recognize your repeated visits and preferences, as well as to measure the effectiveness of our documentation and whether users find what they're searching for. With your consent, you're helping us to make our documentation better. actions: - accept - reject plugins: - search: separator: '[\s\-,:!=\[\]()"/]+|(?!\b)(?=[A-Z][a-z])|\.(?!\d)|&[lg]t;' copyright: | Copyright © 2025 by elims - Change cookie settings ================================================ FILE: platformio.ini ================================================ ; PlatformIO Project Configuration File ; ; Build options: build flags, source filter ; Upload options: custom upload port, speed and extra flags ; Library options: dependencies, extra library storages ; Advanced options: extra scripting ; ; Please visit documentation for the other options and examples ; https://docs.platformio.org/page/projectconf.html [platformio] description = ESP32 Sveltekit Template data_dir = data extra_configs = factory_settings.ini features.ini default_envs = esp32-s3-devkitc-1 [env] framework = arduino platform = https://github.com/pioarduino/platform-espressif32/releases/download/55.03.32/platform-espressif32.zip build_flags = ${factory_settings.build_flags} ${features.build_flags} -D BUILD_TARGET=\"$PIOENV\" -D APP_NAME=\"ESP32-Sveltekit\" ; Must only contain characters from [a-zA-Z0-9-_] as this is converted into a filename -D APP_VERSION=\"0.6.0\" ; semver compatible version string ; Move all networking stuff to the protocol core 0 and leave business logic on application core 1 -D ESP32SVELTEKIT_RUNNING_CORE=0 ; Uncomment EMBED_WWW to embed the WWW data in the firmware binary -D EMBED_WWW ; Uncomment to configure Cross-Origin Resource Sharing ; -D ENABLE_CORS ; -D CORS_ORIGIN=\"*\" ; Uncomment to enable informations from ESP32-Sveltekit in Serial Monitor -D SERIAL_INFO ; Uncomment to skip SSL certificate verification when downloading firmware updates -D DOWNLOAD_OTA_SKIP_CERT_VERIFY ; D E B U G B U I L D F L A G S ; =============================== ; These build flags are only for debugging purposes and should not be used in production -D CONFIG_ARDUHAL_LOG_COLORS ; Uncomment to show log messages from the ESP Arduino Core and ESP32-SvelteKit -D CORE_DEBUG_LEVEL=4 ; Serve config files from flash and access at /config/filename.json ;-D SERVE_CONFIG_FILES ; Uncomment to teleplot all task high watermarks to Serial ; -D TELEPLOT_TASKS ; Uncomment to use JSON instead of MessagePack for event messages. Default is MessagePack. ; -D EVENT_USE_JSON=1 lib_compat_mode = strict ; Uncomment to include the a Root CA SSL Certificate Bundle for all SSL needs ; Needs -D FT_DOWNLOAD_FIRMWARE=1 and -D FT_NTP=1 board_build.embed_files = src/certs/x509_crt_bundle.bin ; Source for SSL Cert Store can bei either downloaded from Mozilla with 'mozilla' ('https://curl.se/ca/cacert.pem') ; or from a curated Adafruit repository with 'adafruit' (https://raw.githubusercontent.com/adafruit/certificates/main/data/roots-filtered.pem) ; or complied from a 'folder' full of *.pem / *.dem files stored in the ./ssl_certs folder ;board_ssl_cert_source = mozilla board_ssl_cert_source = adafruit monitor_speed = 115200 monitor_filters = esp32_exception_decoder log2file board_build.filesystem = littlefs extra_scripts = pre:scripts/build_interface.py pre:scripts/generate_cert_bundle.py scripts/merge_bin.py scripts/rename_fw.py scripts/save_elf.py lib_deps = ArduinoJson@>=7.0.0 elims/PsychicMqttClient@^0.2.4 [env:esp32-c3-devkitm-1] board = esp32-c3-devkitm-1 board_build.mcu = esp32c3 ; Uncomment min_spiffs.csv setting if using EMBED_WWW with ESP32 board_build.partitions = min_spiffs.csv ; Use USB CDC for firmware upload and serial terminal ; board_upload.before_reset = usb_reset ; build_flags = ; ${env.build_flags} ; -DARDUINO_USB_CDC_ON_BOOT=1 ; -DARDUINO_USB_MODE=1 [env:esp32-s3-devkitc-1] board = esp32-s3-devkitc-1 board_build.mcu = esp32s3 board_build.partitions = default_8MB.csv ; Use USB CDC for firmware upload and serial terminal ; board_upload.before_reset = usb_reset build_flags = ${env.build_flags} -DARDUINO_USB_CDC_ON_BOOT=1 -DARDUINO_USB_MODE=1 [env:esp32dev] ; Works for nodemcu-32s, devkit-v1 boards and probably others. You can change the pin defines below if needed. board = esp32dev board_build.partitions = min_spiffs.csv build_flags = ${env.build_flags} -D LED_BUILTIN=2 -D KEY_BUILTIN=0 [env:Kincony-B16M] ; Works for the Kincony B16M smart home controller with Ethernet support board = esp32-s3-devkitc-1 board_build.partitions = default_16MB.csv board_upload.before_reset = usb-reset build_flags = ${env.build_flags} -DARDUINO_USB_CDC_ON_BOOT=1 -DARDUINO_USB_MODE=1 -DFT_ETHERNET=1 -DUSE_TWO_ETH_PORTS=0 -DETH_PHY_TYPE=ETH_PHY_W5500 -DETH_PHY_ADDR=1 -DETH_PHY_CS=41 -DETH_PHY_IRQ=2 ; -1 if you won't wire -DETH_PHY_RST=1 ; -1 if you won't wire -DETH_SPI_SCK=42 -DETH_SPI_MISO=44 -DETH_SPI_MOSI=43 [env:esp32-wt32-eth01] ; Works for the WT32-ETH01 board with Ethernet support board = wt32-eth01 board_build.partitions = min_spiffs.csv build_flags = ${env.build_flags} ; Not an LED but an unused GPIO pin -DLED_BUILTIN=14 -DKEY_BUILTIN=0 -DFT_ETHERNET=1 ; Only use the filtered Adafruit SSL cert bundle as the full Mozilla bundle is too large for this board with the whole demo app board_ssl_cert_source = adafruit ================================================ FILE: scripts/build_interface.py ================================================ # ESP32 SvelteKit -- # # A simple, secure and extensible framework for IoT projects for ESP32 platforms # with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. # https://github.com/theelims/ESP32-sveltekit # # Copyright (C) 2018 - 2023 rjwats # Copyright (C) 2023 - 2024 theelims # Copyright (C) 2023 Maxtrium B.V. [ code available under dual license ] # Copyright (C) 2024 runeharlyk # Copyright (C) 2025 hmbacher # # All Rights Reserved. This software may be modified and distributed under # the terms of the LGPL v3 license. See the LICENSE file for details. from pathlib import Path from shutil import copytree, rmtree, copyfileobj from os.path import exists, getmtime import os import sys import gzip import mimetypes import glob from datetime import datetime # Import shared prebuild utilities from prebuild_utils import is_build_task # Check if this script should run if not is_build_task(['build', 'upload', 'buildfs', 'erase_upload']): # Skip script execution for all other tasks print("Skipping interface build for non-build task.") sys.exit(0) Import("env") project_dir = env["PROJECT_DIR"] buildFlags = env.ParseFlags(env["BUILD_FLAGS"]) interface_dir = project_dir + "/interface" output_file = project_dir + "/lib/framework/WWWData.h" source_www_dir = interface_dir + "/src" build_dir = interface_dir + "/build" filesystem_dir = project_dir + "/data/www" def find_latest_timestamp_for_app(): return max( (getmtime(f) for f in glob.glob(f"{source_www_dir}/**/*", recursive=True)) ) def should_regenerate_output_file(): if not flag_exists("EMBED_WWW") or not exists(output_file): return True last_source_change = find_latest_timestamp_for_app() last_build = getmtime(output_file) print( f"Newest file: {datetime.fromtimestamp(last_source_change)}, output file: {datetime.fromtimestamp(last_build)}" ) return last_build < last_source_change def gzip_file(file): with open(file, 'rb') as f_in: with gzip.open(file + '.gz', 'wb') as f_out: copyfileobj(f_in, f_out) os.remove(file) def flag_exists(flag): for define in buildFlags.get("CPPDEFINES"): if (define == flag or (isinstance(define, list) and define[0] == flag)): return True return False def get_package_manager(): if exists(os.path.join(interface_dir, "pnpm-lock.yaml")): return "pnpm" if exists(os.path.join(interface_dir, "yarn.lock")): return "yarn" else: return "npm" def build_webapp(): package_manager = get_package_manager() print(f"Building interface with {package_manager}") os.chdir(interface_dir) env.Execute(f"{package_manager} install") env.Execute(f"{package_manager} run build") os.chdir("..") def embed_webapp(): if flag_exists("EMBED_WWW"): print("Converting interface to PROGMEM") build_progmem() return add_app_to_filesystem() def build_progmem(): mimetypes.init() with open(output_file, "w") as progmem: progmem.write("#include \n") progmem.write("#include \n") assetMap = {} for idx, path in enumerate(Path(build_dir).rglob("*.*")): asset_path = path.relative_to(build_dir).as_posix() asset_mime = ( mimetypes.guess_type(asset_path)[0] or "application/octet-stream" ) print(f"Converting {asset_path}") asset_var = f"ESP_SVELTEKIT_DATA_{idx}" progmem.write(f"// {asset_path}\n") progmem.write(f"const uint8_t {asset_var}[] = {{\n\t") file_data = gzip.compress(path.read_bytes()) for i, byte in enumerate(file_data): if i and not (i % 16): progmem.write("\n\t") progmem.write(f"0x{byte:02X},") progmem.write("\n};\n\n") assetMap[asset_path] = { "name": asset_var, "mime": asset_mime, "size": len(file_data), } progmem.write( "typedef std::function RouteRegistrationHandler;\n\n" ) progmem.write("class WWWData {\n") progmem.write("\tpublic:\n") progmem.write( "\t\tstatic void registerRoutes(RouteRegistrationHandler handler) {\n" ) for asset_path, asset in assetMap.items(): progmem.write( f'\t\t\thandler("/{asset_path}", "{asset["mime"]}", {asset["name"]}, {asset["size"]});\n' ) progmem.write("\t\t}\n") progmem.write("};\n\n") def add_app_to_filesystem(): build_path = Path(build_dir) www_path = Path(filesystem_dir) if www_path.exists() and www_path.is_dir(): rmtree(www_path) print("Copying and compress interface to data directory") copytree(build_path, www_path) for current_path, _, files in os.walk(www_path): for file in files: gzip_file(os.path.join(current_path, file)) if ("upload" in BUILD_TARGETS): print("Build LittleFS file system image and upload to ESP32") env.Execute("pio run --target uploadfs") print("running: build_interface.py") if should_regenerate_output_file(): build_webapp() embed_webapp() ================================================ FILE: scripts/generate_cert_bundle.py ================================================ #!/usr/bin/env python # # modified ESP32 x509 certificate bundle generation utility to run with platformio # # Converts PEM and DER certificates to a custom bundle format which stores just the # subject name and public key to reduce space # # The bundle will have the format: number of certificates; crt 1 subject name length; crt 1 public key length; # crt 1 subject name; crt 1 public key; crt 2... # # SPDX-FileCopyrightText: 2018-2022 Espressif Systems (Shanghai) CO LTD # SPDX-License-Identifier: Apache-2.0 from __future__ import with_statement from pathlib import Path import os import struct import sys import requests from io import open # Import shared prebuild utilities from prebuild_utils import is_build_task # Check if this script should run if not is_build_task(['build', 'upload', 'buildfs', 'erase_upload']): # Skip script execution for all other tasks print("Skipping certificate bundle generation for non-build task.") sys.exit(0) Import("env") try: from cryptography import x509 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization except ImportError: env.Execute("$PYTHONEXE -m pip install cryptography") ca_bundle_bin_file = 'x509_crt_bundle.bin' mozilla_cacert_url = 'https://curl.se/ca/cacert.pem' adafruit_filtered_cacert_url = 'https://raw.githubusercontent.com/adafruit/certificates/main/data/roots-filtered.pem' adafruit_full_cacert_url = 'https://raw.githubusercontent.com/adafruit/certificates/main/data/roots-full.pem' certs_dir = Path("./ssl_certs") binary_dir = Path("./src/certs") quiet = False def download_cacert_file(source): if source == "mozilla": response = requests.get(mozilla_cacert_url) elif source == "adafruit": response = requests.get(adafruit_filtered_cacert_url) elif source == "adafruit-full": response = requests.get(adafruit_full_cacert_url) else: raise InputError('Invalid certificate source') if response.status_code == 200: # Ensure the directory exists, create it if necessary os.makedirs(certs_dir, exist_ok=True) # Generate the full path to the output file output_file = os.path.join(certs_dir, "cacert.pem") # Write the certificate bundle to the output file with utf-8 encoding with open(output_file, "w", encoding="utf-8") as f: f.write(response.text) status('Certificate bundle downloaded to: %s' % output_file) else: status('Failed to fetch the certificate bundle.') def status(msg): """ Print status message to stderr """ if not quiet: critical(msg) def critical(msg): """ Print critical message to stderr """ sys.stderr.write('SSL Cert Store: ') sys.stderr.write(msg) sys.stderr.write('\n') class CertificateBundle: def __init__(self): self.certificates = [] self.compressed_crts = [] if os.path.isfile(ca_bundle_bin_file): os.remove(ca_bundle_bin_file) def add_from_path(self, crts_path): found = False for file_path in os.listdir(crts_path): found |= self.add_from_file(os.path.join(crts_path, file_path)) if found is False: raise InputError('No valid x509 certificates found in %s' % crts_path) def add_from_file(self, file_path): try: if file_path.endswith('.pem'): status('Parsing certificates from %s' % file_path) with open(file_path, 'r', encoding='utf-8') as f: crt_str = f.read() self.add_from_pem(crt_str) return True elif file_path.endswith('.der'): status('Parsing certificates from %s' % file_path) with open(file_path, 'rb') as f: crt_str = f.read() self.add_from_der(crt_str) return True except ValueError: critical('Invalid certificate in %s' % file_path) raise InputError('Invalid certificate') return False def add_from_pem(self, crt_str): """ A single PEM file may have multiple certificates """ crt = '' count = 0 start = False for strg in crt_str.splitlines(True): if strg == '-----BEGIN CERTIFICATE-----\n' and start is False: crt = '' start = True elif strg == '-----END CERTIFICATE-----\n' and start is True: crt += strg + '\n' start = False # 🌙 show warning try: cert = x509.load_pem_x509_certificate(crt.encode(), default_backend()) # Check serial number if cert.serial_number <= 0: status(f'Warning: Certificate {cert} has invalid serial number: {cert.serial_number}') self.certificates.append(cert) count += 1 except Exception as e: status(f'Failed to load certificate: {e}') if start is True: crt += strg if count == 0: raise InputError('No certificate found') status('Successfully added %d certificates' % count) def add_from_der(self, crt_str): self.certificates.append(x509.load_der_x509_certificate(crt_str, default_backend())) status('Successfully added 1 certificate') def create_bundle(self): # Sort certificates in order to do binary search when looking up certificates self.certificates = sorted(self.certificates, key=lambda cert: cert.subject.public_bytes(default_backend())) bundle = struct.pack('>H', len(self.certificates)) for crt in self.certificates: """ Read the public key as DER format """ pub_key = crt.public_key() pub_key_der = pub_key.public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo) """ Read the subject name as DER format """ sub_name_der = crt.subject.public_bytes(default_backend()) name_len = len(sub_name_der) key_len = len(pub_key_der) len_data = struct.pack('>HH', name_len, key_len) bundle += len_data bundle += sub_name_der bundle += pub_key_der return bundle class InputError(RuntimeError): def __init__(self, e): super(InputError, self).__init__(e) def main(): bundle = CertificateBundle() try: cert_source = env.GetProjectOption("board_ssl_cert_source") if (cert_source == "mozilla" or cert_source == "adafruit"): download_cacert_file(cert_source) bundle.add_from_file(os.path.join(certs_dir, "cacert.pem")) elif (cert_source == "folder"): bundle.add_from_path(certs_dir) except ValueError: critical('Invalid configuration option: use \'board_ssl_cert_source\' parameter in platformio.ini' ) raise InputError('Invalid certificate') status('Successfully added %d certificates in total' % len(bundle.certificates)) crt_bundle = bundle.create_bundle() # Ensure the directory exists, create it if necessary os.makedirs(binary_dir, exist_ok=True) output_file = os.path.join(binary_dir, ca_bundle_bin_file) with open(output_file, 'wb') as f: f.write(crt_bundle) status('Successfully created %s' % output_file) try: main() except InputError as e: print(e) sys.exit(2) ================================================ FILE: scripts/merge_bin.py ================================================ import os import re Import("env") APP_BIN = "$BUILD_DIR/${PROGNAME}.bin" OUTPUT_DIR = "build{}merged{}".format(os.path.sep, os.path.sep) BOARD_CONFIG = env.BoardConfig() def readFlag(flag): buildFlags = env.ParseFlags(env["BUILD_FLAGS"]) # print(buildFlags.get("CPPDEFINES")) for define in buildFlags.get("CPPDEFINES"): if (define == flag or (isinstance(define, list) and define[0] == flag)): # print("Found "+flag+" = "+define[1]) # strip quotes ("") from define[1] cleanedFlag = re.sub(r'^"|"$', '', define[1]) return cleanedFlag return None def merge_bin(source, target, env): # check if output directories exist and create if necessary if not os.path.isdir("build"): os.mkdir("build") if not os.path.isdir(OUTPUT_DIR): os.mkdir(OUTPUT_DIR) MERGED_BIN = "$PROJECT_DIR{}{}{}_{}_{}_webflash.bin".format(os.path.sep, OUTPUT_DIR, readFlag("APP_NAME"), env.get('PIOENV'), readFlag("APP_VERSION").replace(".", "-")) # The list contains all extra images (bootloader, partitions, eboot) and # the final application binary flash_images = env.Flatten(env.get("FLASH_EXTRA_IMAGES", [])) + ["$ESP32_APP_OFFSET", APP_BIN] flash_size = env.BoardConfig().get("upload.flash_size", "4MB") flash_freq = env.BoardConfig().get("build.f_flash", "40000000L") flash_freq = str(flash_freq).replace("L", "") flash_freq = str(int(int(flash_freq) / 1000000)) + "m" flash_mode = env.BoardConfig().get("build.flash_mode", "dio") memory_type = env.BoardConfig().get("build.arduino.memory_type", "qio_qspi") if flash_mode == "qio" or flash_mode == "qout": flash_mode = "dio" if memory_type == "opi_opi" or memory_type == "opi_qspi": flash_mode = "dout" # Run esptool to merge images into a single binary env.Execute( " ".join( [ "$PYTHONEXE", "$OBJCOPY", "--chip", BOARD_CONFIG.get("build.mcu", "esp32"), "merge-bin", "-o", MERGED_BIN, "--flash-mode", flash_mode, "--flash-freq", flash_freq, "--flash-size", flash_size ] + flash_images ) ) # Add a post action that runs esptoolpy to merge available flash images env.AddPostAction(APP_BIN , merge_bin) ================================================ FILE: scripts/prebuild_utils.py ================================================ #!/usr/bin/env python3 """ Shared utilities for PlatformIO pre-build scripts. """ import os import sys def is_build_task(required_tasks): """ Check if the current PlatformIO task requires pre-build script execution. Args: required_tasks: List of PlatformIO tasks that need the calling script Returns: bool: True if script should run, False if it should be skipped """ # Get caller's filename for logging try: caller_frame = sys._getframe(1) script_name = os.path.basename(caller_frame.f_code.co_filename) except (AttributeError, ValueError): script_name = os.path.basename(sys.argv[0]) if sys.argv else 'unknown_script' # Check command line arguments for build tasks cmd_args = ' '.join(sys.argv).lower() # Map PlatformIO direct flags to our task names - only skip for truly non-build tasks skip_flags = { '--clean': 'clean', '--erase': 'erase', '--monitor': 'monitor' } # Check for direct PlatformIO flags that should skip pre-build scripts for flag, task_name in skip_flags.items(): if flag in cmd_args: if task_name not in required_tasks: print(f"Skipping {script_name} for {task_name} task") return False # Check for --target format for non-build targets only skip_targets = ['clean', 'erase', 'monitor', 'metrics-only'] has_skip_target = any( f'--target {task}' in cmd_args or f'-t {task}' in cmd_args for task in skip_targets if task not in required_tasks ) if has_skip_target: print(f"Skipping {script_name} for non-build task") return False # Continue execution for all other tasks (including size, metrics, etc. that may need building) return True ================================================ FILE: scripts/rename_fw.py ================================================ """ EMS-ESP - https://github.com/emsesp/EMS-ESP Copyright 2020-2023 Paul Derbyshire This program 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. This program 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 program. If not, see . """ import shutil import re import os Import("env") import hashlib OUTPUT_DIR = "build{}release{}".format(os.path.sep, os.path.sep) def readFlag(flag): buildFlags = env.ParseFlags(env["BUILD_FLAGS"]) # print(buildFlags.get("CPPDEFINES")) for define in buildFlags.get("CPPDEFINES"): if (define == flag or (isinstance(define, list) and define[0] == flag)): # print("Found "+flag+" = "+define[1]) # strip quotes ("") from define[1] cleanedFlag = re.sub(r'^"|"$', '', define[1]) return cleanedFlag return None def bin_copy(source, target, env): # get the build info app_version = readFlag("APP_VERSION") app_name = readFlag("APP_NAME") build_target = env.get('PIOENV') # print information's print("App Version: " + app_version) print("App Name: " + app_name) print("Build Target: " + build_target) # convert . to - so Windows doesn't complain variant = app_name + "_" + build_target + "_" + app_version.replace(".", "-") # check if output directories exist and create if necessary if not os.path.isdir(OUTPUT_DIR): os.mkdir(OUTPUT_DIR) # create string with location and file names based on variant bin_file = "{}{}.bin".format(OUTPUT_DIR, variant) md5_file = "{}{}.md5".format(OUTPUT_DIR, variant) # check if new target files exist and remove if necessary for f in [bin_file]: if os.path.isfile(f): os.remove(f) # check if new target files exist and remove if necessary for f in [md5_file]: if os.path.isfile(f): os.remove(f) print("Renaming file to "+bin_file) # copy firmware.bin to firmware/.bin shutil.copy(str(target[0]), bin_file) with open(bin_file,"rb") as f: result = hashlib.md5(f.read()) print("Calculating MD5: "+result.hexdigest()) file1 = open(md5_file, 'w') file1.write(result.hexdigest()) file1.close() env.AddPostAction("$BUILD_DIR/${PROGNAME}.bin", [bin_copy]) env.AddPostAction("$BUILD_DIR/${PROGNAME}.md5", [bin_copy]) ================================================ FILE: scripts/save_elf.py ================================================ import shutil import re import os Import("env") import hashlib OUTPUT_DIR = "build{}elf{}".format(os.path.sep,os.path.sep) def elf_copy(source, target, env): # check if output directories exist and create if necessary if not os.path.isdir("build"): os.mkdir("build") if not os.path.isdir(OUTPUT_DIR): os.mkdir(OUTPUT_DIR) with open(str(target[0]),"rb") as f: result = hashlib.sha256(f.read()) # create string with location and file names based on variant elf_file = "{}{}.elf".format(OUTPUT_DIR, result.hexdigest()) # check if new target files exist and remove if necessary for f in [elf_file]: if os.path.isfile(f): os.remove(f) print("Saving ELF file to "+elf_file) # copy firmware.bin to firmware/.bin shutil.copy(str(target[0]), elf_file) env.AddPostAction("$BUILD_DIR/${PROGNAME}.elf", [elf_copy]) ================================================ FILE: src/LightMqttSettingsService.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include LightMqttSettingsService::LightMqttSettingsService(PsychicHttpServer *server, ESP32SvelteKit *sveltekit) : _httpEndpoint(LightMqttSettings::read, LightMqttSettings::update, this, server, LIGHT_BROKER_SETTINGS_PATH, sveltekit->getSecurityManager(), AuthenticationPredicates::IS_AUTHENTICATED), _fsPersistence(LightMqttSettings::read, LightMqttSettings::update, this, sveltekit->getFS(), LIGHT_BROKER_SETTINGS_FILE), _mqttSettingsService(sveltekit->getMqttSettingsService()) { // configure settings service update handler to update LED state addUpdateHandler([&](const String &originId) { onConfigUpdated(); }, false); } void LightMqttSettingsService::begin() { _httpEndpoint.begin(); _fsPersistence.readFromFS(); } void LightMqttSettingsService::onConfigUpdated() { // Notify the MQTT client about the updated configuration _mqttSettingsService->setStatusTopic(_state.stateTopic); // Optionally, you can also log or handle the updated configuration here ESP_LOGI(LIGHT_TAG, "MQTT Configuration updated"); } ================================================ FILE: src/LightMqttSettingsService.h ================================================ #ifndef LightMqttSettingsService_h #define LightMqttSettingsService_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #include #define LIGHT_TAG "💡" #define LIGHT_BROKER_SETTINGS_FILE "/config/brokerSettings.json" #define LIGHT_BROKER_SETTINGS_PATH "/rest/brokerSettings" #ifndef FACTORY_MQTT_STATUS_TOPIC #define FACTORY_MQTT_STATUS_TOPIC "esp32sveltekit/status" #endif // end FACTORY_MQTT_STATUS_TOPIC class LightMqttSettings { public: String mqttPath; String name; String uniqueId; String stateTopic; static void read(LightMqttSettings &settings, JsonObject &root) { root["mqtt_path"] = settings.mqttPath; root["name"] = settings.name; root["unique_id"] = settings.uniqueId; root["status_topic"] = settings.stateTopic; } static StateUpdateResult update(JsonObject &root, LightMqttSettings &settings, const String& originID) { settings.mqttPath = root["mqtt_path"] | SettingValue::format("homeassistant/light/#{unique_id}"); settings.name = root["name"] | SettingValue::format("light-#{unique_id}"); settings.uniqueId = root["unique_id"] | SettingValue::format("light-#{unique_id}"); settings.stateTopic = root["status_topic"] | SettingValue::format(FACTORY_MQTT_STATUS_TOPIC); return StateUpdateResult::CHANGED; } }; class LightMqttSettingsService : public StatefulService { public: LightMqttSettingsService(PsychicHttpServer *server, ESP32SvelteKit *sveltekit); void begin(); void onConfigUpdated(); private: HttpEndpoint _httpEndpoint; FSPersistence _fsPersistence; MqttSettingsService *_mqttSettingsService; }; #endif // end LightMqttSettingsService_h ================================================ FILE: src/LightStateService.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include LightStateService::LightStateService(PsychicHttpServer *server, ESP32SvelteKit *sveltekit, LightMqttSettingsService *lightMqttSettingsService) : _httpEndpoint(LightState::read, LightState::update, this, server, LIGHT_SETTINGS_ENDPOINT_PATH, sveltekit->getSecurityManager(), AuthenticationPredicates::IS_AUTHENTICATED), _eventEndpoint(LightState::read, LightState::update, this, sveltekit->getSocket(), LIGHT_SETTINGS_EVENT), _mqttEndpoint(LightState::homeAssistRead, LightState::homeAssistUpdate, this, sveltekit->getMqttClient()), _webSocketServer(LightState::read, LightState::update, this, server, LIGHT_SETTINGS_SOCKET_PATH, sveltekit->getSecurityManager(), AuthenticationPredicates::IS_AUTHENTICATED), _mqttClient(sveltekit->getMqttClient()), _lightMqttSettingsService(lightMqttSettingsService) { // configure led to be output pinMode(LED_BUILTIN, OUTPUT); // configure MQTT callback _mqttClient->onConnect(std::bind(&LightStateService::registerConfig, this)); // configure update handler for when the light settings change _lightMqttSettingsService->addUpdateHandler([&](const String &originId) { registerConfig(); }, false); // configure settings service update handler to update LED state addUpdateHandler([&](const String &originId) { onConfigUpdated(); }, false); } void LightStateService::begin() { _httpEndpoint.begin(); _eventEndpoint.begin(); _state.ledOn = DEFAULT_LED_STATE; onConfigUpdated(); } void LightStateService::onConfigUpdated() { digitalWrite(LED_BUILTIN, _state.ledOn ? 1 : 0); } void LightStateService::registerConfig() { if (!_mqttClient->connected()) { return; } String configTopic; String subTopic; String pubTopic; JsonDocument doc; _lightMqttSettingsService->read([&](LightMqttSettings &settings) { configTopic = settings.mqttPath + "/config"; subTopic = settings.mqttPath + "/set"; pubTopic = settings.mqttPath + "/state"; doc["~"] = settings.mqttPath; doc["name"] = settings.name; doc["unique_id"] = settings.uniqueId; }); doc["cmd_t"] = "~/set"; doc["stat_t"] = "~/state"; doc["schema"] = "json"; doc["brightness"] = false; String payload; serializeJson(doc, payload); _mqttClient->publish(configTopic.c_str(), 0, false, payload.c_str()); _mqttEndpoint.configureTopics(pubTopic, subTopic); } ================================================ FILE: src/LightStateService.h ================================================ #ifndef LightStateService_h #define LightStateService_h /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #include #include #include #define DEFAULT_LED_STATE false #define OFF_STATE "OFF" #define ON_STATE "ON" #define LIGHT_SETTINGS_ENDPOINT_PATH "/rest/lightState" #define LIGHT_SETTINGS_SOCKET_PATH "/ws/lightState" #define LIGHT_SETTINGS_EVENT "led" class LightState { public: bool ledOn; static void read(LightState &settings, JsonObject &root) { root["led_on"] = settings.ledOn; } static StateUpdateResult update(JsonObject &root, LightState &lightState, const String& originID) { boolean newState = root["led_on"] | DEFAULT_LED_STATE; if (lightState.ledOn != newState) { lightState.ledOn = newState; return StateUpdateResult::CHANGED; } return StateUpdateResult::UNCHANGED; } static void homeAssistRead(LightState &settings, JsonObject &root) { root["state"] = settings.ledOn ? ON_STATE : OFF_STATE; } static StateUpdateResult homeAssistUpdate(JsonObject &root, LightState &lightState, const String& originID) { String state = root["state"]; // parse new led state boolean newState = false; if (state.equals(ON_STATE)) { newState = true; } else if (!state.equals(OFF_STATE)) { return StateUpdateResult::ERROR; } // change the new state, if required if (lightState.ledOn != newState) { lightState.ledOn = newState; return StateUpdateResult::CHANGED; } return StateUpdateResult::UNCHANGED; } }; class LightStateService : public StatefulService { public: LightStateService(PsychicHttpServer *server, ESP32SvelteKit *sveltekit, LightMqttSettingsService *lightMqttSettingsService); void begin(); private: HttpEndpoint _httpEndpoint; EventEndpoint _eventEndpoint; MqttEndpoint _mqttEndpoint; WebSocketServer _webSocketServer; PsychicMqttClient *_mqttClient; LightMqttSettingsService *_lightMqttSettingsService; void registerConfig(); void onConfigUpdated(); }; #endif ================================================ FILE: src/main.cpp ================================================ /** * ESP32 SvelteKit * * A simple, secure and extensible framework for IoT projects for ESP32 platforms * with responsive Sveltekit front-end built with TailwindCSS and DaisyUI. * https://github.com/theelims/ESP32-sveltekit * * Copyright (C) 2018 - 2023 rjwats * Copyright (C) 2023 - 2025 theelims * * All Rights Reserved. This software may be modified and distributed under * the terms of the LGPL v3 license. See the LICENSE file for details. **/ #include #include #include #include #define SERIAL_BAUD_RATE 115200 PsychicHttpServer server; ESP32SvelteKit esp32sveltekit(&server, 70); LightMqttSettingsService lightMqttSettingsService = LightMqttSettingsService(&server, &esp32sveltekit); LightStateService lightStateService = LightStateService(&server, &esp32sveltekit, &lightMqttSettingsService); void setup() { // start serial and filesystem Serial.begin(SERIAL_BAUD_RATE); // start ESP32-SvelteKit esp32sveltekit.begin(); // load the initial light settings lightStateService.begin(); // start the light service lightMqttSettingsService.begin(); } void loop() { // Delete Arduino loop task, as it is not needed in this example vTaskDelete(NULL); } ================================================ FILE: ssl_certs/DigiCert_Global_Root_CA.pem ================================================ -----BEGIN CERTIFICATE----- MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG 9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97 nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt 43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4 gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg 06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4= -----END CERTIFICATE-----