From 01ffe420eb8243ca8a31c57244e1836a6726bd26 Mon Sep 17 00:00:00 2001 From: Shadowtrance Date: Thu, 22 Jan 2026 06:47:59 +1000 Subject: [PATCH 01/10] Webserver addition and TactilityC symbols (#451) --- .../service/webserver/settings.properties | 27 + Data/data/webserver/dashboard.html | 1147 ++++++++++ Data/data/webserver/version.json | 3 + .../Statusbar/assets/webserver_ap_white.png | Bin 0 -> 663 bytes .../assets/webserver_station_white.png | Bin 0 -> 755 bytes Data/webserver/default.html | 63 + Data/webserver/version.json | 3 + Documentation/webserver.md | 515 +++++ Tactility/CMakeLists.txt | 1 + .../Include/Tactility/network/HttpServer.h | 4 +- .../service/webserver/AssetVersion.h | 72 + .../Tactility/settings/WebServerSettings.h | 66 + .../service/webserver/WebServerService.h | 105 + Tactility/Source/Tactility.cpp | 17 +- .../webserversettings/WebServerSettings.cpp | 408 ++++ Tactility/Source/network/HttpServer.cpp | 34 +- Tactility/Source/network/HttpdReq.cpp | 27 +- .../Source/service/webserver/AssetVersion.cpp | 395 ++++ .../service/webserver/WebServerService.cpp | 1862 +++++++++++++++++ .../Source/settings/WebServerSettings.cpp | 260 +++ TactilityC/Source/symbols/freertos.cpp | 3 + TactilityC/Source/tt_init.cpp | 15 +- 22 files changed, 5006 insertions(+), 21 deletions(-) create mode 100644 Data/data/service/webserver/settings.properties create mode 100644 Data/data/webserver/dashboard.html create mode 100644 Data/data/webserver/version.json create mode 100644 Data/system/service/Statusbar/assets/webserver_ap_white.png create mode 100644 Data/system/service/Statusbar/assets/webserver_station_white.png create mode 100644 Data/webserver/default.html create mode 100644 Data/webserver/version.json create mode 100644 Documentation/webserver.md create mode 100644 Tactility/Include/Tactility/service/webserver/AssetVersion.h create mode 100644 Tactility/Include/Tactility/settings/WebServerSettings.h create mode 100644 Tactility/Private/Tactility/service/webserver/WebServerService.h create mode 100644 Tactility/Source/app/webserversettings/WebServerSettings.cpp create mode 100644 Tactility/Source/service/webserver/AssetVersion.cpp create mode 100644 Tactility/Source/service/webserver/WebServerService.cpp create mode 100644 Tactility/Source/settings/WebServerSettings.cpp diff --git a/Data/data/service/webserver/settings.properties b/Data/data/service/webserver/settings.properties new file mode 100644 index 00000000..fceba429 --- /dev/null +++ b/Data/data/service/webserver/settings.properties @@ -0,0 +1,27 @@ +# Web Server Settings +# WiFi and HTTP server configuration + +# WiFi Enable (0=disabled, 1=enabled) +wifiEnabled=0 + +# WiFi Mode (0=Station/Client, 1=Access Point) +wifiMode=0 + +# Access Point Mode Settings (create own WiFi network) +# apSsid will be auto-generated as Tactility-XXXX if empty +# apPassword will be auto-generated if empty or insecure (WPA2 requires 8-63 chars) +# apOpenNetwork: if 1, create open network without password (ignores apPassword) +apSsid= +apPassword= +apOpenNetwork=0 +apChannel=1 + +# Web Server Settings +webServerEnabled=0 +webServerPort=80 + +# HTTP Basic Authentication (optional) +# When auth is enabled with empty/insecure credentials, strong random credentials are auto-generated +webServerAuthEnabled=0 +webServerUsername= +webServerPassword= diff --git a/Data/data/webserver/dashboard.html b/Data/data/webserver/dashboard.html new file mode 100644 index 00000000..54ec3b02 --- /dev/null +++ b/Data/data/webserver/dashboard.html @@ -0,0 +1,1147 @@ + + + + + + Tactility Dashboard + + + +
+
+

Tactility Dashboard

+

Loading...

+
+ +
+ + + +
+ + +
+
+
Loading system information...
+
+
+ + +
+
+ +
+
+ + +
+
+ + +
+
+ + + +
+
+
+ + +
+
+ + + +
NameTypeSizeAction
Select the Files tab to browse
+
+ + +
+
+
+

Drag & drop an .app file here, or click to select

+ + +
+
+

Installed Apps

+
+
Loading apps...
+
+
+
+ +
+ Tactility WebServer - Auto-refreshes every 30 seconds +
+
+ + + + diff --git a/Data/data/webserver/version.json b/Data/data/webserver/version.json new file mode 100644 index 00000000..5dfe44db --- /dev/null +++ b/Data/data/webserver/version.json @@ -0,0 +1,3 @@ +{ + "version": 0 +} diff --git a/Data/system/service/Statusbar/assets/webserver_ap_white.png b/Data/system/service/Statusbar/assets/webserver_ap_white.png new file mode 100644 index 0000000000000000000000000000000000000000..2d39d9652e39673f623b40434aded51390a2a160 GIT binary patch literal 663 zcmV;I0%-k-P)Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D0xU^HK~y+Tm6Xkk zPhk|t&vR$UyNo8XP*cQWcHT;pg_I&$u*59l4OOl*|&3HSz_vfbY`Sm3(e(lpJ%rfK%u-fTNX8(;-+SuIa(FPdy< zyOMMX*wl)D4guGs{H;y==aKXlI1eoE8t(^APc|!od_vL>P$P5$IB9!N(=_{lGm^%- zvAhFzmi}qj?vwOD(wObd<#`WaucY_Dh4Sn#fW^Ie0EZ;q6M8G@jil=}_10)FUsZZ% zMbgD?W*>!a3f+_RyCzX6U(dfmM` zpvS=WQa3Ni`P}60p$|e$+c^KU>yc7FE5JHQ6H^xYh|ra8|D1DvUV3IF=X`w1moe7< zG*~0)YgaQcRQe(!s-={g|0@wiU%7D7L$&zl{UQ+6N xbOHX2?IpI4+S(RT)xh2U{{A~DC70SBzX6d;N;5i?S|Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D0*FaOK~y+Tg_J>v zl~okS|L49Ldm&{OXqP%x+GR*+8xX9|KR`&3PKwZF>*!$fkH7cyDZ+ znG3eJ$#yR@zsbz2zzb@-eH?f{$%~o!-=;A~kU!i02$<=N2f%kp{cu3R=G0d~gp1 z*bUqSF1Oc&8DQ6FG&%@e0M=|DsCAMQbzltetfZlo2c_Pe?MEYGF(S@yY;4T-`~B;+ z=79jSwl7T>`B&iOx_->W4sB0CE=H7PNk2*&*q-Uqw$H`j zq@E-xyfY%6lXO_pX~}aG4J0XIvUXw+xZHll9Pp;36-o29vZ%b#<(BRdbxbrYrJT2Y z!}dx + + + + + Tactility Dashboard + + + +

Tactility Default Dashboard

+ +
+

Version 0 - Default Placeholder

+

This is the default dashboard bundled with firmware.

+

To customize this interface:

+
    +
  1. Create your custom dashboard HTML/CSS/JS files
  2. +
  3. Add them to /sdcard/tactility/webserver/
  4. +
  5. Create version.json with {"version": 1} or higher
  6. +
  7. Reboot or click "Sync Assets" on the Core Interface
  8. +
+

Your custom assets will automatically replace this page!

+
+ + + + diff --git a/Data/webserver/version.json b/Data/webserver/version.json new file mode 100644 index 00000000..5dfe44db --- /dev/null +++ b/Data/webserver/version.json @@ -0,0 +1,3 @@ +{ + "version": 0 +} diff --git a/Documentation/webserver.md b/Documentation/webserver.md new file mode 100644 index 00000000..a4839b3a --- /dev/null +++ b/Documentation/webserver.md @@ -0,0 +1,515 @@ +# WebServer Service + +The WebServer service provides a built-in HTTP server for remote device management, file operations, and system monitoring through a web browser. + +## Features + +- **Dashboard**: Real-time system information, memory stats, and storage overview +- **File Browser**: Navigate, upload, download, rename, and delete files on internal storage and SD card +- **App Management**: List installed apps, run apps remotely, install/uninstall external apps +- **WiFi Status**: View current WiFi connection details +- **Screenshot Capture**: Capture the current display as a PNG +- **System Controls**: Sync assets, reboot device + +## Enabling the WebServer + +The WebServer is disabled by default to conserve memory. Enable it through: + +1. **Settings App**: Navigate to Settings > WebServer Settings +2. **Programmatically**: Call `tt::service::webserver::setWebServerEnabled(true)` + +When enabled, a statusbar icon appears indicating the server mode (AP or Station). + +## Accessing the Dashboard + +Once enabled, access the dashboard by navigating to the device's IP address in a web browser: + +```text +http:/// +``` + +**Access Point Mode:** When using AP mode, connect to the device's WiFi network (SSID shown in settings, default `Tactility-XXXX`) and navigate to `http://192.168.4.1/` + +The root URL redirects to `/dashboard.html` which provides a tabbed interface for all features. + +## API Endpoints + +All API endpoints return JSON responses unless otherwise noted. + +### System Information + +#### GET /api/sysinfo + +Returns comprehensive system information. + +**Response:** +```json +{ + "firmware": { + "version": "1.0.0", + "idf_version": "5.3.0" + }, + "chip": { + "model": "ESP32-S3", + "cores": 2, + "revision": 0, + "features": ["Embedded Flash", "WiFi 2.4GHz", "BLE"], + "flash_size": 16777216 + }, + "heap": { + "free": 123456, + "total": 327680, + "min_free": 100000, + "largest_block": 65536 + }, + "psram": { + "free": 4000000, + "total": 8388608, + "min_free": 3500000, + "largest_block": 2000000 + }, + "storage": { + "data": { + "free": 1000000, + "total": 3145728, + "mounted": true + }, + "sdcard": { + "free": 15000000000, + "total": 32000000000, + "mounted": true + } + }, + "uptime": 3600, + "task_count": 25 +} +``` + +### WiFi Status + +#### GET /api/wifi + +Returns current WiFi connection status. + +**Response:** +```json +{ + "state": "connected", + "ip": "192.168.1.100", + "ssid": "MyNetwork", + "rssi": -45, + "secure": true +} +``` + +**State values:** +- `off` - WiFi radio is off +- `turning_on` - WiFi is starting +- `turning_off` - WiFi is stopping +- `on` - WiFi is on but not connected +- `connecting` - Connection in progress +- `connected` - Connected to access point + +### Screenshot + +#### GET /api/screenshot + +Captures the current display and returns a PNG. The screenshot is also saved to storage with an incrementing filename. + +**Response:** PNG data (`image/png`) + +**Save Location:** +- SD card root (if mounted): `/sdcard/webscreenshot1.png`, `/sdcard/webscreenshot2.png`, etc. +- Internal storage (fallback): `/data/webscreenshot1.png`, `/data/webscreenshot2.png`, etc. + +**Requirements:** `TT_FEATURE_SCREENSHOT_ENABLED` must be defined in the build. + +**Note:** Returns 501 Not Implemented if screenshot feature is disabled. + +### App Management + +#### GET /api/apps + +Lists all installed applications. + +**Response:** +```json +{ + "apps": [ + { + "id": "com.example.myapp", + "name": "My App", + "version": "1.0.0", + "category": "user", + "isExternal": true, + "hidden": false, + "icon": "/data/app/com.example.myapp/icon.png" + } + ] +} +``` + +**Category values:** `user`, `system`, `settings` + +#### POST /api/apps/run?id=xxx + +Runs an application by its ID. If the app is already running, it will be stopped first. + +**Parameters:** +- `id` (required): Application ID + +**Response:** `ok` on success + +#### POST /api/apps/uninstall?id=xxx + +Uninstalls an external application. System apps cannot be uninstalled. + +**Parameters:** +- `id` (required): Application ID + +**Response:** `ok` on success + +**Errors:** +- 403 Forbidden: Cannot uninstall system apps +- 500 Internal Server Error: Uninstall failed + +#### PUT /api/apps/install + +Installs an application from an uploaded `.app` file (tar archive). + +**Content-Type:** `multipart/form-data` + +**Form field:** `file` - The `.app` file to install + +**Response:** `ok` on success + +### File System Operations + +#### GET /fs/list?path=/path + +Lists directory contents. + +**Parameters:** +- `path` (optional): Directory path. Defaults to `/` which shows mount points. + +**Response:** +```json +{ + "path": "/data", + "entries": [ + {"name": "app", "type": "dir", "size": 0}, + {"name": "settings.json", "type": "file", "size": 1234} + ] +} +``` + +**Special paths:** +- `/` - Shows available mount points (data, sdcard if mounted) +- `/data` - Internal flash storage +- `/sdcard` - SD card (if mounted) + +#### GET /fs/download?path=/path/to/file + +Downloads a file. + +**Parameters:** +- `path` (required): Full path to the file + +**Response:** File contents with appropriate Content-Type header and Content-Disposition for download. + +#### POST /fs/upload?path=/path/to/file + +Uploads a file. The request body contains the raw file data. + +**Parameters:** +- `path` (required): Full destination path including filename + +**Content-Type:** Any (raw file data in body) + +**Response:** `Uploaded X bytes` + +**Limits:** Maximum file size is 10MB. + +#### POST /fs/mkdir?path=/path/to/newdir + +Creates a new directory. + +**Parameters:** +- `path` (required): Full path of directory to create + +**Response:** `ok` on success + +#### POST /fs/delete?path=/path/to/item + +Deletes a file or directory (recursive for directories). + +**Parameters:** +- `path` (required): Full path to delete + +**Response:** `ok` on success + +**Restrictions:** Cannot delete mount points (`/data`, `/sdcard`). + +#### POST /fs/rename?path=/path/to/old&newName=newname + +Renames a file or directory. + +**Parameters:** +- `path` (required): Full path to the item to rename +- `newName` (required): New name (filename only, not a path) + +**Response:** `ok` on success + +**Restrictions:** +- `newName` cannot contain path separators or `..` +- Cannot overwrite existing items + +#### GET /fs/tree + +Returns a tree structure of all mount points and their immediate contents. + +**Response:** +```json +{ + "mounts": [ + { + "name": "data", + "path": "/data", + "entries": [ + {"name": "app", "type": "dir"}, + {"name": "tmp", "type": "dir"} + ] + } + ] +} +``` + +### Admin Operations + +#### POST /admin/sync + +Synchronizes web assets from the Data partition. + +**Response:** `Assets synchronized successfully` + +#### POST /admin/reboot + +Reboots the device after a 1-second delay. + +**Response:** `Rebooting...` + +## Static Assets + +The WebServer serves static files from: + +1. **Primary**: `/data/webserver/` (internal flash) +2. **Fallback**: `/sdcard/tactility/webserver/` (SD card) + +The dashboard HTML file is served from these locations. If `dashboard.html` doesn't exist, `default.html` is served as a fallback. + +## Asset Synchronization + +The WebServer includes an asset synchronization system that keeps web assets in sync between the Data partition and SD card. This enables recovery after firmware updates and backup of user customizations. + +### Storage Locations + +| Location | Path | Purpose | +|----------|------|---------| +| Data Partition | `/data/webserver/` | Primary storage, served by WebServer | +| SD Card | `/sdcard/tactility/webserver/` | Backup storage for recovery | + +### Version Tracking + +Each storage location maintains a `version.json` file: + +```json +{ + "version": 1 +} +``` + +The version is an integer that increments when assets are updated. This allows the sync system to determine which location has newer assets. + +### Sync Scenarios + +The `syncAssets()` function handles several scenarios: + +#### First Boot (No SD Card Backup) +- **Condition**: Data partition has assets, SD card backup doesn't exist +- **Action**: Skip backup during boot to avoid watchdog timeout +- **Note**: SD backup is deferred to first settings save + +#### No SD Card Available +- **Condition**: SD card not mounted or unavailable +- **Action**: Create default Data structure with version 0 if needed +- **Note**: System operates normally without SD backup + +#### Post-Flash Recovery +- **Condition**: Data partition empty, SD card has backup +- **Action**: Copy entire SD backup to Data partition +- **Use Case**: Restoring assets after flashing new firmware that erased Data + +#### Firmware Update (SD Newer) +- **Condition**: SD version > Data version +- **Action**: Copy SD assets to Data partition +- **Use Case**: SD card contains newer assets from a firmware update package + +#### User Customization (Data Newer) +- **Condition**: Data version > SD version +- **Action**: Defer backup to avoid boot watchdog timeout +- **Note**: Backup occurs on next settings save or manual sync + +#### Versions Match +- **Condition**: Data version == SD version +- **Action**: No synchronization needed + +### Boot Watchdog Considerations + +Some sync operations are intentionally deferred during boot to avoid triggering the ESP32 watchdog timer: + +- **Deferred**: Copying from Data to SD (user customization backup) +- **Deferred**: Creating SD version.json +- **Immediate**: Copying from SD to Data (recovery and firmware update) + +This ensures the device boots reliably even with slow or corrupted SD cards. + +### Manual Synchronization + +#### Settings App +Navigate to **Settings > Web Server** and tap **"Sync Assets Now"** to manually trigger synchronization. + +#### API Endpoint +Send a POST request to `/admin/sync`: + +```bash +curl -X POST http:///admin/sync +``` + +**Response:** `Assets synchronized successfully` + +### Programmatic Access + +```cpp +#include + +// Check asset status +bool hasData = tt::service::webserver::hasDataAssets(); +bool hasSd = tt::service::webserver::hasSdAssets(); + +// Load versions +tt::service::webserver::AssetVersion dataVer, sdVer; +tt::service::webserver::loadDataVersion(dataVer); +tt::service::webserver::loadSdVersion(sdVer); + +// Trigger sync +bool success = tt::service::webserver::syncAssets(); +``` + +### Directory Structure + +```text +/data/webserver/ +├── version.json # Version tracking +├── dashboard.html # Main dashboard UI +└── ... # Other web assets + +/sdcard/tactility/webserver/ +├── version.json # Version tracking (backup) +├── dashboard.html # Dashboard backup +└── ... # Other web assets (backup) +``` + +### Updating Assets + +To update web assets with a new version: + +1. Place new assets in `/sdcard/tactility/webserver/` +2. Update `/sdcard/tactility/webserver/version.json` with a higher version number +3. Reboot the device or trigger manual sync +4. The sync system will detect the newer SD version and copy to Data + +## Security Considerations + +> **⚠️ Security Warning**: The WebServer is unauthenticated by default, allowing anyone on the network to: +> - Upload, download, and delete files +> - Install and uninstall applications +> - Reboot the device +> - Capture screenshots +> +> **Strongly recommended**: +> - Enable HTTP Basic Authentication in Settings > Web Server before exposing the device to untrusted networks +> - Keep "AP Open Network" disabled (use WPA2 password protection) to prevent unauthorized network access + +- **⚠️ Open Network Option**: The "AP Open Network" setting allows creating an unprotected access point without a password. **This is convenient for quick access but exposes the device to anyone within WiFi range**, potentially allowing unauthorized access to all WebServer functionality if HTTP authentication is also disabled. +- **Automatic credential generation**: Credentials are automatically generated when empty: + - **AP Password**: Generated when empty (unless "AP Open Network" is enabled) + - **HTTP Auth**: Generated when auth is enabled but username or password are empty + - Generated credentials are 12 alphanumeric characters (~71 bits of entropy) and persisted immediately + - User-set credentials are preserved (the system only replaces empty credentials, not weak user-chosen passwords) + - Check Settings > Web Server to view the generated credentials +- File operations are restricted to `/data` and `/sdcard` paths +- Path traversal attacks are blocked (e.g., `../` is rejected) +- Mount points cannot be deleted +- System apps cannot be uninstalled via the API + +## Configuration + +Settings are stored in the WebServer settings file and can be configured via **Settings > Web Server**: + +| Setting | Description | Default | +|---------|-------------|---------| +| WiFi Mode | Station (connect to existing network) or Access Point (create own network) | Station | +| AP Open Network | Create an open AP without password protection | Disabled | +| AP Password | Password for Access Point mode (WPA2, 8-63 chars). Disabled when Open Network is enabled. | Auto-generated | +| Web Server Enabled | Whether the HTTP server is running | Disabled | +| Require Authentication | Enable HTTP Basic Authentication | Disabled | +| Username | Authentication username (when auth enabled) | Auto-generated | +| Password | Authentication password (when auth enabled) | Auto-generated | + +**Note:** The system automatically generates secure credentials when they are empty. Generated credentials are 12-character alphanumeric strings with ~71 bits of entropy. See **Security Considerations** for details. + +**Note:** WiFi Station credentials are managed separately via the WiFi settings menu. + +## Statusbar Icons + +When the WebServer is running, a statusbar icon indicates the WiFi mode: +- `webserver_ap_white.png` - Access Point mode +- `webserver_station_white.png` - Station mode + +## Events + +The WebServer publishes events: +- `WebServerStarted` - Fired when the HTTP server starts +- `WebServerStopped` - Fired when the HTTP server stops +- `WebServerSettingsChanged` - Fired when settings are modified + +## Troubleshooting + +### "No slots left for registering handler" + +The ESP-IDF HTTP server has a limit on URI handlers. The WebServer configures this dynamically based on the number of handlers needed, but if you see this error, check `CONFIG_HTTPD_MAX_URI_HANDLERS` in sdkconfig. + +### 404 for dashboard.html + +Ensure the `dashboard.html` file exists in `/data/webserver/`. Run the asset sync operation or copy files manually. + +### Screenshot fails + +- Verify `TT_FEATURE_SCREENSHOT_ENABLED` is defined +- Check available heap memory (screenshot requires ~width*height*3 bytes) +- Ensure the save location (SD card or `/data`) is writable +- Screenshots are saved as `webscreenshot1.png`, `webscreenshot2.png`, etc. up to 9999 + +### File upload fails + +- Check file size is under 10MB limit +- Verify the destination path is writable +- Ensure the parent directory exists + +### Asset sync fails + +- Check SD card is properly mounted and writable +- Verify sufficient space on destination (Data or SD card) +- Check logs for specific file copy errors +- Maximum directory depth is 16 levels +- If sync hangs during boot, the SD card may be slow or corrupted diff --git a/Tactility/CMakeLists.txt b/Tactility/CMakeLists.txt index b4895b72..0f78a544 100644 --- a/Tactility/CMakeLists.txt +++ b/Tactility/CMakeLists.txt @@ -27,6 +27,7 @@ if (DEFINED ENV{ESP_IDF_VERSION}) vfs fatfs lwip + spi_flash ) if ("${IDF_TARGET}" STREQUAL "esp32s3") list(APPEND REQUIRES_LIST esp_tinyusb) diff --git a/Tactility/Include/Tactility/network/HttpServer.h b/Tactility/Include/Tactility/network/HttpServer.h index c15fea93..27dd8ee4 100644 --- a/Tactility/Include/Tactility/network/HttpServer.h +++ b/Tactility/Include/Tactility/network/HttpServer.h @@ -52,10 +52,10 @@ public: address(address), stackSize(stackSize), matchUri(matchUri), - handlers(handlers) + handlers(std::move(handlers)) {} - void start(); + bool start(); void stop(); diff --git a/Tactility/Include/Tactility/service/webserver/AssetVersion.h b/Tactility/Include/Tactility/service/webserver/AssetVersion.h new file mode 100644 index 00000000..e96d9881 --- /dev/null +++ b/Tactility/Include/Tactility/service/webserver/AssetVersion.h @@ -0,0 +1,72 @@ +#pragma once + +#include + +namespace tt::service::webserver { + +/** + * @brief Asset version tracking for web server content synchronization + * + * Manages version.json files in both Data partition and SD card to ensure + * proper synchronization and recovery of web assets. + */ +struct AssetVersion { + uint32_t version; // Integer version number + + AssetVersion() : version(0) {} + explicit AssetVersion(uint32_t v) : version(v) {} +}; + +/** + * @brief Load asset version from Data partition + * @param[out] version The version structure to populate + * @return true if version was loaded successfully + */ +bool loadDataVersion(AssetVersion& version); + +/** + * @brief Load asset version from SD card + * @param[out] version The version structure to populate + * @return true if version was loaded successfully + */ +bool loadSdVersion(AssetVersion& version); + +/** + * @brief Save asset version to Data partition + * @param[in] version The version to save + * @return true if version was saved successfully + */ +bool saveDataVersion(const AssetVersion& version); + +/** + * @brief Save asset version to SD card + * @param[in] version The version to save + * @return true if version was saved successfully + */ +bool saveSdVersion(const AssetVersion& version); + +/** + * @brief Check if Data partition has any web assets + * @return true if Data partition contains web assets + */ +bool hasDataAssets(); + +/** + * @brief Check if SD card has any web assets + * @return true if SD card contains web assets backup + */ +bool hasSdAssets(); + +/** + * @brief Synchronize assets between Data partition and SD card based on version + * + * Logic: + * - If Data is empty: Copy from SD card (recovery mode) + * - If SD version > Data version: Copy SD -> Data (firmware update) + * - If Data version > SD version: Copy Data -> SD (backup customizations) + * + * @return true if sync completed successfully + */ +bool syncAssets(); + +} // namespace tt::service::webserver diff --git a/Tactility/Include/Tactility/settings/WebServerSettings.h b/Tactility/Include/Tactility/settings/WebServerSettings.h new file mode 100644 index 00000000..96abdcfc --- /dev/null +++ b/Tactility/Include/Tactility/settings/WebServerSettings.h @@ -0,0 +1,66 @@ +#pragma once + +#include +#include + +namespace tt::settings::webserver { + +enum class WiFiMode : uint8_t { + Station = 0, // Connect to existing WiFi network + AccessPoint = 1 // Create own WiFi network +}; + +struct WebServerSettings { + // WiFi Configuration + bool wifiEnabled = false; // Enable/disable WiFi entirely + WiFiMode wifiMode = WiFiMode::Station; // Station or Access Point + + // Access Point Mode Settings + std::string apSsid{}; // Default: "Tactility-XXXX" (last 4 of MAC) + std::string apPassword{}; // Password for WPA2 (8-63 chars) + bool apOpenNetwork = false; // If true, create open network (no password) + uint8_t apChannel = 1; // 1-13 + + // Web Server Settings + bool webServerEnabled = false; + uint16_t webServerPort = 80; // Default: 80 + + // Optional HTTP Basic Auth + bool webServerAuthEnabled = false; + std::string webServerUsername{}; + std::string webServerPassword{}; +}; + +/** + * @brief Load web server settings from persistent storage + * @param[out] settings The settings structure to populate + * @return true if settings were loaded successfully, false otherwise + */ +bool load(WebServerSettings& settings); + +/** + * @brief Get default web server settings + * @return Default settings structure + */ +WebServerSettings getDefault(); + +/** + * @brief Load settings or return defaults if loading fails + * @return Settings structure (either loaded or default) + */ +WebServerSettings loadOrGetDefault(); + +/** + * @brief Save web server settings to persistent storage + * @param[in] settings The settings to save + * @return true if settings were saved successfully, false otherwise + */ +bool save(const WebServerSettings& settings); + +/** + * @brief Generate default AP SSID based on device MAC address + * @return SSID string in format "Tactility-XXXX" + */ +std::string generateDefaultApSsid(); + +} diff --git a/Tactility/Private/Tactility/service/webserver/WebServerService.h b/Tactility/Private/Tactility/service/webserver/WebServerService.h new file mode 100644 index 00000000..a27dc525 --- /dev/null +++ b/Tactility/Private/Tactility/service/webserver/WebServerService.h @@ -0,0 +1,105 @@ +#pragma once +#ifdef ESP_PLATFORM + +#include +#include +#include +#include + +#include +#include +#include + +namespace tt::service::webserver { + +enum class WebServerEvent { + /** WebServer settings have been modified (WiFi/HTTP credentials, enable/disable states) */ + WebServerSettingsChanged, + /** HTTP server has started and is accepting connections */ + WebServerStarted, + /** HTTP server has stopped and is no longer accepting connections */ + WebServerStopped +}; + +/** + * @brief Web server service with resilient asset architecture + * + * Provides: + * - Core HTML endpoints (hardcoded in firmware) + * - Dynamic asset serving from Data partition + * - SD card fallback + * - Asset synchronization + */ +class WebServerService final : public Service { +private: + mutable RecursiveMutex mutex; + std::unique_ptr httpServer; + PubSub::SubscriptionHandle settingsEventSubscription = nullptr; + std::shared_ptr> pubsub = std::make_shared>(); + int8_t statusbarIconId = -1; // Statusbar icon for WebServer state + + // AP mode WiFi management + esp_netif_t* apNetif = nullptr; + bool apWifiInitialized = false; + + bool startApMode(); + void stopApMode(); + + // Core HTML endpoints (hardcoded in firmware) + static esp_err_t handleRoot(httpd_req_t* request); + static esp_err_t handleSync(httpd_req_t* request); + static esp_err_t handleReboot(httpd_req_t* request); + + // File browser endpoints + static esp_err_t handleFileBrowser(httpd_req_t* request); + static esp_err_t handleFsList(httpd_req_t* request); + static esp_err_t handleFsTree(httpd_req_t* request); + static esp_err_t handleFsDownload(httpd_req_t* request); + static esp_err_t handleFsMkdir(httpd_req_t* request); + static esp_err_t handleFsDelete(httpd_req_t* request); + static esp_err_t handleFsRename(httpd_req_t* request); + static esp_err_t handleFsUpload(httpd_req_t* request); + // Consolidated dispatch handlers to reduce URI handler table usage + static esp_err_t handleFsGenericGet(httpd_req_t* request); + static esp_err_t handleFsGenericPost(httpd_req_t* request); + // Admin dispatcher to consolidate small POST endpoints (sync/reboot) + static esp_err_t handleAdminPost(httpd_req_t* request); + + // API endpoints + static esp_err_t handleApiGet(httpd_req_t* request); + static esp_err_t handleApiPost(httpd_req_t* request); + static esp_err_t handleApiPut(httpd_req_t* request); + static esp_err_t handleApiSysinfo(httpd_req_t* request); + static esp_err_t handleApiApps(httpd_req_t* request); + static esp_err_t handleApiAppsRun(httpd_req_t* request); + static esp_err_t handleApiAppsUninstall(httpd_req_t* request); + static esp_err_t handleApiAppsInstall(httpd_req_t* request); + static esp_err_t handleApiWifi(httpd_req_t* request); + static esp_err_t handleApiScreenshot(httpd_req_t* request); + + // Dynamic asset serving + static esp_err_t handleAssets(httpd_req_t* request); + + bool startServer(); + void stopServer(); + +public: + + bool onStart(ServiceContext& service) override; + void onStop(ServiceContext& service) override; + + void setEnabled(bool enabled); + bool isEnabled() const; + + std::shared_ptr> getPubsub() const { return pubsub; } +}; + +// Global accessor for controlling the WebServer service +void setWebServerEnabled(bool enabled); + +// Get the pubsub for subscribing to WebServer events +std::shared_ptr> getPubsub(); + +} // namespace + +#endif diff --git a/Tactility/Source/Tactility.cpp b/Tactility/Source/Tactility.cpp index 4f4cd4ed..e6b0ed4a 100644 --- a/Tactility/Source/Tactility.cpp +++ b/Tactility/Source/Tactility.cpp @@ -60,6 +60,9 @@ namespace service { #if TT_FEATURE_SCREENSHOT_ENABLED namespace screenshot { extern const ServiceManifest manifest; } #endif +#ifdef ESP_PLATFORM + namespace webserver { extern const ServiceManifest manifest; } +#endif } @@ -104,17 +107,17 @@ namespace app { namespace wifiapsettings { extern const AppManifest manifest; } namespace wificonnect { extern const AppManifest manifest; } namespace wifimanage { extern const AppManifest manifest; } +#ifdef ESP_PLATFORM + namespace webserversettings { extern const AppManifest manifest; } +#endif #if TT_FEATURE_SCREENSHOT_ENABLED - namespace screenshot { extern const AppManifest manifest; } + namespace screenshot { extern const AppManifest manifest; } #endif #ifdef ESP_PLATFORM namespace crashdiagnostics { extern const AppManifest manifest; } #endif } -#ifndef ESP_PLATFORM -#endif - // endregion // List of all apps excluding Boot app (as Boot app calls this function indirectly) @@ -146,6 +149,9 @@ static void registerInternalApps() { addAppManifest(app::wifiapsettings::manifest); addAppManifest(app::wificonnect::manifest); addAppManifest(app::wifimanage::manifest); +#ifdef ESP_PLATFORM + addAppManifest(app::webserversettings::manifest); +#endif #if defined(CONFIG_TINYUSB_MSC_ENABLED) && CONFIG_TINYUSB_MSC_ENABLED addAppManifest(app::usbsettings::manifest); @@ -263,6 +269,9 @@ static void registerAndStartPrimaryServices() { #if defined(CONFIG_TT_WIFI_ENABLED) && !defined(CONFIG_ESP_WIFI_REMOTE_ENABLED) addService(service::espnow::manifest); #endif +#ifdef ESP_PLATFORM + addService(service::webserver::manifest); +#endif } void createTempDirectory(const std::string& rootPath) { diff --git a/Tactility/Source/app/webserversettings/WebServerSettings.cpp b/Tactility/Source/app/webserversettings/WebServerSettings.cpp new file mode 100644 index 00000000..68f8ca07 --- /dev/null +++ b/Tactility/Source/app/webserversettings/WebServerSettings.cpp @@ -0,0 +1,408 @@ +#ifdef ESP_PLATFORM + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +namespace tt::app::webserversettings { + +static const auto LOGGER = tt::Logger("WebServerSettingsApp"); + +class WebServerSettingsApp final : public App { + + settings::webserver::WebServerSettings wsSettings; + settings::webserver::WebServerSettings originalSettings; + bool updated = false; + bool wifiSettingsChanged = false; + bool webServerEnabledChanged = false; + lv_obj_t* dropdownWifiMode = nullptr; + lv_obj_t* textAreaApPassword = nullptr; + lv_obj_t* switchApOpenNetwork = nullptr; + lv_obj_t* switchWebServerEnabled = nullptr; + lv_obj_t* switchWebServerAuthEnabled = nullptr; + lv_obj_t* textAreaWebServerUsername = nullptr; + lv_obj_t* textAreaWebServerPassword = nullptr; + lv_obj_t* labelUrl = nullptr; + lv_obj_t* labelUrlValue = nullptr; + + static void onWifiModeChanged(lv_event_t* e) { + auto* app = static_cast(lv_event_get_user_data(e)); + auto* dropdown = static_cast(lv_event_get_target(e)); + auto index = lv_dropdown_get_selected(dropdown); + getMainDispatcher().dispatch([app, index] { + app->wsSettings.wifiMode = static_cast(index); + app->updated = true; + app->wifiSettingsChanged = true; + app->updateUrlDisplay(); + }); + } + + static void onWebServerEnabledSwitch(lv_event_t* e) { + auto* app = static_cast(lv_event_get_user_data(e)); + bool enabled = lv_obj_has_state(app->switchWebServerEnabled, LV_STATE_CHECKED); + getMainDispatcher().dispatch([app, enabled] { + app->wsSettings.webServerEnabled = enabled; + app->updated = true; + app->webServerEnabledChanged = true; + app->updateUrlDisplay(); + }); + } + + static void onWebServerAuthEnabledSwitch(lv_event_t* e) { + auto* app = static_cast(lv_event_get_user_data(e)); + bool enabled = lv_obj_has_state(app->switchWebServerAuthEnabled, LV_STATE_CHECKED); + + if (app->textAreaWebServerUsername && app->textAreaWebServerPassword) { + if (enabled) { + lv_obj_remove_state(app->textAreaWebServerUsername, LV_STATE_DISABLED); + lv_obj_add_flag(app->textAreaWebServerUsername, LV_OBJ_FLAG_CLICKABLE); + + lv_obj_remove_state(app->textAreaWebServerPassword, LV_STATE_DISABLED); + lv_obj_add_flag(app->textAreaWebServerPassword, LV_OBJ_FLAG_CLICKABLE); + } else { + lv_obj_add_state(app->textAreaWebServerUsername, LV_STATE_DISABLED); + lv_obj_remove_flag(app->textAreaWebServerUsername, LV_OBJ_FLAG_CLICKABLE); + + lv_obj_add_state(app->textAreaWebServerPassword, LV_STATE_DISABLED); + lv_obj_remove_flag(app->textAreaWebServerPassword, LV_OBJ_FLAG_CLICKABLE); + } + } + + getMainDispatcher().dispatch([app, enabled] { + app->wsSettings.webServerAuthEnabled = enabled; + app->updated = true; + }); + } + + static void onCredentialChanged(lv_event_t* e) { + auto* app = static_cast(lv_event_get_user_data(e)); + getMainDispatcher().dispatch([app] { + app->updated = true; + }); + } + + static void onApPasswordChanged(lv_event_t* e) { + auto* app = static_cast(lv_event_get_user_data(e)); + getMainDispatcher().dispatch([app] { + app->updated = true; + app->wifiSettingsChanged = true; + }); + } + + static void onApOpenNetworkSwitch(lv_event_t* e) { + auto* app = static_cast(lv_event_get_user_data(e)); + bool openNetwork = lv_obj_has_state(app->switchApOpenNetwork, LV_STATE_CHECKED); + + if (app->textAreaApPassword) { + if (openNetwork) { + lv_obj_add_state(app->textAreaApPassword, LV_STATE_DISABLED); + lv_obj_remove_flag(app->textAreaApPassword, LV_OBJ_FLAG_CLICKABLE); + } else { + lv_obj_remove_state(app->textAreaApPassword, LV_STATE_DISABLED); + lv_obj_add_flag(app->textAreaApPassword, LV_OBJ_FLAG_CLICKABLE); + } + } + + getMainDispatcher().dispatch([app, openNetwork] { + app->wsSettings.apOpenNetwork = openNetwork; + app->updated = true; + app->wifiSettingsChanged = true; + }); + } + + static void onSyncAssets(lv_event_t* e) { + auto* app = static_cast(lv_event_get_user_data(e)); + auto* btn = static_cast(lv_event_get_target_obj(e)); + lv_obj_add_state(btn, LV_STATE_DISABLED); + LOGGER.info("Manual asset sync triggered"); + + getMainDispatcher().dispatch([app, btn]{ + bool success = service::webserver::syncAssets(); + if (success) { + LOGGER.info("Asset sync completed successfully"); + } else { + LOGGER.error("Asset sync failed"); + } + // Only re-enable if button still exists (user hasn't navigated away) + if (lv_obj_is_valid(btn)) { + lv_obj_remove_state(btn, LV_STATE_DISABLED); + } + }); + } + + void updateUrlDisplay() { + if (!labelUrlValue) return; + + if (!wsSettings.webServerEnabled) { + lv_label_set_text(labelUrlValue, "Disabled"); + return; + } + + std::string url = "http://"; + + if (wsSettings.wifiMode == settings::webserver::WiFiMode::AccessPoint) { + // AP mode - always 192.168.4.1 + url += "192.168.4.1"; + } else { + // Station mode - try to get actual IP + esp_netif_t* netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF"); + if (netif != nullptr) { + esp_netif_ip_info_t ip_info; + if (esp_netif_get_ip_info(netif, &ip_info) == ESP_OK && ip_info.ip.addr != 0) { + char ip_str[16]; + snprintf(ip_str, sizeof(ip_str), IPSTR, IP2STR(&ip_info.ip)); + url += ip_str; + } else { + url = "Connecting..."; + } + } else { + url = "Not connected"; + } + } + + if (url.starts_with("http://")) { + if (wsSettings.webServerPort != 80) { + url += ":" + std::to_string(wsSettings.webServerPort); + } + } + + lv_label_set_text(labelUrlValue, url.c_str()); + } + +public: + void onCreate(TT_UNUSED AppContext& app) override { + wsSettings = settings::webserver::loadOrGetDefault(); + originalSettings = wsSettings; + } + + void onShow(AppContext& app, lv_obj_t* parent) override { + lv_obj_set_flex_flow(parent, LV_FLEX_FLOW_COLUMN); + lv_obj_set_style_pad_row(parent, 0, LV_STATE_DEFAULT); + + lv_obj_t* toolbar = lvgl::toolbar_create(parent, app); + + // Web Server Enable toggle + switchWebServerEnabled = lvgl::toolbar_add_switch_action(toolbar); + if (wsSettings.webServerEnabled) { + lv_obj_add_state(switchWebServerEnabled, LV_STATE_CHECKED); + } + lv_obj_add_event_cb(switchWebServerEnabled, onWebServerEnabledSwitch, LV_EVENT_VALUE_CHANGED, this); + + auto* main_wrapper = lv_obj_create(parent); + lv_obj_set_flex_flow(main_wrapper, LV_FLEX_FLOW_COLUMN); + lv_obj_set_width(main_wrapper, LV_PCT(100)); + lv_obj_set_flex_grow(main_wrapper, 1); + + // WiFi Mode dropdown + auto* wifi_mode_wrapper = lv_obj_create(main_wrapper); + lv_obj_set_size(wifi_mode_wrapper, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_style_pad_all(wifi_mode_wrapper, 0, LV_STATE_DEFAULT); + lv_obj_set_style_border_width(wifi_mode_wrapper, 0, LV_STATE_DEFAULT); + auto* wifi_mode_label = lv_label_create(wifi_mode_wrapper); + lv_label_set_text(wifi_mode_label, "WiFi Mode"); + lv_obj_align(wifi_mode_label, LV_ALIGN_LEFT_MID, 0, 0); + dropdownWifiMode = lv_dropdown_create(wifi_mode_wrapper); + lv_obj_align(dropdownWifiMode, LV_ALIGN_RIGHT_MID, 0, 0); + lv_dropdown_set_options(dropdownWifiMode, "Station\nAccess Point"); + lv_dropdown_set_selected(dropdownWifiMode, static_cast(wsSettings.wifiMode)); + lv_obj_add_event_cb(dropdownWifiMode, onWifiModeChanged, LV_EVENT_VALUE_CHANGED, this); + + // AP Open Network toggle + auto* ap_open_wrapper = lv_obj_create(main_wrapper); + lv_obj_set_size(ap_open_wrapper, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_style_pad_all(ap_open_wrapper, 0, LV_STATE_DEFAULT); + lv_obj_set_style_border_width(ap_open_wrapper, 0, LV_STATE_DEFAULT); + auto* ap_open_label = lv_label_create(ap_open_wrapper); + lv_label_set_text(ap_open_label, "AP Open Network"); + lv_obj_align(ap_open_label, LV_ALIGN_LEFT_MID, 0, 0); + switchApOpenNetwork = lv_switch_create(ap_open_wrapper); + if (wsSettings.apOpenNetwork) lv_obj_add_state(switchApOpenNetwork, LV_STATE_CHECKED); + lv_obj_align(switchApOpenNetwork, LV_ALIGN_RIGHT_MID, 0, 0); + lv_obj_add_event_cb(switchApOpenNetwork, onApOpenNetworkSwitch, LV_EVENT_VALUE_CHANGED, this); + + // AP Password + auto* ap_pass_wrapper = lv_obj_create(main_wrapper); + lv_obj_set_size(ap_pass_wrapper, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_style_pad_all(ap_pass_wrapper, 0, LV_STATE_DEFAULT); + lv_obj_set_style_border_width(ap_pass_wrapper, 0, LV_STATE_DEFAULT); + auto* ap_pass_label = lv_label_create(ap_pass_wrapper); + lv_label_set_text(ap_pass_label, "AP Password"); + lv_obj_align(ap_pass_label, LV_ALIGN_LEFT_MID, 0, 0); + textAreaApPassword = lv_textarea_create(ap_pass_wrapper); + lv_obj_set_width(textAreaApPassword, 120); + lv_obj_align(textAreaApPassword, LV_ALIGN_RIGHT_MID, 0, 0); + lv_textarea_set_one_line(textAreaApPassword, true); + lv_textarea_set_max_length(textAreaApPassword, 64); + lv_textarea_set_password_mode(textAreaApPassword, true); + lv_textarea_set_text(textAreaApPassword, wsSettings.apPassword.c_str()); + lv_obj_add_event_cb(textAreaApPassword, onApPasswordChanged, LV_EVENT_VALUE_CHANGED, this); + // Disable password field if open network is enabled + if (wsSettings.apOpenNetwork) { + lv_obj_add_state(textAreaApPassword, LV_STATE_DISABLED); + lv_obj_remove_flag(textAreaApPassword, LV_OBJ_FLAG_CLICKABLE); + } + + // Web Server Authentication Enable toggle + auto* ws_auth_wrapper = lv_obj_create(main_wrapper); + lv_obj_set_size(ws_auth_wrapper, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_style_pad_all(ws_auth_wrapper, 0, LV_STATE_DEFAULT); + lv_obj_set_style_border_width(ws_auth_wrapper, 0, LV_STATE_DEFAULT); + auto* ws_auth_label = lv_label_create(ws_auth_wrapper); + lv_label_set_text(ws_auth_label, "Require Authentication"); + lv_obj_align(ws_auth_label, LV_ALIGN_LEFT_MID, 0, 0); + switchWebServerAuthEnabled = lv_switch_create(ws_auth_wrapper); + if (wsSettings.webServerAuthEnabled) lv_obj_add_state(switchWebServerAuthEnabled, LV_STATE_CHECKED); + lv_obj_align(switchWebServerAuthEnabled, LV_ALIGN_RIGHT_MID, 0, 0); + lv_obj_add_event_cb(switchWebServerAuthEnabled, onWebServerAuthEnabledSwitch, LV_EVENT_VALUE_CHANGED, this); + + // WebServer Username + auto* ws_user_wrapper = lv_obj_create(main_wrapper); + lv_obj_set_size(ws_user_wrapper, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_style_pad_all(ws_user_wrapper, 0, LV_STATE_DEFAULT); + lv_obj_set_style_border_width(ws_user_wrapper, 0, LV_STATE_DEFAULT); + auto* ws_user_label = lv_label_create(ws_user_wrapper); + lv_label_set_text(ws_user_label, "Username"); + lv_obj_align(ws_user_label, LV_ALIGN_LEFT_MID, 0, 0); + textAreaWebServerUsername = lv_textarea_create(ws_user_wrapper); + lv_obj_set_width(textAreaWebServerUsername, 120); + lv_obj_align(textAreaWebServerUsername, LV_ALIGN_RIGHT_MID, 0, 0); + lv_textarea_set_one_line(textAreaWebServerUsername, true); + lv_textarea_set_max_length(textAreaWebServerUsername, 32); + lv_textarea_set_text(textAreaWebServerUsername, wsSettings.webServerUsername.c_str()); + lv_obj_add_event_cb(textAreaWebServerUsername, onCredentialChanged, LV_EVENT_VALUE_CHANGED, this); + + // WebServer Password + auto* ws_pass_wrapper = lv_obj_create(main_wrapper); + lv_obj_set_size(ws_pass_wrapper, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_style_pad_all(ws_pass_wrapper, 0, LV_STATE_DEFAULT); + lv_obj_set_style_border_width(ws_pass_wrapper, 0, LV_STATE_DEFAULT); + auto* ws_pass_label = lv_label_create(ws_pass_wrapper); + lv_label_set_text(ws_pass_label, "Password"); + lv_obj_align(ws_pass_label, LV_ALIGN_LEFT_MID, 0, 0); + textAreaWebServerPassword = lv_textarea_create(ws_pass_wrapper); + lv_obj_set_width(textAreaWebServerPassword, 120); + lv_obj_align(textAreaWebServerPassword, LV_ALIGN_RIGHT_MID, 0, 0); + lv_textarea_set_one_line(textAreaWebServerPassword, true); + lv_textarea_set_max_length(textAreaWebServerPassword, 64); + lv_textarea_set_password_mode(textAreaWebServerPassword, true); + lv_textarea_set_text(textAreaWebServerPassword, wsSettings.webServerPassword.c_str()); + lv_obj_add_event_cb(textAreaWebServerPassword, onCredentialChanged, LV_EVENT_VALUE_CHANGED, this); + + // URL Display + auto* url_wrapper = lv_obj_create(main_wrapper); + lv_obj_set_size(url_wrapper, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_style_pad_all(url_wrapper, 10, LV_STATE_DEFAULT); + lv_obj_set_style_border_width(url_wrapper, 1, LV_STATE_DEFAULT); + lv_obj_set_flex_flow(url_wrapper, LV_FLEX_FLOW_COLUMN); + lv_obj_set_style_flex_cross_place(url_wrapper, LV_FLEX_ALIGN_START, 0); + + labelUrl = lv_label_create(url_wrapper); + lv_label_set_text(labelUrl, "Web Server URL:"); + + labelUrlValue = lv_label_create(url_wrapper); + lv_obj_set_style_text_color(labelUrlValue, lv_palette_main(LV_PALETTE_BLUE), 0); + + updateUrlDisplay(); + + // Sync Assets button + auto* sync_wrapper = lv_obj_create(main_wrapper); + lv_obj_set_size(sync_wrapper, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_style_pad_all(sync_wrapper, 10, LV_STATE_DEFAULT); + lv_obj_set_style_border_width(sync_wrapper, 1, LV_STATE_DEFAULT); + lv_obj_set_flex_flow(sync_wrapper, LV_FLEX_FLOW_COLUMN); + lv_obj_set_style_flex_cross_place(sync_wrapper, LV_FLEX_ALIGN_START, 0); + + auto* sync_label = lv_label_create(sync_wrapper); + lv_label_set_text(sync_label, "Asset Synchronization"); + lv_obj_set_style_text_font(sync_label, &lv_font_montserrat_14, 0); + + auto* sync_info = lv_label_create(sync_wrapper); + lv_label_set_long_mode(sync_info, LV_LABEL_LONG_WRAP); + lv_obj_set_width(sync_info, LV_PCT(95)); + lv_obj_set_style_text_color(sync_info, lv_palette_main(LV_PALETTE_GREY), 0); + lv_label_set_text(sync_info, "Sync web assets between Data partition and SD card backup"); + + auto* sync_button = lv_btn_create(sync_wrapper); + lv_obj_set_width(sync_button, LV_SIZE_CONTENT); + auto* sync_button_label = lv_label_create(sync_button); + lv_label_set_text(sync_button_label, "Sync Assets Now"); + lv_obj_center(sync_button_label); + lv_obj_add_event_cb(sync_button, onSyncAssets, LV_EVENT_CLICKED, this); + + // Info text + auto* info_label = lv_label_create(main_wrapper); + lv_label_set_long_mode(info_label, LV_LABEL_LONG_WRAP); + lv_obj_set_width(info_label, LV_PCT(95)); + lv_obj_set_style_text_color(info_label, lv_palette_main(LV_PALETTE_GREY), 0); + lv_label_set_text(info_label, + "WiFi Station credentials are managed separately.\n" + "Use the WiFi menu to connect to networks.\n\n" + "AP mode uses the password configured above."); + } + + void onHide(TT_UNUSED AppContext& app) override { + if (updated) { + // Read values from text areas + if (textAreaApPassword) { + wsSettings.apPassword = lv_textarea_get_text(textAreaApPassword); + } + if (textAreaWebServerUsername) { + wsSettings.webServerUsername = lv_textarea_get_text(textAreaWebServerUsername); + } + if (textAreaWebServerPassword) { + wsSettings.webServerPassword = lv_textarea_get_text(textAreaWebServerPassword); + } + + // Save to flash only (settings sync at boot handles SD restore) + const auto copy = wsSettings; + const bool wifiChanged = wifiSettingsChanged; + const bool webServerChanged = webServerEnabledChanged; + + getMainDispatcher().dispatch([copy, wifiChanged, webServerChanged]{ + // Save to flash (fast, low memory pressure) + if (!settings::webserver::save(copy)) { + LOGGER.warn("Failed to persist WebServer settings; changes may be lost on reboot"); + } + + // Publish event immediately after save so WebServer cache refreshes BEFORE requests arrive + service::webserver::getPubsub()->publish(service::webserver::WebServerEvent::WebServerSettingsChanged); + + // Only reconnect WiFi if WiFi settings actually changed + if (wifiChanged) { + LOGGER.info("WiFi mode changed to {}", copy.wifiMode == settings::webserver::WiFiMode::AccessPoint ? "AP" : "Station"); + } + + // Control WebServer service immediately + if (webServerChanged) { + LOGGER.info("WebServer {}", copy.webServerEnabled ? "enabling..." : "disabling..."); + service::webserver::setWebServerEnabled(copy.webServerEnabled); + } + }); + } + } +}; + +extern const AppManifest manifest = { + .appId = "WebServerSettings", + .appName = "Web Server", + .appIcon = TT_ASSETS_APP_ICON_SETTINGS, + .appCategory = Category::System, + .createApp = create +}; + +} + +#endif diff --git a/Tactility/Source/network/HttpServer.cpp b/Tactility/Source/network/HttpServer.cpp index 03792700..d6b9b673 100644 --- a/Tactility/Source/network/HttpServer.cpp +++ b/Tactility/Source/network/HttpServer.cpp @@ -9,39 +9,58 @@ namespace tt::network { static const auto LOGGER = Logger("HttpServer"); +static constexpr size_t INTERNAL_URI_HANDLER_COUNT = 2; + bool HttpServer::startInternal() { httpd_config_t config = HTTPD_DEFAULT_CONFIG(); config.stack_size = stackSize; config.server_port = port; config.uri_match_fn = matchUri; + config.max_uri_handlers = handlers.size() + INTERNAL_URI_HANDLER_COUNT; if (httpd_start(&server, &config) != ESP_OK) { LOGGER.error("Failed to start http server on port {}", port); return false; } + bool allRegistered = true; for (std::vector::reference handler : handlers) { - httpd_register_uri_handler(server, &handler); + if (httpd_register_uri_handler(server, &handler) != ESP_OK) { + LOGGER.error("Failed to register URI handler: {}", handler.uri); + allRegistered = false; + } + } + if (!allRegistered) { + httpd_stop(server); + server = nullptr; + return false; } LOGGER.info("Started on port {}", config.server_port); - return true; } void HttpServer::stopInternal() { LOGGER.info("Stopping server"); - if (server != nullptr && httpd_stop(server) != ESP_OK) { - LOGGER.warn("Error while stopping"); - server = nullptr; + if (server != nullptr) { + if (httpd_stop(server) == ESP_OK) { + server = nullptr; + } else { + LOGGER.warn("Error while stopping"); + } } } -void HttpServer::start() { +bool HttpServer::start() { auto lock = mutex.asScopedLock(); lock.lock(); - startInternal(); + if (isStarted()) { + LOGGER.warn("Already started"); + return true; + } + + return startInternal(); } void HttpServer::stop() { @@ -50,6 +69,7 @@ void HttpServer::stop() { if (!isStarted()) { LOGGER.warn("Not started"); + return; } stopInternal(); diff --git a/Tactility/Source/network/HttpdReq.cpp b/Tactility/Source/network/HttpdReq.cpp index d142f2fb..49b211f5 100644 --- a/Tactility/Source/network/HttpdReq.cpp +++ b/Tactility/Source/network/HttpdReq.cpp @@ -83,18 +83,35 @@ std::unique_ptr receiveByteArray(httpd_req_t* request, size_t length, si return nullptr; } + constexpr int MAX_TIMEOUT_RETRIES = 5; + int timeout_retries = 0; while (bytesRead < length) { size_t read_size = length - bytesRead; - size_t bytes_received = httpd_req_recv(request, buffer + bytesRead, read_size); + int bytes_received = httpd_req_recv(request, buffer + bytesRead, read_size); + if (bytes_received == HTTPD_SOCK_ERR_TIMEOUT) { + // Timeout - retry with backoff + timeout_retries++; + if (timeout_retries >= MAX_TIMEOUT_RETRIES) { + LOGGER.warn("Recv timeout after {} retries, read {}/{} bytes", timeout_retries, bytesRead, length); + free(buffer); + return nullptr; + } + LOGGER.warn("Recv timeout, retry {}/{}", timeout_retries, MAX_TIMEOUT_RETRIES); + vTaskDelay(pdMS_TO_TICKS(100 * timeout_retries)); // Exponential backoff + continue; + } if (bytes_received <= 0) { LOGGER.warn("Received error {} after reading {}/{} bytes", bytes_received, bytesRead, length); + free(buffer); return nullptr; } + // Successful read - reset timeout counter + timeout_retries = 0; bytesRead += bytes_received; } - return std::unique_ptr(std::move(buffer)); + return std::unique_ptr(buffer); } std::string receiveTextUntil(httpd_req_t* request, const std::string& terminator) { @@ -131,7 +148,7 @@ std::map parseContentDisposition(const std::vectorsubstr(prefix.size()); auto parts = string::split(parseable, "; "); - for (auto part : parts) { + for (const auto& part : parts) { auto key_value = string::split(part, "="); if (key_value.size() == 2) { // Trim trailing newlines @@ -150,7 +167,7 @@ std::map parseContentDisposition(const std::vector + +#include +#include + +#include +#include +#include +#include +#include + +namespace tt::service::webserver { + +static const auto LOGGER = tt::Logger("AssetVersion"); +constexpr auto* DATA_VERSION_FILE = "/data/webserver/version.json"; +constexpr auto* SD_VERSION_FILE = "/sdcard/tactility/webserver/version.json"; +constexpr auto* DATA_ASSETS_DIR = "/data/webserver"; +constexpr auto* SD_ASSETS_DIR = "/sdcard/tactility/webserver"; + +static bool loadVersionFromFile(const char* path, AssetVersion& version) { + if (!file::isFile(path)) { + LOGGER.warn("Version file not found: {}", path); + return false; + } + + // Read file content + std::string content; + { + auto lock = file::getLock(path); + lock->lock(portMAX_DELAY); + + FILE* fp = fopen(path, "r"); + if (!fp) { + LOGGER.error("Failed to open version file: {}", path); + lock->unlock(); + return false; + } + + char buffer[256]; + size_t bytesRead = fread(buffer, 1, sizeof(buffer) - 1, fp); + bool readError = ferror(fp) != 0; + fclose(fp); + lock->unlock(); + + if (readError) { + LOGGER.error("Error reading version file: {}", path); + return false; + } + if (bytesRead == 0) { + LOGGER.error("Version file is empty: {}", path); + return false; + } + buffer[bytesRead] = '\0'; + content = buffer; + } + + // Parse JSON + cJSON* json = cJSON_Parse(content.c_str()); + if (json == nullptr) { + LOGGER.error("Failed to parse version JSON: {}", path); + return false; + } + + cJSON* versionItem = cJSON_GetObjectItem(json, "version"); + if (versionItem == nullptr || !cJSON_IsNumber(versionItem)) { + LOGGER.error("Invalid version JSON format: {}", path); + cJSON_Delete(json); + return false; + } + + double versionValue = versionItem->valuedouble; + if (versionValue < 0 || versionValue > UINT32_MAX) { + LOGGER.error("Version out of valid range [0, {}]: {}", UINT32_MAX, path); + cJSON_Delete(json); + return false; + } + version.version = static_cast(versionValue); + cJSON_Delete(json); + + LOGGER.info("Loaded version {} from {}", version.version, path); + return true; +} + +static bool saveVersionToFile(const char* path, const AssetVersion& version) { + // Create directory if it doesn't exist + std::string dirPath(path); + size_t lastSlash = dirPath.find_last_of('/'); + if (lastSlash != std::string::npos) { + dirPath = dirPath.substr(0, lastSlash); + if (!file::isDirectory(dirPath.c_str())) { + if (!file::findOrCreateDirectory(dirPath.c_str(), 0755)) { + LOGGER.error("Failed to create directory: {}", dirPath); + return false; + } + } + } + + // Create JSON + cJSON* json = cJSON_CreateObject(); + if (json == nullptr) { + LOGGER.error("Failed to create JSON object for version"); + return false; + } + cJSON_AddNumberToObject(json, "version", version.version); + + char* jsonString = cJSON_Print(json); + if (jsonString == nullptr) { + LOGGER.error("Failed to serialize version JSON"); + cJSON_Delete(json); + return false; + } + + // Write to file + bool success = false; + { + auto lock = file::getLock(path); + lock->lock(portMAX_DELAY); + + FILE* fp = fopen(path, "w"); + if (fp) { + size_t len = strlen(jsonString); + size_t written = fwrite(jsonString, 1, len, fp); + success = (written == len); + if (success) { + if (fflush(fp) != 0) { + LOGGER.error("Failed to flush version file: {}", path); + success = false; + } else { + int fd = fileno(fp); + if (fd >= 0 && fsync(fd) != 0) { + LOGGER.error("Failed to fsync version file: {}", path); + success = false; + } + } + } + fclose(fp); + } + lock->unlock(); + } + + cJSON_free(jsonString); + cJSON_Delete(json); + + if (success) { + LOGGER.info("Saved version {} to {}", version.version, path); + } else { + LOGGER.error("Failed to write version file: {}", path); + } + + return success; +} + +bool loadDataVersion(AssetVersion& version) { + return loadVersionFromFile(DATA_VERSION_FILE, version); +} + +bool loadSdVersion(AssetVersion& version) { + return loadVersionFromFile(SD_VERSION_FILE, version); +} + +bool saveDataVersion(const AssetVersion& version) { + return saveVersionToFile(DATA_VERSION_FILE, version); +} + +bool saveSdVersion(const AssetVersion& version) { + return saveVersionToFile(SD_VERSION_FILE, version); +} + +bool hasDataAssets() { + return file::isDirectory(DATA_ASSETS_DIR); +} + +bool hasSdAssets() { + return file::isDirectory(SD_ASSETS_DIR); +} + +static bool copyDirectory(const char* src, const char* dst, int depth = 0) { + constexpr int MAX_DEPTH = 16; + if (depth >= MAX_DEPTH) { + LOGGER.error("Max directory depth exceeded: {}", src); + return false; + } + LOGGER.info("Copying directory: {} -> {}", src, dst); + + // Create destination directory + if (!file::isDirectory(dst)) { + if (!file::findOrCreateDirectory(dst, 0755)) { + LOGGER.error("Failed to create destination directory: {}", dst); + return false; + } + } + + // List source directory and copy each entry + bool copySuccess = true; + bool listSuccess = file::listDirectory(src, [&](const dirent& entry) { + // Skip "." and ".." entries (though listDirectory should already filter these) + if (strcmp(entry.d_name, ".") == 0 || strcmp(entry.d_name, "..") == 0) { + return; + } + + std::string srcPath = file::getChildPath(src, entry.d_name); + std::string dstPath = file::getChildPath(dst, entry.d_name); + + if (entry.d_type == file::TT_DT_DIR) { + // Recursively copy subdirectory + if (!copyDirectory(srcPath.c_str(), dstPath.c_str(), depth + 1)) { + copySuccess = false; + } + } else if (entry.d_type == file::TT_DT_REG) { + // Copy file using atomic temp file approach + auto lock = file::getLock(srcPath); + lock->lock(portMAX_DELAY); + + // Generate unique temp file path + std::string tempPath = std::format("{}.tmp.{}", dstPath, esp_random()); + + FILE* srcFile = fopen(srcPath.c_str(), "rb"); + if (!srcFile) { + LOGGER.error("Failed to open source file: {}", srcPath); + lock->unlock(); + copySuccess = false; + return; + } + + FILE* tempFile = fopen(tempPath.c_str(), "wb"); + if (!tempFile) { + LOGGER.error("Failed to create temp file: {}", tempPath); + fclose(srcFile); + lock->unlock(); + copySuccess = false; + return; + } + + // Copy in chunks + char buffer[512]; + size_t bytesRead; + bool fileCopySuccess = true; + while ((bytesRead = fread(buffer, 1, sizeof(buffer), srcFile)) > 0) { + size_t bytesWritten = fwrite(buffer, 1, bytesRead, tempFile); + if (bytesWritten != bytesRead) { + LOGGER.error("Failed to write to temp file: {}", tempPath); + fileCopySuccess = false; + copySuccess = false; + break; + } + } + + if (fileCopySuccess && ferror(srcFile)) { + LOGGER.error("Error reading source file: {}", srcPath); + fileCopySuccess = false; + copySuccess = false; + } + + fclose(srcFile); + + // Flush and sync temp file before closing + if (fileCopySuccess) { + if (fflush(tempFile) != 0) { + LOGGER.error("Failed to flush temp file: {}", tempPath); + fileCopySuccess = false; + copySuccess = false; + } else { + int fd = fileno(tempFile); + if (fd >= 0 && fsync(fd) != 0) { + LOGGER.error("Failed to fsync temp file: {}", tempPath); + fileCopySuccess = false; + copySuccess = false; + } + } + } + + fclose(tempFile); + + if (fileCopySuccess) { + // Atomically rename temp file to destination + if (rename(tempPath.c_str(), dstPath.c_str()) != 0) { + LOGGER.error("Failed to rename temp file {} to {}", tempPath, dstPath); + remove(tempPath.c_str()); + fileCopySuccess = false; + copySuccess = false; + } + } else { + // Clean up temp file on failure + remove(tempPath.c_str()); + } + + lock->unlock(); + + if (fileCopySuccess) { + LOGGER.info("Copied file: {}", entry.d_name); + } + } + }); + + if (!listSuccess) { + LOGGER.error("Failed to list source directory: {}", src); + return false; + } + + return copySuccess; +} + +bool syncAssets() { + LOGGER.info("Starting asset synchronization..."); + + // Check if Data partition and SD card exist + bool dataExists = hasDataAssets(); + bool sdExists = hasSdAssets(); + + // FIRST BOOT SCENARIO: Data has version 0, SD card is missing + if (dataExists && !sdExists) { + LOGGER.info("First boot - Data exists but SD card backup missing"); + LOGGER.warn("Skipping SD backup during boot - will be created on first settings save"); + LOGGER.warn("This avoids watchdog timeout if SD card is slow or corrupted"); + return true; // Don't block boot - defer copy to runtime + } + + // NO SD CARD: Just ensure Data has default structure + if (!sdExists) { + LOGGER.warn("No SD card available - creating default Data structure if needed"); + if (!dataExists) { + if (!file::findOrCreateDirectory(DATA_ASSETS_DIR, 0755)) { + LOGGER.error("Failed to create Data assets directory"); + return false; + } + AssetVersion defaultVersion(0); // Start at version 0 - SD card updates will be version 1+ + if (!saveDataVersion(defaultVersion)) { + LOGGER.error("Failed to save default Data version"); + return false; + } + LOGGER.info("Created default Data assets structure (version 0)"); + } + return true; + } + + // POST-FLASH RECOVERY: Data empty but SD card exists + if (!dataExists) { + LOGGER.info("Data partition empty - copying from SD card (recovery mode)"); + if (!copyDirectory(SD_ASSETS_DIR, DATA_ASSETS_DIR)) { + LOGGER.error("Failed to copy assets from SD card to Data"); + return false; + } + LOGGER.info("Recovery complete - assets restored from SD card"); + return true; + } + + // NORMAL OPERATION: Both exist - compare versions + AssetVersion dataVersion, sdVersion; + bool hasDataVer = loadDataVersion(dataVersion); + bool hasSdVer = loadSdVersion(sdVersion); + + if (!hasDataVer) { + LOGGER.warn("No Data version.json - assuming version 0"); + dataVersion.version = 0; + if (!saveDataVersion(dataVersion)) { + LOGGER.warn("Failed to save default Data version (non-fatal)"); + } + } + + if (!hasSdVer) { + LOGGER.warn("No SD version.json - assuming version 0"); + sdVersion.version = 0; + // DON'T save to SD during boot - defer to runtime + LOGGER.warn("Skipping SD version.json creation during boot - will be created on first settings save"); + } + + LOGGER.info("Version comparison - Data: {}, SD: {}", dataVersion.version, sdVersion.version); + + if (sdVersion.version > dataVersion.version) { + // Firmware update - copy SD -> Data + LOGGER.info("SD card newer (v{} > v{}) - copying assets SD -> Data (firmware update)", + sdVersion.version, dataVersion.version); + if (!copyDirectory(SD_ASSETS_DIR, DATA_ASSETS_DIR)) { + LOGGER.error("Failed to copy assets from SD to Data"); + return false; + } + LOGGER.info("Firmware update complete - assets updated from SD card"); + } else if (dataVersion.version > sdVersion.version) { + // User customization - backup Data -> SD + LOGGER.warn("Data newer (v{} > v{}) - deferring SD backup to avoid boot watchdog", + dataVersion.version, sdVersion.version); + LOGGER.warn("SD backup will occur on first WebServer settings save"); + return true; // Don't block boot - defer copy to runtime + } else { + LOGGER.info("Versions match (v{}) - no sync needed", dataVersion.version); + } + + return true; +} + +} // namespace + +#endif diff --git a/Tactility/Source/service/webserver/WebServerService.cpp b/Tactility/Source/service/webserver/WebServerService.cpp new file mode 100644 index 00000000..a8689059 --- /dev/null +++ b/Tactility/Source/service/webserver/WebServerService.cpp @@ -0,0 +1,1862 @@ +#ifdef ESP_PLATFORM + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#if TT_FEATURE_SCREENSHOT_ENABLED +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace tt::service::webserver { + +static const auto LOGGER = tt::Logger("WebServerService"); + +// Helper to convert chip model enum to human-readable string +static const char* getChipModelName(esp_chip_model_t model) { + switch (model) { + case CHIP_ESP32: return "ESP32"; + case CHIP_ESP32S2: return "ESP32-S2"; + case CHIP_ESP32S3: return "ESP32-S3"; + case CHIP_ESP32C3: return "ESP32-C3"; + case CHIP_ESP32C2: return "ESP32-C2"; + case CHIP_ESP32C6: return "ESP32-C6"; + case CHIP_ESP32H2: return "ESP32-H2"; +#ifdef CHIP_ESP32P4 + case CHIP_ESP32P4: return "ESP32-P4"; +#endif +#ifdef CHIP_ESP32C5 + case CHIP_ESP32C5: return "ESP32-C5"; +#endif +#ifdef CHIP_ESP32C61 + case CHIP_ESP32C61: return "ESP32-C61"; +#endif + default: return "Unknown"; + } +} + +// Cached settings to avoid SD card reads on every HTTP request +static Mutex g_settingsMutex; +static settings::webserver::WebServerSettings g_cachedSettings; +static bool g_settingsCached = false; + +// Global instance pointer for controlling the service (atomic to prevent TOCTOU races) +static std::atomic g_webServerInstance{nullptr}; + +constexpr int MAX_UPLOAD_SIZE = 10 * 1024 * 1024; // 10 MB limit + +static void publish_event(WebServerService* webserver, WebServerEvent event) { + webserver->getPubsub()->publish(event); +} + +std::shared_ptr> getPubsub() { + WebServerService* webserver = g_webServerInstance.load(); + if (webserver == nullptr) { + tt_crash("Service not running"); + } + + return webserver->getPubsub(); +} + +static bool secureCompare(const std::string& a, const std::string& b) { + size_t maxLen = std::max(a.size(), b.size()); + volatile unsigned char result = 0; + result |= (a.size() != b.size()); + for (size_t i = 0; i < maxLen; ++i) { + unsigned char ca = (i < a.size()) ? static_cast(a[i]) : 0; + unsigned char cb = (i < b.size()) ? static_cast(b[i]) : 0; + result |= ca ^ cb; + } + return result == 0; +} + +// Helper to send 401 Unauthorized response with WWW-Authenticate header +static esp_err_t sendUnauthorized(httpd_req_t* request, const char* message) { + httpd_resp_set_hdr(request, "WWW-Authenticate", "Basic realm=\"Tactility\""); + httpd_resp_send_err(request, HTTPD_401_UNAUTHORIZED, message); + return ESP_OK; // Response was sent successfully +} + +// Helper to validate HTTP Basic Auth on sensitive endpoints +// Returns ESP_OK with authPassed=true if auth succeeded or is disabled +// Returns ESP_OK with authPassed=false if auth failed (401 response already sent) +static esp_err_t validateRequestAuth(httpd_req_t* request, bool& authPassed) { + authPassed = false; + + // Copy settings under lock to avoid race with settings update callback + settings::webserver::WebServerSettings settings; + { + auto lock = g_settingsMutex.asScopedLock(); + lock.lock(); + settings = g_cachedSettings; + } + + if (!settings.webServerAuthEnabled) { + authPassed = true; + return ESP_OK; // Auth disabled, allow request + } + + // Get Authorization header + size_t auth_len = httpd_req_get_hdr_value_len(request, "Authorization"); + if (auth_len == 0) { + return sendUnauthorized(request, "Authorization required"); + } + + std::string auth_header(auth_len + 1, '\0'); + if (httpd_req_get_hdr_value_str(request, "Authorization", auth_header.data(), auth_len + 1) != ESP_OK) { + LOGGER.warn("Failed to read Authorization header"); + return sendUnauthorized(request, "Authorization required"); + } + auth_header.resize(auth_len); // Remove null terminator from string length + + // Check for "Basic " prefix + if (auth_header.rfind("Basic ", 0) != 0) { + LOGGER.warn("Authorization header is not Basic auth"); + return sendUnauthorized(request, "Basic authorization required"); + } + + // Extract base64 encoded credentials + std::string base64_creds = auth_header.substr(6); + + // Decode base64 using mbedtls (available in ESP-IDF) + size_t decoded_len = 0; + // First pass to get length + mbedtls_base64_decode(nullptr, 0, &decoded_len, + reinterpret_cast(base64_creds.c_str()), + base64_creds.length()); + + std::string decoded(decoded_len, '\0'); + size_t actual_len = 0; + int ret = mbedtls_base64_decode(reinterpret_cast(decoded.data()), + decoded_len, &actual_len, + reinterpret_cast(base64_creds.c_str()), + base64_creds.length()); + if (ret != 0) { + LOGGER.warn("Failed to decode base64 credentials"); + return sendUnauthorized(request, "Invalid credentials format"); + } + decoded.resize(actual_len); + + // Parse username:password + size_t colon_pos = decoded.find(':'); + if (colon_pos == std::string::npos) { + LOGGER.warn("Invalid credentials format (no colon separator)"); + return sendUnauthorized(request, "Invalid credentials format"); + } + + std::string username = decoded.substr(0, colon_pos); + std::string password = decoded.substr(colon_pos + 1); + + // Validate against cached settings + bool usernameMatch = secureCompare(username, settings.webServerUsername); + bool passwordMatch = secureCompare(password, settings.webServerPassword); + if (!usernameMatch || !passwordMatch) { + LOGGER.warn("Invalid credentials for user '{}'", username); + return sendUnauthorized(request, "Invalid credentials"); + } + + authPassed = true; + return ESP_OK; // Auth successful +} + +bool WebServerService::onStart(ServiceContext& service) { + LOGGER.info("Starting WebServer service..."); + + // Register global instance + g_webServerInstance.store(this); + + // Create statusbar icon (hidden initially, shown when server actually starts) + statusbarIconId = lvgl::statusbar_icon_add(); + lvgl::statusbar_icon_set_visibility(statusbarIconId, false); + + // Run asset synchronization on startup + if (!syncAssets()) { + LOGGER.warn("Asset sync failed, but continuing with available assets"); + } + + // Load and cache settings once at boot + bool serverEnabled; + { + auto lock = g_settingsMutex.asScopedLock(); + lock.lock(); + g_cachedSettings = settings::webserver::loadOrGetDefault(); + g_settingsCached = true; + serverEnabled = g_cachedSettings.webServerEnabled; + } + // Subscribe to settings change events to refresh cache + settingsEventSubscription = pubsub->subscribe([](WebServerEvent event) { + if (event == WebServerEvent::WebServerSettingsChanged) { + auto lock = g_settingsMutex.asScopedLock(); + lock.lock(); + g_cachedSettings = settings::webserver::loadOrGetDefault(); + g_settingsCached = true; + } + }); + + // Start HTTP server only if enabled in settings (default: OFF to save memory) + if (serverEnabled) { + LOGGER.info("WebServer enabled in settings, starting HTTP server..."); + setEnabled(true); + } else { + LOGGER.info("WebServer disabled in settings, NOT starting HTTP server (saves ~10KB RAM)"); + setEnabled(false); + } + + return true; +} + +void WebServerService::onStop(ServiceContext& service) { + g_webServerInstance.store(nullptr); + + pubsub->unsubscribe(settingsEventSubscription); + settingsEventSubscription = 0; + + setEnabled(false); + + // Remove statusbar icon + if (statusbarIconId >= 0) { + lvgl::statusbar_icon_remove(statusbarIconId); + statusbarIconId = -1; + } +} + +// region Enable/Disable + +void WebServerService::setEnabled(bool enabled) { + auto lock = mutex.asScopedLock(); + lock.lock(); + + if (enabled) { + if (!httpServer || !httpServer->isStarted()) { + startServer(); + } + } else { + if (httpServer && httpServer->isStarted()) { + stopServer(); + } + } +} + +bool WebServerService::isEnabled() const { + auto lock = mutex.asScopedLock(); + lock.lock(); + return httpServer && httpServer->isStarted(); +} + +// region AP Mode WiFi Management + +bool WebServerService::startApMode() { + // Copy settings locally + settings::webserver::WebServerSettings settings; + { + auto lock = g_settingsMutex.asScopedLock(); + lock.lock(); + settings = g_cachedSettings; + } + + if (settings.wifiMode != settings::webserver::WiFiMode::AccessPoint) { + LOGGER.info("Not in AP mode, skipping AP WiFi initialization"); + return true; // Not an error, just not needed + } + + LOGGER.info("Starting WiFi in Access Point mode..."); + + wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); + if (esp_wifi_init(&cfg) != ESP_OK) { + LOGGER.error("esp_wifi_init() failed"); + return false; + } + apWifiInitialized = true; + + // Create the AP network interface + apNetif = esp_netif_create_default_wifi_ap(); + if (apNetif == nullptr) { + LOGGER.error("esp_netif_create_default_wifi_ap() failed"); + esp_wifi_deinit(); + apWifiInitialized = false; + return false; + } + + if (esp_wifi_set_mode(WIFI_MODE_AP) != ESP_OK) { + LOGGER.error("esp_wifi_set_mode(AP) failed"); + stopApMode(); + return false; + } + + // Configure static IP for AP: 192.168.4.1/24 + esp_netif_ip_info_t ip_info; + memset(&ip_info, 0, sizeof(esp_netif_ip_info_t)); + ip_info.ip.addr = ipaddr_addr("192.168.4.1"); + ip_info.gw.addr = ipaddr_addr("192.168.4.1"); + ip_info.netmask.addr = ipaddr_addr("255.255.255.0"); + + if (esp_netif_dhcps_stop(apNetif) != ESP_OK) { + LOGGER.error("esp_netif_dhcps_stop() failed"); + stopApMode(); + return false; + } + + if (esp_netif_set_ip_info(apNetif, &ip_info) != ESP_OK) { + LOGGER.error("esp_netif_set_ip_info() failed"); + stopApMode(); + return false; + } + + if (esp_netif_dhcps_start(apNetif) != ESP_OK) { + LOGGER.error("esp_netif_dhcps_start() failed"); + stopApMode(); + return false; + } + + // Configure WiFi AP settings + wifi_config_t wifi_config; + memset(&wifi_config, 0, sizeof(wifi_config_t)); + + // Set SSID + strncpy(reinterpret_cast(wifi_config.ap.ssid), settings.apSsid.c_str(), sizeof(wifi_config.ap.ssid) - 1); + wifi_config.ap.ssid[sizeof(wifi_config.ap.ssid) - 1] = '\0'; + wifi_config.ap.ssid_len = static_cast(settings.apSsid.length()); + + // Set password and auth mode + if (settings.apOpenNetwork) { + // User explicitly chose an open network + wifi_config.ap.authmode = WIFI_AUTH_OPEN; + LOGGER.info("AP configured with OPEN authentication (user choice)"); + } else if (settings.apPassword.length() >= 8 && settings.apPassword.length() <= 63) { + wifi_config.ap.authmode = WIFI_AUTH_WPA2_PSK; + strncpy(reinterpret_cast(wifi_config.ap.password), settings.apPassword.c_str(), sizeof(wifi_config.ap.password) - 1); + wifi_config.ap.password[sizeof(wifi_config.ap.password) - 1] = '\0'; + LOGGER.info("AP configured with WPA2-PSK authentication"); + } else { + if (!settings.apPassword.empty()) { + LOGGER.warn("AP password invalid (must be 8-63 chars, got {}) - using OPEN mode", settings.apPassword.length()); + } + wifi_config.ap.authmode = WIFI_AUTH_OPEN; + LOGGER.warn("AP configured with OPEN authentication (no password)"); + } + + wifi_config.ap.max_connection = 4; + wifi_config.ap.channel = settings.apChannel; + + if (esp_wifi_set_config(WIFI_IF_AP, &wifi_config) != ESP_OK) { + LOGGER.error("esp_wifi_set_config(AP) failed"); + stopApMode(); + return false; + } + + if (esp_wifi_start() != ESP_OK) { + LOGGER.error("esp_wifi_start() failed"); + stopApMode(); + return false; + } + + LOGGER.info("WiFi AP started - SSID: '{}', Channel: {}, IP: 192.168.4.1", settings.apSsid, settings.apChannel); + return true; +} + +void WebServerService::stopApMode() { + if (apWifiInitialized) { + esp_err_t err; + err = esp_wifi_stop(); + if (err != ESP_OK && err != ESP_ERR_WIFI_NOT_STARTED) { + LOGGER.warn("esp_wifi_stop() in cleanup: {}", esp_err_to_name(err)); + } + LOGGER.info("WiFi AP stopped"); + + err = esp_wifi_set_mode(WIFI_MODE_STA); + if (err != ESP_OK) { + LOGGER.warn("esp_wifi_set_mode() in cleanup: {}", esp_err_to_name(err)); + } + LOGGER.info("Wifi mode set back to STA"); + + apWifiInitialized = false; + } + + if (apNetif != nullptr) { + esp_netif_destroy(apNetif); + apNetif = nullptr; + } +} + +// endregion + +bool WebServerService::startServer() { + // Copy settings locally to minimize lock duration + settings::webserver::WebServerSettings settings; + { + auto lock = g_settingsMutex.asScopedLock(); + lock.lock(); + settings = g_cachedSettings; + } + + // Start AP mode WiFi if configured + if (settings.wifiMode == settings::webserver::WiFiMode::AccessPoint) { + if (!startApMode()) { + LOGGER.error("Failed to start AP mode WiFi - HTTP server will not start"); + return false; + } + } + + // NOTE: If you see 'no slots left for registering handler', increase CONFIG_HTTPD_MAX_URI_HANDLERS in sdkconfig (default is 8, 16+ recommended for many endpoints) + void* ctx = this; // Avoid IDE warnings about 'this' in designated initializers + std::vector handlers = { + { + .uri = "/", + .method = HTTP_GET, + .handler = handleRoot, + .user_ctx = ctx + }, + // Note: /upload removed in favor of POST /fs/upload handled by /fs/* dispatcher + { + .uri = "/filebrowser", + .method = HTTP_GET, + .handler = handleFileBrowser, + .user_ctx = ctx + }, + // Consolidated /fs/* handlers (dispatch internally) to save uri handler slots + { + .uri = "/fs/*", + .method = HTTP_GET, + .handler = handleFsGenericGet, + .user_ctx = ctx + }, + { + .uri = "/fs/*", + .method = HTTP_POST, + .handler = handleFsGenericPost, + .user_ctx = ctx + }, + // Consolidated admin POST endpoints to save handler slots + { + .uri = "/admin/*", + .method = HTTP_POST, + .handler = handleAdminPost, + .user_ctx = ctx + }, + // API endpoints for system info, apps, wifi, etc + { + .uri = "/api/*", + .method = HTTP_GET, + .handler = handleApiGet, + .user_ctx = ctx + }, + { + .uri = "/api/*", + .method = HTTP_POST, + .handler = handleApiPost, + .user_ctx = ctx + }, + { + .uri = "/api/*", + .method = HTTP_PUT, + .handler = handleApiPut, + .user_ctx = ctx + }, + { + .uri = "/*", // Catch-all for dynamic assets + .method = HTTP_GET, + .handler = handleAssets, + .user_ctx = ctx + } + }; + + httpServer = std::make_unique( + settings.webServerPort, + "0.0.0.0", + handlers, + 8192 // Stack size + ); + + httpServer->start(); + if (!httpServer->isStarted()) { + LOGGER.error("Failed to start HTTP server on port {}", settings.webServerPort); + httpServer.reset(); + return false; + } + + LOGGER.info("HTTP server started successfully on port {}", settings.webServerPort); + publish_event(this, WebServerEvent::WebServerStarted); + + // Show statusbar icon (different icon for AP vs Station mode) + if (statusbarIconId >= 0) { + const char* icon_name = (settings.wifiMode == settings::webserver::WiFiMode::AccessPoint) + ? "webserver_ap_white.png" + : "webserver_station_white.png"; + auto icon_path = std::string("A:/system/service/Statusbar/assets/") + icon_name; + lvgl::statusbar_icon_set_image(statusbarIconId, icon_path); + lvgl::statusbar_icon_set_visibility(statusbarIconId, true); + LOGGER.info("WebServer statusbar icon shown ({} mode)", + settings.wifiMode == settings::webserver::WiFiMode::AccessPoint ? "AP" : "Station"); + } + + return true; +} + +void WebServerService::stopServer() { + if (!httpServer) { + return; + } + + httpServer->stop(); + httpServer.reset(); + + // Stop AP mode WiFi if we started it + if (apWifiInitialized || apNetif != nullptr) { + stopApMode(); + } + + LOGGER.info("HTTP server stopped"); + publish_event(this, WebServerEvent::WebServerStopped); + + if (statusbarIconId >= 0) { + lvgl::statusbar_icon_set_visibility(statusbarIconId, false); + } +} + +// region Endpoints + + + +esp_err_t WebServerService::handleRoot(httpd_req_t* request) { + LOGGER.info("GET / -> redirecting to /dashboard.html"); + httpd_resp_set_status(request, "302 Found"); + httpd_resp_set_hdr(request, "Location", "/dashboard.html"); + return httpd_resp_send(request, nullptr, 0); +} + +// region File Browser helpers & handlers + +// Helper to determine content type from file extension +static const char* getContentType(const std::string& path) { + // Check from the end to avoid matching extensions in directory names + auto endsWith = [&path](const char* ext) { + size_t extLen = strlen(ext); + return path.length() >= extLen && + path.compare(path.length() - extLen, extLen, ext) == 0; + }; + + // HTML/Text + if (endsWith(".html") || endsWith(".htm")) return "text/html"; + if (endsWith(".css")) return "text/css"; + if (endsWith(".js")) return "application/javascript"; + if (endsWith(".json")) return "application/json"; + if (endsWith(".xml")) return "application/xml"; + if (endsWith(".txt")) return "text/plain"; + + // Images + if (endsWith(".png")) return "image/png"; + if (endsWith(".jpg") || endsWith(".jpeg")) return "image/jpeg"; + if (endsWith(".gif")) return "image/gif"; + if (endsWith(".svg")) return "image/svg+xml"; + if (endsWith(".ico")) return "image/x-icon"; + if (endsWith(".webp")) return "image/webp"; + + // Fonts + if (endsWith(".woff")) return "font/woff"; + if (endsWith(".woff2")) return "font/woff2"; + if (endsWith(".ttf")) return "font/ttf"; + if (endsWith(".otf")) return "font/otf"; + if (endsWith(".eot")) return "application/vnd.ms-fontobject"; + + // Audio/Video + if (endsWith(".mp3")) return "audio/mpeg"; + if (endsWith(".wav")) return "audio/wav"; + if (endsWith(".ogg")) return "audio/ogg"; + if (endsWith(".mp4")) return "video/mp4"; + if (endsWith(".webm")) return "video/webm"; + + // Archives/Documents + if (endsWith(".pdf")) return "application/pdf"; + if (endsWith(".zip")) return "application/zip"; + if (endsWith(".gz")) return "application/gzip"; + + // Default + return "application/octet-stream"; +} + +static bool isAllowedBasePath(const std::string& path, bool allowRoot = false) { + if (path.empty()) return false; + // Check for ".." as a complete path component + if (path == ".." || path.starts_with("../") || + path.find("/../") != std::string::npos || path.ends_with("/..")) { + return false; + } + if (allowRoot && path == "/") return true; + return path == "/data" || path.starts_with("/data/") || path == "/sdcard" || path.starts_with("/sdcard/"); +} + +// Normalize client-supplied path: URL-decode, trim quotes/control chars, ensure leading slash, collapse duplicate slashes +static std::string normalizePath(const std::string& raw) { + // Helper: hex to int + auto hexVal = [](char c)->int { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return 10 + (c - 'a'); + if (c >= 'A' && c <= 'F') return 10 + (c - 'A'); + return -1; + }; + + std::string s = raw; + // Remove surrounding single or double quotes + if (s.size() >= 2 && ((s.front() == '\'' && s.back() == '\'') || (s.front() == '"' && s.back() == '"'))) { + s = s.substr(1, s.size() - 2); + } + + // URL-decode: %xx and '+' -> ' ' + std::string decoded; + decoded.reserve(s.size()); + for (size_t i = 0; i < s.size(); ++i) { + char c = s[i]; + if (c == '%') { + if (i + 2 < s.size()) { + int hi = hexVal(s[i+1]); + int lo = hexVal(s[i+2]); + if (hi >= 0 && lo >= 0) { + decoded.push_back(static_cast((hi << 4) | lo)); + i += 2; + continue; + } + } + // malformed %, keep it + decoded.push_back(c); + } else if (c == '+') { + decoded.push_back(' '); + } else { + // strip control characters + if (static_cast(c) > 31) decoded.push_back(c); + } + } + + // Trim whitespace from ends + size_t start = 0; + while (start < decoded.size() && isspace((unsigned char)decoded[start])) ++start; + size_t end = decoded.size(); + while (end > start && isspace((unsigned char)decoded[end-1])) --end; + std::string trimmed = decoded.substr(start, end - start); + + // Ensure leading slash + if (!trimmed.empty() && trimmed.front() != '/') trimmed = '/' + trimmed; + if (trimmed.empty()) trimmed = "/"; + + // Collapse duplicate slashes + std::string out; + out.reserve(trimmed.size()); + bool lastSlash = false; + for (char c : trimmed) { + if (c == '/') { + if (!lastSlash) { out.push_back(c); lastSlash = true; } + } else { out.push_back(c); lastSlash = false; } + } + + return out; +} + +static std::string escapeJson(const std::string& s) { + std::ostringstream o; + for (char c : s) { + switch (c) { + case '"': o << "\\\""; break; + case '\\': o << "\\\\"; break; + case '\n': o << "\\n"; break; + case '\r': o << "\\r"; break; + case '\t': o << "\\t"; break; + default: + if (static_cast(c) < 0x20) { + o << "\\u" << std::hex << std::setw(4) << std::setfill('0') << (int)c; + } else { + o << c; + } + } + } + return o.str(); +} + +static bool getQueryParam(httpd_req_t* req, const char* key, std::string& out) { + size_t len = httpd_req_get_url_query_len(req) + 1; + if (len <= 1) return false; + std::unique_ptr buf(new char[len]); + if (httpd_req_get_url_query_str(req, buf.get(), len) != ESP_OK) return false; + // Allocate buffer large enough for the entire query string (worst case) + std::unique_ptr value(new char[len]); + if (httpd_query_key_value(buf.get(), key, value.get(), len) == ESP_OK) { + out = value.get(); + return true; + } + return false; +} + +static bool uriMatches(const char* uri, const char* route) { + const size_t n = strlen(route); + return strncmp(uri, route, n) == 0 && (uri[n] == '\0' || uri[n] == '?' || uri[n] == '/'); +} + +esp_err_t WebServerService::handleFileBrowser(httpd_req_t* request) { + LOGGER.info("GET /filebrowser -> redirecting to /dashboard.html#files"); + httpd_resp_set_status(request, "302 Found"); + httpd_resp_set_hdr(request, "Location", "/dashboard.html#files"); + return httpd_resp_send(request, nullptr, 0); +} + +esp_err_t WebServerService::handleFsList(httpd_req_t* request) { + std::string path; + // Log raw query string for diagnostics + size_t qlen = httpd_req_get_url_query_len(request) + 1; + if (qlen > 1) { + std::unique_ptr qbuf(new char[qlen]); + if (httpd_req_get_url_query_str(request, qbuf.get(), qlen) == ESP_OK) { + LOGGER.info("GET /fs/list raw query: {}", qbuf.get()); + } + } + + if (!getQueryParam(request, "path", path) || path.empty()) path = "/"; + std::string norm = normalizePath(path); + LOGGER.info("GET /fs/list decoded path: '{}' normalized: '{}'", path, norm); + + // Allow root path for listing mount points + if (!isAllowedBasePath(norm, true)) { + LOGGER.warn("GET /fs/list - invalid path requested: '{}' normalized: '{}'", path, norm); + httpd_resp_set_type(request, "application/json"); + httpd_resp_sendstr(request, "{\"error\":\"invalid path\"}"); + return ESP_OK; + } + + std::ostringstream json; + json << "{\"path\":\"" << norm << "\",\"entries\":["; + + // Special handling for root: show available mount points + if (norm == "/") { + // Always show /data + json << "{\"name\":\"data\",\"type\":\"dir\",\"size\":0}"; + + // Show /sdcard if mounted + const auto sdcard_devices = hal::findDevices(hal::Device::Type::SdCard); + for (const auto& sdcard : sdcard_devices) { + if (sdcard->isMounted()) { + json << ",{\"name\":\"sdcard\",\"type\":\"dir\",\"size\":0}"; + break; + } + } + json << "]}"; + } else { + std::vector entries; + int res = file::scandir(norm, entries, file::direntFilterDotEntries, nullptr); + if (res < 0) { + httpd_resp_set_type(request, "application/json"); + httpd_resp_sendstr(request, "{\"error\":\"scan failed\"}"); + return ESP_OK; + } + bool first = true; + for (auto& e : entries) { + if (!first) json << ','; else first = false; + std::string name = e.d_name; + bool is_dir = (e.d_type == file::TT_DT_DIR || e.d_type == file::TT_DT_CHR); + std::string full = norm + "/" + name; + long size = 0; + if (!is_dir) { + struct stat st; + if (stat(full.c_str(), &st) == 0) { + size = st.st_size; + } + } + json << "{\"name\":\"" << escapeJson(name) << "\",\"type\":\"" << (is_dir?"dir":"file") << "\",\"size\":" << size << "}"; + } + json << "]}"; + } + + httpd_resp_set_type(request, "application/json"); + httpd_resp_sendstr(request, json.str().c_str()); + return ESP_OK; +} + +esp_err_t WebServerService::handleFsDownload(httpd_req_t* request) { + std::string path; + if (!getQueryParam(request, "path", path) || path.empty()) { + httpd_resp_send_err(request, HTTPD_400_BAD_REQUEST, "path required"); + return ESP_FAIL; + } + std::string norm = normalizePath(path); + if (!isAllowedBasePath(norm) || !file::isFile(norm)) { + LOGGER.warn("GET /fs/download - not found or invalid path: '{}' normalized: '{}'", path, norm); + httpd_resp_send_err(request, HTTPD_404_NOT_FOUND, "not found"); + return ESP_FAIL; + } + httpd_resp_set_type(request, getContentType(norm)); + // Suggest download - build header into a local string so it remains valid + std::string fname = file::getLastPathSegment(norm); + std::string disposition = std::string("attachment; filename=\"") + fname + "\""; + // RFC5987 fallback (filename*): percent-encode UTF-8 bytes for wider browser compatibility + auto pctEncode = [](const std::string& s)->std::string{ + std::ostringstream oss; + for (unsigned char c : s) { + if (std::isalnum(c) || c=='-' || c=='.' || c=='_' || c=='~') { + oss << c; + } else { + oss << '%'; + std::ostringstream hex; + hex << std::uppercase << std::hex << std::setw(2) << std::setfill('0') << (int)c; + oss << hex.str(); + } + } + return oss.str(); + }; + std::string pct = pctEncode(fname); + if (!pct.empty()) { + disposition += std::string("; filename*=UTF-8''") + pct; + } + // Set single Content-Disposition header (avoid adding duplicate headers) + httpd_resp_set_hdr(request, "Content-Disposition", disposition.c_str()); + FILE* fp = fopen(norm.c_str(), "rb"); + if (!fp) { httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "open failed"); return ESP_FAIL; } + char buf[512]; size_t n; + while ((n = fread(buf,1,sizeof(buf),fp))>0) { + if (httpd_resp_send_chunk(request, buf, n) != ESP_OK) { fclose(fp); return ESP_FAIL; } + } + fclose(fp); + httpd_resp_send_chunk(request, nullptr, 0); + return ESP_OK; +} + +esp_err_t WebServerService::handleFsUpload(httpd_req_t* request) { + std::string path; + + // Log raw query and decoded path for diagnostics + size_t qlen = httpd_req_get_url_query_len(request) + 1; + if (qlen > 1) { + std::unique_ptr qbuf(new char[qlen]); + if (httpd_req_get_url_query_str(request, qbuf.get(), qlen) == ESP_OK) { + LOGGER.info("POST /fs/upload raw query: {}", qbuf.get()); + } + } + + if (!getQueryParam(request, "path", path) || path.empty()) { + httpd_resp_send_err(request, HTTPD_400_BAD_REQUEST, "path required"); + return ESP_FAIL; + } + + // Log decoded path and headers + char content_type[64] = {0}; + httpd_req_get_hdr_value_str(request, "Content-Type", content_type, sizeof(content_type)); + std::string norm = normalizePath(path); + LOGGER.info("POST /fs/upload decoded path: '{}' normalized: '{}' Content-Length: {} Content-Type: {}", path, norm, (int)request->content_len, content_type[0] ? content_type : "(null)"); + + if (!isAllowedBasePath(norm)) { + LOGGER.warn("POST /fs/upload - invalid path requested: '{}' normalized: '{}'", path, norm); + httpd_resp_send_err(request, HTTPD_403_FORBIDDEN, "invalid path"); + return ESP_FAIL; + } + + if (request->content_len > MAX_UPLOAD_SIZE) { + httpd_resp_send_err(request, HTTPD_400_BAD_REQUEST, "file too large"); + return ESP_FAIL; + } + + // Ensure parent directory exists (after size check to avoid creating dirs for rejected uploads) + if (!file::findOrCreateParentDirectory(norm, 0755)) { + httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "failed to create parent directory"); + return ESP_FAIL; + } + FILE* fp = fopen(norm.c_str(), "wb"); + if (!fp) { httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "open failed"); return ESP_FAIL; } + char buf[512]; int remaining = request->content_len; int received=0; + constexpr int MAX_TIMEOUT_RETRIES = 5; + int timeout_retries = 0; + while (remaining > 0) { + int to_read = remaining > (int)sizeof(buf) ? (int)sizeof(buf) : remaining; + int ret = httpd_req_recv(request, buf, to_read); + if (ret == HTTPD_SOCK_ERR_TIMEOUT) { + // Timeout - retry with backoff + timeout_retries++; + if (timeout_retries >= MAX_TIMEOUT_RETRIES) { + LOGGER.error("Upload recv timeout after {} retries", timeout_retries); + fclose(fp); + remove(norm.c_str()); // Clean up partial file + httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "recv timeout"); + return ESP_FAIL; + } + LOGGER.warn("Upload recv timeout, retry {}/{}", timeout_retries, MAX_TIMEOUT_RETRIES); + vTaskDelay(pdMS_TO_TICKS(100 * timeout_retries)); // Linear backoff + continue; + } + if (ret <= 0) { + LOGGER.error("Upload recv failed with error {}", ret); + fclose(fp); + remove(norm.c_str()); // Clean up partial file + httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "recv failed"); + return ESP_FAIL; + } + // Successful read - reset timeout counter + timeout_retries = 0; + size_t written = fwrite(buf, 1, ret, fp); + if (written != (size_t)ret) { + fclose(fp); + remove(norm.c_str()); + httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "write failed"); + return ESP_FAIL; + } + remaining -= ret; + received += ret; + } + fclose(fp); + httpd_resp_set_type(request, "text/plain"); + std::string msg = std::string("Uploaded ") + std::to_string(received) + " bytes"; + httpd_resp_sendstr(request, msg.c_str()); + return ESP_OK; +} + +// Generic GET dispatcher for /fs/* URIs +esp_err_t WebServerService::handleFsGenericGet(httpd_req_t* request) { + // Auth check for all /fs/* endpoints (file system access is sensitive) + bool authPassed = false; + esp_err_t authResult = validateRequestAuth(request, authPassed); + if (!authPassed) { + return authResult; + } + + const char* uri = request->uri; + if (uriMatches(uri, "/fs/list")) return handleFsList(request); + if (uriMatches(uri, "/fs/download")) return handleFsDownload(request); + if (uriMatches(uri, "/fs/tree")) return handleFsTree(request); + LOGGER.warn("GET {} - not found in fs generic dispatcher", uri); + httpd_resp_send_err(request, HTTPD_404_NOT_FOUND, "not found"); + return ESP_FAIL; +} + +// Generic POST dispatcher for /fs/* URIs +esp_err_t WebServerService::handleFsGenericPost(httpd_req_t* request) { + // Auth check for all /fs/* endpoints (file system access is sensitive) + bool authPassed = false; + esp_err_t authResult = validateRequestAuth(request, authPassed); + if (!authPassed) { + return authResult; + } + + const char* uri = request->uri; + if (uriMatches(uri, "/fs/mkdir")) return handleFsMkdir(request); + if (uriMatches(uri, "/fs/delete")) return handleFsDelete(request); + if (uriMatches(uri, "/fs/rename")) return handleFsRename(request); + if (uriMatches(uri, "/fs/upload")) return handleFsUpload(request); + LOGGER.warn("POST {} - not found in fs generic dispatcher", uri); + httpd_resp_send_err(request, HTTPD_404_NOT_FOUND, "not found"); + return ESP_FAIL; +} + +// Admin dispatcher for consolidated small POST endpoints (e.g. sync, reboot) +esp_err_t WebServerService::handleAdminPost(httpd_req_t* request) { + // Auth check for all /admin/* endpoints (admin actions are sensitive) + bool authPassed = false; + esp_err_t authResult = validateRequestAuth(request, authPassed); + if (!authPassed) { + return authResult; + } + + const char* uri = request->uri; + if (strncmp(uri, "/admin/sync", 11) == 0) return handleSync(request); + if (strncmp(uri, "/admin/reboot", 13) == 0) return handleReboot(request); + LOGGER.info("POST {} - not found in admin dispatcher", uri); + httpd_resp_send_err(request, HTTPD_404_NOT_FOUND, "not found"); + return ESP_FAIL; +} + +// API GET dispatcher - returns JSON system information +// Note: /api/sysinfo is intentionally public for monitoring use cases +esp_err_t WebServerService::handleApiGet(httpd_req_t* request) { + const char* uri = request->uri; + + // Public endpoint: sysinfo (basic device info for monitoring) + if (strncmp(uri, "/api/sysinfo", 12) == 0) { + return handleApiSysinfo(request); + } + + // Protected endpoints require authentication + bool authPassed = false; + esp_err_t authResult = validateRequestAuth(request, authPassed); + if (!authPassed) { + return authResult; + } + + // Auth-protected endpoints + if (strncmp(uri, "/api/apps", 9) == 0) { + return handleApiApps(request); + } + if (strncmp(uri, "/api/wifi", 9) == 0) { + return handleApiWifi(request); + } + if (strncmp(uri, "/api/screenshot", 15) == 0) { + return handleApiScreenshot(request); + } + + LOGGER.warn("GET {} - not found in api dispatcher", uri); + httpd_resp_send_err(request, HTTPD_404_NOT_FOUND, "not found"); + return ESP_FAIL; +} + +// API POST dispatcher - all POST endpoints require authentication +esp_err_t WebServerService::handleApiPost(httpd_req_t* request) { + bool authPassed = false; + esp_err_t authResult = validateRequestAuth(request, authPassed); + if (!authPassed) { + return authResult; + } + + const char* uri = request->uri; + if (strncmp(uri, "/api/apps/run", 13) == 0) { + return handleApiAppsRun(request); + } + if (strncmp(uri, "/api/apps/uninstall", 19) == 0) { + return handleApiAppsUninstall(request); + } + + LOGGER.warn("POST {} - not found in api dispatcher", uri); + httpd_resp_send_err(request, HTTPD_404_NOT_FOUND, "not found"); + return ESP_FAIL; +} + +// API PUT dispatcher - all PUT endpoints require authentication +esp_err_t WebServerService::handleApiPut(httpd_req_t* request) { + bool authPassed = false; + esp_err_t authResult = validateRequestAuth(request, authPassed); + if (!authPassed) { + return authResult; + } + + const char* uri = request->uri; + if (strncmp(uri, "/api/apps/install", 17) == 0) { + return handleApiAppsInstall(request); + } + + LOGGER.warn("PUT {} - not found in api dispatcher", uri); + httpd_resp_send_err(request, HTTPD_404_NOT_FOUND, "not found"); + return ESP_FAIL; +} + +esp_err_t WebServerService::handleApiSysinfo(httpd_req_t* request) { + LOGGER.info("GET /api/sysinfo"); + + std::ostringstream json; + json << "{"; + + // Firmware info + json << "\"firmware\":{"; + json << "\"version\":\"" << TT_VERSION << "\","; + json << "\"idf_version\":\"" << ESP_IDF_VERSION_MAJOR << "." << ESP_IDF_VERSION_MINOR << "." << ESP_IDF_VERSION_PATCH << "\""; + json << "},"; + + // Chip info + esp_chip_info_t chip_info; + esp_chip_info(&chip_info); + json << "\"chip\":{"; + json << "\"model\":\"" << getChipModelName(chip_info.model) << "\","; + json << "\"cores\":" << (int)chip_info.cores << ","; + json << "\"revision\":" << (int)chip_info.revision << ","; + + // Decode features into an array of strings + json << "\"features\":["; + bool first_feature = true; + if (chip_info.features & CHIP_FEATURE_EMB_FLASH) { + json << "\"Embedded Flash\""; + first_feature = false; + } + if (chip_info.features & CHIP_FEATURE_WIFI_BGN) { + if (!first_feature) json << ","; + json << "\"WiFi 2.4GHz\""; + first_feature = false; + } + if (chip_info.features & CHIP_FEATURE_BLE) { + if (!first_feature) json << ","; + json << "\"BLE\""; + first_feature = false; + } + if (chip_info.features & CHIP_FEATURE_BT) { + if (!first_feature) json << ","; + json << "\"Bluetooth Classic\""; + first_feature = false; + } + if (chip_info.features & CHIP_FEATURE_IEEE802154) { + if (!first_feature) json << ","; + json << "\"IEEE 802.15.4\""; + first_feature = false; + } + if (chip_info.features & CHIP_FEATURE_EMB_PSRAM) { + if (!first_feature) json << ","; + json << "\"Embedded PSRAM\""; + } + json << "],"; + + // Internal flash size + uint32_t flash_size = 0; + esp_flash_get_size(nullptr, &flash_size); + json << "\"flash_size\":" << flash_size; + json << "},"; + + // Memory - Internal heap + size_t heap_free = heap_caps_get_free_size(MALLOC_CAP_INTERNAL); + size_t heap_total = heap_caps_get_total_size(MALLOC_CAP_INTERNAL); + size_t heap_min_free = heap_caps_get_minimum_free_size(MALLOC_CAP_INTERNAL); + size_t heap_largest = heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL); + + json << "\"heap\":{"; + json << "\"free\":" << heap_free << ","; + json << "\"total\":" << heap_total << ","; + json << "\"min_free\":" << heap_min_free << ","; + json << "\"largest_block\":" << heap_largest; + json << "},"; + + // Memory - PSRAM (external) + size_t psram_free = heap_caps_get_free_size(MALLOC_CAP_SPIRAM); + size_t psram_total = heap_caps_get_total_size(MALLOC_CAP_SPIRAM); + size_t psram_min_free = heap_caps_get_minimum_free_size(MALLOC_CAP_SPIRAM); + size_t psram_largest = heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM); + + json << "\"psram\":{"; + json << "\"free\":" << psram_free << ","; + json << "\"total\":" << psram_total << ","; + json << "\"min_free\":" << psram_min_free << ","; + json << "\"largest_block\":" << psram_largest; + json << "},"; + + // Storage info + json << "\"storage\":{"; + uint64_t storage_total = 0, storage_free = 0; + + // Data partition + json << "\"data\":{"; + if (esp_vfs_fat_info(file::MOUNT_POINT_DATA, &storage_total, &storage_free) == ESP_OK) { + json << "\"free\":" << storage_free << ","; + json << "\"total\":" << storage_total << ","; + json << "\"mounted\":true"; + } else { + json << "\"mounted\":false"; + } + json << "},"; + + // SD card - check all sdcard devices + json << "\"sdcard\":{"; + bool sdcard_found = false; + const auto sdcard_devices = hal::findDevices(hal::Device::Type::SdCard); + for (const auto& sdcard : sdcard_devices) { + if (sdcard->isMounted() && esp_vfs_fat_info(sdcard->getMountPath().c_str(), &storage_total, &storage_free) == ESP_OK) { + json << "\"free\":" << storage_free << ","; + json << "\"total\":" << storage_total << ","; + json << "\"mounted\":true"; + sdcard_found = true; + break; + } + } + if (!sdcard_found) { + json << "\"mounted\":false"; + } + json << "}"; + + json << "},"; // end storage + + // Uptime (in seconds) + TickType_t ticks = xTaskGetTickCount(); + float uptime_sec = static_cast(ticks) / configTICK_RATE_HZ; + json << "\"uptime\":" << static_cast(uptime_sec) << ","; + + // Task count + UBaseType_t task_count = uxTaskGetNumberOfTasks(); + json << "\"task_count\":" << task_count << ","; + + // Feature flags + json << "\"features_enabled\":{"; +#if TT_FEATURE_SCREENSHOT_ENABLED + json << "\"screenshot\":true"; +#else + json << "\"screenshot\":false"; +#endif + json << "}"; + + json << "}"; + + httpd_resp_set_type(request, "application/json"); + httpd_resp_sendstr(request, json.str().c_str()); + return ESP_OK; +} + +// GET /api/apps - List installed apps +esp_err_t WebServerService::handleApiApps(httpd_req_t* request) { + LOGGER.info("GET /api/apps"); + + auto manifests = app::getAppManifests(); + + std::ostringstream json; + json << "{\"apps\":["; + + bool first = true; + for (const auto& manifest : manifests) { + if (!first) json << ","; + first = false; + + json << "{"; + json << "\"id\":\"" << escapeJson(manifest->appId) << "\","; + json << "\"name\":\"" << escapeJson(manifest->appName) << "\","; + json << "\"version\":\"" << escapeJson(manifest->appVersionName) << "\","; + + const char* category = "user"; + if (manifest->appCategory == app::Category::System) category = "system"; + else if (manifest->appCategory == app::Category::Settings) category = "settings"; + json << "\"category\":\"" << category << "\","; + + json << "\"isExternal\":" << (manifest->appLocation.isExternal() ? "true" : "false") << ","; + json << "\"hidden\":" << ((manifest->appFlags & app::AppManifest::Flags::Hidden) ? "true" : "false"); + + if (!manifest->appIcon.empty()) { + json << ",\"icon\":\"" << escapeJson(manifest->appIcon) << "\""; + } + + json << "}"; + } + + json << "]}"; + + httpd_resp_set_type(request, "application/json"); + httpd_resp_sendstr(request, json.str().c_str()); + return ESP_OK; +} + +// POST /api/apps/run?id=xxx - Run an app +esp_err_t WebServerService::handleApiAppsRun(httpd_req_t* request) { + LOGGER.info("POST /api/apps/run"); + + std::string appId; + if (!getQueryParam(request, "id", appId) || appId.empty()) { + httpd_resp_send_err(request, HTTPD_400_BAD_REQUEST, "id parameter required"); + return ESP_FAIL; + } + + auto manifest = app::findAppManifestById(appId); + if (!manifest) { + httpd_resp_send_err(request, HTTPD_404_NOT_FOUND, "app not found"); + return ESP_FAIL; + } + + // Stop if already running + if (app::isRunning(appId)) { + app::stopAll(appId); + } + + app::start(appId); + + LOGGER.info("[200] /api/apps/run {}", appId); + httpd_resp_sendstr(request, "ok"); + return ESP_OK; +} + +// POST /api/apps/uninstall?id=xxx - Uninstall an app +esp_err_t WebServerService::handleApiAppsUninstall(httpd_req_t* request) { + LOGGER.info("POST /api/apps/uninstall"); + + std::string appId; + if (!getQueryParam(request, "id", appId) || appId.empty()) { + httpd_resp_send_err(request, HTTPD_400_BAD_REQUEST, "id parameter required"); + return ESP_FAIL; + } + + auto manifest = app::findAppManifestById(appId); + if (!manifest) { + LOGGER.info("[200] /api/apps/uninstall {} (app wasn't installed)", appId); + httpd_resp_sendstr(request, "ok"); + return ESP_OK; + } + + // Only allow uninstalling external apps + if (manifest->appLocation.isInternal()) { + httpd_resp_send_err(request, HTTPD_403_FORBIDDEN, "cannot uninstall system apps"); + return ESP_FAIL; + } + + if (app::uninstall(appId)) { + LOGGER.info("[200] /api/apps/uninstall {}", appId); + httpd_resp_sendstr(request, "ok"); + return ESP_OK; + } else { + LOGGER.warn("[500] /api/apps/uninstall {}", appId); + httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "uninstall failed"); + return ESP_FAIL; + } +} + +// PUT /api/apps/install - Install an app from multipart form upload +esp_err_t WebServerService::handleApiAppsInstall(httpd_req_t* request) { + LOGGER.info("PUT /api/apps/install"); + + std::string boundary; + if (!network::getMultiPartBoundaryOrSendError(request, boundary)) { + return ESP_FAIL; + } + + size_t content_left = request->content_len; + constexpr size_t MAX_APP_UPLOAD_SIZE = 20 * 1024 * 1024; + + // Read headers until empty line (skip boundary line first) + auto content_headers_data = network::receiveTextUntil(request, "\r\n\r\n"); + content_left -= content_headers_data.length(); + + // Split headers into lines and filter empty ones + auto content_headers = string::split(content_headers_data, "\r\n") + | std::views::filter([](const std::string& line) { + return line.length() > 0; + }) + | std::ranges::to(); + + auto content_disposition_map = network::parseContentDisposition(content_headers); + if (content_disposition_map.empty()) { + LOGGER.warn("parseContentDisposition returned empty map for: {}", content_headers_data); + httpd_resp_send_err(request, HTTPD_400_BAD_REQUEST, "invalid content disposition"); + return ESP_FAIL; + } + + auto filename_entry = content_disposition_map.find("filename"); + if (filename_entry == content_disposition_map.end()) { + LOGGER.warn("filename not found in content disposition map"); + httpd_resp_send_err(request, HTTPD_400_BAD_REQUEST, "filename parameter missing"); + return ESP_FAIL; + } + + // Calculate file size + auto boundary_and_newlines_after_file = std::format("\r\n--{}--\r\n", boundary); + if (content_left <= boundary_and_newlines_after_file.length()) { + httpd_resp_send_err(request, HTTPD_400_BAD_REQUEST, "invalid multipart payload"); + return ESP_FAIL; + } + + auto file_size = content_left - boundary_and_newlines_after_file.length(); + if (file_size == 0 || file_size > MAX_APP_UPLOAD_SIZE) { + httpd_resp_send_err(request, HTTPD_400_BAD_REQUEST, "file too large"); + return ESP_FAIL; + } + + // Create tmp directory + const std::string tmp_path = getTempPath(); + if (!file::findOrCreateDirectory(tmp_path, 0777)) { + httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "failed to create temp directory"); + return ESP_FAIL; + } + + std::string safe_name = file::getLastPathSegment(filename_entry->second); + if (safe_name.empty() || safe_name.find("..") != std::string::npos || + safe_name.find('/') != std::string::npos || safe_name.find('\\') != std::string::npos) { + httpd_resp_send_err(request, HTTPD_400_BAD_REQUEST, "invalid filename"); + return ESP_FAIL; + } + auto file_path = std::format("{}/{}", tmp_path, safe_name); + + if (network::receiveFile(request, file_size, file_path) != file_size) { + file::deleteFile(file_path); + httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "failed to save file"); + return ESP_FAIL; + } + + content_left -= file_size; + + // Read and discard trailing boundary + if (!network::readAndDiscardOrSendError(request, boundary_and_newlines_after_file)) { + return ESP_FAIL; + } + + // Install the app + if (!app::install(file_path)) { + file::deleteFile(file_path); + httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "installation failed"); + return ESP_FAIL; + } + + // Cleanup temp file + if (!file::deleteFile(file_path)) { + LOGGER.warn("Failed to delete temp file {}", file_path); + } + + LOGGER.info("[200] /api/apps/install -> {}", file_path); + httpd_resp_sendstr(request, "ok"); + return ESP_OK; +} + +// Helper to convert radio state to string +static const char* radioStateToJsonString(wifi::RadioState state) { + switch (state) { + case wifi::RadioState::On: return "on"; + case wifi::RadioState::OnPending: return "turning_on"; + case wifi::RadioState::Off: return "off"; + case wifi::RadioState::OffPending: return "turning_off"; + case wifi::RadioState::ConnectionPending: return "connecting"; + case wifi::RadioState::ConnectionActive: return "connected"; + default: return "unknown"; + } +} + +// GET /api/wifi - WiFi status +esp_err_t WebServerService::handleApiWifi(httpd_req_t* request) { + LOGGER.info("GET /api/wifi"); + + auto state = wifi::getRadioState(); + auto ip = wifi::getIp(); + auto ssid = wifi::getConnectionTarget(); + auto rssi = wifi::getRssi(); + bool secure = wifi::isConnectionSecure(); + + std::ostringstream json; + json << "{"; + json << "\"state\":\"" << radioStateToJsonString(state) << "\","; + json << "\"ip\":\"" << escapeJson(ip) << "\","; + json << "\"ssid\":\"" << escapeJson(ssid) << "\","; + json << "\"rssi\":" << rssi << ","; + json << "\"secure\":" << (secure ? "true" : "false"); + json << "}"; + + httpd_resp_set_type(request, "application/json"); + httpd_resp_sendstr(request, json.str().c_str()); + return ESP_OK; +} + +// GET /api/screenshot - Capture and return screenshot as PNG +// Screenshots are saved to SD card root (if available) or /data with incrementing numbers +esp_err_t WebServerService::handleApiScreenshot(httpd_req_t* request) { + LOGGER.info("GET /api/screenshot"); + +#if TT_FEATURE_SCREENSHOT_ENABLED + // Determine save location: prefer SD card root if mounted, otherwise /data + std::string save_path; + auto sdcard_devices = hal::findDevices(hal::Device::Type::SdCard); + for (const auto& sdcard : sdcard_devices) { + if (sdcard->isMounted()) { + save_path = sdcard->getMountPath(); + break; + } + } + if (save_path.empty()) { + save_path = file::MOUNT_POINT_DATA; + } + + // Find next available filename with incrementing number + std::string screenshot_path; + bool found_slot = false; + for (int i = 1; i <= 9999; ++i) { + screenshot_path = std::format("{}/webscreenshot{}.png", save_path, i); + if (!file::isFile(screenshot_path)) { + found_slot = true; + break; + } + } + if (!found_slot) { + httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "no available screenshot slots"); + return ESP_FAIL; + } + + LOGGER.info("Screenshot will be saved to: {}", screenshot_path); + + // LVGL's lodepng uses lv_fs which requires the "A:" prefix + std::string lvgl_screenshot_path = lvgl::PATH_PREFIX + screenshot_path; + + // Capture screenshot using LVGL + if (lvgl::lock(pdMS_TO_TICKS(100))) { + bool success = lv_screenshot_create(lv_scr_act(), LV_100ASK_SCREENSHOT_SV_PNG, lvgl_screenshot_path.c_str()); + lvgl::unlock(); + + if (!success) { + LOGGER.error("lv_screenshot_create failed for path: {}", lvgl_screenshot_path); + httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "screenshot capture failed"); + return ESP_FAIL; + } + LOGGER.info("Screenshot captured successfully"); + } else { + LOGGER.error("Could not acquire LVGL lock within 100ms"); + httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "could not acquire LVGL lock"); + return ESP_FAIL; + } + + // Send the file (use regular path for fopen, not LVGL path) + httpd_resp_set_type(request, "image/png"); + + FILE* fp = fopen(screenshot_path.c_str(), "rb"); + if (!fp) { + httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "failed to open screenshot"); + return ESP_FAIL; + } + + char buf[512]; + size_t n; + while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) { + if (httpd_resp_send_chunk(request, buf, n) != ESP_OK) { + fclose(fp); + return ESP_FAIL; + } + } + fclose(fp); + httpd_resp_send_chunk(request, nullptr, 0); + + // File is kept on storage (not deleted) for user access + LOGGER.info("[200] /api/screenshot -> {}", screenshot_path); + return ESP_OK; +#else + httpd_resp_send_err(request, HTTPD_501_METHOD_NOT_IMPLEMENTED, "screenshot feature not enabled"); + return ESP_FAIL; +#endif +} + +esp_err_t WebServerService::handleFsTree(httpd_req_t* request) { + + LOGGER.info("GET /fs/tree"); + + std::ostringstream json; + json << "{"; + // Gather mount points + auto mounts = file::getMountPoints(); + json << "\"mounts\": ["; + bool firstMount = true; + for (auto& m : mounts) { + if (!firstMount) json << ','; else firstMount = false; + std::string name = m.d_name; + std::string path = (name == std::string("data") || name == std::string("/data")) ? std::string("/data") : std::string("/") + name; + // normalize possible duplicate slash + if (!path.starts_with("/")) path = std::string("/") + path; + json << "{\"name\":\"" << escapeJson(name) << "\",\"path\":\"" << escapeJson(path) << "\",\"entries\": ["; + + std::vector entries; + int res = file::scandir(path, entries, file::direntFilterDotEntries, nullptr); + if (res > 0) { + bool first = true; + for (auto& e : entries) { + if (!first) json << ','; else first = false; + std::string en = e.d_name; + bool is_dir = (e.d_type == file::TT_DT_DIR || e.d_type == file::TT_DT_CHR); + json << "{\"name\":\"" << escapeJson(en) << "\",\"type\":\"" << (is_dir?"dir":"file") << "\"}"; + } + } + + json << "]}"; + } + json << "]}"; + + httpd_resp_set_type(request, "application/json"); + httpd_resp_sendstr(request, json.str().c_str()); + return ESP_OK; +} + +// Create a directory at the specified path (POST /fs/mkdir?path=/data/newdir) +esp_err_t WebServerService::handleFsMkdir(httpd_req_t* request) { + std::string path; + if (!getQueryParam(request, "path", path) || path.empty()) { + httpd_resp_send_err(request, HTTPD_400_BAD_REQUEST, "path required"); + return ESP_FAIL; + } + std::string norm = normalizePath(path); + LOGGER.info("POST /fs/mkdir requested: '{}' normalized: '{}'", path, norm); + if (!isAllowedBasePath(norm)) { + httpd_resp_send_err(request, HTTPD_403_FORBIDDEN, "invalid path"); + return ESP_FAIL; + } + bool ok = file::findOrCreateDirectory(norm, 0755); + if (!ok) { httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "mkdir failed"); return ESP_FAIL; } + httpd_resp_sendstr(request, "ok"); + return ESP_OK; +} + +static bool isRootMountPoint(const std::string& path) { + return path == "/data" || path == "/sdcard"; +} + +// Delete a file or directory (POST /fs/delete?path=/data/foo) +esp_err_t WebServerService::handleFsDelete(httpd_req_t* request) { + std::string path; + if (!getQueryParam(request, "path", path) || path.empty()) { + httpd_resp_send_err(request, HTTPD_400_BAD_REQUEST, "path required"); + return ESP_FAIL; + } + std::string norm = normalizePath(path); + LOGGER.info("POST /fs/delete requested: '{}' normalized: '{}'", path, norm); + if (!isAllowedBasePath(norm)) { + httpd_resp_send_err(request, HTTPD_403_FORBIDDEN, "invalid path"); + return ESP_FAIL; + } + if (isRootMountPoint(norm)) { + httpd_resp_send_err(request, HTTPD_403_FORBIDDEN, "cannot delete mount point"); + return ESP_FAIL; + } + bool ok = true; + if (file::isDirectory(norm)) ok = file::deleteRecursively(norm); + else if (file::isFile(norm)) ok = file::deleteFile(norm); + else ok = false; + if (!ok) { httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "delete failed"); return ESP_FAIL; } + httpd_resp_sendstr(request, "ok"); + return ESP_OK; +} + +// Rename a file or folder (POST /fs/rename?path=/data/oldname&newName=newname) +esp_err_t WebServerService::handleFsRename(httpd_req_t* request) { + std::string path; + std::string newName; + if (!getQueryParam(request, "path", path) || path.empty()) { + httpd_resp_send_err(request, HTTPD_400_BAD_REQUEST, "path required"); + return ESP_FAIL; + } + if (!getQueryParam(request, "newName", newName) || newName.empty()) { + httpd_resp_send_err(request, HTTPD_400_BAD_REQUEST, "newName required"); + return ESP_FAIL; + } + std::string norm = normalizePath(path); + LOGGER.info("POST /fs/rename requested: '{}' normalized: '{}' -> newName: '{}'", path.c_str(), norm.c_str(), newName.c_str()); + if (!isAllowedBasePath(norm)) { + httpd_resp_send_err(request, HTTPD_403_FORBIDDEN, "invalid path"); + return ESP_FAIL; + } + + // Basic validation of newName: must not contain path separators or '..' + // Trim whitespace from newName + auto trim = [](std::string& s){ size_t st=0; while (stst && isspace((unsigned char)s[ed-1])) --ed; s = s.substr(st, ed-st); }; + trim(newName); + if (newName.empty() || newName.find('/') != std::string::npos || newName.find('\\') != std::string::npos || newName.find("..") != std::string::npos) { + httpd_resp_send_err(request, HTTPD_400_BAD_REQUEST, "invalid newName"); + return ESP_FAIL; + } + + // compute parent directory + std::string parent = "/"; + size_t pos = norm.find_last_of('/'); + if (pos != std::string::npos) { + parent = (pos == 0) ? std::string("/") : norm.substr(0, pos); + } + + if (!isAllowedBasePath(parent)) { + httpd_resp_send_err(request, HTTPD_403_FORBIDDEN, "invalid target parent"); + return ESP_FAIL; + } + + std::string target = file::getChildPath(parent, newName); + + // Prevent overwrite: fail if target exists + if (file::isFile(target) || file::isDirectory(target)) { + httpd_resp_send_err(request, HTTPD_400_BAD_REQUEST, "target exists"); + return ESP_FAIL; + } + + // perform rename + int r = rename(norm.c_str(), target.c_str()); + if (r != 0) { + int e = errno; + LOGGER.warn("rename failed errno={} ({}) -> {} -> {}", e, strerror(e), norm, target); + // Return errno string to client to aid debugging + std::string msg = std::string("rename failed: ") + strerror(e); + httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, msg.c_str()); + return ESP_FAIL; + } + httpd_resp_sendstr(request, "ok"); + return ESP_OK; +} + +// endregion + +esp_err_t WebServerService::handleSync(httpd_req_t* request) { + + LOGGER.info("POST /sync"); + + bool success = syncAssets(); + + if (success) { + httpd_resp_sendstr(request, "Assets synchronized successfully"); + } else { + httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "Asset sync failed"); + } + + return success ? ESP_OK : ESP_FAIL; +} + +esp_err_t WebServerService::handleReboot(httpd_req_t* request) { + + LOGGER.info("POST /reboot"); + + httpd_resp_sendstr(request, "Rebooting..."); + + // Reboot after a short delay to allow response to be sent + vTaskDelay(pdMS_TO_TICKS(2000)); + esp_restart(); + + return ESP_OK; // Unreachable, but satisfies function signature +} + +esp_err_t WebServerService::handleAssets(httpd_req_t* request) { + // Auth check for UI access control + bool authPassed = false; + esp_err_t authResult = validateRequestAuth(request, authPassed); + if (!authPassed) { + return authResult; + } + + const char* uri = request->uri; + LOGGER.info("GET {}", uri); + + // Special case: serve favicon from system assets + if (strcmp(uri, "/favicon.ico") == 0) { + const char* faviconPath = "/data/system/spinner.png"; + if (file::isFile(faviconPath)) { + httpd_resp_set_type(request, "image/png"); + httpd_resp_set_hdr(request, "Cache-Control", "public, max-age=86400"); + + auto lock = file::getLock(faviconPath); + lock->lock(portMAX_DELAY); + + FILE* fp = fopen(faviconPath, "rb"); + if (fp) { + char buffer[512]; + size_t bytesRead; + while ((bytesRead = fread(buffer, 1, sizeof(buffer), fp)) > 0) { + if (httpd_resp_send_chunk(request, buffer, bytesRead) != ESP_OK) { + fclose(fp); + lock->unlock(); + return ESP_FAIL; + } + } + fclose(fp); + lock->unlock(); + httpd_resp_send_chunk(request, nullptr, 0); + LOGGER.info("[200] {} (favicon)", uri); + return ESP_OK; + } + lock->unlock(); + } + // If favicon not found, return 404 silently (browsers handle this gracefully) + httpd_resp_send_err(request, HTTPD_404_NOT_FOUND, "Not found"); + return ESP_FAIL; + } + + // Special case: if requesting dashboard.html but it doesn't exist, serve default.html + std::string requestedPath = uri; + if (auto qpos = requestedPath.find('?'); qpos != std::string::npos) { + requestedPath = requestedPath.substr(0, qpos); + } + requestedPath = normalizePath(requestedPath); + if (requestedPath == "/.." || requestedPath.ends_with("/..") || requestedPath.find("/../") != std::string::npos) { + httpd_resp_send_err(request, HTTPD_400_BAD_REQUEST, "invalid path"); + return ESP_FAIL; + } + + std::string dataPath = std::string("/data/webserver") + requestedPath; + + if (requestedPath == "/dashboard.html" && !file::isFile(dataPath.c_str())) { + // Dashboard doesn't exist, try default.html + dataPath = "/data/webserver/default.html"; + LOGGER.info("dashboard.html not found, serving default.html"); + } + + // Try to serve from Data partition first + if (file::isFile(dataPath.c_str())) { + httpd_resp_set_type(request, getContentType(dataPath)); + + // Read and send file using standard C FILE* operations + auto lock = file::getLock(dataPath); + lock->lock(portMAX_DELAY); + + FILE* fp = fopen(dataPath.c_str(), "rb"); + if (fp) { + char buffer[512]; + size_t bytesRead; + while ((bytesRead = fread(buffer, 1, sizeof(buffer), fp)) > 0) { + if (httpd_resp_send_chunk(request, buffer, bytesRead) != ESP_OK) { + fclose(fp); + lock->unlock(); + return ESP_FAIL; + } + } + fclose(fp); + lock->unlock(); + + httpd_resp_send_chunk(request, nullptr, 0); // End of chunks + LOGGER.info("[200] {} (from Data)", uri); + return ESP_OK; + } + lock->unlock(); + } + + // Fallback to SD card + std::string sdPath = std::string("/sdcard/tactility/webserver") + requestedPath; + if (file::isFile(sdPath.c_str())) { + httpd_resp_set_type(request, getContentType(sdPath)); + + auto lock = file::getLock(sdPath); + lock->lock(portMAX_DELAY); + + FILE* fp = fopen(sdPath.c_str(), "rb"); + if (fp) { + char buffer[512]; + size_t bytesRead; + while ((bytesRead = fread(buffer, 1, sizeof(buffer), fp)) > 0) { + if (httpd_resp_send_chunk(request, buffer, bytesRead) != ESP_OK) { + fclose(fp); + lock->unlock(); + return ESP_FAIL; + } + } + fclose(fp); + lock->unlock(); + + httpd_resp_send_chunk(request, nullptr, 0); // End of chunks + LOGGER.info("[200] {} (from SD)", uri); + return ESP_OK; + } + lock->unlock(); + } + + // File not found + LOGGER.warn("[404] {}", uri); + httpd_resp_send_err(request, HTTPD_404_NOT_FOUND, "File not found"); + return ESP_FAIL; +} + +extern const ServiceManifest manifest = { + .id = "WebServer", + .createService = create +}; + +void setWebServerEnabled(bool enabled) { + WebServerService* instance = g_webServerInstance.load(); + if (instance != nullptr) { + instance->setEnabled(enabled); + // Don't log here - startServer()/stopServer() already log the actual result + } else { + LOGGER.warn("WebServer service not available, cannot {}", enabled ? "start" : "stop"); + } +} + +} // namespace + +#endif // ESP_PLATFORM diff --git a/Tactility/Source/settings/WebServerSettings.cpp b/Tactility/Source/settings/WebServerSettings.cpp new file mode 100644 index 00000000..4029fbf9 --- /dev/null +++ b/Tactility/Source/settings/WebServerSettings.cpp @@ -0,0 +1,260 @@ +#include +#include +#include +#include + +#include +#include +#include + +#ifdef ESP_PLATFORM +#include +#include +#include +#else +#include +#endif + +namespace tt::settings::webserver { + +static const auto LOGGER = tt::Logger("WebServerSettings"); +constexpr auto* SETTINGS_FILE = "/data/service/webserver/settings.properties"; + +// Property keys +constexpr auto* KEY_WIFI_ENABLED = "wifiEnabled"; +constexpr auto* KEY_WIFI_MODE = "wifiMode"; +constexpr auto* KEY_AP_SSID = "apSsid"; +constexpr auto* KEY_AP_PASSWORD = "apPassword"; +constexpr auto* KEY_AP_OPEN_NETWORK = "apOpenNetwork"; +constexpr auto* KEY_AP_CHANNEL = "apChannel"; +constexpr auto* KEY_WEBSERVER_ENABLED = "webServerEnabled"; +constexpr auto* KEY_WEBSERVER_PORT = "webServerPort"; +constexpr auto* KEY_WEBSERVER_AUTH_ENABLED = "webServerAuthEnabled"; +constexpr auto* KEY_WEBSERVER_USERNAME = "webServerUsername"; +constexpr auto* KEY_WEBSERVER_PASSWORD = "webServerPassword"; + +std::string generateDefaultApSsid() { +#ifdef ESP_PLATFORM + uint8_t mac[6]; + if (esp_read_mac(mac, ESP_MAC_WIFI_STA) != ESP_OK) { + return "Tactility-0000"; + } + char ssid[16]; + snprintf(ssid, sizeof(ssid), "Tactility-%02X%02X", mac[2] ^ mac[3], mac[4] ^ mac[5]); + return std::string(ssid); +#else + return "Tactility-0000"; +#endif +} + +/** + * @brief Generate a cryptographically secure random string for credentials + * @param length The desired length of the string + * @return A random alphanumeric string + */ +static std::string generateRandomCredential(size_t length) { + static constexpr char charset[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + static constexpr size_t charsetSize = sizeof(charset) - 1; + + std::string result; + result.reserve(length); + +#ifdef ESP_PLATFORM + for (size_t i = 0; i < length; ++i) { + uint32_t randomValue = esp_random(); + result += charset[randomValue % charsetSize]; + } +#else + static std::random_device rd; + static std::mt19937 gen(rd()); + std::uniform_int_distribution<> dis(0, charsetSize - 1); + for (size_t i = 0; i < length; ++i) { + result += charset[dis(gen)]; + } +#endif + + return result; +} + +/** + * @brief Check if a credential value is empty (needs auto-generation) + * @param value The credential value to check + * @return true if the credential is empty and needs generation + */ +static bool isEmptyCredential(const std::string& value) { + return value.empty(); +} + +bool load(WebServerSettings& settings) { + std::map map; + if (!file::loadPropertiesFile(SETTINGS_FILE, map)) { + return false; + } + + // Parse all settings from the map + auto wifi_enabled = map.find(KEY_WIFI_ENABLED); + auto wifi_mode = map.find(KEY_WIFI_MODE); + auto ap_ssid = map.find(KEY_AP_SSID); + auto ap_password = map.find(KEY_AP_PASSWORD); + auto ap_open_network = map.find(KEY_AP_OPEN_NETWORK); + auto ap_channel = map.find(KEY_AP_CHANNEL); + auto webserver_enabled = map.find(KEY_WEBSERVER_ENABLED); + auto webserver_port = map.find(KEY_WEBSERVER_PORT); + auto webserver_auth_enabled = map.find(KEY_WEBSERVER_AUTH_ENABLED); + auto webserver_username = map.find(KEY_WEBSERVER_USERNAME); + auto webserver_password = map.find(KEY_WEBSERVER_PASSWORD); + + // WiFi settings + settings.wifiEnabled = (wifi_enabled != map.end()) + ? (wifi_enabled->second == "1" || wifi_enabled->second == "true") + : false; // Default disabled + + settings.wifiMode = (wifi_mode != map.end() && wifi_mode->second == "1") + ? WiFiMode::AccessPoint + : WiFiMode::Station; + + auto parseInt = [](const std::string& value, int min, int max, int fallback) -> int { + int v = 0; + auto [ptr, ec] = std::from_chars(value.data(), value.data() + value.size(), v); + if (ec != std::errc{} || v < min || v > max) { + return fallback; + } + return v; + }; + + // AP mode settings + settings.apSsid = (ap_ssid != map.end() && !ap_ssid->second.empty()) + ? ap_ssid->second + : generateDefaultApSsid(); + settings.apPassword = (ap_password != map.end()) ? ap_password->second : ""; + settings.apOpenNetwork = (ap_open_network != map.end()) + ? (ap_open_network->second == "1" || ap_open_network->second == "true") + : false; + settings.apChannel = (ap_channel != map.end()) + ? static_cast(parseInt(ap_channel->second, 1, 13, 1)) + : 1; + + // Security: If AP password is empty, generate a strong random password. + // Skip this if user explicitly wants an open network. + // Note: We only auto-generate for EMPTY passwords, not user-set ones. + if (!settings.apOpenNetwork && isEmptyCredential(settings.apPassword)) { + LOGGER.info("AP password is empty - generating secure random password"); + + // Generate 12-character random password (alphanumeric, ~71 bits of entropy) + // WPA2 requires 8-63 characters, so 12 is well within range + settings.apPassword = generateRandomCredential(12); + + // Persist the generated password immediately + map[KEY_AP_PASSWORD] = settings.apPassword; + if (file::savePropertiesFile(SETTINGS_FILE, map)) { + LOGGER.info("Generated and saved new secure AP password"); + } else { + LOGGER.error("Failed to save generated AP password"); + } + } + + // Web server settings + settings.webServerEnabled = (webserver_enabled != map.end()) + ? (webserver_enabled->second == "1" || webserver_enabled->second == "true") + : false; + + settings.webServerPort = (webserver_port != map.end()) + ? static_cast(parseInt(webserver_port->second, 1, 65535, 80)) + : 80; + + // Web server auth settings + settings.webServerAuthEnabled = (webserver_auth_enabled != map.end()) + ? (webserver_auth_enabled->second == "1" || webserver_auth_enabled->second == "true") + : false; + + // Load credentials from file, defaulting to empty if not present + settings.webServerUsername = (webserver_username != map.end()) ? webserver_username->second : ""; + settings.webServerPassword = (webserver_password != map.end()) ? webserver_password->second : ""; + + // Security: If auth is enabled but credentials are empty, + // generate strong random credentials and persist them immediately. + // Note: We only auto-generate for EMPTY credentials, allowing users to set their own. + if (settings.webServerAuthEnabled && + (isEmptyCredential(settings.webServerUsername) || isEmptyCredential(settings.webServerPassword))) { + + LOGGER.info("Auth enabled with empty credentials - generating secure random credentials"); + + // Generate 12-character random credentials (alphanumeric, ~71 bits of entropy each) + settings.webServerUsername = generateRandomCredential(12); + settings.webServerPassword = generateRandomCredential(12); + + // Persist the generated credentials immediately + // We need to save these to the file so they're consistent across reboots + map[KEY_WEBSERVER_USERNAME] = settings.webServerUsername; + map[KEY_WEBSERVER_PASSWORD] = settings.webServerPassword; + if (file::savePropertiesFile(SETTINGS_FILE, map)) { + LOGGER.info("Generated and saved new secure credentials"); + } else { + LOGGER.error("Failed to save generated credentials - auth may be inconsistent across reboots"); + } + } + + return true; +} + +WebServerSettings getDefault() { + return WebServerSettings{ + .wifiEnabled = false, // Default WiFi OFF + .wifiMode = WiFiMode::Station, + .apSsid = generateDefaultApSsid(), + .apPassword = "", // Empty - will be auto-generated on first use (unless apOpenNetwork) + .apOpenNetwork = false, // Default to secured network + .apChannel = 1, + .webServerEnabled = false, // Default WebServer OFF for security + .webServerPort = 80, + .webServerAuthEnabled = false, // Auth disabled by default + .webServerUsername = "", // Empty - will be generated if auth is enabled + .webServerPassword = "" // Empty - will be generated if auth is enabled + }; +} + +WebServerSettings loadOrGetDefault() { + WebServerSettings settings; + + bool loadedFromFlash = load(settings); + if (!loadedFromFlash) { + // First boot - use defaults (WiFi OFF, WebServer OFF) + settings = getDefault(); + // Save defaults to flash so toggle states persist + if (save(settings)) { + LOGGER.info("First boot - saved default settings (WiFi OFF WebServer OFF)"); + } else { + LOGGER.warn("First boot - failed to save default settings to flash"); + } + } + + return settings; +} + +bool save(const WebServerSettings& settings) { + std::map map; + + // WiFi settings + map[KEY_WIFI_ENABLED] = settings.wifiEnabled ? "1" : "0"; + map[KEY_WIFI_MODE] = (settings.wifiMode == WiFiMode::AccessPoint) ? "1" : "0"; + + // AP mode settings + map[KEY_AP_SSID] = settings.apSsid; + map[KEY_AP_PASSWORD] = settings.apPassword; + map[KEY_AP_OPEN_NETWORK] = settings.apOpenNetwork ? "1" : "0"; + map[KEY_AP_CHANNEL] = std::to_string(settings.apChannel); + + // Web server settings + map[KEY_WEBSERVER_ENABLED] = settings.webServerEnabled ? "1" : "0"; + map[KEY_WEBSERVER_PORT] = std::to_string(settings.webServerPort); + + // Web server auth settings + map[KEY_WEBSERVER_AUTH_ENABLED] = settings.webServerAuthEnabled ? "1" : "0"; + map[KEY_WEBSERVER_USERNAME] = settings.webServerUsername; + map[KEY_WEBSERVER_PASSWORD] = settings.webServerPassword; + + // Save to flash storage only (no SD backup - settings sync at boot handles restore) + return file::savePropertiesFile(SETTINGS_FILE, map); +} + +} diff --git a/TactilityC/Source/symbols/freertos.cpp b/TactilityC/Source/symbols/freertos.cpp index 7f94cb21..f3829e1d 100644 --- a/TactilityC/Source/symbols/freertos.cpp +++ b/TactilityC/Source/symbols/freertos.cpp @@ -26,6 +26,8 @@ const esp_elfsym freertos_symbols[] = { ESP_ELFSYM_EXPORT(vTaskSetThreadLocalStoragePointer), ESP_ELFSYM_EXPORT(vTaskSetThreadLocalStoragePointerAndDelCallback), ESP_ELFSYM_EXPORT(vTaskGetInfo), + ESP_ELFSYM_EXPORT(vTaskResume), + ESP_ELFSYM_EXPORT(vTaskSuspend), ESP_ELFSYM_EXPORT(xTaskCreate), ESP_ELFSYM_EXPORT(xTaskAbortDelay), ESP_ELFSYM_EXPORT(xTaskCheckForTimeOut), @@ -77,6 +79,7 @@ const esp_elfsym freertos_symbols[] = { ESP_ELFSYM_EXPORT(xQueueGenericSend), ESP_ELFSYM_EXPORT(xQueueGenericSendFromISR), ESP_ELFSYM_EXPORT(xQueueSemaphoreTake), + ESP_ELFSYM_EXPORT(xQueueReceive), // Timer ESP_ELFSYM_EXPORT(pvTimerGetTimerID), ESP_ELFSYM_EXPORT(xTimerCreate), diff --git a/TactilityC/Source/tt_init.cpp b/TactilityC/Source/tt_init.cpp index dfe71611..68a66188 100644 --- a/TactilityC/Source/tt_init.cpp +++ b/TactilityC/Source/tt_init.cpp @@ -177,6 +177,7 @@ const esp_elfsym main_symbols[] { ESP_ELFSYM_EXPORT(esp_log), ESP_ELFSYM_EXPORT(esp_log_write), ESP_ELFSYM_EXPORT(esp_log_timestamp), + ESP_ELFSYM_EXPORT(esp_err_to_name), // Tactility ESP_ELFSYM_EXPORT(tt_app_start), ESP_ELFSYM_EXPORT(tt_app_start_with_bundle), @@ -385,11 +386,8 @@ const esp_elfsym main_symbols[] { ESP_ELFSYM_EXPORT(lv_obj_set_style_pad_right), ESP_ELFSYM_EXPORT(lv_obj_set_style_pad_column), ESP_ELFSYM_EXPORT(lv_obj_set_style_pad_row), - ESP_ELFSYM_EXPORT(lv_obj_set_style_border_width), - ESP_ELFSYM_EXPORT(lv_obj_set_style_border_opa), ESP_ELFSYM_EXPORT(lv_obj_set_style_border_post), ESP_ELFSYM_EXPORT(lv_obj_set_style_border_side), - ESP_ELFSYM_EXPORT(lv_obj_set_style_border_color), ESP_ELFSYM_EXPORT(lv_obj_set_style_text_opa), ESP_ELFSYM_EXPORT(lv_obj_set_style_text_align), ESP_ELFSYM_EXPORT(lv_obj_set_style_text_color), @@ -412,6 +410,10 @@ const esp_elfsym main_symbols[] { ESP_ELFSYM_EXPORT(lv_obj_set_style_outline_width), ESP_ELFSYM_EXPORT(lv_obj_set_style_outline_pad), ESP_ELFSYM_EXPORT(lv_obj_set_style_outline_opa), + ESP_ELFSYM_EXPORT(lv_obj_scroll_to_y), + ESP_ELFSYM_EXPORT(lv_obj_set_scrollbar_mode), + ESP_ELFSYM_EXPORT(lv_obj_get_child_count), + ESP_ELFSYM_EXPORT(lv_obj_get_child), // lv_font ESP_ELFSYM_EXPORT(lv_font_get_default), // lv_theme @@ -506,6 +508,9 @@ const esp_elfsym main_symbols[] { ESP_ELFSYM_EXPORT(lv_textarea_set_placeholder_text), ESP_ELFSYM_EXPORT(lv_textarea_set_text), ESP_ELFSYM_EXPORT(lv_textarea_set_text_selection), + ESP_ELFSYM_EXPORT(lv_textarea_set_max_length), + ESP_ELFSYM_EXPORT(lv_textarea_set_cursor_click_pos), + ESP_ELFSYM_EXPORT(lv_textarea_add_text), // lv_palette ESP_ELFSYM_EXPORT(lv_palette_main), ESP_ELFSYM_EXPORT(lv_palette_darken), @@ -574,6 +579,10 @@ const esp_elfsym main_symbols[] { ESP_ELFSYM_EXPORT(lv_line_set_points_mutable), // lv_group ESP_ELFSYM_EXPORT(lv_group_remove_obj), + ESP_ELFSYM_EXPORT(lv_group_focus_obj), + ESP_ELFSYM_EXPORT(lv_group_get_default), + ESP_ELFSYM_EXPORT(lv_group_add_obj), + ESP_ELFSYM_EXPORT(lv_group_set_default), // lv_mem ESP_ELFSYM_EXPORT(lv_free), ESP_ELFSYM_EXPORT(lv_malloc), From b8214fd378506fe7b4debc76e45433b9612d0676 Mon Sep 17 00:00:00 2001 From: Shadowtrance Date: Sat, 24 Jan 2026 02:30:13 +1000 Subject: [PATCH 02/10] Trackball Pointer Mode & driver rewrite (#453) --- Data/system/cursor.png | Bin 0 -> 546 bytes Data/system_sources/cursor.svg | 44 ++ Devices/lilygo-tdeck/Source/Init.cpp | 19 - .../Source/Trackball/Trackball.cpp | 467 ++++++++++++++---- .../lilygo-tdeck/Source/Trackball/Trackball.h | 45 +- .../Source/devices/KeyboardBacklight.cpp | 19 +- .../Source/devices/TrackballDevice.cpp | 47 +- Tactility/Include/Tactility/Assets.h | 1 + .../Tactility/settings/KeyboardSettings.h | 9 +- .../Tactility/settings/TrackballSettings.h | 27 + Tactility/Source/Tactility.cpp | 6 + .../Source/app/keyboard/KeyboardSettings.cpp | 63 +-- .../app/trackball/TrackballSettings.cpp | 219 ++++++++ .../Source/settings/KeyboardSettings.cpp | 7 +- .../Source/settings/TrackballSettings.cpp | 86 ++++ 15 files changed, 850 insertions(+), 209 deletions(-) create mode 100644 Data/system/cursor.png create mode 100644 Data/system_sources/cursor.svg create mode 100644 Tactility/Include/Tactility/settings/TrackballSettings.h create mode 100644 Tactility/Source/app/trackball/TrackballSettings.cpp create mode 100644 Tactility/Source/settings/TrackballSettings.cpp diff --git a/Data/system/cursor.png b/Data/system/cursor.png new file mode 100644 index 0000000000000000000000000000000000000000..7f35bc39fa00d9b00ed3b1946f09888edde2b14c GIT binary patch literal 546 zcmV+-0^R+IP)mt|^wS>@2rT8ykfIyHr~YT56YK*=iw7Aqdvn zrV!F7g0gj30$QfoG2_Q=f}JE+y|}oM`3}G(082!0>H!h? z{eE9styYxJ=L4nGBN1H#I6Dcz%y;c}dndm&nM|bFY;Ku(V~qKhNF=TR%C~4PN&jnG(x3RsI|Taa2_AVhf1aLbM_2+K4`z+5=sT2Tkj_$!hrtb=c!hVvo*-R|U+5oUm z1*C~+IUbKiM5JD?huLiQ(~GNoSRkTX$8o~taw$rwEr7TG1psit%p2ErMQeTk>Sy{_ k(YEayW6T49^Va~s0I58c_p1yfmjD0&07*qoM6N<$g0&&?f&c&j literal 0 HcmV?d00001 diff --git a/Data/system_sources/cursor.svg b/Data/system_sources/cursor.svg new file mode 100644 index 00000000..f8f79e1c --- /dev/null +++ b/Data/system_sources/cursor.svg @@ -0,0 +1,44 @@ + + + + + + diff --git a/Devices/lilygo-tdeck/Source/Init.cpp b/Devices/lilygo-tdeck/Source/Init.cpp index 8b88c405..5646dac6 100644 --- a/Devices/lilygo-tdeck/Source/Init.cpp +++ b/Devices/lilygo-tdeck/Source/Init.cpp @@ -7,10 +7,6 @@ #include #include #include -#include -#include - -#include static const auto LOGGER = tt::Logger("T-Deck"); @@ -89,21 +85,6 @@ bool initBoot() { LOGGER.error("{} start failed", trackball->getName()); } } - - // Backlight doesn't seem to turn on until toggled on and off from keyboard settings... - // Or let the display and backlight sleep then wake it up. - // Then it works fine...until reboot, then you need to toggle again. - // The current keyboard firmware sets backlight duty to 0 on boot. - // https://github.com/Xinyuan-LilyGO/T-Deck/blob/master/firmware/T-Keyboard_Keyboard_ESP32C3_250620.bin - // https://github.com/Xinyuan-LilyGO/T-Deck/blob/master/examples/Keyboard_ESP32C3/Keyboard_ESP32C3.ino#L25 - // https://github.com/Xinyuan-LilyGO/T-Deck/blob/master/examples/Keyboard_ESP32C3/Keyboard_ESP32C3.ino#L217 - auto kbSettings = tt::settings::keyboard::loadOrGetDefault(); - bool result = keyboardbacklight::setBrightness(kbSettings.backlightEnabled ? kbSettings.backlightBrightness : 0); - if (!result) { - LOGGER.warn("Failed to set keyboard backlight brightness"); - } - - trackball::setEnabled(kbSettings.trackballEnabled); }); return true; diff --git a/Devices/lilygo-tdeck/Source/Trackball/Trackball.cpp b/Devices/lilygo-tdeck/Source/Trackball/Trackball.cpp index c59c1916..b2bd6a06 100644 --- a/Devices/lilygo-tdeck/Source/Trackball/Trackball.cpp +++ b/Devices/lilygo-tdeck/Source/Trackball/Trackball.cpp @@ -1,6 +1,8 @@ #include "Trackball.h" +#include #include +#include static const auto LOGGER = tt::Logger("Trackball"); @@ -8,19 +10,292 @@ namespace trackball { static TrackballConfig g_config; static lv_indev_t* g_indev = nullptr; -static bool g_initialized = false; -static bool g_enabled = true; +static std::atomic g_initialized{false}; +static std::atomic g_enabled{true}; +static std::atomic g_mode{Mode::Encoder}; -// Track last GPIO states for edge detection -static bool g_lastState[5] = {false, false, false, false, false}; +// Interrupt-driven position tracking (atomic for ISR safety) +static std::atomic g_cursorX{160}; +static std::atomic g_cursorY{120}; +static std::atomic g_buttonPressed{false}; -static void read_cb(lv_indev_t* indev, lv_indev_data_t* data) { - if (!g_initialized || !g_enabled) { - data->state = LV_INDEV_STATE_RELEASED; - data->enc_diff = 0; +// Encoder mode: accumulated diff since last read +static std::atomic g_encoderDiff{0}; + +// Sensitivity cached for ISR access (atomic for thread safety) +static std::atomic g_encoderSensitivity{1}; // Steps per tick for encoder +static std::atomic g_pointerSensitivity{10}; // Pixels per tick for pointer + +// Cursor object for pointer mode +static lv_obj_t* g_cursor = nullptr; + +// Screen dimensions (T-Deck: 320x240) +static constexpr int32_t SCREEN_WIDTH = 320; +static constexpr int32_t SCREEN_HEIGHT = 240; + +static constexpr int32_t CURSOR_SIZE = 16; + +// ISR handler for trackball directions +static void IRAM_ATTR trackball_isr_handler(void* arg) { + // Skip accumulating movement when disabled + if (!g_enabled.load(std::memory_order_relaxed)) { return; } - + + gpio_num_t pin = static_cast(reinterpret_cast(arg)); + + if (g_mode.load(std::memory_order_relaxed) == Mode::Pointer) { + // Pointer mode: update absolute position using atomic fetch_add/sub + // Clamping is done in read_cb to avoid race conditions + int32_t step = g_pointerSensitivity.load(std::memory_order_relaxed); + if (pin == g_config.pinRight) { + g_cursorX.fetch_add(step, std::memory_order_relaxed); + } else if (pin == g_config.pinLeft) { + g_cursorX.fetch_sub(step, std::memory_order_relaxed); + } else if (pin == g_config.pinUp) { + g_cursorY.fetch_sub(step, std::memory_order_relaxed); + } else if (pin == g_config.pinDown) { + g_cursorY.fetch_add(step, std::memory_order_relaxed); + } + } else { + // Encoder mode: accumulate diff + int32_t step = g_encoderSensitivity.load(std::memory_order_relaxed); + if (pin == g_config.pinRight || pin == g_config.pinDown) { + g_encoderDiff.fetch_add(step, std::memory_order_relaxed); + } else if (pin == g_config.pinLeft || pin == g_config.pinUp) { + g_encoderDiff.fetch_sub(step, std::memory_order_relaxed); + } + } +} + +// ISR handler for button (any edge) +static void IRAM_ATTR button_isr_handler(void* arg) { + // Read current button state (active low) + bool pressed = gpio_get_level(g_config.pinClick) == 0; + g_buttonPressed.store(pressed, std::memory_order_relaxed); +} + +// Helper to clamp value to range +static inline int32_t clamp(int32_t val, int32_t minVal, int32_t maxVal) { + if (val < minVal) return minVal; + if (val > maxVal) return maxVal; + return val; +} + +static void read_cb(lv_indev_t* indev, lv_indev_data_t* data) { + Mode currentMode = g_mode.load(std::memory_order_relaxed); + + if (!g_initialized.load(std::memory_order_relaxed) || !g_enabled.load(std::memory_order_relaxed)) { + data->state = LV_INDEV_STATE_RELEASED; + if (currentMode == Mode::Encoder) { + data->enc_diff = 0; + } else { + // Clamp cursor position to screen bounds + int32_t x = clamp(g_cursorX.load(std::memory_order_relaxed), 0, SCREEN_WIDTH - CURSOR_SIZE - 1); + int32_t y = clamp(g_cursorY.load(std::memory_order_relaxed), 0, SCREEN_HEIGHT - CURSOR_SIZE - 1); + g_cursorX.store(x, std::memory_order_relaxed); + g_cursorY.store(y, std::memory_order_relaxed); + data->point.x = static_cast(x); + data->point.y = static_cast(y); + } + return; + } + + if (currentMode == Mode::Encoder) { + // Read and reset accumulated encoder diff + int32_t diff = g_encoderDiff.exchange(0); + data->enc_diff = static_cast(clamp(diff, INT16_MIN, INT16_MAX)); + + if (diff != 0) { + lv_disp_trig_activity(nullptr); + } + } else { + // Pointer mode: read and clamp cursor position + int32_t x = clamp(g_cursorX.load(std::memory_order_relaxed), 0, SCREEN_WIDTH - CURSOR_SIZE - 1); + int32_t y = clamp(g_cursorY.load(std::memory_order_relaxed), 0, SCREEN_HEIGHT - CURSOR_SIZE - 1); + + // Store clamped values back to prevent unbounded growth + g_cursorX.store(x, std::memory_order_relaxed); + g_cursorY.store(y, std::memory_order_relaxed); + + data->point.x = static_cast(x); + data->point.y = static_cast(y); + } + + // Button state (same for both modes) + bool pressed = g_buttonPressed.load(std::memory_order_relaxed); + data->state = pressed ? LV_INDEV_STATE_PRESSED : LV_INDEV_STATE_RELEASED; + + if (pressed) { + lv_disp_trig_activity(nullptr); + } +} + +lv_indev_t* init(const TrackballConfig& config) { + if (g_initialized.load(std::memory_order_relaxed)) { + LOGGER.warn("Already initialized"); + return g_indev; + } + + g_config = config; + + // Set default sensitivities if not specified + if (g_config.encoderSensitivity == 0) { + g_config.encoderSensitivity = 1; + } + if (g_config.pointerSensitivity == 0) { + g_config.pointerSensitivity = 10; + } + g_encoderSensitivity.store(g_config.encoderSensitivity, std::memory_order_relaxed); + g_pointerSensitivity.store(g_config.pointerSensitivity, std::memory_order_relaxed); + + // Initialize cursor position to center + g_cursorX.store(SCREEN_WIDTH / 2, std::memory_order_relaxed); + g_cursorY.store(SCREEN_HEIGHT / 2, std::memory_order_relaxed); + g_encoderDiff.store(0, std::memory_order_relaxed); + g_buttonPressed.store(false, std::memory_order_relaxed); + + // Configure direction pins as interrupt inputs (falling edge) + const gpio_num_t dirPins[4] = { + config.pinRight, + config.pinUp, + config.pinLeft, + config.pinDown + }; + + gpio_config_t io_conf = {}; + io_conf.intr_type = GPIO_INTR_NEGEDGE; // Falling edge (active low) + io_conf.mode = GPIO_MODE_INPUT; + io_conf.pull_up_en = GPIO_PULLUP_ENABLE; + io_conf.pull_down_en = GPIO_PULLDOWN_DISABLE; + + // Install GPIO ISR service (if not already installed) + static bool isr_service_installed = false; + if (!isr_service_installed) { + esp_err_t err = gpio_install_isr_service(ESP_INTR_FLAG_IRAM); + if (err == ESP_OK || err == ESP_ERR_INVALID_STATE) { + // ESP_ERR_INVALID_STATE means already installed, which is fine + isr_service_installed = true; + } else { + LOGGER.error("Failed to install GPIO ISR service: {}", esp_err_to_name(err)); + return nullptr; + } + } + + // Track added handlers for cleanup on failure + int handlersAdded = 0; + + // Configure and attach ISR for direction pins + for (int i = 0; i < 4; i++) { + io_conf.pin_bit_mask = (1ULL << dirPins[i]); + esp_err_t err = gpio_config(&io_conf); + if (err != ESP_OK) { + LOGGER.error("Failed to configure GPIO {}: {}", static_cast(dirPins[i]), esp_err_to_name(err)); + // Cleanup previously added handlers + for (int j = 0; j < handlersAdded; j++) { + gpio_isr_handler_remove(dirPins[j]); + } + return nullptr; + } + + err = gpio_isr_handler_add(dirPins[i], trackball_isr_handler, reinterpret_cast(static_cast(dirPins[i]))); + if (err != ESP_OK) { + LOGGER.error("Failed to add ISR for GPIO {}: {}", static_cast(dirPins[i]), esp_err_to_name(err)); + // Cleanup previously added handlers + for (int j = 0; j < handlersAdded; j++) { + gpio_isr_handler_remove(dirPins[j]); + } + return nullptr; + } + handlersAdded++; + } + + // Configure button pin (any edge for press/release detection) + io_conf.intr_type = GPIO_INTR_ANYEDGE; + io_conf.pin_bit_mask = (1ULL << config.pinClick); + esp_err_t err = gpio_config(&io_conf); + if (err != ESP_OK) { + LOGGER.error("Failed to configure button GPIO {}: {}", static_cast(config.pinClick), esp_err_to_name(err)); + // Cleanup direction handlers + for (int i = 0; i < 4; i++) { + gpio_isr_handler_remove(dirPins[i]); + } + return nullptr; + } + + err = gpio_isr_handler_add(config.pinClick, button_isr_handler, nullptr); + if (err != ESP_OK) { + LOGGER.error("Failed to add button ISR: {}", esp_err_to_name(err)); + // Cleanup direction handlers + for (int i = 0; i < 4; i++) { + gpio_isr_handler_remove(dirPins[i]); + } + return nullptr; + } + + // Read initial button state + g_buttonPressed.store(gpio_get_level(config.pinClick) == 0); + + // Register as LVGL encoder input device for group navigation (default mode) + g_indev = lv_indev_create(); + if (g_indev == nullptr) { + LOGGER.error("Failed to register LVGL input device"); + // Cleanup ISR handlers on failure + const gpio_num_t pins[5] = { + config.pinRight, config.pinUp, config.pinLeft, + config.pinDown, config.pinClick + }; + for (int i = 0; i < 5; i++) { + gpio_intr_disable(pins[i]); + gpio_isr_handler_remove(pins[i]); + } + return nullptr; + } + + lv_indev_set_type(g_indev, LV_INDEV_TYPE_ENCODER); + lv_indev_set_read_cb(g_indev, read_cb); + g_initialized.store(true, std::memory_order_relaxed); + LOGGER.info("Initialized with interrupts (R:{} U:{} L:{} D:{} Click:{})", + static_cast(config.pinRight), + static_cast(config.pinUp), + static_cast(config.pinLeft), + static_cast(config.pinDown), + static_cast(config.pinClick)); + + return g_indev; +} + +// Create cursor for pointer mode +static void createCursor() { + if (g_cursor != nullptr || g_indev == nullptr) return; + + g_cursor = lv_image_create(lv_layer_sys()); + if (g_cursor != nullptr) { + lv_obj_remove_flag(g_cursor, LV_OBJ_FLAG_CLICKABLE); + + // Set cursor image + lv_image_set_src(g_cursor, TT_ASSETS_UI_CURSOR); + lv_indev_set_cursor(g_indev, g_cursor); + LOGGER.debug("Cursor created"); + } +} + +// Destroy cursor when switching back to encoder mode +static void destroyCursor() { + if (g_cursor == nullptr) return; + + // Delete the cursor object - this automatically detaches it from the indev + lv_obj_delete(g_cursor); + g_cursor = nullptr; + LOGGER.debug("Cursor destroyed"); +} + +void deinit() { + if (!g_initialized.load(std::memory_order_relaxed)) return; + + destroyCursor(); + + // Disable interrupts and remove ISR handlers const gpio_num_t pins[5] = { g_config.pinRight, g_config.pinUp, @@ -28,122 +303,96 @@ static void read_cb(lv_indev_t* indev, lv_indev_data_t* data) { g_config.pinDown, g_config.pinClick }; - - // Read GPIO states and detect changes (active low with pull-up) - bool currentStates[5]; - for (int i = 0; i < 5; i++) { - currentStates[i] = gpio_get_level(pins[i]) == 0; - } - - // Process directional inputs as encoder steps - // Right/Down = positive diff (next item), Left/Up = negative diff (prev item) - int16_t diff = 0; - - // Right pressed (rising edge) - if (currentStates[0] && !g_lastState[0]) { - diff += g_config.movementStep; - } - // Up pressed (rising edge) - if (currentStates[1] && !g_lastState[1]) { - diff -= g_config.movementStep; - } - // Left pressed (rising edge) - if (currentStates[2] && !g_lastState[2]) { - diff -= g_config.movementStep; - } - // Down pressed (rising edge) - if (currentStates[3] && !g_lastState[3]) { - diff += g_config.movementStep; - } - - // Update last states - for (int i = 0; i < 5; i++) { - g_lastState[i] = currentStates[i]; - } - - // Update encoder diff and button state - data->enc_diff = diff; - data->state = currentStates[4] ? LV_INDEV_STATE_PRESSED : LV_INDEV_STATE_RELEASED; - - // Trigger activity for wake-on-trackball - if (diff != 0 || currentStates[4]) { - lv_disp_trig_activity(nullptr); - } -} -lv_indev_t* init(const TrackballConfig& config) { - if (g_initialized) { - LOGGER.warn("Already initialized"); - return g_indev; - } - - g_config = config; - - // Set default movement step if not specified - if (g_config.movementStep == 0) { - g_config.movementStep = 10; - } - - // Configure all GPIO pins as inputs with pull-ups (active low) - const gpio_num_t pins[5] = { - config.pinRight, - config.pinUp, - config.pinLeft, - config.pinDown, - config.pinClick - }; - - gpio_config_t io_conf = {}; - io_conf.intr_type = GPIO_INTR_DISABLE; - io_conf.mode = GPIO_MODE_INPUT; - io_conf.pull_up_en = GPIO_PULLUP_ENABLE; - io_conf.pull_down_en = GPIO_PULLDOWN_DISABLE; - for (int i = 0; i < 5; i++) { - io_conf.pin_bit_mask = (1ULL << pins[i]); - gpio_config(&io_conf); - g_lastState[i] = gpio_get_level(pins[i]) == 0; - } - - // Register as LVGL encoder input device for group navigation - g_indev = lv_indev_create(); - lv_indev_set_type(g_indev, LV_INDEV_TYPE_ENCODER); - lv_indev_set_read_cb(g_indev, read_cb); - - if (g_indev != nullptr) { - g_initialized = true; - LOGGER.info("Initialized as encoder (R:{} U:{} L:{} D:{} Click:{})", - static_cast(config.pinRight), - static_cast(config.pinUp), - static_cast(config.pinLeft), - static_cast(config.pinDown), - static_cast(config.pinClick)); - } else { - LOGGER.error("Failed to register LVGL input device"); + gpio_intr_disable(pins[i]); + gpio_isr_handler_remove(pins[i]); } - return g_indev; -} - -void deinit() { if (g_indev) { lv_indev_delete(g_indev); g_indev = nullptr; } - g_initialized = false; + + g_initialized.store(false, std::memory_order_relaxed); + g_mode.store(Mode::Encoder, std::memory_order_relaxed); + g_enabled.store(true, std::memory_order_relaxed); LOGGER.info("Deinitialized"); } -void setMovementStep(uint8_t step) { - if (step > 0) { - g_config.movementStep = step; - LOGGER.debug("Movement step set to {}", step); +void setEncoderSensitivity(uint8_t sensitivity) { + if (sensitivity > 0) { + // Only update the atomic - ISR reads from atomic, not g_config + g_encoderSensitivity.store(sensitivity, std::memory_order_relaxed); + LOGGER.debug("Encoder sensitivity set to {}", sensitivity); + } +} + +void setPointerSensitivity(uint8_t sensitivity) { + if (sensitivity > 0) { + // Only update the atomic - ISR reads from atomic, not g_config + g_pointerSensitivity.store(sensitivity, std::memory_order_relaxed); + LOGGER.debug("Pointer sensitivity set to {}", sensitivity); } } void setEnabled(bool enabled) { - g_enabled = enabled; + g_enabled.store(enabled, std::memory_order_relaxed); + + if (!enabled) { + // Clear accumulated state to prevent jumps on re-enable + g_encoderDiff.store(0, std::memory_order_relaxed); + } + + // Hide/show cursor based on enabled state when in pointer mode + // Note: Must be called from LVGL thread (main thread) for thread safety + lv_obj_t* cursor = g_cursor; // Local copy to avoid race with setMode + if (cursor != nullptr) { + if (enabled) { + lv_obj_clear_flag(cursor, LV_OBJ_FLAG_HIDDEN); + } else { + lv_obj_add_flag(cursor, LV_OBJ_FLAG_HIDDEN); + } + } + LOGGER.info("{}", enabled ? "Enabled" : "Disabled"); } +void setMode(Mode mode) { + // Note: Must be called from LVGL thread (main thread) for thread safety + if (!g_initialized.load(std::memory_order_relaxed) || g_indev == nullptr) { + LOGGER.warn("Cannot set mode - not initialized"); + return; + } + + if (g_mode.load(std::memory_order_relaxed) == mode) { + return; + } + + g_mode.store(mode, std::memory_order_relaxed); + + if (mode == Mode::Pointer) { + // Switch to pointer mode + lv_indev_set_type(g_indev, LV_INDEV_TYPE_POINTER); + createCursor(); + if (!g_enabled.load(std::memory_order_relaxed) && g_cursor != nullptr) { + lv_obj_add_flag(g_cursor, LV_OBJ_FLAG_HIDDEN); + } + // Reset cursor to center when switching modes + g_cursorX.store(SCREEN_WIDTH / 2, std::memory_order_relaxed); + g_cursorY.store(SCREEN_HEIGHT / 2, std::memory_order_relaxed); + LOGGER.info("Switched to Pointer mode"); + } else { + // Switch to encoder mode + destroyCursor(); + lv_indev_set_type(g_indev, LV_INDEV_TYPE_ENCODER); + g_encoderDiff.store(0, std::memory_order_relaxed); // Reset encoder diff + LOGGER.info("Switched to Encoder mode"); + } +} + +Mode getMode() { + return g_mode.load(std::memory_order_relaxed); +} + } diff --git a/Devices/lilygo-tdeck/Source/Trackball/Trackball.h b/Devices/lilygo-tdeck/Source/Trackball/Trackball.h index acfe9c29..4f67c9f8 100644 --- a/Devices/lilygo-tdeck/Source/Trackball/Trackball.h +++ b/Devices/lilygo-tdeck/Source/Trackball/Trackball.h @@ -5,16 +5,25 @@ namespace trackball { +/** + * @brief Trackball operating mode + */ +enum class Mode { + Encoder, // Navigation via enc_diff (scroll wheel behavior) + Pointer // Mouse cursor via point.x/y +}; + /** * @brief Trackball configuration structure */ struct TrackballConfig { - gpio_num_t pinRight; // Right direction GPIO - gpio_num_t pinUp; // Up direction GPIO - gpio_num_t pinLeft; // Left direction GPIO - gpio_num_t pinDown; // Down direction GPIO - gpio_num_t pinClick; // Click/select button GPIO - uint8_t movementStep; // Pixels to move per trackball event (default: 10) + gpio_num_t pinRight; // Right direction GPIO + gpio_num_t pinUp; // Up direction GPIO + gpio_num_t pinLeft; // Left direction GPIO + gpio_num_t pinDown; // Down direction GPIO + gpio_num_t pinClick; // Click/select button GPIO + uint8_t encoderSensitivity = 1; // Encoder mode: steps per tick + uint8_t pointerSensitivity = 10; // Pointer mode: pixels per tick }; /** @@ -30,10 +39,16 @@ lv_indev_t* init(const TrackballConfig& config); void deinit(); /** - * @brief Set movement step size - * @param step Encoder steps per trackball event + * @brief Set encoder mode sensitivity + * @param sensitivity Steps per trackball tick (1-10, default: 1) */ -void setMovementStep(uint8_t step); +void setEncoderSensitivity(uint8_t sensitivity); + +/** + * @brief Set pointer mode sensitivity + * @param sensitivity Pixels per trackball tick (1-10, default: 10) + */ +void setPointerSensitivity(uint8_t sensitivity); /** * @brief Enable or disable trackball input processing @@ -41,4 +56,16 @@ void setMovementStep(uint8_t step); */ void setEnabled(bool enabled); +/** + * @brief Set trackball operating mode + * @param mode Encoder or Pointer mode + */ +void setMode(Mode mode); + +/** + * @brief Get current trackball operating mode + * @return Current mode + */ +Mode getMode(); + } diff --git a/Devices/lilygo-tdeck/Source/devices/KeyboardBacklight.cpp b/Devices/lilygo-tdeck/Source/devices/KeyboardBacklight.cpp index a9137779..41ef5b67 100644 --- a/Devices/lilygo-tdeck/Source/devices/KeyboardBacklight.cpp +++ b/Devices/lilygo-tdeck/Source/devices/KeyboardBacklight.cpp @@ -1,16 +1,31 @@ #include "KeyboardBacklight.h" #include // Driver #include +#include // TODO: Add Mutex and consider refactoring into a class bool KeyboardBacklightDevice::start() { if (initialized) { return true; } - + // T-Deck uses I2C_NUM_0 for internal peripherals initialized = keyboardbacklight::init(I2C_NUM_0); - return initialized; + if (!initialized) { + return false; + } + + // Backlight doesn't seem to turn on until toggled on and off from keyboard settings... + // Or let the display and backlight sleep then wake it up. + // Then it works fine...until reboot, then you need to toggle again. + // The current keyboard firmware sets backlight duty to 0 on boot. + // https://github.com/Xinyuan-LilyGO/T-Deck/blob/master/firmware/T-Keyboard_Keyboard_ESP32C3_250620.bin + // https://github.com/Xinyuan-LilyGO/T-Deck/blob/master/examples/Keyboard_ESP32C3/Keyboard_ESP32C3.ino#L25 + // https://github.com/Xinyuan-LilyGO/T-Deck/blob/master/examples/Keyboard_ESP32C3/Keyboard_ESP32C3.ino#L217 + auto kbSettings = tt::settings::keyboard::loadOrGetDefault(); + keyboardbacklight::setBrightness(kbSettings.backlightEnabled ? kbSettings.backlightBrightness : 0); + + return true; } bool KeyboardBacklightDevice::stop() { diff --git a/Devices/lilygo-tdeck/Source/devices/TrackballDevice.cpp b/Devices/lilygo-tdeck/Source/devices/TrackballDevice.cpp index 16b65f26..9b24f10f 100644 --- a/Devices/lilygo-tdeck/Source/devices/TrackballDevice.cpp +++ b/Devices/lilygo-tdeck/Source/devices/TrackballDevice.cpp @@ -1,28 +1,49 @@ #include "TrackballDevice.h" #include // Driver +#include +#include +#include + +static const auto LOGGER = tt::Logger("TrackballDevice"); bool TrackballDevice::start() { if (initialized) { return true; } - + // T-Deck trackball GPIO configuration from LilyGo reference trackball::TrackballConfig config = { - .pinRight = GPIO_NUM_2, // BOARD_TBOX_G02 - .pinUp = GPIO_NUM_3, // BOARD_TBOX_G01 - .pinLeft = GPIO_NUM_1, // BOARD_TBOX_G04 - .pinDown = GPIO_NUM_15, // BOARD_TBOX_G03 - .pinClick = GPIO_NUM_0, // BOARD_BOOT_PIN - .movementStep = 1 // pixels per movement + .pinRight = GPIO_NUM_2, // BOARD_TBOX_G02 + .pinUp = GPIO_NUM_3, // BOARD_TBOX_G01 + .pinLeft = GPIO_NUM_1, // BOARD_TBOX_G04 + .pinDown = GPIO_NUM_15, // BOARD_TBOX_G03 + .pinClick = GPIO_NUM_0, // BOARD_BOOT_PIN + .encoderSensitivity = 1, // 1 step per tick for menu navigation + .pointerSensitivity = 10 // 10 pixels per tick for cursor movement }; - + indev = trackball::init(config); - if (indev != nullptr) { - initialized = true; - return true; + if (indev == nullptr) { + return false; } - - return false; + + initialized = true; + + // Apply persisted trackball settings (requires LVGL lock for cursor manipulation) + auto tbSettings = tt::settings::trackball::loadOrGetDefault(); + if (tt::lvgl::lock(100)) { + trackball::setMode(tbSettings.trackballMode == tt::settings::trackball::TrackballMode::Pointer + ? trackball::Mode::Pointer + : trackball::Mode::Encoder); + trackball::setEncoderSensitivity(tbSettings.encoderSensitivity); + trackball::setPointerSensitivity(tbSettings.pointerSensitivity); + trackball::setEnabled(tbSettings.trackballEnabled); + tt::lvgl::unlock(); + } else { + LOGGER.warn("Failed to acquire LVGL lock for trackball settings"); + } + + return true; } bool TrackballDevice::stop() { diff --git a/Tactility/Include/Tactility/Assets.h b/Tactility/Include/Tactility/Assets.h index b3efa797..6e7a865f 100644 --- a/Tactility/Include/Tactility/Assets.h +++ b/Tactility/Include/Tactility/Assets.h @@ -10,6 +10,7 @@ // UI #define TT_ASSETS_UI_SPINNER TT_ASSET("spinner.png") +#define TT_ASSETS_UI_CURSOR TT_ASSET("cursor.png") // App icons #define TT_ASSETS_APP_ICON_FALLBACK TT_ASSET("app_icon_fallback_dark_mode.png") diff --git a/Tactility/Include/Tactility/settings/KeyboardSettings.h b/Tactility/Include/Tactility/settings/KeyboardSettings.h index c65dbafd..baab26d8 100644 --- a/Tactility/Include/Tactility/settings/KeyboardSettings.h +++ b/Tactility/Include/Tactility/settings/KeyboardSettings.h @@ -5,11 +5,10 @@ namespace tt::settings::keyboard { struct KeyboardSettings { - bool backlightEnabled; - uint8_t backlightBrightness; // 0-255 - bool trackballEnabled; - bool backlightTimeoutEnabled; - uint32_t backlightTimeoutMs; // Timeout in milliseconds + bool backlightEnabled = true; + uint8_t backlightBrightness = 127; // 0-255 + bool backlightTimeoutEnabled = true; + uint32_t backlightTimeoutMs = 60000; // Timeout in milliseconds }; bool load(KeyboardSettings& settings); diff --git a/Tactility/Include/Tactility/settings/TrackballSettings.h b/Tactility/Include/Tactility/settings/TrackballSettings.h new file mode 100644 index 00000000..ff769a50 --- /dev/null +++ b/Tactility/Include/Tactility/settings/TrackballSettings.h @@ -0,0 +1,27 @@ +#pragma once + +#include + +namespace tt::settings::trackball { + +enum class TrackballMode : uint8_t { + Encoder = 0, // Scroll wheel navigation (default) + Pointer = 1 // Mouse cursor mode +}; + +struct TrackballSettings { + bool trackballEnabled = false; + TrackballMode trackballMode = TrackballMode::Encoder; + uint8_t encoderSensitivity = 1; // Steps per tick (1-10) + uint8_t pointerSensitivity = 10; // Pixels per tick (1-10) +}; + +bool load(TrackballSettings& settings); + +TrackballSettings loadOrGetDefault(); + +TrackballSettings getDefault(); + +bool save(const TrackballSettings& settings); + +} diff --git a/Tactility/Source/Tactility.cpp b/Tactility/Source/Tactility.cpp index e6b0ed4a..6f30c6eb 100644 --- a/Tactility/Source/Tactility.cpp +++ b/Tactility/Source/Tactility.cpp @@ -103,6 +103,9 @@ namespace app { namespace systeminfo { extern const AppManifest manifest; } namespace timedatesettings { extern const AppManifest manifest; } namespace timezone { extern const AppManifest manifest; } +#if defined(ESP_PLATFORM) && defined(CONFIG_TT_DEVICE_LILYGO_TDECK) + namespace trackballsettings { extern const AppManifest manifest; } +#endif namespace usbsettings { extern const AppManifest manifest; } namespace wifiapsettings { extern const AppManifest manifest; } namespace wificonnect { extern const AppManifest manifest; } @@ -146,6 +149,9 @@ static void registerInternalApps() { addAppManifest(app::systeminfo::manifest); addAppManifest(app::timedatesettings::manifest); addAppManifest(app::timezone::manifest); +#if defined(ESP_PLATFORM) && defined(CONFIG_TT_DEVICE_LILYGO_TDECK) + addAppManifest(app::trackballsettings::manifest); +#endif addAppManifest(app::wifiapsettings::manifest); addAppManifest(app::wificonnect::manifest); addAppManifest(app::wifimanage::manifest); diff --git a/Tactility/Source/app/keyboard/KeyboardSettings.cpp b/Tactility/Source/app/keyboard/KeyboardSettings.cpp index 075d1842..89bc1f9a 100644 --- a/Tactility/Source/app/keyboard/KeyboardSettings.cpp +++ b/Tactility/Source/app/keyboard/KeyboardSettings.cpp @@ -13,14 +13,21 @@ namespace keyboardbacklight { bool setBrightness(uint8_t brightness); } -namespace trackball { - void setEnabled(bool enabled); -} - namespace tt::app::keyboardsettings { constexpr auto* TAG = "KeyboardSettings"; +// Shared timeout values: 15s, 30s, 1m, 2m, 5m, Never (0) +static constexpr uint32_t TIMEOUT_VALUES_MS[] = {15000, 30000, 60000, 120000, 300000, 0}; +static constexpr size_t TIMEOUT_DEFAULT_IDX = 2; // 1 minute + +static uint32_t timeoutMsToIndex(uint32_t ms) { + for (size_t i = 0; i < sizeof(TIMEOUT_VALUES_MS) / sizeof(TIMEOUT_VALUES_MS[0]); ++i) { + if (TIMEOUT_VALUES_MS[i] == ms) return static_cast(i); + } + return TIMEOUT_DEFAULT_IDX; +} + static void applyKeyboardBacklight(bool enabled, uint8_t brightness) { keyboardbacklight::setBrightness(enabled ? brightness : 0); } @@ -30,7 +37,6 @@ class KeyboardSettingsApp final : public App { settings::keyboard::KeyboardSettings kbSettings; bool updated = false; lv_obj_t* switchBacklight = nullptr; - lv_obj_t* switchTrackball = nullptr; lv_obj_t* sliderBrightness = nullptr; lv_obj_t* switchTimeoutEnable = nullptr; lv_obj_t* timeoutDropdown = nullptr; @@ -57,14 +63,6 @@ class KeyboardSettingsApp final : public App { } } - static void onTrackballSwitch(lv_event_t* e) { - auto* app = static_cast(lv_event_get_user_data(e)); - bool enabled = lv_obj_has_state(app->switchTrackball, LV_STATE_CHECKED); - app->kbSettings.trackballEnabled = enabled; - app->updated = true; - trackball::setEnabled(enabled); - } - static void onTimeoutEnableSwitch(lv_event_t* e) { auto* app = static_cast(lv_event_get_user_data(e)); bool enabled = lv_obj_has_state(app->switchTimeoutEnable, LV_STATE_CHECKED); @@ -83,17 +81,16 @@ class KeyboardSettingsApp final : public App { auto* app = static_cast(lv_event_get_user_data(event)); auto* dropdown = static_cast(lv_event_get_target(event)); uint32_t idx = lv_dropdown_get_selected(dropdown); - // Map dropdown index to ms: 0=15s,1=30s,2=1m,3=2m,4=5m,5=Never - static const uint32_t values_ms[] = {15000, 30000, 60000, 120000, 300000, 0}; - if (idx < (sizeof(values_ms)/sizeof(values_ms[0]))) { - app->kbSettings.backlightTimeoutMs = values_ms[idx]; - app->updated = true; + if (idx < (sizeof(TIMEOUT_VALUES_MS) / sizeof(TIMEOUT_VALUES_MS[0]))) { + app->kbSettings.backlightTimeoutMs = TIMEOUT_VALUES_MS[idx]; + app->updated = true; } } public: void onShow(AppContext& app, lv_obj_t* parent) override { kbSettings = settings::keyboard::loadOrGetDefault(); + updated = false; lv_obj_set_flex_flow(parent, LV_FLEX_FLOW_COLUMN); lv_obj_set_style_pad_row(parent, 0, LV_STATE_DEFAULT); @@ -136,20 +133,6 @@ public: if (!kbSettings.backlightEnabled) lv_obj_add_state(sliderBrightness, LV_STATE_DISABLED); lv_obj_add_event_cb(sliderBrightness, onBrightnessChanged, LV_EVENT_VALUE_CHANGED, this); - // Trackball toggle - auto* tb_wrapper = lv_obj_create(main_wrapper); - lv_obj_set_size(tb_wrapper, LV_PCT(100), LV_SIZE_CONTENT); - lv_obj_set_style_pad_all(tb_wrapper, 0, LV_STATE_DEFAULT); - lv_obj_set_style_border_width(tb_wrapper, 0, LV_STATE_DEFAULT); - - auto* tb_label = lv_label_create(tb_wrapper); - lv_label_set_text(tb_label, "Trackball"); - lv_obj_align(tb_label, LV_ALIGN_LEFT_MID, 0, 0); - switchTrackball = lv_switch_create(tb_wrapper); - if (kbSettings.trackballEnabled) lv_obj_add_state(switchTrackball, LV_STATE_CHECKED); - lv_obj_align(switchTrackball, LV_ALIGN_RIGHT_MID, 0, 0); - lv_obj_add_event_cb(switchTrackball, onTrackballSwitch, LV_EVENT_VALUE_CHANGED, this); - // Backlight timeout enable auto* to_enable_wrapper = lv_obj_create(main_wrapper); lv_obj_set_size(to_enable_wrapper, LV_PCT(100), LV_SIZE_CONTENT); @@ -181,20 +164,7 @@ public: lv_obj_set_style_border_width(timeoutDropdown, 1, LV_PART_MAIN); lv_obj_add_event_cb(timeoutDropdown, onTimeoutChanged, LV_EVENT_VALUE_CHANGED, this); // Initialize dropdown selection from settings - uint32_t ms = kbSettings.backlightTimeoutMs; - uint32_t idx = 2; // default 1 minute - if (ms == 15000) idx = 0; - else if (ms == 30000) - idx = 1; - else if (ms == 60000) - idx = 2; - else if (ms == 120000) - idx = 3; - else if (ms == 300000) - idx = 4; - else if (ms == 0) - idx = 5; - lv_dropdown_set_selected(timeoutDropdown, idx); + lv_dropdown_set_selected(timeoutDropdown, timeoutMsToIndex(kbSettings.backlightTimeoutMs)); if (!kbSettings.backlightTimeoutEnabled) { lv_obj_add_state(timeoutDropdown, LV_STATE_DISABLED); } @@ -204,6 +174,7 @@ public: if (updated) { const auto copy = kbSettings; getMainDispatcher().dispatch([copy]{ settings::keyboard::save(copy); }); + updated = false; } } }; diff --git a/Tactility/Source/app/trackball/TrackballSettings.cpp b/Tactility/Source/app/trackball/TrackballSettings.cpp new file mode 100644 index 00000000..332060e7 --- /dev/null +++ b/Tactility/Source/app/trackball/TrackballSettings.cpp @@ -0,0 +1,219 @@ +#ifdef ESP_PLATFORM + +#include + +#include +#include +#include + +#include + +// Forward declare driver functions +namespace trackball { + void setEnabled(bool enabled); + enum class Mode { Encoder, Pointer }; + void setMode(Mode mode); + void setEncoderSensitivity(uint8_t sensitivity); + void setPointerSensitivity(uint8_t sensitivity); +} + +namespace tt::app::trackballsettings { + +constexpr auto* TAG = "TrackballSettings"; + +static trackball::Mode toDriverMode(settings::trackball::TrackballMode mode) { + switch (mode) { + case settings::trackball::TrackballMode::Encoder: return trackball::Mode::Encoder; + case settings::trackball::TrackballMode::Pointer: return trackball::Mode::Pointer; + } + return trackball::Mode::Encoder; // default +} + +// Convert settings enum to dropdown index (dropdown order: Encoder=0, Pointer=1) +static uint32_t modeToDropdownIndex(settings::trackball::TrackballMode mode) { + switch (mode) { + case settings::trackball::TrackballMode::Encoder: return 0; + case settings::trackball::TrackballMode::Pointer: return 1; + } + return 0; // default to Encoder +} + +class TrackballSettingsApp final : public App { + + settings::trackball::TrackballSettings tbSettings; + bool updated = false; + lv_obj_t* switchTrackball = nullptr; + lv_obj_t* trackballModeDropdown = nullptr; + lv_obj_t* encoderSensitivitySlider = nullptr; + lv_obj_t* pointerSensitivitySlider = nullptr; + + static void onTrackballSwitch(lv_event_t* e) { + auto* app = static_cast(lv_event_get_user_data(e)); + bool enabled = lv_obj_has_state(app->switchTrackball, LV_STATE_CHECKED); + app->tbSettings.trackballEnabled = enabled; + app->updated = true; + trackball::setEnabled(enabled); + + // Enable/disable controls based on trackball state + if (enabled) { + if (app->trackballModeDropdown) lv_obj_clear_state(app->trackballModeDropdown, LV_STATE_DISABLED); + if (app->encoderSensitivitySlider) lv_obj_clear_state(app->encoderSensitivitySlider, LV_STATE_DISABLED); + if (app->pointerSensitivitySlider) lv_obj_clear_state(app->pointerSensitivitySlider, LV_STATE_DISABLED); + } else { + if (app->trackballModeDropdown) lv_obj_add_state(app->trackballModeDropdown, LV_STATE_DISABLED); + if (app->encoderSensitivitySlider) lv_obj_add_state(app->encoderSensitivitySlider, LV_STATE_DISABLED); + if (app->pointerSensitivitySlider) lv_obj_add_state(app->pointerSensitivitySlider, LV_STATE_DISABLED); + } + } + + static void onTrackballModeChanged(lv_event_t* e) { + auto* app = static_cast(lv_event_get_user_data(e)); + uint32_t selected = lv_dropdown_get_selected(app->trackballModeDropdown); + + // Validate selection matches expected enum values (dropdown order: Encoder=0, Pointer=1) + settings::trackball::TrackballMode mode; + switch (selected) { + case 0: mode = settings::trackball::TrackballMode::Encoder; break; + case 1: mode = settings::trackball::TrackballMode::Pointer; break; + default: return; // Invalid selection, ignore + } + + app->tbSettings.trackballMode = mode; + app->updated = true; + + // Apply mode change immediately + trackball::setMode(toDriverMode(mode)); + } + + static void onEncoderSensitivityChanged(lv_event_t* e) { + auto* app = static_cast(lv_event_get_user_data(e)); + int32_t value = lv_slider_get_value(app->encoderSensitivitySlider); + app->tbSettings.encoderSensitivity = static_cast(value); + app->updated = true; + + // Apply immediately + trackball::setEncoderSensitivity(static_cast(value)); + } + + static void onPointerSensitivityChanged(lv_event_t* e) { + auto* app = static_cast(lv_event_get_user_data(e)); + int32_t value = lv_slider_get_value(app->pointerSensitivitySlider); + app->tbSettings.pointerSensitivity = static_cast(value); + app->updated = true; + + // Apply immediately + trackball::setPointerSensitivity(static_cast(value)); + } + +public: + void onShow(AppContext& app, lv_obj_t* parent) override { + tbSettings = settings::trackball::loadOrGetDefault(); + auto ui_scale = hal::getConfiguration()->uiScale; + updated = false; + + lv_obj_set_flex_flow(parent, LV_FLEX_FLOW_COLUMN); + lv_obj_set_style_pad_row(parent, 0, LV_STATE_DEFAULT); + + lv_obj_t* toolbar = lvgl::toolbar_create(parent, app); + + switchTrackball = lvgl::toolbar_add_switch_action(toolbar); + lv_obj_add_event_cb(switchTrackball, onTrackballSwitch, LV_EVENT_VALUE_CHANGED, this); + if (tbSettings.trackballEnabled) lv_obj_add_state(switchTrackball, LV_STATE_CHECKED); + + auto* main_wrapper = lv_obj_create(parent); + lv_obj_set_flex_flow(main_wrapper, LV_FLEX_FLOW_COLUMN); + lv_obj_set_width(main_wrapper, LV_PCT(100)); + lv_obj_set_flex_grow(main_wrapper, 1); + + // Trackball mode dropdown + auto* tb_mode_wrapper = lv_obj_create(main_wrapper); + lv_obj_set_size(tb_mode_wrapper, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_style_pad_all(tb_mode_wrapper, 0, LV_STATE_DEFAULT); + lv_obj_set_style_border_width(tb_mode_wrapper, 0, LV_STATE_DEFAULT); + + auto* tb_mode_label = lv_label_create(tb_mode_wrapper); + lv_label_set_text(tb_mode_label, "Mode"); + lv_obj_align(tb_mode_label, LV_ALIGN_LEFT_MID, 0, 0); + + trackballModeDropdown = lv_dropdown_create(tb_mode_wrapper); + lv_dropdown_set_options(trackballModeDropdown, "Encoder\nPointer"); + lv_obj_align(trackballModeDropdown, LV_ALIGN_RIGHT_MID, 0, 0); + lv_obj_set_style_border_color(trackballModeDropdown, lv_color_hex(0xFAFAFA), LV_PART_MAIN); + lv_obj_set_style_border_width(trackballModeDropdown, 1, LV_PART_MAIN); + lv_dropdown_set_selected(trackballModeDropdown, modeToDropdownIndex(tbSettings.trackballMode)); + lv_obj_add_event_cb(trackballModeDropdown, onTrackballModeChanged, LV_EVENT_VALUE_CHANGED, this); + + // Disable dropdown if trackball is disabled + if (!tbSettings.trackballEnabled) { + lv_obj_add_state(trackballModeDropdown, LV_STATE_DISABLED); + } + + // Encoder sensitivity slider + auto* enc_sens_wrapper = lv_obj_create(main_wrapper); + lv_obj_set_size(enc_sens_wrapper, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_style_pad_hor(enc_sens_wrapper, 0, LV_STATE_DEFAULT); + lv_obj_set_style_border_width(enc_sens_wrapper, 0, LV_STATE_DEFAULT); + if (ui_scale != hal::UiScale::Smallest) { + lv_obj_set_style_pad_ver(enc_sens_wrapper, 4, LV_STATE_DEFAULT); + } + + auto* enc_sens_label = lv_label_create(enc_sens_wrapper); + lv_label_set_text(enc_sens_label, "Encoder Speed"); + lv_obj_align(enc_sens_label, LV_ALIGN_LEFT_MID, 0, 0); + + encoderSensitivitySlider = lv_slider_create(enc_sens_wrapper); + lv_slider_set_range(encoderSensitivitySlider, 1, 10); + lv_slider_set_value(encoderSensitivitySlider, tbSettings.encoderSensitivity, LV_ANIM_OFF); + lv_obj_set_width(encoderSensitivitySlider, LV_PCT(50)); + lv_obj_align(encoderSensitivitySlider, LV_ALIGN_RIGHT_MID, 0, 0); + lv_obj_add_event_cb(encoderSensitivitySlider, onEncoderSensitivityChanged, LV_EVENT_VALUE_CHANGED, this); + + if (!tbSettings.trackballEnabled) { + lv_obj_add_state(encoderSensitivitySlider, LV_STATE_DISABLED); + } + + // Pointer sensitivity slider + auto* ptr_sens_wrapper = lv_obj_create(main_wrapper); + lv_obj_set_size(ptr_sens_wrapper, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_style_pad_hor(ptr_sens_wrapper, 0, LV_STATE_DEFAULT); + lv_obj_set_style_border_width(ptr_sens_wrapper, 0, LV_STATE_DEFAULT); + if (ui_scale != hal::UiScale::Smallest) { + lv_obj_set_style_pad_ver(ptr_sens_wrapper, 4, LV_STATE_DEFAULT); + } + + auto* ptr_sens_label = lv_label_create(ptr_sens_wrapper); + lv_label_set_text(ptr_sens_label, "Pointer Speed"); + lv_obj_align(ptr_sens_label, LV_ALIGN_LEFT_MID, 0, 0); + + pointerSensitivitySlider = lv_slider_create(ptr_sens_wrapper); + lv_slider_set_range(pointerSensitivitySlider, 1, 10); + lv_slider_set_value(pointerSensitivitySlider, tbSettings.pointerSensitivity, LV_ANIM_OFF); + lv_obj_set_width(pointerSensitivitySlider, LV_PCT(50)); + lv_obj_align(pointerSensitivitySlider, LV_ALIGN_RIGHT_MID, 0, 0); + lv_obj_add_event_cb(pointerSensitivitySlider, onPointerSensitivityChanged, LV_EVENT_VALUE_CHANGED, this); + + if (!tbSettings.trackballEnabled) { + lv_obj_add_state(pointerSensitivitySlider, LV_STATE_DISABLED); + } + } + + void onHide(TT_UNUSED AppContext& app) override { + if (updated) { + const auto copy = tbSettings; + getMainDispatcher().dispatch([copy]{ settings::trackball::save(copy); }); + updated = false; + } + } +}; + +extern const AppManifest manifest = { + .appId = "TrackballSettings", + .appName = "Trackball", + .appIcon = TT_ASSETS_APP_ICON_SETTINGS, + .appCategory = Category::Settings, + .createApp = create +}; + +} + +#endif diff --git a/Tactility/Source/settings/KeyboardSettings.cpp b/Tactility/Source/settings/KeyboardSettings.cpp index 2f7a2697..af2811a6 100644 --- a/Tactility/Source/settings/KeyboardSettings.cpp +++ b/Tactility/Source/settings/KeyboardSettings.cpp @@ -9,7 +9,6 @@ namespace tt::settings::keyboard { constexpr auto* SETTINGS_FILE = "/data/settings/keyboard.properties"; constexpr auto* KEY_BACKLIGHT_ENABLED = "backlightEnabled"; constexpr auto* KEY_BACKLIGHT_BRIGHTNESS = "backlightBrightness"; -constexpr auto* KEY_TRACKBALL_ENABLED = "trackballEnabled"; constexpr auto* KEY_BACKLIGHT_TIMEOUT_ENABLED = "backlightTimeoutEnabled"; constexpr auto* KEY_BACKLIGHT_TIMEOUT_MS = "backlightTimeoutMs"; @@ -21,15 +20,13 @@ bool load(KeyboardSettings& settings) { auto bl_enabled = map.find(KEY_BACKLIGHT_ENABLED); auto bl_brightness = map.find(KEY_BACKLIGHT_BRIGHTNESS); - auto tb_enabled = map.find(KEY_TRACKBALL_ENABLED); auto bl_timeout_enabled = map.find(KEY_BACKLIGHT_TIMEOUT_ENABLED); auto bl_timeout_ms = map.find(KEY_BACKLIGHT_TIMEOUT_MS); settings.backlightEnabled = (bl_enabled != map.end()) ? (bl_enabled->second == "1" || bl_enabled->second == "true" || bl_enabled->second == "True") : true; settings.backlightBrightness = (bl_brightness != map.end()) ? static_cast(std::stoi(bl_brightness->second)) : 127; - settings.trackballEnabled = (tb_enabled != map.end()) ? (tb_enabled->second == "1" || tb_enabled->second == "true" || tb_enabled->second == "True") : true; settings.backlightTimeoutEnabled = (bl_timeout_enabled != map.end()) ? (bl_timeout_enabled->second == "1" || bl_timeout_enabled->second == "true" || bl_timeout_enabled->second == "True") : true; - settings.backlightTimeoutMs = (bl_timeout_ms != map.end()) ? static_cast(std::stoul(bl_timeout_ms->second)) : 30000; // Default 30 seconds + settings.backlightTimeoutMs = (bl_timeout_ms != map.end()) ? static_cast(std::stoul(bl_timeout_ms->second)) : 60000; // Default 60 seconds return true; } @@ -38,7 +35,6 @@ KeyboardSettings getDefault() { return KeyboardSettings{ .backlightEnabled = true, .backlightBrightness = 127, - .trackballEnabled = true, .backlightTimeoutEnabled = true, .backlightTimeoutMs = 60000 // 60 seconds default }; @@ -56,7 +52,6 @@ bool save(const KeyboardSettings& settings) { std::map map; map[KEY_BACKLIGHT_ENABLED] = settings.backlightEnabled ? "1" : "0"; map[KEY_BACKLIGHT_BRIGHTNESS] = std::to_string(settings.backlightBrightness); - map[KEY_TRACKBALL_ENABLED] = settings.trackballEnabled ? "1" : "0"; map[KEY_BACKLIGHT_TIMEOUT_ENABLED] = settings.backlightTimeoutEnabled ? "1" : "0"; map[KEY_BACKLIGHT_TIMEOUT_MS] = std::to_string(settings.backlightTimeoutMs); return file::savePropertiesFile(SETTINGS_FILE, map); diff --git a/Tactility/Source/settings/TrackballSettings.cpp b/Tactility/Source/settings/TrackballSettings.cpp new file mode 100644 index 00000000..7478b948 --- /dev/null +++ b/Tactility/Source/settings/TrackballSettings.cpp @@ -0,0 +1,86 @@ +#include +#include + +#include +#include +#include + +namespace tt::settings::trackball { + +constexpr auto* SETTINGS_FILE = "/data/settings/trackball.properties"; +constexpr auto* KEY_TRACKBALL_ENABLED = "trackballEnabled"; +constexpr auto* KEY_TRACKBALL_MODE = "trackballMode"; +constexpr auto* KEY_ENCODER_SENSITIVITY = "encoderSensitivity"; +constexpr auto* KEY_POINTER_SENSITIVITY = "pointerSensitivity"; + +constexpr uint8_t MIN_ENCODER_SENSITIVITY = 1; +constexpr uint8_t MAX_ENCODER_SENSITIVITY = 10; +constexpr uint8_t MIN_POINTER_SENSITIVITY = 1; +constexpr uint8_t MAX_POINTER_SENSITIVITY = 10; + +bool load(TrackballSettings& settings) { + std::map map; + if (!file::loadPropertiesFile(SETTINGS_FILE, map)) { + return false; + } + + auto tb_enabled = map.find(KEY_TRACKBALL_ENABLED); + auto tb_mode = map.find(KEY_TRACKBALL_MODE); + auto enc_sens = map.find(KEY_ENCODER_SENSITIVITY); + auto ptr_sens = map.find(KEY_POINTER_SENSITIVITY); + + // Safe integer parsing without exceptions + auto safeParseUint8 = [](const std::string& str, uint8_t defaultVal) -> uint8_t { + if (str.empty()) return defaultVal; + unsigned int val = 0; + for (char c : str) { + if (c < '0' || c > '9') return defaultVal; + if (val > 25) return defaultVal; // Early exit: val*10+9 would exceed 255 + val = val * 10 + (c - '0'); + if (val > 255) return defaultVal; + } + return static_cast(val); + }; + + auto isTrueValue = [](const std::string& s) { + return s == "1" || s == "true" || s == "True" || s == "TRUE"; + }; + settings.trackballEnabled = (tb_enabled != map.end()) ? isTrueValue(tb_enabled->second) : true; + settings.trackballMode = (tb_mode != map.end() && tb_mode->second == "1") ? TrackballMode::Pointer : TrackballMode::Encoder; + settings.encoderSensitivity = (enc_sens != map.end()) ? safeParseUint8(enc_sens->second, MIN_ENCODER_SENSITIVITY) : MIN_ENCODER_SENSITIVITY; + settings.pointerSensitivity = (ptr_sens != map.end()) ? safeParseUint8(ptr_sens->second, MAX_POINTER_SENSITIVITY) : MAX_POINTER_SENSITIVITY; + + // Clamp values to valid ranges + settings.encoderSensitivity = std::clamp(settings.encoderSensitivity, MIN_ENCODER_SENSITIVITY, MAX_ENCODER_SENSITIVITY); + settings.pointerSensitivity = std::clamp(settings.pointerSensitivity, MIN_POINTER_SENSITIVITY, MAX_POINTER_SENSITIVITY); + + return true; +} + +TrackballSettings getDefault() { + return TrackballSettings{ + .trackballEnabled = true, + .trackballMode = TrackballMode::Encoder, + .encoderSensitivity = MIN_ENCODER_SENSITIVITY, + .pointerSensitivity = MAX_POINTER_SENSITIVITY + }; +} + +TrackballSettings loadOrGetDefault() { + TrackballSettings s; + if (!load(s)) { + s = getDefault(); + } + return s; +} + +bool save(const TrackballSettings& settings) { + std::map map; + map[KEY_TRACKBALL_ENABLED] = settings.trackballEnabled ? "1" : "0"; + map[KEY_TRACKBALL_MODE] = (settings.trackballMode == TrackballMode::Pointer) ? "1" : "0"; + map[KEY_ENCODER_SENSITIVITY] = std::to_string(std::clamp(settings.encoderSensitivity, MIN_ENCODER_SENSITIVITY, MAX_ENCODER_SENSITIVITY)); + map[KEY_POINTER_SENSITIVITY] = std::to_string(std::clamp(settings.pointerSensitivity, MIN_POINTER_SENSITIVITY, MAX_POINTER_SENSITIVITY)); + return file::savePropertiesFile(SETTINGS_FILE, map); +} + +} From 0d16eb606f7ab2af0b6bb91bff88c96572b6a861 Mon Sep 17 00:00:00 2001 From: Shadowtrance Date: Sat, 24 Jan 2026 21:42:49 +1000 Subject: [PATCH 03/10] ESP-NOW chat & P4 fixes (#454) * Espnow chat fix Fixes chat app not appearing and coexistence with wifi STA mode. Wifi OFF and obviously not connected, espnow starts. Wifi ON and connected, espnow starts. Wifi ON and NOT connected, espnow starts. * Fix P4 build --- Firmware/Kconfig | 7 -- .../Include/Tactility/service/espnow/EspNow.h | 4 +- Tactility/Source/Tactility.cpp | 8 +- Tactility/Source/app/chat/ChatApp.cpp | 4 +- Tactility/Source/service/espnow/EspNow.cpp | 4 +- .../Source/service/espnow/EspNowService.cpp | 4 +- .../Source/service/espnow/EspNowWifi.cpp | 102 +++++++----------- 7 files changed, 49 insertions(+), 84 deletions(-) diff --git a/Firmware/Kconfig b/Firmware/Kconfig index 1aded79f..649bde91 100644 --- a/Firmware/Kconfig +++ b/Firmware/Kconfig @@ -96,11 +96,4 @@ menu "Tactility App" help The minimum time to show the splash screen in milliseconds. When set to 0, startup will continue to desktop as soon as boot operations are finished. - - config TT_WIFI_ENABLED - bool "Enable WiFi Support" - default n - help - Enable WiFi support for Tactility. - Uses native WiFi on ESP32/ESP32-S3 or ESP-Hosted on ESP32-P4. endmenu diff --git a/Tactility/Include/Tactility/service/espnow/EspNow.h b/Tactility/Include/Tactility/service/espnow/EspNow.h index 80cbd76d..429a5664 100644 --- a/Tactility/Include/Tactility/service/espnow/EspNow.h +++ b/Tactility/Include/Tactility/service/espnow/EspNow.h @@ -4,7 +4,7 @@ #include #endif -#ifdef CONFIG_ESP_WIFI_ENABLED +#if defined(CONFIG_SOC_WIFI_SUPPORTED) && !defined(CONFIG_SLAVE_SOC_WIFI_SUPPORTED) #include #include @@ -56,4 +56,4 @@ void unsubscribeReceiver(ReceiverSubscription subscription); } -#endif // ESP_PLATFORM \ No newline at end of file +#endif // CONFIG_SOC_WIFI_SUPPORTED && !CONFIG_SLAVE_SOC_WIFI_SUPPORTED \ No newline at end of file diff --git a/Tactility/Source/Tactility.cpp b/Tactility/Source/Tactility.cpp index 6f30c6eb..97b28cb0 100644 --- a/Tactility/Source/Tactility.cpp +++ b/Tactility/Source/Tactility.cpp @@ -45,7 +45,7 @@ namespace service { #ifdef ESP_PLATFORM namespace development { extern const ServiceManifest manifest; } #endif -#if defined(CONFIG_TT_WIFI_ENABLED) && !defined(CONFIG_ESP_WIFI_REMOTE_ENABLED) +#if defined(CONFIG_SOC_WIFI_SUPPORTED) && !defined(CONFIG_SLAVE_SOC_WIFI_SUPPORTED) namespace espnow { extern const ServiceManifest manifest; } #endif // Secondary (UI) @@ -79,7 +79,7 @@ namespace app { namespace applist { extern const AppManifest manifest; } namespace appsettings { extern const AppManifest manifest; } namespace boot { extern const AppManifest manifest; } -#if defined(CONFIG_TT_WIFI_ENABLED) && !defined(CONFIG_ESP_WIFI_REMOTE_ENABLED) +#if defined(CONFIG_SOC_WIFI_SUPPORTED) && !defined(CONFIG_SLAVE_SOC_WIFI_SUPPORTED) namespace chat { extern const AppManifest manifest; } #endif namespace development { extern const AppManifest manifest; } @@ -167,7 +167,7 @@ static void registerInternalApps() { addAppManifest(app::screenshot::manifest); #endif -#if defined(CONFIG_TT_WIFI_ENABLED) && !defined(CONFIG_ESP_WIFI_REMOTE_ENABLED) +#if defined(CONFIG_SOC_WIFI_SUPPORTED) && !defined(CONFIG_SLAVE_SOC_WIFI_SUPPORTED) addAppManifest(app::chat::manifest); #endif @@ -272,7 +272,7 @@ static void registerAndStartPrimaryServices() { addService(service::development::manifest); #endif -#if defined(CONFIG_TT_WIFI_ENABLED) && !defined(CONFIG_ESP_WIFI_REMOTE_ENABLED) +#if defined(CONFIG_SOC_WIFI_SUPPORTED) && !defined(CONFIG_SLAVE_SOC_WIFI_SUPPORTED) addService(service::espnow::manifest); #endif #ifdef ESP_PLATFORM diff --git a/Tactility/Source/app/chat/ChatApp.cpp b/Tactility/Source/app/chat/ChatApp.cpp index f678cc1e..aa349748 100644 --- a/Tactility/Source/app/chat/ChatApp.cpp +++ b/Tactility/Source/app/chat/ChatApp.cpp @@ -2,7 +2,7 @@ #include #endif -#if defined(CONFIG_TT_WIFI_ENABLED) && !defined(CONFIG_ESP_WIFI_REMOTE_ENABLED) +#if defined(CONFIG_SOC_WIFI_SUPPORTED) && !defined(CONFIG_SLAVE_SOC_WIFI_SUPPORTED) #include #include @@ -149,4 +149,4 @@ extern const AppManifest manifest = { } -#endif +#endif // CONFIG_SOC_WIFI_SUPPORTED && !CONFIG_SLAVE_SOC_WIFI_SUPPORTED diff --git a/Tactility/Source/service/espnow/EspNow.cpp b/Tactility/Source/service/espnow/EspNow.cpp index 015c7a56..42c934e3 100644 --- a/Tactility/Source/service/espnow/EspNow.cpp +++ b/Tactility/Source/service/espnow/EspNow.cpp @@ -2,7 +2,7 @@ #include #endif -#if defined(CONFIG_TT_WIFI_ENABLED) && !defined(CONFIG_ESP_WIFI_REMOTE_ENABLED) +#if defined(CONFIG_SOC_WIFI_SUPPORTED) && !defined(CONFIG_SLAVE_SOC_WIFI_SUPPORTED) #include #include @@ -81,4 +81,4 @@ void unsubscribeReceiver(ReceiverSubscription subscription) { } -#endif // ESP_PLATFORM +#endif // CONFIG_SOC_WIFI_SUPPORTED && !CONFIG_SLAVE_SOC_WIFI_SUPPORTED diff --git a/Tactility/Source/service/espnow/EspNowService.cpp b/Tactility/Source/service/espnow/EspNowService.cpp index 86c6416c..476b1b7c 100644 --- a/Tactility/Source/service/espnow/EspNowService.cpp +++ b/Tactility/Source/service/espnow/EspNowService.cpp @@ -2,7 +2,7 @@ #include #endif -#if defined(CONFIG_TT_WIFI_ENABLED) && !defined(CONFIG_ESP_WIFI_REMOTE_ENABLED) +#if defined(CONFIG_SOC_WIFI_SUPPORTED) && !defined(CONFIG_SLAVE_SOC_WIFI_SUPPORTED) #include #include @@ -208,4 +208,4 @@ extern const ServiceManifest manifest = { } -#endif // ESP_PLATFORM +#endif // CONFIG_SOC_WIFI_SUPPORTED && !CONFIG_SLAVE_SOC_WIFI_SUPPORTED diff --git a/Tactility/Source/service/espnow/EspNowWifi.cpp b/Tactility/Source/service/espnow/EspNowWifi.cpp index 81b5af7d..806e3d89 100644 --- a/Tactility/Source/service/espnow/EspNowWifi.cpp +++ b/Tactility/Source/service/espnow/EspNowWifi.cpp @@ -2,9 +2,8 @@ #include #endif -#if defined(CONFIG_TT_WIFI_ENABLED) && !defined(CONFIG_ESP_WIFI_REMOTE_ENABLED) +#if defined(CONFIG_SOC_WIFI_SUPPORTED) && !defined(CONFIG_SLAVE_SOC_WIFI_SUPPORTED) -#include #include #include #include @@ -15,74 +14,47 @@ namespace tt::service::espnow { static const auto LOGGER = Logger("EspNowService"); - -static bool disableWifiService() { - auto wifi_state = wifi::getRadioState(); - if (wifi_state != wifi::RadioState::Off && wifi_state != wifi::RadioState::OffPending) { - wifi::setEnabled(false); - } - - if (wifi::getRadioState() == wifi::RadioState::Off) { - return true; - } else { - TickType_t timeout_time = kernel::getTicks() + kernel::millisToTicks(2000); - while (kernel::getTicks() < timeout_time && wifi::getRadioState() != wifi::RadioState::Off) { - kernel::delayTicks(50); - } - - return wifi::getRadioState() == wifi::RadioState::Off; - } -} +static bool wifiStartedByEspNow = false; bool initWifi(const EspNowConfig& config) { - // ESP-NOW can coexist with WiFi STA mode; only preserve WiFi state if already connected auto wifi_state = wifi::getRadioState(); - bool wifi_was_connected = (wifi_state == wifi::RadioState::ConnectionActive); - - // If WiFi is off or in other states, temporarily disable it to initialize ESP-NOW - // If WiFi is already connected, keep it running and just add ESP-NOW on top - if (!wifi_was_connected && wifi_state != wifi::RadioState::Off && wifi_state != wifi::RadioState::OffPending) { - if (!disableWifiService()) { - LOGGER.error("Failed to disable wifi"); - return false; - } - } + bool wifi_already_running = (wifi_state != wifi::RadioState::Off && wifi_state != wifi::RadioState::OffPending); wifi_mode_t mode; if (config.mode == Mode::Station) { - // Use STA mode to allow coexistence with normal WiFi connection mode = wifi_mode_t::WIFI_MODE_STA; } else { mode = wifi_mode_t::WIFI_MODE_AP; } - // Only reinitialize WiFi if it's not already running - if (wifi::getRadioState() == wifi::RadioState::Off) { - wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); - if (esp_wifi_init(&cfg) != ESP_OK) { - LOGGER.error("esp_wifi_init() failed"); - return false; - } + // Only initialize WiFi if it's not already running; ESP-NOW coexists with STA mode + wifiStartedByEspNow = !wifi_already_running; + if (wifiStartedByEspNow) { + wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); + if (esp_wifi_init(&cfg) != ESP_OK) { + LOGGER.error("esp_wifi_init() failed"); + return false; + } - if (esp_wifi_set_storage(WIFI_STORAGE_RAM) != ESP_OK) { - LOGGER.error("esp_wifi_set_storage() failed"); - return false; - } + if (esp_wifi_set_storage(WIFI_STORAGE_RAM) != ESP_OK) { + LOGGER.error("esp_wifi_set_storage() failed"); + return false; + } - if (esp_wifi_set_mode(mode) != ESP_OK) { - LOGGER.error("esp_wifi_set_mode() failed"); - return false; - } + if (esp_wifi_set_mode(mode) != ESP_OK) { + LOGGER.error("esp_wifi_set_mode() failed"); + return false; + } - if (esp_wifi_start() != ESP_OK) { - LOGGER.error("esp_wifi_start() failed"); - return false; - } - } + if (esp_wifi_start() != ESP_OK) { + LOGGER.error("esp_wifi_start() failed"); + return false; + } - if (esp_wifi_set_channel(config.channel, WIFI_SECOND_CHAN_NONE) != ESP_OK) { - LOGGER.error("esp_wifi_set_channel() failed"); - return false; + if (esp_wifi_set_channel(config.channel, WIFI_SECOND_CHAN_NONE) != ESP_OK) { + LOGGER.error("esp_wifi_set_channel() failed"); + return false; + } } if (config.longRange) { @@ -98,22 +70,22 @@ bool initWifi(const EspNowConfig& config) { } } - LOGGER.info("WiFi initialized for ESP-NOW (preserved existing connection: {})", wifi_was_connected ? "yes" : "no"); + LOGGER.info("WiFi initialized for ESP-NOW (wifi already running: {})", wifi_already_running ? "yes" : "no"); return true; } bool deinitWifi() { - // Don't deinitialize WiFi completely - just disable ESP-NOW - // This allows normal WiFi connection to continue - // Only stop/deinit if WiFi was originally off - - // Since we're only using WiFi for ESP-NOW, we can safely keep it in a minimal state - // or shut it down. For now, keep it running to support STA + ESP-NOW coexistence. - - LOGGER.info("ESP-NOW WiFi deinitialized (WiFi service continues independently)"); + if (wifiStartedByEspNow) { + esp_wifi_stop(); + esp_wifi_deinit(); + wifiStartedByEspNow = false; + LOGGER.info("WiFi stopped (was started by ESP-NOW)"); + } else { + LOGGER.info("WiFi left running (managed by WiFi service)"); + } return true; } } // namespace tt::service::espnow -#endif // ESP_PLATFORM +#endif // CONFIG_SOC_WIFI_SUPPORTED && !CONFIG_SLAVE_SOC_WIFI_SUPPORTED From 4b6ed871a9b67e84d26630090e9e3a13a10e4a68 Mon Sep 17 00:00:00 2001 From: Ken Van Hoeylandt Date: Sat, 24 Jan 2026 15:47:11 +0100 Subject: [PATCH 04/10] Implemented TactilityKernel and DevicetreeCompiler, updated licenses & copyrights (#452) **New features** - Created a devicetree DTS and YAML parser in Python - Created new modules: - TactilityKernel (LGPL v3.0 license) - Platforms/PlatformEsp32 (LGPL v3.0 license) - Platforms/PlatformPosix (LGPL v3.0 license) - Tests/TactilityKernelTests Most boards have a placeholder DTS file, while T-Lora Pager has a few devices attached. **Licenses** Clarified licenses and copyrights better. - Add explanation about the intent behind them. - Added explanation about licenses for past and future subprojects - Added more details explanations with regards to the logo usage - Copied licenses to subprojects to make it more explicit --- .github/workflows/tests.yml | 8 +- Buildscripts/DevicetreeCompiler/.gitignore | 4 + .../DevicetreeCompiler/LICENSE-Apache-2.0.md | 0 Buildscripts/DevicetreeCompiler/compile.py | 28 + .../source/binding_files.py | 19 + .../source/binding_parser.py | 57 ++ .../DevicetreeCompiler/source/config.py | 50 ++ .../DevicetreeCompiler/source/files.py | 9 + .../DevicetreeCompiler/source/generator.py | 217 ++++++ .../DevicetreeCompiler/source/grammar.lark | 46 ++ .../DevicetreeCompiler/source/main.py | 46 ++ .../DevicetreeCompiler/source/models.py | 42 ++ .../DevicetreeCompiler/source/printing.py | 20 + .../DevicetreeCompiler/source/transformer.py | 67 ++ Buildscripts/release-sdk.sh | 48 +- CMakeLists.txt | 21 +- Devices/LICENSE-GPL-3.0.md | 675 ++++++++++++++++++ Devices/btt-panda-touch/Source/Drivers.cpp | 7 + Devices/btt-panda-touch/devicetree.yaml | 3 + Devices/cyd-2432s024c/Source/Drivers.cpp | 7 + Devices/cyd-2432s024c/devicetree.yaml | 3 + Devices/cyd-2432s028r/Source/Drivers.cpp | 7 + Devices/cyd-2432s028r/devicetree.yaml | 3 + Devices/cyd-2432s028rv3/Source/Drivers.cpp | 7 + Devices/cyd-2432s028rv3/devicetree.yaml | 3 + Devices/cyd-2432s032c/Source/Drivers.cpp | 7 + Devices/cyd-2432s032c/devicetree.yaml | 3 + Devices/cyd-4848s040c/Source/Drivers.cpp | 7 + Devices/cyd-4848s040c/devicetree.yaml | 3 + Devices/cyd-8048s043c/Source/Drivers.cpp | 7 + Devices/cyd-8048s043c/devicetree.yaml | 3 + Devices/cyd-e32r28t/Source/Drivers.cpp | 7 + Devices/cyd-e32r28t/devicetree.yaml | 3 + Devices/cyd-e32r32p/Source/Drivers.cpp | 7 + Devices/cyd-e32r32p/devicetree.yaml | 3 + .../Source/Drivers.cpp | 7 + .../devicetree.yaml | 3 + .../Source/Drivers.cpp | 7 + .../devicetree.yaml | 3 + .../Source/Drivers.cpp | 7 + .../devicetree.yaml | 3 + .../Source/Drivers.cpp | 7 + .../devicetree.yaml | 3 + .../Source/Drivers.cpp | 7 + .../devicetree.yaml | 3 + .../Source/Drivers.cpp | 7 + .../devicetree.yaml | 3 + Devices/generic-esp32/Source/Drivers.cpp | 7 + Devices/generic-esp32/devicetree.yaml | 3 + Devices/generic-esp32c6/Source/Drivers.cpp | 7 + Devices/generic-esp32c6/devicetree.yaml | 3 + Devices/generic-esp32p4/Source/Drivers.cpp | 7 + Devices/generic-esp32p4/devicetree.yaml | 3 + Devices/generic-esp32s3/Source/Drivers.cpp | 7 + Devices/generic-esp32s3/devicetree.yaml | 3 + .../guition-jc1060p470ciwy/Source/Drivers.cpp | 7 + .../guition-jc1060p470ciwy/devicetree.yaml | 3 + .../guition-jc2432w328c/Source/Drivers.cpp | 7 + Devices/guition-jc2432w328c/devicetree.yaml | 3 + .../guition-jc8048w550c/Source/Drivers.cpp | 7 + Devices/guition-jc8048w550c/devicetree.yaml | 3 + .../heltec-wifi-lora-32-v3/Source/Drivers.cpp | 7 + .../heltec-wifi-lora-32-v3/devicetree.yaml | 3 + Devices/lilygo-tdeck/Source/Drivers.cpp | 7 + Devices/lilygo-tdeck/devicetree.yaml | 3 + Devices/lilygo-tdisplay-s3/Source/Drivers.cpp | 7 + Devices/lilygo-tdisplay-s3/devicetree.yaml | 3 + Devices/lilygo-tdisplay/Source/Drivers.cpp | 7 + Devices/lilygo-tdisplay/devicetree.yaml | 3 + Devices/lilygo-tdongle-s3/Source/Drivers.cpp | 7 + Devices/lilygo-tdongle-s3/devicetree.yaml | 3 + Devices/lilygo-tlora-pager/CMakeLists.txt | 2 +- Devices/lilygo-tlora-pager/Source/Drivers.cpp | 10 + .../Source/bindings/tlora_pager.h | 15 + .../Source/drivers/Register.cpp | 10 + .../Source/drivers/TloraPager.cpp | 27 + .../Source/drivers/TloraPager.h | 11 + Devices/lilygo-tlora-pager/devicetree.yaml | 4 + .../lilygo-tlora-pager/lilygo,tlora-pager.dts | 23 + .../lilygo,tlora-pager.yaml | 5 + .../m5stack-cardputer-adv/Source/Drivers.cpp | 7 + Devices/m5stack-cardputer-adv/devicetree.yaml | 3 + Devices/m5stack-cardputer/Source/Drivers.cpp | 7 + Devices/m5stack-cardputer/devicetree.yaml | 3 + Devices/m5stack-core2/Source/Drivers.cpp | 7 + Devices/m5stack-core2/devicetree.yaml | 3 + Devices/m5stack-cores3/Source/Drivers.cpp | 7 + Devices/m5stack-cores3/devicetree.yaml | 3 + .../m5stack-stickc-plus/Source/Drivers.cpp | 7 + Devices/m5stack-stickc-plus/devicetree.yaml | 3 + .../m5stack-stickc-plus2/Source/Drivers.cpp | 7 + Devices/m5stack-stickc-plus2/devicetree.yaml | 3 + Devices/placeholder.dts | 8 + Devices/simulator/Source/Drivers.cpp | 7 + Devices/simulator/devicetree.yaml | 4 + Devices/simulator/simulator.dts | 8 + Devices/unphone/Source/Drivers.cpp | 7 + Devices/unphone/devicetree.yaml | 3 + .../Source/Drivers.cpp | 7 + .../waveshare-esp32-s3-geek/devicetree.yaml | 3 + .../waveshare-s3-lcd-13/Source/Drivers.cpp | 7 + Devices/waveshare-s3-lcd-13/devicetree.yaml | 3 + .../Source/Drivers.cpp | 7 + .../devicetree.yaml | 3 + .../Source/Drivers.cpp | 7 + .../devicetree.yaml | 3 + .../Source/Drivers.cpp | 7 + .../waveshare-s3-touch-lcd-43/devicetree.yaml | 3 + .../Source/Drivers.cpp | 7 + .../devicetree.yaml | 3 + Documentation/LICENSE-Apache-2.0.md | 195 +++++ Documentation/LICENSE-GPL-3.0.md | 675 ++++++++++++++++++ Documentation/LICENSE-LGPL-3.0.md | 157 ++++ Documentation/ideas.md | 1 + Documentation/license-tactilitykernel.md | 157 ++++ Firmware/.gitignore | 1 + Firmware/CMakeLists.txt | 52 +- Firmware/Source/Main.cpp | 12 + LICENSE.md | 76 +- Libraries/lv_screenshot/CMakeLists.txt | 4 - Libraries/minmea/CMakeLists.txt | 4 - Platforms/LICENSE-LGPL-3.0.md | 157 ++++ .../Bindings/espressif,esp32-gpio.yaml | 5 + .../Bindings/espressif,esp32-i2c.yaml | 12 + Platforms/PlatformEsp32/CMakeLists.txt | 20 + .../Include/Tactility/bindings/esp32_gpio.h | 14 + .../Include/Tactility/bindings/esp32_i2c.h | 14 + .../Include/Tactility/drivers/Esp32Gpio.h | 15 + .../Include/Tactility/drivers/Esp32I2c.h | 19 + Platforms/PlatformEsp32/Source/Esp32Gpio.cpp | 116 +++ Platforms/PlatformEsp32/Source/Esp32I2c.cpp | 91 +++ Platforms/PlatformEsp32/Source/Register.cpp | 12 + Platforms/PlatformEsp32/devicetree.yaml | 3 + Platforms/PlatformPosix/CMakeLists.txt | 20 + Platforms/PlatformPosix/Source/Register.cpp | 9 + Platforms/PlatformPosix/devicetree.yaml | 2 + COPYRIGHT.md => THIRD-PARTY-NOTICES.md | 16 +- Tactility/CMakeLists.txt | 7 +- Tactility/Include/Tactility/Tactility.h | 2 - Tactility/LICENSE-GPL-3.0.md | 675 ++++++++++++++++++ TactilityC/CMakeLists.txt | 3 - TactilityC/LICENSE-Apache-2.0.md | 195 +++++ TactilityCore/CMakeLists.txt | 7 +- .../Include/Tactility/LoggerAdapterGeneric.h | 2 +- TactilityCore/LICENSE-GPL-3.0.md | 675 ++++++++++++++++++ TactilityCore/LICENSE.md | 636 ----------------- TactilityFreeRtos/CMakeLists.txt | 3 - .../Include/Tactility/freertoscompat/Queue.h | 2 + TactilityFreeRtos/LICENSE-Apache-2.0.md | 195 +++++ TactilityKernel/Bindings/gpio-controller.yaml | 6 + TactilityKernel/Bindings/i2c-controller.yaml | 10 + TactilityKernel/Bindings/i2c-device.yaml | 6 + TactilityKernel/Bindings/root.yaml | 6 + TactilityKernel/CMakeLists.txt | 18 + TactilityKernel/Include/Tactility/Device.h | 183 +++++ TactilityKernel/Include/Tactility/Driver.h | 50 ++ TactilityKernel/Include/Tactility/Error.h | 8 + .../Include/Tactility/FreeRTOS/FreeRTOS.h | 10 + .../Include/Tactility/FreeRTOS/README.md | 3 + .../Include/Tactility/FreeRTOS/event_groups.h | 10 + .../Include/Tactility/FreeRTOS/port.h | 8 + .../Include/Tactility/FreeRTOS/queue.h | 10 + .../Include/Tactility/FreeRTOS/semphr.h | 9 + .../Include/Tactility/FreeRTOS/task.h | 10 + .../Include/Tactility/FreeRTOS/timers.h | 9 + TactilityKernel/Include/Tactility/Log.h | 35 + .../Include/Tactility/bindings/bindings.h | 8 + .../Include/Tactility/bindings/gpio.h | 3 + .../Include/Tactility/bindings/root.h | 7 + .../Include/Tactility/concurrent/Mutex.h | 45 ++ .../Tactility/concurrent/RecursiveMutex.h | 44 ++ .../Include/Tactility/drivers/Gpio.h | 90 +++ .../Tactility/drivers/GpioController.h | 28 + .../Include/Tactility/drivers/I2cController.h | 28 + .../Include/Tactility/drivers/Root.h | 13 + TactilityKernel/LICENSE-LGPL-3.0.md | 157 ++++ TactilityKernel/Source/Device.cpp | 225 ++++++ TactilityKernel/Source/Driver.cpp | 188 +++++ TactilityKernel/Source/Log.cpp | 17 + .../Source/drivers/GpioController.cpp | 28 + .../Source/drivers/I2cController.cpp | 25 + TactilityKernel/Source/drivers/Register.cpp | 10 + TactilityKernel/Source/drivers/Root.cpp | 16 + TactilityKernel/devicetree.yaml | 1 + Tests/CMakeLists.txt | 2 + Tests/LICENSE-GPL-3.0.md | 675 ++++++++++++++++++ Tests/Tactility/Main.cpp | 4 +- Tests/TactilityCore/Main.cpp | 4 +- Tests/TactilityFreeRtos/Main.cpp | 4 +- Tests/TactilityKernel/CMakeLists.txt | 14 + Tests/TactilityKernel/DeviceTest.cpp | 190 +++++ .../TactilityKernel/DriverIntegrationTest.cpp | 64 ++ Tests/TactilityKernel/DriverTest.cpp | 58 ++ Tests/TactilityKernel/Main.cpp | 57 ++ 194 files changed, 7807 insertions(+), 741 deletions(-) create mode 100644 Buildscripts/DevicetreeCompiler/.gitignore rename Documentation/license-tactilitysdk.md => Buildscripts/DevicetreeCompiler/LICENSE-Apache-2.0.md (100%) create mode 100644 Buildscripts/DevicetreeCompiler/compile.py create mode 100644 Buildscripts/DevicetreeCompiler/source/binding_files.py create mode 100644 Buildscripts/DevicetreeCompiler/source/binding_parser.py create mode 100644 Buildscripts/DevicetreeCompiler/source/config.py create mode 100644 Buildscripts/DevicetreeCompiler/source/files.py create mode 100644 Buildscripts/DevicetreeCompiler/source/generator.py create mode 100644 Buildscripts/DevicetreeCompiler/source/grammar.lark create mode 100644 Buildscripts/DevicetreeCompiler/source/main.py create mode 100644 Buildscripts/DevicetreeCompiler/source/models.py create mode 100644 Buildscripts/DevicetreeCompiler/source/printing.py create mode 100644 Buildscripts/DevicetreeCompiler/source/transformer.py create mode 100644 Devices/LICENSE-GPL-3.0.md create mode 100644 Devices/btt-panda-touch/Source/Drivers.cpp create mode 100644 Devices/btt-panda-touch/devicetree.yaml create mode 100644 Devices/cyd-2432s024c/Source/Drivers.cpp create mode 100644 Devices/cyd-2432s024c/devicetree.yaml create mode 100644 Devices/cyd-2432s028r/Source/Drivers.cpp create mode 100644 Devices/cyd-2432s028r/devicetree.yaml create mode 100644 Devices/cyd-2432s028rv3/Source/Drivers.cpp create mode 100644 Devices/cyd-2432s028rv3/devicetree.yaml create mode 100644 Devices/cyd-2432s032c/Source/Drivers.cpp create mode 100644 Devices/cyd-2432s032c/devicetree.yaml create mode 100644 Devices/cyd-4848s040c/Source/Drivers.cpp create mode 100644 Devices/cyd-4848s040c/devicetree.yaml create mode 100644 Devices/cyd-8048s043c/Source/Drivers.cpp create mode 100644 Devices/cyd-8048s043c/devicetree.yaml create mode 100644 Devices/cyd-e32r28t/Source/Drivers.cpp create mode 100644 Devices/cyd-e32r28t/devicetree.yaml create mode 100644 Devices/cyd-e32r32p/Source/Drivers.cpp create mode 100644 Devices/cyd-e32r32p/devicetree.yaml create mode 100644 Devices/elecrow-crowpanel-advance-28/Source/Drivers.cpp create mode 100644 Devices/elecrow-crowpanel-advance-28/devicetree.yaml create mode 100644 Devices/elecrow-crowpanel-advance-35/Source/Drivers.cpp create mode 100644 Devices/elecrow-crowpanel-advance-35/devicetree.yaml create mode 100644 Devices/elecrow-crowpanel-advance-50/Source/Drivers.cpp create mode 100644 Devices/elecrow-crowpanel-advance-50/devicetree.yaml create mode 100644 Devices/elecrow-crowpanel-basic-28/Source/Drivers.cpp create mode 100644 Devices/elecrow-crowpanel-basic-28/devicetree.yaml create mode 100644 Devices/elecrow-crowpanel-basic-35/Source/Drivers.cpp create mode 100644 Devices/elecrow-crowpanel-basic-35/devicetree.yaml create mode 100644 Devices/elecrow-crowpanel-basic-50/Source/Drivers.cpp create mode 100644 Devices/elecrow-crowpanel-basic-50/devicetree.yaml create mode 100644 Devices/generic-esp32/Source/Drivers.cpp create mode 100644 Devices/generic-esp32/devicetree.yaml create mode 100644 Devices/generic-esp32c6/Source/Drivers.cpp create mode 100644 Devices/generic-esp32c6/devicetree.yaml create mode 100644 Devices/generic-esp32p4/Source/Drivers.cpp create mode 100644 Devices/generic-esp32p4/devicetree.yaml create mode 100644 Devices/generic-esp32s3/Source/Drivers.cpp create mode 100644 Devices/generic-esp32s3/devicetree.yaml create mode 100644 Devices/guition-jc1060p470ciwy/Source/Drivers.cpp create mode 100644 Devices/guition-jc1060p470ciwy/devicetree.yaml create mode 100644 Devices/guition-jc2432w328c/Source/Drivers.cpp create mode 100644 Devices/guition-jc2432w328c/devicetree.yaml create mode 100644 Devices/guition-jc8048w550c/Source/Drivers.cpp create mode 100644 Devices/guition-jc8048w550c/devicetree.yaml create mode 100644 Devices/heltec-wifi-lora-32-v3/Source/Drivers.cpp create mode 100644 Devices/heltec-wifi-lora-32-v3/devicetree.yaml create mode 100644 Devices/lilygo-tdeck/Source/Drivers.cpp create mode 100644 Devices/lilygo-tdeck/devicetree.yaml create mode 100644 Devices/lilygo-tdisplay-s3/Source/Drivers.cpp create mode 100644 Devices/lilygo-tdisplay-s3/devicetree.yaml create mode 100644 Devices/lilygo-tdisplay/Source/Drivers.cpp create mode 100644 Devices/lilygo-tdisplay/devicetree.yaml create mode 100644 Devices/lilygo-tdongle-s3/Source/Drivers.cpp create mode 100644 Devices/lilygo-tdongle-s3/devicetree.yaml create mode 100644 Devices/lilygo-tlora-pager/Source/Drivers.cpp create mode 100644 Devices/lilygo-tlora-pager/Source/bindings/tlora_pager.h create mode 100644 Devices/lilygo-tlora-pager/Source/drivers/Register.cpp create mode 100644 Devices/lilygo-tlora-pager/Source/drivers/TloraPager.cpp create mode 100644 Devices/lilygo-tlora-pager/Source/drivers/TloraPager.h create mode 100644 Devices/lilygo-tlora-pager/devicetree.yaml create mode 100644 Devices/lilygo-tlora-pager/lilygo,tlora-pager.dts create mode 100644 Devices/lilygo-tlora-pager/lilygo,tlora-pager.yaml create mode 100644 Devices/m5stack-cardputer-adv/Source/Drivers.cpp create mode 100644 Devices/m5stack-cardputer-adv/devicetree.yaml create mode 100644 Devices/m5stack-cardputer/Source/Drivers.cpp create mode 100644 Devices/m5stack-cardputer/devicetree.yaml create mode 100644 Devices/m5stack-core2/Source/Drivers.cpp create mode 100644 Devices/m5stack-core2/devicetree.yaml create mode 100644 Devices/m5stack-cores3/Source/Drivers.cpp create mode 100644 Devices/m5stack-cores3/devicetree.yaml create mode 100644 Devices/m5stack-stickc-plus/Source/Drivers.cpp create mode 100644 Devices/m5stack-stickc-plus/devicetree.yaml create mode 100644 Devices/m5stack-stickc-plus2/Source/Drivers.cpp create mode 100644 Devices/m5stack-stickc-plus2/devicetree.yaml create mode 100644 Devices/placeholder.dts create mode 100644 Devices/simulator/Source/Drivers.cpp create mode 100644 Devices/simulator/devicetree.yaml create mode 100644 Devices/simulator/simulator.dts create mode 100644 Devices/unphone/Source/Drivers.cpp create mode 100644 Devices/unphone/devicetree.yaml create mode 100644 Devices/waveshare-esp32-s3-geek/Source/Drivers.cpp create mode 100644 Devices/waveshare-esp32-s3-geek/devicetree.yaml create mode 100644 Devices/waveshare-s3-lcd-13/Source/Drivers.cpp create mode 100644 Devices/waveshare-s3-lcd-13/devicetree.yaml create mode 100644 Devices/waveshare-s3-touch-lcd-128/Source/Drivers.cpp create mode 100644 Devices/waveshare-s3-touch-lcd-128/devicetree.yaml create mode 100644 Devices/waveshare-s3-touch-lcd-147/Source/Drivers.cpp create mode 100644 Devices/waveshare-s3-touch-lcd-147/devicetree.yaml create mode 100644 Devices/waveshare-s3-touch-lcd-43/Source/Drivers.cpp create mode 100644 Devices/waveshare-s3-touch-lcd-43/devicetree.yaml create mode 100644 Devices/wireless-tag-wt32-sc01-plus/Source/Drivers.cpp create mode 100644 Devices/wireless-tag-wt32-sc01-plus/devicetree.yaml create mode 100644 Documentation/LICENSE-Apache-2.0.md create mode 100644 Documentation/LICENSE-GPL-3.0.md create mode 100644 Documentation/LICENSE-LGPL-3.0.md create mode 100644 Documentation/license-tactilitykernel.md create mode 100644 Firmware/.gitignore create mode 100644 Platforms/LICENSE-LGPL-3.0.md create mode 100644 Platforms/PlatformEsp32/Bindings/espressif,esp32-gpio.yaml create mode 100644 Platforms/PlatformEsp32/Bindings/espressif,esp32-i2c.yaml create mode 100644 Platforms/PlatformEsp32/CMakeLists.txt create mode 100644 Platforms/PlatformEsp32/Include/Tactility/bindings/esp32_gpio.h create mode 100644 Platforms/PlatformEsp32/Include/Tactility/bindings/esp32_i2c.h create mode 100644 Platforms/PlatformEsp32/Include/Tactility/drivers/Esp32Gpio.h create mode 100644 Platforms/PlatformEsp32/Include/Tactility/drivers/Esp32I2c.h create mode 100644 Platforms/PlatformEsp32/Source/Esp32Gpio.cpp create mode 100644 Platforms/PlatformEsp32/Source/Esp32I2c.cpp create mode 100644 Platforms/PlatformEsp32/Source/Register.cpp create mode 100644 Platforms/PlatformEsp32/devicetree.yaml create mode 100644 Platforms/PlatformPosix/CMakeLists.txt create mode 100644 Platforms/PlatformPosix/Source/Register.cpp create mode 100644 Platforms/PlatformPosix/devicetree.yaml rename COPYRIGHT.md => THIRD-PARTY-NOTICES.md (80%) create mode 100644 Tactility/LICENSE-GPL-3.0.md create mode 100644 TactilityC/LICENSE-Apache-2.0.md create mode 100644 TactilityCore/LICENSE-GPL-3.0.md delete mode 100644 TactilityCore/LICENSE.md create mode 100644 TactilityFreeRtos/LICENSE-Apache-2.0.md create mode 100644 TactilityKernel/Bindings/gpio-controller.yaml create mode 100644 TactilityKernel/Bindings/i2c-controller.yaml create mode 100644 TactilityKernel/Bindings/i2c-device.yaml create mode 100644 TactilityKernel/Bindings/root.yaml create mode 100644 TactilityKernel/CMakeLists.txt create mode 100644 TactilityKernel/Include/Tactility/Device.h create mode 100644 TactilityKernel/Include/Tactility/Driver.h create mode 100644 TactilityKernel/Include/Tactility/Error.h create mode 100644 TactilityKernel/Include/Tactility/FreeRTOS/FreeRTOS.h create mode 100644 TactilityKernel/Include/Tactility/FreeRTOS/README.md create mode 100644 TactilityKernel/Include/Tactility/FreeRTOS/event_groups.h create mode 100644 TactilityKernel/Include/Tactility/FreeRTOS/port.h create mode 100644 TactilityKernel/Include/Tactility/FreeRTOS/queue.h create mode 100644 TactilityKernel/Include/Tactility/FreeRTOS/semphr.h create mode 100644 TactilityKernel/Include/Tactility/FreeRTOS/task.h create mode 100644 TactilityKernel/Include/Tactility/FreeRTOS/timers.h create mode 100644 TactilityKernel/Include/Tactility/Log.h create mode 100644 TactilityKernel/Include/Tactility/bindings/bindings.h create mode 100644 TactilityKernel/Include/Tactility/bindings/gpio.h create mode 100644 TactilityKernel/Include/Tactility/bindings/root.h create mode 100644 TactilityKernel/Include/Tactility/concurrent/Mutex.h create mode 100644 TactilityKernel/Include/Tactility/concurrent/RecursiveMutex.h create mode 100644 TactilityKernel/Include/Tactility/drivers/Gpio.h create mode 100644 TactilityKernel/Include/Tactility/drivers/GpioController.h create mode 100644 TactilityKernel/Include/Tactility/drivers/I2cController.h create mode 100644 TactilityKernel/Include/Tactility/drivers/Root.h create mode 100644 TactilityKernel/LICENSE-LGPL-3.0.md create mode 100644 TactilityKernel/Source/Device.cpp create mode 100644 TactilityKernel/Source/Driver.cpp create mode 100644 TactilityKernel/Source/Log.cpp create mode 100644 TactilityKernel/Source/drivers/GpioController.cpp create mode 100644 TactilityKernel/Source/drivers/I2cController.cpp create mode 100644 TactilityKernel/Source/drivers/Register.cpp create mode 100644 TactilityKernel/Source/drivers/Root.cpp create mode 100644 TactilityKernel/devicetree.yaml create mode 100644 Tests/LICENSE-GPL-3.0.md create mode 100644 Tests/TactilityKernel/CMakeLists.txt create mode 100644 Tests/TactilityKernel/DeviceTest.cpp create mode 100644 Tests/TactilityKernel/DriverIntegrationTest.cpp create mode 100644 Tests/TactilityKernel/DriverTest.cpp create mode 100644 Tests/TactilityKernel/Main.cpp diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 9c5d7c06..34f4da79 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -20,8 +20,10 @@ jobs: - name: "Build Tests" run: cmake --build build --target build-tests - name: "Run TactilityCore Tests" - run: build/Tests/TactilityCore/TactilityCoreTests --exit + run: build/Tests/TactilityCore/TactilityCoreTests - name: "Run TactilityFreeRtos Tests" - run: build/Tests/TactilityFreeRtos/TactilityFreeRtosTests --exit + run: build/Tests/TactilityFreeRtos/TactilityFreeRtosTests - name: "Run TactilityHeadless Tests" - run: build/Tests/Tactility/TactilityTests --exit + run: build/Tests/Tactility/TactilityTests + - name: "Run TactilityKernel Tests" + run: build/Tests/TactilityKernel/TactilityKernelTests diff --git a/Buildscripts/DevicetreeCompiler/.gitignore b/Buildscripts/DevicetreeCompiler/.gitignore new file mode 100644 index 00000000..5923bb7a --- /dev/null +++ b/Buildscripts/DevicetreeCompiler/.gitignore @@ -0,0 +1,4 @@ +.venv/ +.idea/ +__pycache__/ +build/ \ No newline at end of file diff --git a/Documentation/license-tactilitysdk.md b/Buildscripts/DevicetreeCompiler/LICENSE-Apache-2.0.md similarity index 100% rename from Documentation/license-tactilitysdk.md rename to Buildscripts/DevicetreeCompiler/LICENSE-Apache-2.0.md diff --git a/Buildscripts/DevicetreeCompiler/compile.py b/Buildscripts/DevicetreeCompiler/compile.py new file mode 100644 index 00000000..b5db6034 --- /dev/null +++ b/Buildscripts/DevicetreeCompiler/compile.py @@ -0,0 +1,28 @@ +import sys + +from source.printing import print_error +from source.main import main + +def print_help(): + print("Usage: python compile.py [in_file] [out_path] [arguments]\n") + print(f"\t[in_path] the path where the root devicetree.yaml file is") + print(f"\t[out_path] output folder for C file output") + print("") + print("Optional arguments:\n") + print("\t--help prints this help text") + print("\t--verbose output debug info") + +if __name__ == "__main__": + if "--help" in sys.argv: + print_help() + sys.exit() + args = [a for a in sys.argv[1:] if not a.startswith("--")] + if len(args) < 2: + print_error("Missing argument") + print_help() + sys.exit() + is_verbose = "--verbose" in sys.argv + devicetree_yaml_config = args[0] + output_path = args[1] + main(devicetree_yaml_config, output_path, is_verbose) + diff --git a/Buildscripts/DevicetreeCompiler/source/binding_files.py b/Buildscripts/DevicetreeCompiler/source/binding_files.py new file mode 100644 index 00000000..d6973310 --- /dev/null +++ b/Buildscripts/DevicetreeCompiler/source/binding_files.py @@ -0,0 +1,19 @@ +import os + +def find_bindings(directory_path: str) -> list[str]: + yaml_files = [] + for root, dirs, files in os.walk(directory_path): + for file in files: + if file.endswith(".yaml"): + full_path = os.path.join(root, file) + yaml_files.append(os.path.abspath(full_path)) + return yaml_files + +def find_all_bindings(directory_paths: list[str]) -> list[str]: + yaml_files = [] + for directory_path in directory_paths: + new_paths = find_bindings(directory_path) + if len(new_paths) == 0: + raise Exception(f"No bindings found in {directory_path}") + yaml_files += new_paths + return yaml_files \ No newline at end of file diff --git a/Buildscripts/DevicetreeCompiler/source/binding_parser.py b/Buildscripts/DevicetreeCompiler/source/binding_parser.py new file mode 100644 index 00000000..b6f7f116 --- /dev/null +++ b/Buildscripts/DevicetreeCompiler/source/binding_parser.py @@ -0,0 +1,57 @@ +import yaml +import os +from .models import Binding, BindingProperty + +def parse_binding(file_path: str, binding_dirs: list[str]) -> Binding: + with open(file_path, 'r') as f: + data = yaml.safe_load(f) + + description = data.get('description', '') + bus = data.get('bus', None) + properties_dict = {} + + # Handle inclusions + includes = data.get('include', []) + all_includes = list(includes) # Copy for iteration + for include_file in includes: + include_path = None + for binding_dir in binding_dirs: + potential_path = os.path.join(binding_dir, include_file) + if os.path.exists(potential_path): + include_path = potential_path + break + + if not include_path: + print(f"Warning: Could not find include file {include_file}") + continue + + parent_binding = parse_binding(include_path, binding_dirs) + if not description and parent_binding.description: + description = parent_binding.description + if not bus and parent_binding.bus: + bus = parent_binding.bus + for prop in parent_binding.properties: + properties_dict[prop.name] = prop + for include in parent_binding.includes: + all_includes.append(include) + + # Parse local properties + compatible = data.get('compatible', None) + properties_raw = data.get('properties', {}) + for name, details in properties_raw.items(): + prop = BindingProperty( + name=name, + type=details.get('type', 'unknown'), + required=details.get('required', False), + description=details.get('description', '').strip(), + ) + properties_dict[name] = prop + filename = os.path.basename(file_path) + return Binding( + filename=filename, + compatible=compatible, + description=description.strip(), + properties=list(properties_dict.values()), + includes=all_includes, + bus=bus + ) diff --git a/Buildscripts/DevicetreeCompiler/source/config.py b/Buildscripts/DevicetreeCompiler/source/config.py new file mode 100644 index 00000000..432a3f84 --- /dev/null +++ b/Buildscripts/DevicetreeCompiler/source/config.py @@ -0,0 +1,50 @@ +from dataclasses import dataclass, field +import yaml +import os + +@dataclass +class DeviceTreeConfig: + dependencies: list[str] = field(default_factory=list) + bindings: list[str] = field(default_factory=list) + dts: str = "" + +def parse_config(file_path: str, project_root: str) -> DeviceTreeConfig: + """ + Parses devicetree.yaml and recursively finds dependencies. + Returns a list of DeviceTreeConfig objects in post-order (dependencies first). + """ + config = DeviceTreeConfig([], [], "") + visited = set() + + def _parse_recursive(current_path: str, is_root: bool): + abs_path = os.path.abspath(current_path) + if abs_path in visited: + return + visited.add(abs_path) + + # Try to see if it's a directory and contains devicetree.yaml + if os.path.isdir(abs_path): + abs_path = os.path.join(abs_path, "devicetree.yaml") + + with open(abs_path, 'r') as f: + data = yaml.safe_load(f) or {} + + # Handle dependencies before adding current config (post-order) + deps = data.get("dependencies", []) + for dep in deps: + # Dependencies are relative to project_root + dep_path = os.path.join(project_root, dep) + _parse_recursive(dep_path, False) + + if is_root: + config.dependencies += deps + dts_path = data.get("dts", "") + config.dts = os.path.join(current_path, dts_path) + + bindings = data.get("bindings", "") + if bindings: + bindings_resolved = os.path.join(current_path, bindings) + config.bindings.append(bindings_resolved) + + _parse_recursive(file_path, True) + return config diff --git a/Buildscripts/DevicetreeCompiler/source/files.py b/Buildscripts/DevicetreeCompiler/source/files.py new file mode 100644 index 00000000..1e262672 --- /dev/null +++ b/Buildscripts/DevicetreeCompiler/source/files.py @@ -0,0 +1,9 @@ +def read_file(path: str): + with open(path, "r") as file: + result = file.read() + return result + +def write_file(path: str, content: str): + with open(path, "w") as file: + result = file.write(content) + return result diff --git a/Buildscripts/DevicetreeCompiler/source/generator.py b/Buildscripts/DevicetreeCompiler/source/generator.py new file mode 100644 index 00000000..ebb3e590 --- /dev/null +++ b/Buildscripts/DevicetreeCompiler/source/generator.py @@ -0,0 +1,217 @@ +import os.path +from textwrap import dedent + +from source.models import * + +def write_include(file, include: IncludeC, verbose: bool): + if verbose: + print("Processing include:") + print(f" {include.statement}") + file.write(include.statement) + file.write('\n') + +def get_device_identifier_safe(device: Device): + if device.identifier == "/": + return "root" + else: + return device.identifier + +def get_device_type_name(device: Device, bindings: list[Binding]): + device_binding = find_device_binding(device, bindings) + if device_binding is None: + raise Exception(f"Binding not found for {device.identifier}") + if device_binding.compatible is None: + raise Exception(f"Couldn't find compatible binding for {device.identifier}") + compatible_safe = device_binding.compatible.split(",")[-1] + return compatible_safe.replace("-", "_") + +def find_device_property(device: Device, name: str) -> DeviceProperty: + for property in device.properties: + if property.name == name: + return property + return None + +def find_device_binding(device: Device, bindings: list[Binding]) -> Binding: + compatible_property = find_device_property(device, "compatible") + if compatible_property is None: + raise Exception(f"property 'compatible' not found in device {device.identifier}") + for binding in bindings: + if binding.compatible == compatible_property.value: + return binding + return None + +def find_binding(compatible: str, bindings: list[Binding]) -> Binding: + for binding in bindings: + if binding.compatible == compatible: + return binding + return None + +def property_to_string(property: DeviceProperty) -> str: + type = property.type + if type == "value": + return property.value + elif type == "text": + return f"\"{property.value}\"" + elif type == "values": + return "{ " + ",".join(property.value) + " }" + else: + raise Exception(f"property_to_string() has an unsupported type: {type}") + +def resolve_parameters_from_bindings(device: Device, bindings: list[Binding]) -> list: + compatible_property = find_device_property(device, "compatible") + if compatible_property is None: + raise Exception(f"Cannot find 'compatible' property for {device.identifier}") + device_binding = find_binding(compatible_property.value, bindings) + if device_binding is None: + raise Exception(f"Binding not found for {device.identifier} and compatible '{compatible_property.value}'") + # Filter out system properties + binding_properties = [] + for property in device_binding.properties: + if property.name != "compatible": + binding_properties.append(property) + # Allocate total expected configuration arguments + result = [0] * len(binding_properties) + for index, binding_property in enumerate(binding_properties): + device_property = find_device_property(device, binding_property.name) + if device_property is None: + if binding_property.required: + raise Exception(f"device {device.identifier} doesn't have property '{binding_property.name}'") + else: + result[index] = '0' + else: + result[index] = property_to_string(device_property) + return result + +def write_config(file, device: Device, bindings: list[Binding], type_name: str): + device_identifier = get_device_identifier_safe(device) + config_type = f"{type_name}_config_dt" + config_variable_name = f"{device_identifier}_config" + file.write(f"static const {config_type} {config_variable_name}" " = {\n") + config_params = resolve_parameters_from_bindings(device, bindings) + # Indent all params + for index, config_param in enumerate(config_params): + config_params[index] = f"\t{config_param}" + # Join with command and newline + if len(config_params) > 0: + config_params_joined = ",\n".join(config_params) + file.write(f"{config_params_joined}\n") + file.write("};\n\n") + +def write_device_structs(file, device: Device, parent_device: Device, bindings: list[Binding], verbose: bool): + if verbose: + print(f"Writing device struct for '{device.identifier}'") + # Assemble some pre-requisites + type_name = get_device_type_name(device, bindings) + compatible_property = find_device_property(device, "compatible") + if compatible_property is None: + raise Exception(f"Cannot find 'compatible' property for {device.identifier}") + identifier = get_device_identifier_safe(device) + config_variable_name = f"{identifier}_config" + if parent_device is not None: + parent_identifier = get_device_identifier_safe(parent_device) + parent_value = f"&{parent_identifier}" + else: + parent_value = "NULL" + # Write config struct + write_config(file, device, bindings, type_name) + # Write device struct + file.write(f"static struct Device {identifier}" " = {\n") + file.write(f"\t.name = \"{device.identifier}\",\n") # Use original name + file.write(f"\t.config = &{config_variable_name},\n") + file.write(f"\t.parent = {parent_value},\n") + file.write("};\n\n") + # Child devices + for child_device in device.devices: + write_device_structs(file, child_device, device, bindings, verbose) + +def write_device_init(file, device: Device, bindings: list[Binding], verbose: bool): + if verbose: + print(f"Processing device init code for '{device.identifier}'") + # Assemble some pre-requisites + compatible_property = find_device_property(device, "compatible") + if compatible_property is None: + raise Exception(f"Cannot find 'compatible' property for {device.identifier}") + # Type & instance names + identifier = get_device_identifier_safe(device) + device_variable = identifier + # Write device struct + file.write(f"\tif (init_builtin_device(&{device_variable}, \"{compatible_property.value}\") != 0) return -1;\n") + # Write children + for child_device in device.devices: + write_device_init(file, child_device, bindings, verbose) + +def generate_devicetree_c(filename: str, items: list[object], bindings: list[Binding], verbose: bool): + with open(filename, "w") as file: + file.write(dedent('''\ + // Default headers + #include + #include + #include + // DTS headers + ''')) + + # Write all headers first + for item in items: + if type(item) is IncludeC: + write_include(file, item, verbose) + file.write("\n") + + file.write(dedent('''\ + #define TAG LOG_TAG(devicetree) + + static int init_builtin_device(struct Device* device, const char* compatible) { + struct Driver* driver = driver_find_compatible(compatible); + if (driver == NULL) { + LOG_E(TAG, "Can't find driver: %s", compatible); + return -1; + } + device_construct(device); + device_set_driver(device, driver); + device_add(device); + const int err = device_start(device); + if (err != 0) { + LOG_E(TAG, "Failed to start device %s with driver %s: error code %d", device->name, compatible, err); + return -1; + } + return 0; + } + + ''')) + + # Then write all devices + for item in items: + if type(item) is Device: + write_device_structs(file, item, None, bindings, verbose) + # Init function body start + file.write("int devices_builtin_init() {\n") + # Init function body logic + for item in items: + if type(item) is Device: + write_device_init(file, item, bindings, verbose) + file.write("\treturn 0;\n") + # Init function body end + file.write("}\n") + +def generate_devicetree_h(filename: str): + with open(filename, "w") as file: + file.write(dedent('''\ + #pragma once + + #ifdef __cplusplus + extern "C" { + #endif + + extern int devices_builtin_init(); + + #ifdef __cplusplus + } + #endif + ''')) + +def generate(output_path: str, items: list[object], bindings: list[Binding], verbose: bool): + if not os.path.exists(output_path): + os.makedirs(output_path) + devicetree_c_filename = os.path.join(output_path, "devicetree.c") + generate_devicetree_c(devicetree_c_filename, items, bindings, verbose) + devicetree_h_filename = os.path.join(output_path, "devicetree.h") + generate_devicetree_h(devicetree_h_filename) diff --git a/Buildscripts/DevicetreeCompiler/source/grammar.lark b/Buildscripts/DevicetreeCompiler/source/grammar.lark new file mode 100644 index 00000000..03a539d7 --- /dev/null +++ b/Buildscripts/DevicetreeCompiler/source/grammar.lark @@ -0,0 +1,46 @@ +%import common.DIGIT -> DIGIT +%import common.LETTER -> LETTER +%import common.HEXDIGIT -> HEXDIGIT +%import common.SIGNED_INT -> SIGNED_INT +%import common.WS -> WS +%import common.SIGNED_NUMBER -> SIGNED_NUMBER +%import common.ESCAPED_STRING -> ESCAPED_STRING +%ignore WS + +// Comment + +COMMENT: /\/\*([^*]|\*+[^*\/])*\*+\// +%ignore COMMENT + +// Boolean + +BOOLEAN: "true" | "false" + +// Main + +INCLUDE_C: /#include <[\w\/.\-]+>/ + +PROPERTY_NAME: /#?[a-zA-Z0-9_\-,]+/ + +QUOTE: "\"" +QUOTED_TEXT: QUOTE /[^"]+/ QUOTE +quoted_text_array: QUOTED_TEXT ("," " "* QUOTED_TEXT)+ +HEX_NUMBER: "0x" HEXDIGIT+ +NUMBER: SIGNED_NUMBER | HEX_NUMBER +PHANDLE: /&[0-9a-zA-Z\-]+/ +C_VARIABLE: /[0-9a-zA-Z_]+/ +VALUE: NUMBER | PHANDLE | C_VARIABLE +value: VALUE +values: VALUE+ +array: NUMBER+ + +property_value: quoted_text_array | QUOTED_TEXT | "<" value ">" | "<" values ">" | "[" array "]" +device_property: PROPERTY_NAME ["=" property_value] ";" + +DEVICE_IDENTIFIER: /[a-zA-Z0-9_\-\/@]+/ + +device: DEVICE_IDENTIFIER "{" (device | device_property)* "};" + +dts_version: /[0-9a-zA-Z\-]+/ + +start: "/" dts_version "/;" INCLUDE_C* device+ diff --git a/Buildscripts/DevicetreeCompiler/source/main.py b/Buildscripts/DevicetreeCompiler/source/main.py new file mode 100644 index 00000000..97b7f0be --- /dev/null +++ b/Buildscripts/DevicetreeCompiler/source/main.py @@ -0,0 +1,46 @@ +import os +from pprint import pprint + +from lark import Lark + +from source.files import * +from source.transformer import * +from source.generator import * +from source.binding_files import find_all_bindings +from source.binding_parser import parse_binding +from source.config import * + +def main(config_path: str, output_path: str, verbose: bool): + print(f"Generating devicetree code\n config: {config_path}\n output: {output_path}") + if not os.path.isdir(config_path): + raise Exception(f"Directory not found: {config_path}") + + config = parse_config(config_path, os.getcwd()) + if verbose: + pprint(config) + + project_dir = os.path.dirname(os.path.realpath(__file__)) + grammar_path = os.path.join(project_dir, "grammar.lark") + lark_data = read_file(grammar_path) + dts_data = read_file(config.dts) + lark = Lark(lark_data) + parsed = lark.parse(dts_data) + if verbose: + print(parsed.pretty()) + transformed = DtsTransformer().transform(parsed) + if verbose: + pprint(transformed) + binding_files = find_all_bindings(config.bindings) + if verbose: + print(f"Bindings found:") + for binding_file in binding_files: + print(f" {binding_file}") + if verbose: + print(f"Parsing bindings") + bindings = [] + for binding_file in binding_files: + bindings.append(parse_binding(binding_file, config.bindings)) + if verbose: + for binding in bindings: + pprint(binding) + generate(output_path, transformed, bindings, verbose) diff --git a/Buildscripts/DevicetreeCompiler/source/models.py b/Buildscripts/DevicetreeCompiler/source/models.py new file mode 100644 index 00000000..b747869f --- /dev/null +++ b/Buildscripts/DevicetreeCompiler/source/models.py @@ -0,0 +1,42 @@ +from dataclasses import dataclass + +@dataclass +class DtsVersion: + version: str + +@dataclass +class Device: + identifier: str + properties: list + devices: list + +@dataclass +class DeviceProperty: + name: str + type: str + value: object + +@dataclass +class PropertyValue: + type: str + value: object + +@dataclass +class IncludeC: + statement: str + +@dataclass +class BindingProperty: + name: str + type: str + required: bool + description: str + +@dataclass +class Binding: + filename: str + compatible: list[str] + description: str + properties: list[BindingProperty] + includes: list[str] + bus: str = None diff --git a/Buildscripts/DevicetreeCompiler/source/printing.py b/Buildscripts/DevicetreeCompiler/source/printing.py new file mode 100644 index 00000000..67b2ad80 --- /dev/null +++ b/Buildscripts/DevicetreeCompiler/source/printing.py @@ -0,0 +1,20 @@ +import sys + +if sys.platform == "win32": + SHELL_COLOR_RED = "" + SHELL_COLOR_ORANGE = "" + SHELL_COLOR_RESET = "" +else: + SHELL_COLOR_RED = "\033[91m" + SHELL_COLOR_ORANGE = "\033[93m" + SHELL_COLOR_RESET = "\033[m" + +def print_warning(message): + print(f"{SHELL_COLOR_ORANGE}WARNING: {message}{SHELL_COLOR_RESET}") + +def print_error(message): + print(f"{SHELL_COLOR_RED}ERROR: {message}{SHELL_COLOR_RESET}") + +def exit_with_error(message): + print_error(message) + sys.exit(1) diff --git a/Buildscripts/DevicetreeCompiler/source/transformer.py b/Buildscripts/DevicetreeCompiler/source/transformer.py new file mode 100644 index 00000000..b4478543 --- /dev/null +++ b/Buildscripts/DevicetreeCompiler/source/transformer.py @@ -0,0 +1,67 @@ +from typing import List + +from lark import Transformer +from lark import Token +from source.models import * + +def flatten_token_array(tokens: List[Token], name: str): + result_list = list() + for token in tokens: + result_list.append(token.value) + return Token(name, result_list) + +class DtsTransformer(Transformer): + # Flatten the start node into a list + def start(self, tokens): + return tokens + def dts_version(self, tokens: List[Token]): + version = tokens[0].value + if version != "dts-v1": + raise Exception(f"Unsupported DTS version: {version}") + return DtsVersion(version) + def device(self, tokens: list): + identifier = "UNKNOWN" + properties = list() + devices = list() + for index, entry in enumerate(tokens): + if index == 0: + identifier = entry.value + elif type(entry) is DeviceProperty: + properties.append(entry) + elif type(entry) is Device: + devices.append(entry) + return Device(identifier, properties, devices) + def device_property(self, objects: List[object]): + name = objects[0] + if len(objects) == 1: + # Boolean property with no value + return DeviceProperty(name, "boolean", True) + if type(objects[1]) is not PropertyValue: + raise Exception(f"Object was not converted to PropertyValue: {objects[1]}") + return DeviceProperty(name, objects[1].type, objects[1].value) + def property_value(self, tokens: List): + token = tokens[0] + if type(token) is Token: + raise Exception(f"Failed to convert token to PropertyValue: {token}") + return token + def values(self, object): + return PropertyValue(type="values", value=object) + def value(self, object): + return PropertyValue(type="value", value=object[0]) + def array(self, object): + return PropertyValue(type="array", value=object) + def VALUE(self, token: Token): + return token.value + def NUMBER(self, token: Token): + return token.value + def PROPERTY_NAME(self, token: Token): + return token.value + def QUOTED_TEXT(self, token: Token): + return PropertyValue("text", token.value[1:-1]) + def quoted_text_array(self, tokens: List[Token]): + result_list = list() + for token in tokens: + result_list.append(token.value) + return PropertyValue("text_array", result_list) + def INCLUDE_C(self, token: Token): + return IncludeC(token.value) \ No newline at end of file diff --git a/Buildscripts/release-sdk.sh b/Buildscripts/release-sdk.sh index 8ac68ac6..eaa60399 100755 --- a/Buildscripts/release-sdk.sh +++ b/Buildscripts/release-sdk.sh @@ -20,37 +20,39 @@ tactility_library_path=$library_path/TactilityC mkdir -p $tactility_library_path/Binary cp build/esp-idf/TactilityC/libTactilityC.a $tactility_library_path/Binary/ mkdir -p $tactility_library_path/Include -find_target_dir=$build_dir/$tactility_library_path/Include/ -cp TactilityC/Include/* $find_target_dir -cp Documentation/license-tactilitysdk.md $build_dir/$tactility_library_path/LICENSE.md +find_target_dir="$build_dir/$tactility_library_path" +cp TactilityC/Include/* "$find_target_dir/Include" +cp TactilityC/*.txt "$find_target_dir" +cp TactilityC/*.md "$find_target_dir" # TactilityFreeRtos tactilityfreertos_library_path=$library_path/TactilityFreeRtos -mkdir -p $tactilityfreertos_library_path/Include -find_target_dir=$build_dir/$tactilityfreertos_library_path/Include/ -cp -r TactilityFreeRtos/Include/* $find_target_dir -cp Documentation/license-tactilitysdk.md $build_dir/$tactilityfreertos_library_path/LICENSE.md +mkdir -p "$tactilityfreertos_library_path/Include" +find_target_dir="$build_dir/$tactilityfreertos_library_path" +cp -r TactilityFreeRtos/Include/* "$find_target_dir/Include" +cp TactilityFreeRtos/*.txt "$find_target_dir" +cp TactilityFreeRtos/*.md "$find_target_dir" # lvgl lvgl_library_path=$library_path/lvgl -mkdir -p $lvgl_library_path/Binary -mkdir -p $lvgl_library_path/Include -cp build/esp-idf/lvgl/liblvgl.a $lvgl_library_path/Binary/ -find_target_dir=$build_dir/$lvgl_library_path/Include/ +mkdir -p "$lvgl_library_path/Binary" +mkdir -p "$lvgl_library_path/Include" +cp build/esp-idf/lvgl/liblvgl.a "$lvgl_library_path/Binary/" +find_target_dir="$build_dir/$lvgl_library_path" cd Libraries/lvgl -find src/ -name '*.h' | cpio -pdm $find_target_dir +find src/ -name '*.h' | cpio -pdm "$find_target_dir/Include" cd - -cp Libraries/lvgl/lvgl.h $find_target_dir -cp Libraries/lvgl/lv_version.h $find_target_dir -cp Libraries/lvgl/LICENCE.txt $lvgl_library_path/LICENSE.txt -cp Libraries/lvgl/src/lv_conf_kconfig.h $lvgl_library_path/Include/lv_conf.h +cp Libraries/lvgl/lvgl.h "$find_target_dir/Include" +cp Libraries/lvgl/lv_version.h "$find_target_dir/Include" +cp Libraries/lvgl/LICENCE.txt "$lvgl_library_path/LICENSE.txt" +cp Libraries/lvgl/src/lv_conf_kconfig.h "$lvgl_library_path/Include/lv_conf.h" # elf_loader -elf_loader_library_path=$library_path/elf_loader -mkdir -p $elf_loader_library_path -cp Libraries/elf_loader/elf_loader.cmake $elf_loader_library_path/ -cp Libraries/elf_loader/license.txt $elf_loader_library_path/ +elf_loader_library_path="$library_path/elf_loader" +mkdir -p "$elf_loader_library_path" +cp Libraries/elf_loader/elf_loader.cmake "$elf_loader_library_path/" +cp Libraries/elf_loader/license.txt "$elf_loader_library_path/" -cp Buildscripts/CMake/TactilitySDK.cmake $target_path/ -cp Buildscripts/CMake/CMakeLists.txt $target_path/ -printf '%s' "$ESP_IDF_VERSION" >> $target_path/idf-version.txt +cp Buildscripts/CMake/TactilitySDK.cmake "$target_path/" +cp Buildscripts/CMake/CMakeLists.txt "$target_path/" +printf '%s' "$ESP_IDF_VERSION" >> "$target_path/idf-version.txt" diff --git a/CMakeLists.txt b/CMakeLists.txt index 39e07512..f34cba51 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,7 +1,6 @@ cmake_minimum_required(VERSION 3.20) set(CMAKE_CXX_STANDARD 23) -set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_ASM_COMPILE_OBJECT "${CMAKE_CXX_COMPILER_TARGET}") include("Buildscripts/logo.cmake") @@ -13,20 +12,28 @@ set(Cyan "${Esc}[36m") file(READ version.txt TACTILITY_VERSION) add_compile_definitions(TT_VERSION="${TACTILITY_VERSION}") +# Determine device identifier and project location +if (DEFINED ENV{ESP_IDF_VERSION}) + include("Buildscripts/device.cmake") + init_tactility_globals("sdkconfig") + get_property(TACTILITY_DEVICE_PROJECT GLOBAL PROPERTY TACTILITY_DEVICE_PROJECT) + get_property(TACTILITY_DEVICE_ID GLOBAL PROPERTY TACTILITY_DEVICE_ID) +else () + set(TACTILITY_DEVICE_PROJECT "Devices/simulator") + set(TACTILITY_DEVICE_ID "simulator") +endif () + if (DEFINED ENV{ESP_IDF_VERSION}) message("Using ESP-IDF ${Cyan}v$ENV{ESP_IDF_VERSION}${ColorReset}") include($ENV{IDF_PATH}/tools/cmake/project.cmake) - include("Buildscripts/device.cmake") - - init_tactility_globals("sdkconfig") - get_property(TACTILITY_DEVICE_PROJECT GLOBAL PROPERTY TACTILITY_DEVICE_PROJECT) - set(COMPONENTS Firmware) set(EXTRA_COMPONENT_DIRS "Firmware" "Devices/${TACTILITY_DEVICE_PROJECT}" "Drivers" + "Platforms/PlatformEsp32" + "TactilityKernel" "Tactility" "TactilityC" "TactilityCore" @@ -69,6 +76,8 @@ if (NOT DEFINED ENV{ESP_IDF_VERSION}) add_subdirectory(Tactility) add_subdirectory(TactilityCore) add_subdirectory(TactilityFreeRtos) + add_subdirectory(TactilityKernel) + add_subdirectory(Platforms/PlatformPosix) add_subdirectory(Devices/simulator) add_subdirectory(Libraries/cJSON) add_subdirectory(Libraries/lv_screenshot) diff --git a/Devices/LICENSE-GPL-3.0.md b/Devices/LICENSE-GPL-3.0.md new file mode 100644 index 00000000..496acdb2 --- /dev/null +++ b/Devices/LICENSE-GPL-3.0.md @@ -0,0 +1,675 @@ +# GNU 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. + +## Preamble + +The GNU General Public License is a free, copyleft license for +software and other kinds of works. + +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom +to share and change all versions of a program--to make sure it remains +free software for all its users. We, the Free Software Foundation, use +the GNU General Public License for most of our software; it applies +also to any other work released this way by its authors. You can apply +it to your programs, too. + +When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you +have certain responsibilities if you distribute copies of the +software, or if you modify it: responsibilities to respect the freedom +of others. + +For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + +Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + +Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the +manufacturer can do so. This is fundamentally incompatible with the +aim of protecting users' freedom to change the software. The +systematic pattern of such abuse occurs in the area of products for +individuals to use, which is precisely where it is most unacceptable. +Therefore, we have designed this version of the GPL to prohibit the +practice for those products. If such problems arise substantially in +other domains, we stand ready to extend this provision to those +domains in future versions of the GPL, as needed to protect the +freedom of users. + +Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish +to avoid the special danger that patents applied to a free program +could make it effectively proprietary. To prevent this, the GPL +assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and +modification follow. + +## TERMS AND CONDITIONS + +### 0. Definitions. + +"This License" refers to version 3 of the GNU General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds +of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of +an exact copy. The resulting work is called a "modified version" of +the earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based +on the Program. + +To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user +through a computer network, with no transfer of a copy, is not +conveying. + +An interactive user interface displays "Appropriate Legal Notices" to +the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + +### 1. Source Code. + +The "source code" for a work means the preferred form of the work for +making modifications to it. "Object code" means any non-source form of +a work. + +A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can +regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same +work. + +### 2. Basic Permissions. + +All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, +without conditions so long as your license otherwise remains in force. +You may convey covered works to others for the sole purpose of having +them make modifications exclusively for you, or provide you with +facilities for running those works, provided that you comply with the +terms of this License in conveying all material for which you do not +control copyright. Those thus making or running the covered works for +you must do so exclusively on your behalf, under your direction and +control, on terms that prohibit them from making any copies of your +copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the +conditions stated below. Sublicensing is not allowed; section 10 makes +it unnecessary. + +### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such +circumvention is effected by exercising rights under this License with +respect to the covered work, and you disclaim any intention to limit +operation or modification of the work as a means of enforcing, against +the work's users, your or third parties' legal rights to forbid +circumvention of technological measures. + +### 4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + +### 5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these +conditions: + +- a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. +- b) The work must carry prominent notices stating that it is + released under this License and any conditions added under + section 7. This requirement modifies the requirement in section 4 + to "keep intact all notices". +- c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. +- d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + +A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + +### 6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms of +sections 4 and 5, provided that you also convey the machine-readable +Corresponding Source under the terms of this License, in one of these +ways: + +- a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. +- b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the Corresponding + Source from a network server at no charge. +- c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. +- d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. +- e) Convey the object code using peer-to-peer transmission, + provided you inform other peers where the object code and + Corresponding Source of the work are being offered to the general + public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, +family, or household purposes, or (2) anything designed or sold for +incorporation into a dwelling. In determining whether a product is a +consumer product, doubtful cases shall be resolved in favor of +coverage. For a particular product received by a particular user, +"normally used" refers to a typical or common use of that class of +product, regardless of the status of the particular user or of the way +in which the particular user actually uses, or expects or is expected +to use, the product. A product is a consumer product regardless of +whether the product has substantial commercial, industrial or +non-consumer uses, unless such uses represent the only significant +mode of use of the product. + +"Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to +install and execute modified versions of a covered work in that User +Product from a modified version of its Corresponding Source. The +information must suffice to ensure that the continued functioning of +the modified object code is in no case prevented or interfered with +solely because modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or +updates for a work that has been modified or installed by the +recipient, or for the User Product in which it has been modified or +installed. Access to a network may be denied when the modification +itself materially and adversely affects the operation of the network +or violates the rules and protocols for communication across the +network. + +Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + +### 7. Additional Terms. + +"Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders +of that material) supplement the terms of this License with terms: + +- a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or +- b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or +- c) Prohibiting misrepresentation of the origin of that material, + or requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or +- d) Limiting the use for publicity purposes of names of licensors + or authors of the material; or +- e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or +- f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions + of it) with contractual assumptions of liability to the recipient, + for any liability that these contractual assumptions directly + impose on those licensors and authors. + +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; the +above requirements apply either way. + +### 8. Termination. + +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + +However, if you cease all violation of this License, then your license +from a particular copyright holder is reinstated (a) provisionally, +unless and until the copyright holder explicitly and finally +terminates your license, and (b) permanently, if the copyright holder +fails to notify you of the violation by some reasonable means prior to +60 days after the cessation. + +Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + +Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + +### 9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run +a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + +### 10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + +### 11. Patents. + +A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned +or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + +If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + +A patent license is "discriminatory" if it does not include within the +scope of its coverage, prohibits the exercise of, or is conditioned on +the non-exercise of one or more of the rights that are specifically +granted under this License. You may not convey a covered work if you +are a party to an arrangement with a third party that is in the +business of distributing software, under which you make payment to the +third party based on the extent of your activity of conveying the +work, and under which the third party grants, to any of the parties +who would receive the covered work from you, a discriminatory patent +license (a) in connection with copies of the covered work conveyed by +you (or copies made from those copies), or (b) primarily for and in +connection with specific products or compilations that contain the +covered work, unless you entered into that arrangement, or that patent +license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + +### 12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under +this License and any other pertinent obligations, then as a +consequence you may not convey it at all. For example, if you agree to +terms that obligate you to collect a royalty for further conveying +from those to whom you convey the Program, the only way you could +satisfy both those terms and this License would be to refrain entirely +from conveying the Program. + +### 13. Use with the GNU Affero General Public License. + +Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + +### 14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions +of the GNU 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 Program +specifies that a certain numbered version of the GNU General Public +License "or any later version" applies to it, you have the option of +following the terms and conditions either of that numbered version or +of any later version published by the Free Software Foundation. If the +Program does not specify a version number of the GNU General Public +License, you may choose any version ever published by the Free +Software Foundation. + +If the Program specifies that a proxy can decide which future versions +of the GNU General Public License can be used, that proxy's public +statement of acceptance of a version permanently authorizes you to +choose that version for the Program. + +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + +### 15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT +WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND +PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE +DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR +CORRECTION. + +### 16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR +CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES +ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT +NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR +LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM +TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER +PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +### 17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + +## How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these +terms. + +To do so, attach the following notices to the program. It is safest to +attach them to the start of each source file to most effectively state +the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 . + +Also add information on how to contact you by electronic and paper +mail. + +If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands \`show w' and \`show c' should show the +appropriate parts of the General Public License. Of course, your +program's commands might be different; for a GUI interface, you would +use an "about box". + +You should also get your employer (if you work as a programmer) or +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. For more information on this, and how to apply and follow +the GNU GPL, see . + +The GNU General Public License does not permit incorporating your +program into proprietary programs. If your program is a subroutine +library, you may consider it more useful to permit linking proprietary +applications with the library. If this is what you want to do, use the +GNU Lesser General Public License instead of this License. But first, +please read . diff --git a/Devices/btt-panda-touch/Source/Drivers.cpp b/Devices/btt-panda-touch/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/btt-panda-touch/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/btt-panda-touch/devicetree.yaml b/Devices/btt-panda-touch/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/btt-panda-touch/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/cyd-2432s024c/Source/Drivers.cpp b/Devices/cyd-2432s024c/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/cyd-2432s024c/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/cyd-2432s024c/devicetree.yaml b/Devices/cyd-2432s024c/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/cyd-2432s024c/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/cyd-2432s028r/Source/Drivers.cpp b/Devices/cyd-2432s028r/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/cyd-2432s028r/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/cyd-2432s028r/devicetree.yaml b/Devices/cyd-2432s028r/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/cyd-2432s028r/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/cyd-2432s028rv3/Source/Drivers.cpp b/Devices/cyd-2432s028rv3/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/cyd-2432s028rv3/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/cyd-2432s028rv3/devicetree.yaml b/Devices/cyd-2432s028rv3/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/cyd-2432s028rv3/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/cyd-2432s032c/Source/Drivers.cpp b/Devices/cyd-2432s032c/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/cyd-2432s032c/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/cyd-2432s032c/devicetree.yaml b/Devices/cyd-2432s032c/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/cyd-2432s032c/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/cyd-4848s040c/Source/Drivers.cpp b/Devices/cyd-4848s040c/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/cyd-4848s040c/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/cyd-4848s040c/devicetree.yaml b/Devices/cyd-4848s040c/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/cyd-4848s040c/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/cyd-8048s043c/Source/Drivers.cpp b/Devices/cyd-8048s043c/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/cyd-8048s043c/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/cyd-8048s043c/devicetree.yaml b/Devices/cyd-8048s043c/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/cyd-8048s043c/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/cyd-e32r28t/Source/Drivers.cpp b/Devices/cyd-e32r28t/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/cyd-e32r28t/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/cyd-e32r28t/devicetree.yaml b/Devices/cyd-e32r28t/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/cyd-e32r28t/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/cyd-e32r32p/Source/Drivers.cpp b/Devices/cyd-e32r32p/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/cyd-e32r32p/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/cyd-e32r32p/devicetree.yaml b/Devices/cyd-e32r32p/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/cyd-e32r32p/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/elecrow-crowpanel-advance-28/Source/Drivers.cpp b/Devices/elecrow-crowpanel-advance-28/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/elecrow-crowpanel-advance-28/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/elecrow-crowpanel-advance-28/devicetree.yaml b/Devices/elecrow-crowpanel-advance-28/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/elecrow-crowpanel-advance-28/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/elecrow-crowpanel-advance-35/Source/Drivers.cpp b/Devices/elecrow-crowpanel-advance-35/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/elecrow-crowpanel-advance-35/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/elecrow-crowpanel-advance-35/devicetree.yaml b/Devices/elecrow-crowpanel-advance-35/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/elecrow-crowpanel-advance-35/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/elecrow-crowpanel-advance-50/Source/Drivers.cpp b/Devices/elecrow-crowpanel-advance-50/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/elecrow-crowpanel-advance-50/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/elecrow-crowpanel-advance-50/devicetree.yaml b/Devices/elecrow-crowpanel-advance-50/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/elecrow-crowpanel-advance-50/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/elecrow-crowpanel-basic-28/Source/Drivers.cpp b/Devices/elecrow-crowpanel-basic-28/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/elecrow-crowpanel-basic-28/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/elecrow-crowpanel-basic-28/devicetree.yaml b/Devices/elecrow-crowpanel-basic-28/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/elecrow-crowpanel-basic-28/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/elecrow-crowpanel-basic-35/Source/Drivers.cpp b/Devices/elecrow-crowpanel-basic-35/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/elecrow-crowpanel-basic-35/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/elecrow-crowpanel-basic-35/devicetree.yaml b/Devices/elecrow-crowpanel-basic-35/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/elecrow-crowpanel-basic-35/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/elecrow-crowpanel-basic-50/Source/Drivers.cpp b/Devices/elecrow-crowpanel-basic-50/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/elecrow-crowpanel-basic-50/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/elecrow-crowpanel-basic-50/devicetree.yaml b/Devices/elecrow-crowpanel-basic-50/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/elecrow-crowpanel-basic-50/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/generic-esp32/Source/Drivers.cpp b/Devices/generic-esp32/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/generic-esp32/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/generic-esp32/devicetree.yaml b/Devices/generic-esp32/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/generic-esp32/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/generic-esp32c6/Source/Drivers.cpp b/Devices/generic-esp32c6/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/generic-esp32c6/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/generic-esp32c6/devicetree.yaml b/Devices/generic-esp32c6/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/generic-esp32c6/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/generic-esp32p4/Source/Drivers.cpp b/Devices/generic-esp32p4/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/generic-esp32p4/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/generic-esp32p4/devicetree.yaml b/Devices/generic-esp32p4/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/generic-esp32p4/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/generic-esp32s3/Source/Drivers.cpp b/Devices/generic-esp32s3/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/generic-esp32s3/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/generic-esp32s3/devicetree.yaml b/Devices/generic-esp32s3/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/generic-esp32s3/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/guition-jc1060p470ciwy/Source/Drivers.cpp b/Devices/guition-jc1060p470ciwy/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/guition-jc1060p470ciwy/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/guition-jc1060p470ciwy/devicetree.yaml b/Devices/guition-jc1060p470ciwy/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/guition-jc1060p470ciwy/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/guition-jc2432w328c/Source/Drivers.cpp b/Devices/guition-jc2432w328c/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/guition-jc2432w328c/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/guition-jc2432w328c/devicetree.yaml b/Devices/guition-jc2432w328c/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/guition-jc2432w328c/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/guition-jc8048w550c/Source/Drivers.cpp b/Devices/guition-jc8048w550c/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/guition-jc8048w550c/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/guition-jc8048w550c/devicetree.yaml b/Devices/guition-jc8048w550c/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/guition-jc8048w550c/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/heltec-wifi-lora-32-v3/Source/Drivers.cpp b/Devices/heltec-wifi-lora-32-v3/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/heltec-wifi-lora-32-v3/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/heltec-wifi-lora-32-v3/devicetree.yaml b/Devices/heltec-wifi-lora-32-v3/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/heltec-wifi-lora-32-v3/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/lilygo-tdeck/Source/Drivers.cpp b/Devices/lilygo-tdeck/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/lilygo-tdeck/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/lilygo-tdeck/devicetree.yaml b/Devices/lilygo-tdeck/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/lilygo-tdeck/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/lilygo-tdisplay-s3/Source/Drivers.cpp b/Devices/lilygo-tdisplay-s3/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/lilygo-tdisplay-s3/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/lilygo-tdisplay-s3/devicetree.yaml b/Devices/lilygo-tdisplay-s3/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/lilygo-tdisplay-s3/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/lilygo-tdisplay/Source/Drivers.cpp b/Devices/lilygo-tdisplay/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/lilygo-tdisplay/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/lilygo-tdisplay/devicetree.yaml b/Devices/lilygo-tdisplay/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/lilygo-tdisplay/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/lilygo-tdongle-s3/Source/Drivers.cpp b/Devices/lilygo-tdongle-s3/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/lilygo-tdongle-s3/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/lilygo-tdongle-s3/devicetree.yaml b/Devices/lilygo-tdongle-s3/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/lilygo-tdongle-s3/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/lilygo-tlora-pager/CMakeLists.txt b/Devices/lilygo-tlora-pager/CMakeLists.txt index 02e89f02..a15cda62 100644 --- a/Devices/lilygo-tlora-pager/CMakeLists.txt +++ b/Devices/lilygo-tlora-pager/CMakeLists.txt @@ -3,5 +3,5 @@ file(GLOB_RECURSE SOURCE_FILES Source/*.c*) idf_component_register( SRCS ${SOURCE_FILES} INCLUDE_DIRS "Source" - REQUIRES Tactility esp_lcd ST7796 BQ25896 BQ27220 TCA8418 DRV2605 PwmBacklight driver esp_adc + REQUIRES Tactility esp_lcd ST7796 BQ25896 BQ27220 TCA8418 DRV2605 PwmBacklight driver esp_adc PlatformEsp32 ) diff --git a/Devices/lilygo-tlora-pager/Source/Drivers.cpp b/Devices/lilygo-tlora-pager/Source/Drivers.cpp new file mode 100644 index 00000000..1eee16a4 --- /dev/null +++ b/Devices/lilygo-tlora-pager/Source/Drivers.cpp @@ -0,0 +1,10 @@ +#include + +extern "C" { + +extern void register_device_drivers() { + extern Driver tlora_pager_driver; + driver_construct(&tlora_pager_driver); +} + +} diff --git a/Devices/lilygo-tlora-pager/Source/bindings/tlora_pager.h b/Devices/lilygo-tlora-pager/Source/bindings/tlora_pager.h new file mode 100644 index 00000000..b550f1d9 --- /dev/null +++ b/Devices/lilygo-tlora-pager/Source/bindings/tlora_pager.h @@ -0,0 +1,15 @@ +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +DEFINE_DEVICETREE(tlora_pager, struct RootConfig) + +#ifdef __cplusplus +} +#endif diff --git a/Devices/lilygo-tlora-pager/Source/drivers/Register.cpp b/Devices/lilygo-tlora-pager/Source/drivers/Register.cpp new file mode 100644 index 00000000..1eee16a4 --- /dev/null +++ b/Devices/lilygo-tlora-pager/Source/drivers/Register.cpp @@ -0,0 +1,10 @@ +#include + +extern "C" { + +extern void register_device_drivers() { + extern Driver tlora_pager_driver; + driver_construct(&tlora_pager_driver); +} + +} diff --git a/Devices/lilygo-tlora-pager/Source/drivers/TloraPager.cpp b/Devices/lilygo-tlora-pager/Source/drivers/TloraPager.cpp new file mode 100644 index 00000000..d1786e5a --- /dev/null +++ b/Devices/lilygo-tlora-pager/Source/drivers/TloraPager.cpp @@ -0,0 +1,27 @@ +#include "TloraPager.h" + +#include + +#include + +extern "C" { + +static int start(Device* device) { + return 0; +} + +static int stop(Device* device) { + return 0; +} + +Driver tlora_pager_driver = { + .name = "T-Lora Pager", + .compatible = (const char*[]) { "lilygo,tlora-pager", nullptr }, + .start_device = start, + .stop_device = stop, + .api = nullptr, + .device_type = nullptr, + .internal = { 0 } +}; + +} diff --git a/Devices/lilygo-tlora-pager/Source/drivers/TloraPager.h b/Devices/lilygo-tlora-pager/Source/drivers/TloraPager.h new file mode 100644 index 00000000..07a90010 --- /dev/null +++ b/Devices/lilygo-tlora-pager/Source/drivers/TloraPager.h @@ -0,0 +1,11 @@ +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#ifdef __cplusplus +} +#endif diff --git a/Devices/lilygo-tlora-pager/devicetree.yaml b/Devices/lilygo-tlora-pager/devicetree.yaml new file mode 100644 index 00000000..82fd189b --- /dev/null +++ b/Devices/lilygo-tlora-pager/devicetree.yaml @@ -0,0 +1,4 @@ +dependencies: + - Platforms/PlatformEsp32 +bindings: ./ +dts: lilygo,tlora-pager.dts diff --git a/Devices/lilygo-tlora-pager/lilygo,tlora-pager.dts b/Devices/lilygo-tlora-pager/lilygo,tlora-pager.dts new file mode 100644 index 00000000..bdd0f9b1 --- /dev/null +++ b/Devices/lilygo-tlora-pager/lilygo,tlora-pager.dts @@ -0,0 +1,23 @@ +/dts-v1/; + +#include +#include +#include + +/ { + compatible = "lilygo,tlora-pager"; + model = "LilyGO T-Lora Pager"; + + gpio0 { + compatible = "espressif,esp32-gpio"; + gpio-count = <49>; + }; + + i2c0 { + compatible = "espressif,esp32-i2c"; + clock-frequency = <100000>; + pin-sda = <&gpio0 3 GPIO_ACTIVE_HIGH>; + pin-scl = <&gpio0 2 GPIO_ACTIVE_HIGH>; + port = ; + }; +}; diff --git a/Devices/lilygo-tlora-pager/lilygo,tlora-pager.yaml b/Devices/lilygo-tlora-pager/lilygo,tlora-pager.yaml new file mode 100644 index 00000000..9e5f0508 --- /dev/null +++ b/Devices/lilygo-tlora-pager/lilygo,tlora-pager.yaml @@ -0,0 +1,5 @@ +description: LilyGO T-Lora Pager + +include: ["root.yaml"] + +compatible: "lilygo,tlora-pager" diff --git a/Devices/m5stack-cardputer-adv/Source/Drivers.cpp b/Devices/m5stack-cardputer-adv/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/m5stack-cardputer-adv/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/m5stack-cardputer-adv/devicetree.yaml b/Devices/m5stack-cardputer-adv/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/m5stack-cardputer-adv/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/m5stack-cardputer/Source/Drivers.cpp b/Devices/m5stack-cardputer/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/m5stack-cardputer/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/m5stack-cardputer/devicetree.yaml b/Devices/m5stack-cardputer/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/m5stack-cardputer/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/m5stack-core2/Source/Drivers.cpp b/Devices/m5stack-core2/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/m5stack-core2/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/m5stack-core2/devicetree.yaml b/Devices/m5stack-core2/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/m5stack-core2/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/m5stack-cores3/Source/Drivers.cpp b/Devices/m5stack-cores3/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/m5stack-cores3/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/m5stack-cores3/devicetree.yaml b/Devices/m5stack-cores3/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/m5stack-cores3/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/m5stack-stickc-plus/Source/Drivers.cpp b/Devices/m5stack-stickc-plus/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/m5stack-stickc-plus/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/m5stack-stickc-plus/devicetree.yaml b/Devices/m5stack-stickc-plus/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/m5stack-stickc-plus/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/m5stack-stickc-plus2/Source/Drivers.cpp b/Devices/m5stack-stickc-plus2/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/m5stack-stickc-plus2/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/m5stack-stickc-plus2/devicetree.yaml b/Devices/m5stack-stickc-plus2/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/m5stack-stickc-plus2/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/placeholder.dts b/Devices/placeholder.dts new file mode 100644 index 00000000..dddca7a8 --- /dev/null +++ b/Devices/placeholder.dts @@ -0,0 +1,8 @@ +/dts-v1/; + +#include + +/ { + compatible = "root"; + model = "Placeholder"; +}; diff --git a/Devices/simulator/Source/Drivers.cpp b/Devices/simulator/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/simulator/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/simulator/devicetree.yaml b/Devices/simulator/devicetree.yaml new file mode 100644 index 00000000..72523d12 --- /dev/null +++ b/Devices/simulator/devicetree.yaml @@ -0,0 +1,4 @@ +dependencies: + - TactilityKernel + - Platforms/PlatformPosix +dts: ../placeholder.dts diff --git a/Devices/simulator/simulator.dts b/Devices/simulator/simulator.dts new file mode 100644 index 00000000..ce2f44c2 --- /dev/null +++ b/Devices/simulator/simulator.dts @@ -0,0 +1,8 @@ +/dts-v1/; + +#include + +/ { + model = "Simulator"; + compatible = "root"; +}; diff --git a/Devices/unphone/Source/Drivers.cpp b/Devices/unphone/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/unphone/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/unphone/devicetree.yaml b/Devices/unphone/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/unphone/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/waveshare-esp32-s3-geek/Source/Drivers.cpp b/Devices/waveshare-esp32-s3-geek/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/waveshare-esp32-s3-geek/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/waveshare-esp32-s3-geek/devicetree.yaml b/Devices/waveshare-esp32-s3-geek/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/waveshare-esp32-s3-geek/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/waveshare-s3-lcd-13/Source/Drivers.cpp b/Devices/waveshare-s3-lcd-13/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/waveshare-s3-lcd-13/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/waveshare-s3-lcd-13/devicetree.yaml b/Devices/waveshare-s3-lcd-13/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/waveshare-s3-lcd-13/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/waveshare-s3-touch-lcd-128/Source/Drivers.cpp b/Devices/waveshare-s3-touch-lcd-128/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/waveshare-s3-touch-lcd-128/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/waveshare-s3-touch-lcd-128/devicetree.yaml b/Devices/waveshare-s3-touch-lcd-128/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/waveshare-s3-touch-lcd-128/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/waveshare-s3-touch-lcd-147/Source/Drivers.cpp b/Devices/waveshare-s3-touch-lcd-147/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/waveshare-s3-touch-lcd-147/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/waveshare-s3-touch-lcd-147/devicetree.yaml b/Devices/waveshare-s3-touch-lcd-147/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/waveshare-s3-touch-lcd-147/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/waveshare-s3-touch-lcd-43/Source/Drivers.cpp b/Devices/waveshare-s3-touch-lcd-43/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/waveshare-s3-touch-lcd-43/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/waveshare-s3-touch-lcd-43/devicetree.yaml b/Devices/waveshare-s3-touch-lcd-43/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/waveshare-s3-touch-lcd-43/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Devices/wireless-tag-wt32-sc01-plus/Source/Drivers.cpp b/Devices/wireless-tag-wt32-sc01-plus/Source/Drivers.cpp new file mode 100644 index 00000000..c8a5c665 --- /dev/null +++ b/Devices/wireless-tag-wt32-sc01-plus/Source/Drivers.cpp @@ -0,0 +1,7 @@ +extern "C" { + +extern void register_device_drivers() { + /* NO-OP */ +} + +} diff --git a/Devices/wireless-tag-wt32-sc01-plus/devicetree.yaml b/Devices/wireless-tag-wt32-sc01-plus/devicetree.yaml new file mode 100644 index 00000000..a1f5d125 --- /dev/null +++ b/Devices/wireless-tag-wt32-sc01-plus/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +dts: ../placeholder.dts diff --git a/Documentation/LICENSE-Apache-2.0.md b/Documentation/LICENSE-Apache-2.0.md new file mode 100644 index 00000000..f5f4b8b5 --- /dev/null +++ b/Documentation/LICENSE-Apache-2.0.md @@ -0,0 +1,195 @@ +Apache License +============== + +_Version 2.0, January 2004_ +_<>_ + +### Terms and Conditions for use, reproduction, and distribution + +#### 1. Definitions + +“License” shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +“Licensor” shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + +“Legal Entity” shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, “control” means **(i)** the power, direct or +indirect, to cause the direction or management of such entity, whether by +contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the +outstanding shares, or **(iii)** beneficial ownership of such entity. + +“You” (or “Your”) shall mean an individual or Legal Entity exercising +permissions granted by this License. + +“Source” form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + +“Object” form shall mean any form resulting from mechanical transformation or +translation of a Source form, including but not limited to compiled object code, +generated documentation, and conversions to other media types. + +“Work” shall mean the work of authorship, whether in Source or Object form, made +available under the License, as indicated by a copyright notice that is included +in or attached to the work (an example is provided in the Appendix below). + +“Derivative Works” shall mean any work, whether in Source or Object form, that +is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative Works +shall not include works that remain separable from, or merely link (or bind by +name) to the interfaces of, the Work and Derivative Works thereof. + +“Contribution” shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative Works +thereof, that is intentionally submitted to Licensor for inclusion in the Work +by the copyright owner or by an individual or Legal Entity authorized to submit +on behalf of the copyright owner. For the purposes of this definition, +“submitted” means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for +the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as “Not a Contribution.” + +“Contributor” shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently +incorporated within the Work. + +#### 2. Grant of Copyright License + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +#### 3. Grant of Patent License + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this section) patent license to make, have +made, use, offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by combination +of their Contribution(s) with the Work to which such Contribution(s) was +submitted. If You institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work or a +Contribution incorporated within the Work constitutes direct or contributory +patent infringement, then any patent licenses granted to You under this License +for that Work shall terminate as of the date such litigation is filed. + +#### 4. Redistribution + +You may reproduce and distribute copies of the Work or Derivative Works thereof +in any medium, with or without modifications, and in Source or Object form, +provided that You meet the following conditions: + +* **(a)** You must give any other recipients of the Work or Derivative Works a copy of +this License; and +* **(b)** You must cause any modified files to carry prominent notices stating that You +changed the files; and +* **(c)** You must retain, in the Source form of any Derivative Works that You distribute, +all copyright, patent, trademark, and attribution notices from the Source form +of the Work, excluding those notices that do not pertain to any part of the +Derivative Works; and +* **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any +Derivative Works that You distribute must include a readable copy of the +attribution notices contained within such NOTICE file, excluding those notices +that do not pertain to any part of the Derivative Works, in at least one of the +following places: within a NOTICE text file distributed as part of the +Derivative Works; within the Source form or documentation, if provided along +with the Derivative Works; or, within a display generated by the Derivative +Works, if and wherever such third-party notices normally appear. The contents of +the NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative Works that +You distribute, alongside or as an addendum to the NOTICE text from the Work, +provided that such additional attribution notices cannot be construed as +modifying the License. + +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + +#### 5. Submission of Contributions + +Unless You explicitly state otherwise, any Contribution intentionally submitted +for inclusion in the Work by You to the Licensor shall be under the terms and +conditions of this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify the terms of +any separate license agreement you may have executed with Licensor regarding +such Contributions. + +#### 6. Trademarks + +This License does not grant permission to use the trade names, trademarks, +service marks, or product names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +#### 7. Disclaimer of Warranty + +Unless required by applicable law or agreed to in writing, Licensor provides the +Work (and each Contributor provides its Contributions) on an “AS IS” BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +including, without limitation, any warranties or conditions of TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your exercise of +permissions under this License. + +#### 8. Limitation of Liability + +In no event and under no legal theory, whether in tort (including negligence), +contract, or otherwise, unless required by applicable law (such as deliberate +and grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, incidental, +or consequential damages of any character arising as a result of this License or +out of the use or inability to use the Work (including but not limited to +damages for loss of goodwill, work stoppage, computer failure or malfunction, or +any and all other commercial damages or losses), even if such Contributor has +been advised of the possibility of such damages. + +#### 9. Accepting Warranty or Additional Liability + +While redistributing the Work or Derivative Works thereof, You may choose to +offer, and charge a fee for, acceptance of support, warranty, indemnity, or +other liability obligations and/or rights consistent with this License. However, +in accepting such obligations, You may act only on Your own behalf and on Your +sole responsibility, not on behalf of any other Contributor, and only if You +agree to indemnify, defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason of your +accepting any such warranty or additional liability. + +_END OF TERMS AND CONDITIONS_ + +### APPENDIX: How to apply the Apache License to your work + +To apply the Apache License to your work, attach the following boilerplate +notice, with the fields enclosed by brackets `[]` replaced with your own +identifying information. (Don't include the brackets!) The text should be +enclosed in the appropriate comment syntax for the file format. We also +recommend that a file or class name and description of purpose be included on +the same “printed page” as the copyright notice for easier identification within +third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/Documentation/LICENSE-GPL-3.0.md b/Documentation/LICENSE-GPL-3.0.md new file mode 100644 index 00000000..496acdb2 --- /dev/null +++ b/Documentation/LICENSE-GPL-3.0.md @@ -0,0 +1,675 @@ +# GNU 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. + +## Preamble + +The GNU General Public License is a free, copyleft license for +software and other kinds of works. + +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom +to share and change all versions of a program--to make sure it remains +free software for all its users. We, the Free Software Foundation, use +the GNU General Public License for most of our software; it applies +also to any other work released this way by its authors. You can apply +it to your programs, too. + +When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you +have certain responsibilities if you distribute copies of the +software, or if you modify it: responsibilities to respect the freedom +of others. + +For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + +Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + +Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the +manufacturer can do so. This is fundamentally incompatible with the +aim of protecting users' freedom to change the software. The +systematic pattern of such abuse occurs in the area of products for +individuals to use, which is precisely where it is most unacceptable. +Therefore, we have designed this version of the GPL to prohibit the +practice for those products. If such problems arise substantially in +other domains, we stand ready to extend this provision to those +domains in future versions of the GPL, as needed to protect the +freedom of users. + +Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish +to avoid the special danger that patents applied to a free program +could make it effectively proprietary. To prevent this, the GPL +assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and +modification follow. + +## TERMS AND CONDITIONS + +### 0. Definitions. + +"This License" refers to version 3 of the GNU General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds +of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of +an exact copy. The resulting work is called a "modified version" of +the earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based +on the Program. + +To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user +through a computer network, with no transfer of a copy, is not +conveying. + +An interactive user interface displays "Appropriate Legal Notices" to +the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + +### 1. Source Code. + +The "source code" for a work means the preferred form of the work for +making modifications to it. "Object code" means any non-source form of +a work. + +A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can +regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same +work. + +### 2. Basic Permissions. + +All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, +without conditions so long as your license otherwise remains in force. +You may convey covered works to others for the sole purpose of having +them make modifications exclusively for you, or provide you with +facilities for running those works, provided that you comply with the +terms of this License in conveying all material for which you do not +control copyright. Those thus making or running the covered works for +you must do so exclusively on your behalf, under your direction and +control, on terms that prohibit them from making any copies of your +copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the +conditions stated below. Sublicensing is not allowed; section 10 makes +it unnecessary. + +### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such +circumvention is effected by exercising rights under this License with +respect to the covered work, and you disclaim any intention to limit +operation or modification of the work as a means of enforcing, against +the work's users, your or third parties' legal rights to forbid +circumvention of technological measures. + +### 4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + +### 5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these +conditions: + +- a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. +- b) The work must carry prominent notices stating that it is + released under this License and any conditions added under + section 7. This requirement modifies the requirement in section 4 + to "keep intact all notices". +- c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. +- d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + +A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + +### 6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms of +sections 4 and 5, provided that you also convey the machine-readable +Corresponding Source under the terms of this License, in one of these +ways: + +- a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. +- b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the Corresponding + Source from a network server at no charge. +- c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. +- d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. +- e) Convey the object code using peer-to-peer transmission, + provided you inform other peers where the object code and + Corresponding Source of the work are being offered to the general + public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, +family, or household purposes, or (2) anything designed or sold for +incorporation into a dwelling. In determining whether a product is a +consumer product, doubtful cases shall be resolved in favor of +coverage. For a particular product received by a particular user, +"normally used" refers to a typical or common use of that class of +product, regardless of the status of the particular user or of the way +in which the particular user actually uses, or expects or is expected +to use, the product. A product is a consumer product regardless of +whether the product has substantial commercial, industrial or +non-consumer uses, unless such uses represent the only significant +mode of use of the product. + +"Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to +install and execute modified versions of a covered work in that User +Product from a modified version of its Corresponding Source. The +information must suffice to ensure that the continued functioning of +the modified object code is in no case prevented or interfered with +solely because modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or +updates for a work that has been modified or installed by the +recipient, or for the User Product in which it has been modified or +installed. Access to a network may be denied when the modification +itself materially and adversely affects the operation of the network +or violates the rules and protocols for communication across the +network. + +Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + +### 7. Additional Terms. + +"Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders +of that material) supplement the terms of this License with terms: + +- a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or +- b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or +- c) Prohibiting misrepresentation of the origin of that material, + or requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or +- d) Limiting the use for publicity purposes of names of licensors + or authors of the material; or +- e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or +- f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions + of it) with contractual assumptions of liability to the recipient, + for any liability that these contractual assumptions directly + impose on those licensors and authors. + +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; the +above requirements apply either way. + +### 8. Termination. + +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + +However, if you cease all violation of this License, then your license +from a particular copyright holder is reinstated (a) provisionally, +unless and until the copyright holder explicitly and finally +terminates your license, and (b) permanently, if the copyright holder +fails to notify you of the violation by some reasonable means prior to +60 days after the cessation. + +Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + +Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + +### 9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run +a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + +### 10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + +### 11. Patents. + +A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned +or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + +If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + +A patent license is "discriminatory" if it does not include within the +scope of its coverage, prohibits the exercise of, or is conditioned on +the non-exercise of one or more of the rights that are specifically +granted under this License. You may not convey a covered work if you +are a party to an arrangement with a third party that is in the +business of distributing software, under which you make payment to the +third party based on the extent of your activity of conveying the +work, and under which the third party grants, to any of the parties +who would receive the covered work from you, a discriminatory patent +license (a) in connection with copies of the covered work conveyed by +you (or copies made from those copies), or (b) primarily for and in +connection with specific products or compilations that contain the +covered work, unless you entered into that arrangement, or that patent +license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + +### 12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under +this License and any other pertinent obligations, then as a +consequence you may not convey it at all. For example, if you agree to +terms that obligate you to collect a royalty for further conveying +from those to whom you convey the Program, the only way you could +satisfy both those terms and this License would be to refrain entirely +from conveying the Program. + +### 13. Use with the GNU Affero General Public License. + +Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + +### 14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions +of the GNU 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 Program +specifies that a certain numbered version of the GNU General Public +License "or any later version" applies to it, you have the option of +following the terms and conditions either of that numbered version or +of any later version published by the Free Software Foundation. If the +Program does not specify a version number of the GNU General Public +License, you may choose any version ever published by the Free +Software Foundation. + +If the Program specifies that a proxy can decide which future versions +of the GNU General Public License can be used, that proxy's public +statement of acceptance of a version permanently authorizes you to +choose that version for the Program. + +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + +### 15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT +WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND +PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE +DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR +CORRECTION. + +### 16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR +CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES +ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT +NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR +LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM +TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER +PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +### 17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + +## How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these +terms. + +To do so, attach the following notices to the program. It is safest to +attach them to the start of each source file to most effectively state +the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 . + +Also add information on how to contact you by electronic and paper +mail. + +If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands \`show w' and \`show c' should show the +appropriate parts of the General Public License. Of course, your +program's commands might be different; for a GUI interface, you would +use an "about box". + +You should also get your employer (if you work as a programmer) or +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. For more information on this, and how to apply and follow +the GNU GPL, see . + +The GNU General Public License does not permit incorporating your +program into proprietary programs. If your program is a subroutine +library, you may consider it more useful to permit linking proprietary +applications with the library. If this is what you want to do, use the +GNU Lesser General Public License instead of this License. But first, +please read . diff --git a/Documentation/LICENSE-LGPL-3.0.md b/Documentation/LICENSE-LGPL-3.0.md new file mode 100644 index 00000000..6fb6a01e --- /dev/null +++ b/Documentation/LICENSE-LGPL-3.0.md @@ -0,0 +1,157 @@ +# 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. diff --git a/Documentation/ideas.md b/Documentation/ideas.md index 76b8286a..96d1ce27 100644 --- a/Documentation/ideas.md +++ b/Documentation/ideas.md @@ -2,6 +2,7 @@ ## Before release +- Add `// SPDX-License-Identifier: LGPL-3.0-only` and similar license mentions to individual files in the project - Change ButtonControl to work with interrupts and xQueue - TCA9534 keyboards should use interrupts - GT911 drivers should use interrupts if it's stable diff --git a/Documentation/license-tactilitykernel.md b/Documentation/license-tactilitykernel.md new file mode 100644 index 00000000..6fb6a01e --- /dev/null +++ b/Documentation/license-tactilitykernel.md @@ -0,0 +1,157 @@ +# 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. diff --git a/Firmware/.gitignore b/Firmware/.gitignore new file mode 100644 index 00000000..673b74ec --- /dev/null +++ b/Firmware/.gitignore @@ -0,0 +1 @@ +Generated/ diff --git a/Firmware/CMakeLists.txt b/Firmware/CMakeLists.txt index eb5d9ff9..8bde86d4 100644 --- a/Firmware/CMakeLists.txt +++ b/Firmware/CMakeLists.txt @@ -2,28 +2,58 @@ cmake_minimum_required(VERSION 3.20) file(GLOB_RECURSE SOURCE_FILES "Source/*.c*") +# For Generate target below if (DEFINED ENV{ESP_IDF_VERSION}) - # Read device id/project include("../Buildscripts/device.cmake") init_tactility_globals("../sdkconfig") get_property(TACTILITY_DEVICE_PROJECT GLOBAL PROPERTY TACTILITY_DEVICE_PROJECT) +else () + set(TACTILITY_DEVICE_ID simulator) + set(COMPONENT_LIB FirmwareSim) +endif () + +set(DEVICETREE_LOCATION "${CMAKE_SOURCE_DIR}/Devices/${TACTILITY_DEVICE_ID}") + +if (DEFINED ENV{ESP_IDF_VERSION}) idf_component_register( - SRCS ${SOURCE_FILES} - REQUIRES ${DEVICE_COMPONENTS} - REQUIRES Tactility TactilityC ${TACTILITY_DEVICE_PROJECT} + SRCS ${SOURCE_FILES} "${CMAKE_SOURCE_DIR}/Firmware/Generated/devicetree.c" + REQUIRES Tactility TactilityC TactilityKernel PlatformEsp32 ${TACTILITY_DEVICE_PROJECT} ) + else () - add_executable(FirmwareSim ${SOURCE_FILES}) - target_link_libraries(FirmwareSim - PRIVATE Tactility - PRIVATE TactilityCore - PRIVATE TactilityFreeRtos - PRIVATE Simulator - PRIVATE SDL2::SDL2-static SDL2-static + add_executable(FirmwareSim ${SOURCE_FILES} "${CMAKE_SOURCE_DIR}/Firmware/Generated/devicetree.c") + target_link_libraries(FirmwareSim PRIVATE + Tactility + TactilityCore + TactilityFreeRtos + TactilityKernel + Simulator + PlatformPosix + SDL2::SDL2-static SDL2-static ) add_definitions(-D_Nullable=) add_definitions(-D_Nonnull=) endif () + +file(MAKE_DIRECTORY "${CMAKE_SOURCE_DIR}/Firmware/Generated") + +# Generate devicetree code and attach to Firmware component +add_custom_command( + OUTPUT "${CMAKE_SOURCE_DIR}/Firmware/Generated/devicetree.c" + "${CMAKE_SOURCE_DIR}/Firmware/Generated/devicetree.h" + COMMAND pip install lark pyyaml + COMMAND python "${CMAKE_SOURCE_DIR}/Buildscripts/DevicetreeCompiler/compile.py" + "${DEVICETREE_LOCATION}" "Firmware/Generated" + WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" + DEPENDS "${DEVICETREE_LOCATION}/devicetree.yaml" # Optional: trigger rebuild if source changes + COMMENT "Generating devicetree source files..." +) +add_custom_target(Generated DEPENDS "${CMAKE_SOURCE_DIR}/Firmware/Generated/devicetree.c") +set_source_files_properties("${CMAKE_SOURCE_DIR}/Firmware/Generated/devicetree.c" PROPERTIES GENERATED TRUE) +set_source_files_properties("${CMAKE_SOURCE_DIR}/Firmware/Generated/devicetree.h" PROPERTIES GENERATED TRUE) +# Update target for generated code +target_sources(${COMPONENT_LIB} PRIVATE "${CMAKE_SOURCE_DIR}/Firmware/Generated/devicetree.c") +target_include_directories(${COMPONENT_LIB} PRIVATE "${CMAKE_SOURCE_DIR}/Firmware/Generated") diff --git a/Firmware/Source/Main.cpp b/Firmware/Source/Main.cpp index 926da64d..d5477ff5 100644 --- a/Firmware/Source/Main.cpp +++ b/Firmware/Source/Main.cpp @@ -1,5 +1,8 @@ #include +#include +#include + #ifdef ESP_PLATFORM #include #else @@ -11,6 +14,10 @@ extern const tt::hal::Configuration hardwareConfiguration; extern "C" { +extern void register_kernel_drivers(); +extern void register_platform_drivers(); +extern void register_device_drivers(); + void app_main() { static const tt::Configuration config = { /** @@ -24,6 +31,11 @@ void app_main() { tt_init_tactility_c(); // ELF bindings for side-loading on ESP32 #endif + register_kernel_drivers(); + register_platform_drivers(); + register_device_drivers(); + + devices_builtin_init(); tt::run(config); } diff --git a/LICENSE.md b/LICENSE.md index 6021f367..3a171c5d 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,26 +1,72 @@ -# Tactility: Main License +# License Grant -The Tactility project code is available under the [GNU General Public License v3](Documentation/license-tactility.md). -Distributions and forks must adhere to the license terms. +## Definitions + +"external apps" or "external applications" refers to applications that are built with the TactilitySDK. +These applications are not part of the Tactility operating system's main firmware. + +"end-users" refers to people who install and/or use Tactility software on their devices. + +## Licensing Intent + +The main intention is to make sure forks of the operating system stay open source, +while external applications can have both open or closed source licenses. + +TactilitySDK combines several subprojects and should not have source code with a GPL licenses inside. + +## Past & Present + +Formerly, there was a mixed usage of [GPL v3.0](Documentation/LICENSE-GPL-3.0.md) for internal subprojects +and [Apache License v2.0](Documentation/LICENSE-Apache-2.0.md) for subprojects that would be used in external apps. + +For future subprojects, [LGPL v3.0](Documentation/LICENSE-LGPL-3.0.md) will be chosen for internal subprojects and +Apache License v2.0 will be chosen for header-only projects. +Existing GPL-licensed projects will retain this license, as it cannot be changed to LGPL. + +The reason is that LGPL allows for logic in header files, but it comes with limitations (e.g. limit of 10 lines of code in headers). +If we write C++ wrappers for C libraries then we want them to be usable for building external apps, without such LGPL limitations. + +## Overview + +Below is an overview of the licenses of some of the subprojects. + +| Project | License | +|--------------------|---------------------| +| Tactility | GPL v3.0 | +| TactilityCore | GPL v3.0 | +| TactilityC | Apache License v2.0 | +| TactilityFreeRTOS | Apache License v2.0 | +| TactilityKernel | LGPL v3.0 | +| Tests | GPL v3.0 | +| Devices/* | GPL v3.0 | +| Drivers/* | (varies) | +| DevicetreeCompiler | Apache License v2.0 | + +Subprojects and directories in this project can contain license files. + +The presence of such a license file indicates that this license applies to all the files and folders that are contained by the folder at the level where the license file resides. + +## Logo The Tactility logo copyrights are owned by Ken Van Hoeylandt. -Firmwares built from [the original repository](https://github.com/ByteWelder/Tactility) can be redistributed with the Tactility logo. -For other usages, [contact me](https://kenvanhoeylandt.net). -Third-party projects that were included in Tactility retain their licenses. +Logo usage is permitted in these scenarios: +- News, blog posts, articles and documentation that write about the official Tactility project. +- Firmwares built with unmodified source code from [the official repository](https://github.com/ByteWelder/Tactility) can be redistributed with the Tactility logo. +- Personal use for local builds that contain Tactility source code (original or modified), and aren't re-distributed online. -# Tactility: Secondary License +Logo usage is forbidden in all other scenarios unless an exception was granted by the author. +For other usages or exceptions, [contact me](https://kenvanhoeylandt.net). -The following projects are also available under [Apache License Version 2.0](Documentation/license-tactilitysdk.md): -- TactilityC -- TactilityFreeRtos -- TactilitySDK (source and binaries) +Practical examples: +- A blog post about Tactility can use screenshots and the logo itself when writing about Tactility +- A developer who forked Tactility to merge new features or fixes to the official Tactility repository is allowed to make builds with the logo, as long as these builds are not re-distributed to end-users. -# Other licenses & copyrights +## Third Party Notices -See [COPYRIGHT.md](COPYRIGHT.md). +Third-party licenses and copyrights are listed in [THIRD-PARTY-NOTICES.md](THIRD-PARTY-NOTICES.md). -# FAQ +## FAQ - Q: Can I build closed source applications? -- A: Yes, but only if you build them as external apps with the TactilitySDK. Internal apps are part of the OS and currently remain licensed under GPL v3. +- A: Yes, external apps can be closed source. All subprojects with an Apache License or LGPL license can be used in this manner. If you fork the project and make an internal app, it must be redistributed under the GPL v3.0 license. diff --git a/Libraries/lv_screenshot/CMakeLists.txt b/Libraries/lv_screenshot/CMakeLists.txt index d6c43221..feee75d3 100644 --- a/Libraries/lv_screenshot/CMakeLists.txt +++ b/Libraries/lv_screenshot/CMakeLists.txt @@ -1,9 +1,5 @@ cmake_minimum_required(VERSION 3.20) -set(CMAKE_CXX_STANDARD 23) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) - if (DEFINED ENV{ESP_IDF_VERSION}) idf_component_register( SRC_DIRS "Source/" diff --git a/Libraries/minmea/CMakeLists.txt b/Libraries/minmea/CMakeLists.txt index 060e07f4..89321e84 100644 --- a/Libraries/minmea/CMakeLists.txt +++ b/Libraries/minmea/CMakeLists.txt @@ -1,9 +1,5 @@ cmake_minimum_required(VERSION 3.20) -set(CMAKE_CXX_STANDARD 23) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) - if (DEFINED ENV{ESP_IDF_VERSION}) idf_component_register( SRC_DIRS "Source/" diff --git a/Platforms/LICENSE-LGPL-3.0.md b/Platforms/LICENSE-LGPL-3.0.md new file mode 100644 index 00000000..6fb6a01e --- /dev/null +++ b/Platforms/LICENSE-LGPL-3.0.md @@ -0,0 +1,157 @@ +# 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. diff --git a/Platforms/PlatformEsp32/Bindings/espressif,esp32-gpio.yaml b/Platforms/PlatformEsp32/Bindings/espressif,esp32-gpio.yaml new file mode 100644 index 00000000..917d14d3 --- /dev/null +++ b/Platforms/PlatformEsp32/Bindings/espressif,esp32-gpio.yaml @@ -0,0 +1,5 @@ +description: ESP32 GPIO Controller + +compatible: "espressif,esp32-gpio" + +include: ["gpio-controller.yaml"] diff --git a/Platforms/PlatformEsp32/Bindings/espressif,esp32-i2c.yaml b/Platforms/PlatformEsp32/Bindings/espressif,esp32-i2c.yaml new file mode 100644 index 00000000..96968f3d --- /dev/null +++ b/Platforms/PlatformEsp32/Bindings/espressif,esp32-i2c.yaml @@ -0,0 +1,12 @@ +description: ESP32 I2C Controller + +include: ["i2c-controller.yaml"] + +compatible: "espressif,esp32-i2c" + +properties: + port: + type: int + description: | + The port number, defined by i2c_port_t. + Depending on the hardware, these values are available: I2C_NUM_0, I2C_NUM_1, LP_I2C_NUM_0 diff --git a/Platforms/PlatformEsp32/CMakeLists.txt b/Platforms/PlatformEsp32/CMakeLists.txt new file mode 100644 index 00000000..d8114435 --- /dev/null +++ b/Platforms/PlatformEsp32/CMakeLists.txt @@ -0,0 +1,20 @@ +cmake_minimum_required(VERSION 3.20) + +file(GLOB_RECURSE SOURCES "Source/*.c**") + +if (DEFINED ENV{ESP_IDF_VERSION}) + + idf_component_register( + SRCS ${SOURCES} + INCLUDE_DIRS "Include/" + REQUIRES TactilityKernel driver + ) + +else () + + add_library(PlatformEsp32 OBJECT) + target_sources(PlatformEsp32 PRIVATE ${SOURCES}) + target_include_directories(PlatformEsp32 PUBLIC Include/) + target_link_libraries(PlatformEsp32 PUBLIC TactilityKernel) + +endif () \ No newline at end of file diff --git a/Platforms/PlatformEsp32/Include/Tactility/bindings/esp32_gpio.h b/Platforms/PlatformEsp32/Include/Tactility/bindings/esp32_gpio.h new file mode 100644 index 00000000..30102715 --- /dev/null +++ b/Platforms/PlatformEsp32/Include/Tactility/bindings/esp32_gpio.h @@ -0,0 +1,14 @@ +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +DEFINE_DEVICETREE(esp32_gpio, struct Esp32GpioConfig) + +#ifdef __cplusplus +} +#endif diff --git a/Platforms/PlatformEsp32/Include/Tactility/bindings/esp32_i2c.h b/Platforms/PlatformEsp32/Include/Tactility/bindings/esp32_i2c.h new file mode 100644 index 00000000..e2826b74 --- /dev/null +++ b/Platforms/PlatformEsp32/Include/Tactility/bindings/esp32_i2c.h @@ -0,0 +1,14 @@ +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +DEFINE_DEVICETREE(esp32_i2c, struct Esp32I2cConfig) + +#ifdef __cplusplus +} +#endif diff --git a/Platforms/PlatformEsp32/Include/Tactility/drivers/Esp32Gpio.h b/Platforms/PlatformEsp32/Include/Tactility/drivers/Esp32Gpio.h new file mode 100644 index 00000000..04245c68 --- /dev/null +++ b/Platforms/PlatformEsp32/Include/Tactility/drivers/Esp32Gpio.h @@ -0,0 +1,15 @@ +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +struct Esp32GpioConfig { + uint8_t gpio_count; +}; + +#ifdef __cplusplus +} +#endif diff --git a/Platforms/PlatformEsp32/Include/Tactility/drivers/Esp32I2c.h b/Platforms/PlatformEsp32/Include/Tactility/drivers/Esp32I2c.h new file mode 100644 index 00000000..55b07b14 --- /dev/null +++ b/Platforms/PlatformEsp32/Include/Tactility/drivers/Esp32I2c.h @@ -0,0 +1,19 @@ +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +struct Esp32I2cConfig { + uint32_t clock_frequency; + struct GpioPinConfig pin_sda; + struct GpioPinConfig pin_scl; + const i2c_port_t port; +}; + +#ifdef __cplusplus +} +#endif diff --git a/Platforms/PlatformEsp32/Source/Esp32Gpio.cpp b/Platforms/PlatformEsp32/Source/Esp32Gpio.cpp new file mode 100644 index 00000000..51bd2e94 --- /dev/null +++ b/Platforms/PlatformEsp32/Source/Esp32Gpio.cpp @@ -0,0 +1,116 @@ +#include + +#include +#include +#include +#include +#include + +#define TAG LOG_TAG(esp32_gpio) + +#define GET_CONFIG(device) ((struct Esp32GpioConfig*)device->internal.driver_data) + +extern "C" { + +static bool set_level(Device* device, gpio_pin_t pin, bool high) { + return gpio_set_level(static_cast(pin), high) == ESP_OK; +} + +static bool get_level(Device* device, gpio_pin_t pin, bool* high) { + *high = gpio_get_level(static_cast(pin)) != 0; + return true; +} + +static bool set_options(Device* device, gpio_pin_t pin, gpio_flags_t options) { + const Esp32GpioConfig* config = GET_CONFIG(device); + + if (pin >= config->gpio_count) { + return false; + } + + gpio_mode_t mode; + if ((options & GPIO_DIRECTION_INPUT_OUTPUT) == GPIO_DIRECTION_INPUT_OUTPUT) { + mode = GPIO_MODE_INPUT_OUTPUT; + } else if (options & GPIO_DIRECTION_INPUT) { + mode = GPIO_MODE_INPUT; + } else if (options & GPIO_DIRECTION_OUTPUT) { + mode = GPIO_MODE_OUTPUT; + } else { + ESP_LOGE(TAG, "set_options: no direction flag specified for pin %d", pin); + return false; + } + + const gpio_config_t esp_config = { + .pin_bit_mask = 1ULL << pin, + .mode = mode, + .pull_up_en = (options & GPIO_PULL_UP) ? GPIO_PULLUP_ENABLE : GPIO_PULLUP_DISABLE, + .pull_down_en = (options & GPIO_PULL_DOWN) ? GPIO_PULLDOWN_ENABLE : GPIO_PULLDOWN_DISABLE, + .intr_type = GPIO_INTERRUPT_FROM_OPTIONS(options), +#if SOC_GPIO_SUPPORT_PIN_HYS_FILTER + .hys_ctrl_mode = GPIO_HYS_SOFT_DISABLE +#endif + }; + + return gpio_config(&esp_config) == ESP_OK; +} + +static bool get_options(Device* device, gpio_pin_t pin, gpio_flags_t* options) { + gpio_io_config_t esp_config; + if (gpio_get_io_config((gpio_num_t)pin, &esp_config) != ESP_OK) { + return false; + } + + gpio_flags_t output = 0; + + if (esp_config.pu) { + output |= GPIO_PULL_UP; + } + + if (esp_config.pd) { + output |= GPIO_PULL_DOWN; + } + + if (esp_config.ie) { + output |= GPIO_DIRECTION_INPUT; + } + + if (esp_config.oe) { + output |= GPIO_DIRECTION_OUTPUT; + } + + if (esp_config.oe_inv) { + output |= GPIO_ACTIVE_LOW; + } + + *options = output; + return true; +} + +static int start(Device* device) { + ESP_LOGI(TAG, "start %s", device->name); + return 0; +} + +static int stop(Device* device) { + ESP_LOGI(TAG, "stop %s", device->name); + return 0; +} + +const static GpioControllerApi esp32_gpio_api = { + .set_level = set_level, + .get_level = get_level, + .set_options = set_options, + .get_options = get_options +}; + +Driver esp32_gpio_driver = { + .name = "esp32_gpio", + .compatible = (const char*[]) { "espressif,esp32-gpio", nullptr }, + .start_device = start, + .stop_device = stop, + .api = (void*)&esp32_gpio_api, + .device_type = nullptr, + .internal = { 0 } +}; + +} // extern "C" diff --git a/Platforms/PlatformEsp32/Source/Esp32I2c.cpp b/Platforms/PlatformEsp32/Source/Esp32I2c.cpp new file mode 100644 index 00000000..4599f7db --- /dev/null +++ b/Platforms/PlatformEsp32/Source/Esp32I2c.cpp @@ -0,0 +1,91 @@ +#include + +#include +#include +#include +#include + +#define TAG LOG_TAG(esp32_i2c) + +struct InternalData { + Mutex mutex { 0 }; + + InternalData() { + mutex_construct(&mutex); + } + + ~InternalData() { + mutex_destruct(&mutex); + } +}; + +#define GET_CONFIG(device) ((Esp32I2cConfig*)device->config) +#define GET_DATA(device) ((InternalData*)device->internal.driver_data) + +#define lock(data) mutex_lock(&data->mutex); +#define unlock(data) mutex_unlock(&data->mutex); + +extern "C" { + +static bool read(Device* device, uint8_t address, uint8_t* data, size_t data_size, TickType_t timeout) { + vPortAssertIfInISR(); + auto* driver_data = GET_DATA(device); + lock(driver_data); + const esp_err_t result = i2c_master_read_from_device(GET_CONFIG(device)->port, address, data, data_size, timeout); + unlock(driver_data); + ESP_ERROR_CHECK_WITHOUT_ABORT(result); + return result == ESP_OK; +} + +static bool write(Device* device, uint8_t address, const uint8_t* data, uint16_t dataSize, TickType_t timeout) { + vPortAssertIfInISR(); + auto* driver_data = GET_DATA(device); + lock(driver_data); + const esp_err_t result = i2c_master_write_to_device(GET_CONFIG(device)->port, address, data, dataSize, timeout); + unlock(driver_data); + ESP_ERROR_CHECK_WITHOUT_ABORT(result); + return result == ESP_OK; +} + +static bool write_read(Device* device, uint8_t address, const uint8_t* write_data, size_t write_data_size, uint8_t* read_data, size_t read_data_size, TickType_t timeout) { + vPortAssertIfInISR(); + auto* driver_data = GET_DATA(device); + lock(driver_data); + const esp_err_t result = i2c_master_write_read_device(GET_CONFIG(device)->port, address, write_data, write_data_size, read_data, read_data_size, timeout); + unlock(driver_data); + ESP_ERROR_CHECK_WITHOUT_ABORT(result); + return result == ESP_OK; +} + +static int start(Device* device) { + ESP_LOGI(TAG, "start %s", device->name); + auto* data = new InternalData(); + device_set_driver_data(device, data); + return 0; +} + +static int stop(Device* device) { + ESP_LOGI(TAG, "stop %s", device->name); + auto* driver_data = static_cast(device_get_driver_data(device)); + device_set_driver_data(device, nullptr); + delete driver_data; + return 0; +} + +const I2cControllerApi esp32_i2c_api = { + .read = read, + .write = write, + .write_read = write_read +}; + +Driver esp32_i2c_driver = { + .name = "esp32_i2c", + .compatible = (const char*[]) { "espressif,esp32-i2c", nullptr }, + .start_device = start, + .stop_device = stop, + .api = (void*)&esp32_i2c_api, + .device_type = &I2C_CONTROLLER_TYPE, + .internal = { 0 } +}; + +} // extern "C" diff --git a/Platforms/PlatformEsp32/Source/Register.cpp b/Platforms/PlatformEsp32/Source/Register.cpp new file mode 100644 index 00000000..1293e28a --- /dev/null +++ b/Platforms/PlatformEsp32/Source/Register.cpp @@ -0,0 +1,12 @@ +#include + +extern "C" { + +extern void register_platform_drivers() { + extern Driver esp32_gpio_driver; + driver_construct(&esp32_gpio_driver); + extern Driver esp32_i2c_driver; + driver_construct(&esp32_i2c_driver); +} + +} diff --git a/Platforms/PlatformEsp32/devicetree.yaml b/Platforms/PlatformEsp32/devicetree.yaml new file mode 100644 index 00000000..df5465c0 --- /dev/null +++ b/Platforms/PlatformEsp32/devicetree.yaml @@ -0,0 +1,3 @@ +dependencies: + - TactilityKernel +bindings: Bindings diff --git a/Platforms/PlatformPosix/CMakeLists.txt b/Platforms/PlatformPosix/CMakeLists.txt new file mode 100644 index 00000000..0f794775 --- /dev/null +++ b/Platforms/PlatformPosix/CMakeLists.txt @@ -0,0 +1,20 @@ +cmake_minimum_required(VERSION 3.20) + +file(GLOB_RECURSE SOURCES "Source/*.c**") + +if (DEFINED ENV{ESP_IDF_VERSION}) + + idf_component_register( + SRCS ${SOURCES} +# INCLUDE_DIRS "Include/" + REQUIRES TactilityKernel driver + ) + +else () + + add_library(PlatformPosix OBJECT) + target_sources(PlatformPosix PRIVATE ${SOURCES}) +# target_include_directories(PlatformPosix PUBLIC Include/) + target_link_libraries(PlatformPosix PUBLIC TactilityKernel) + +endif () \ No newline at end of file diff --git a/Platforms/PlatformPosix/Source/Register.cpp b/Platforms/PlatformPosix/Source/Register.cpp new file mode 100644 index 00000000..6453236e --- /dev/null +++ b/Platforms/PlatformPosix/Source/Register.cpp @@ -0,0 +1,9 @@ +#include + +extern "C" { + +extern void register_platform_drivers() { + /* Placeholder */ +} + +} diff --git a/Platforms/PlatformPosix/devicetree.yaml b/Platforms/PlatformPosix/devicetree.yaml new file mode 100644 index 00000000..6bbb2436 --- /dev/null +++ b/Platforms/PlatformPosix/devicetree.yaml @@ -0,0 +1,2 @@ +dependencies: + - TactilityKernel diff --git a/COPYRIGHT.md b/THIRD-PARTY-NOTICES.md similarity index 80% rename from COPYRIGHT.md rename to THIRD-PARTY-NOTICES.md index 943b3a4e..8fda14b6 100644 --- a/COPYRIGHT.md +++ b/THIRD-PARTY-NOTICES.md @@ -1,8 +1,4 @@ -# Tactility - -See [LICENSE.md](LICENSE.md) - -# Dependencies +# Third-Party Notices ### ESP-IDF @@ -10,12 +6,12 @@ This project uses ESP-IDF to compile the ESP32 firmware. Website: https://www.espressif.com/ -License: [GPL v3.0](https://github.com/espressif/esp-idf/blob/master/LICENSE) +License: [Apache License v2.0](https://github.com/espressif/esp-idf/blob/master/LICENSE) ### Flipper Zero Firmware -Some of the code in this project has originally been adapted from the Flipper Zero firmware. -It was changed to fit the Tactility project. +Some of the code in inside the Tactility or TactilityCore project has originally been adapted +from the Flipper Zero firmware it was changed to fit the Tactility project. Website: https://github.com/flipperdevices/flipperzero-firmware/ @@ -65,6 +61,6 @@ Website: https://github.com/UsefulElectronics/esp32s3-gc9a01-lvgl License: [Explicitly granted by author](https://github.com/ByteWelder/Tactility/pull/295#discussion_r2226215423) -### Other Components +### Other Dependencies -See `/components` for the respective projects and their licenses. +Some dependencies contain their own license. For example: the subprojects in `Libraries/` diff --git a/Tactility/CMakeLists.txt b/Tactility/CMakeLists.txt index 0f78a544..ba8c0430 100644 --- a/Tactility/CMakeLists.txt +++ b/Tactility/CMakeLists.txt @@ -1,12 +1,10 @@ cmake_minimum_required(VERSION 3.20) -set(CMAKE_CXX_STANDARD 23) -set(CMAKE_CXX_STANDARD_REQUIRED ON) - if (DEFINED ENV{ESP_IDF_VERSION}) file(GLOB_RECURSE SOURCE_FILES Source/*.c*) list(APPEND REQUIRES_LIST + TactilityKernel TactilityCore TactilityFreeRtos lvgl @@ -29,6 +27,7 @@ if (DEFINED ENV{ESP_IDF_VERSION}) lwip spi_flash ) + if ("${IDF_TARGET}" STREQUAL "esp32s3") list(APPEND REQUIRES_LIST esp_tinyusb) endif () @@ -50,7 +49,6 @@ if (DEFINED ENV{ESP_IDF_VERSION}) # Read-write fatfs_create_spiflash_image(data "${CMAKE_CURRENT_SOURCE_DIR}/../Data/data" FLASH_IN_PROJECT PRESERVE_TIME) endif () - else() file(GLOB_RECURSE SOURCES "Source/*.c*") @@ -75,6 +73,7 @@ else() PUBLIC cJSON PUBLIC TactilityFreeRtos PUBLIC TactilityCore + PUBLIC TactilityKernel PUBLIC freertos_kernel PUBLIC lvgl PUBLIC lv_screenshot diff --git a/Tactility/Include/Tactility/Tactility.h b/Tactility/Include/Tactility/Tactility.h index bd229f9e..b0fc801e 100644 --- a/Tactility/Include/Tactility/Tactility.h +++ b/Tactility/Include/Tactility/Tactility.h @@ -7,8 +7,6 @@ namespace tt { -namespace app::launcher { extern const AppManifest manifest; } - /** @brief The configuration for the operating system * It contains the hardware configuration, apps and services */ diff --git a/Tactility/LICENSE-GPL-3.0.md b/Tactility/LICENSE-GPL-3.0.md new file mode 100644 index 00000000..496acdb2 --- /dev/null +++ b/Tactility/LICENSE-GPL-3.0.md @@ -0,0 +1,675 @@ +# GNU 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. + +## Preamble + +The GNU General Public License is a free, copyleft license for +software and other kinds of works. + +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom +to share and change all versions of a program--to make sure it remains +free software for all its users. We, the Free Software Foundation, use +the GNU General Public License for most of our software; it applies +also to any other work released this way by its authors. You can apply +it to your programs, too. + +When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you +have certain responsibilities if you distribute copies of the +software, or if you modify it: responsibilities to respect the freedom +of others. + +For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + +Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + +Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the +manufacturer can do so. This is fundamentally incompatible with the +aim of protecting users' freedom to change the software. The +systematic pattern of such abuse occurs in the area of products for +individuals to use, which is precisely where it is most unacceptable. +Therefore, we have designed this version of the GPL to prohibit the +practice for those products. If such problems arise substantially in +other domains, we stand ready to extend this provision to those +domains in future versions of the GPL, as needed to protect the +freedom of users. + +Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish +to avoid the special danger that patents applied to a free program +could make it effectively proprietary. To prevent this, the GPL +assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and +modification follow. + +## TERMS AND CONDITIONS + +### 0. Definitions. + +"This License" refers to version 3 of the GNU General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds +of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of +an exact copy. The resulting work is called a "modified version" of +the earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based +on the Program. + +To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user +through a computer network, with no transfer of a copy, is not +conveying. + +An interactive user interface displays "Appropriate Legal Notices" to +the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + +### 1. Source Code. + +The "source code" for a work means the preferred form of the work for +making modifications to it. "Object code" means any non-source form of +a work. + +A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can +regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same +work. + +### 2. Basic Permissions. + +All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, +without conditions so long as your license otherwise remains in force. +You may convey covered works to others for the sole purpose of having +them make modifications exclusively for you, or provide you with +facilities for running those works, provided that you comply with the +terms of this License in conveying all material for which you do not +control copyright. Those thus making or running the covered works for +you must do so exclusively on your behalf, under your direction and +control, on terms that prohibit them from making any copies of your +copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the +conditions stated below. Sublicensing is not allowed; section 10 makes +it unnecessary. + +### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such +circumvention is effected by exercising rights under this License with +respect to the covered work, and you disclaim any intention to limit +operation or modification of the work as a means of enforcing, against +the work's users, your or third parties' legal rights to forbid +circumvention of technological measures. + +### 4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + +### 5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these +conditions: + +- a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. +- b) The work must carry prominent notices stating that it is + released under this License and any conditions added under + section 7. This requirement modifies the requirement in section 4 + to "keep intact all notices". +- c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. +- d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + +A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + +### 6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms of +sections 4 and 5, provided that you also convey the machine-readable +Corresponding Source under the terms of this License, in one of these +ways: + +- a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. +- b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the Corresponding + Source from a network server at no charge. +- c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. +- d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. +- e) Convey the object code using peer-to-peer transmission, + provided you inform other peers where the object code and + Corresponding Source of the work are being offered to the general + public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, +family, or household purposes, or (2) anything designed or sold for +incorporation into a dwelling. In determining whether a product is a +consumer product, doubtful cases shall be resolved in favor of +coverage. For a particular product received by a particular user, +"normally used" refers to a typical or common use of that class of +product, regardless of the status of the particular user or of the way +in which the particular user actually uses, or expects or is expected +to use, the product. A product is a consumer product regardless of +whether the product has substantial commercial, industrial or +non-consumer uses, unless such uses represent the only significant +mode of use of the product. + +"Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to +install and execute modified versions of a covered work in that User +Product from a modified version of its Corresponding Source. The +information must suffice to ensure that the continued functioning of +the modified object code is in no case prevented or interfered with +solely because modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or +updates for a work that has been modified or installed by the +recipient, or for the User Product in which it has been modified or +installed. Access to a network may be denied when the modification +itself materially and adversely affects the operation of the network +or violates the rules and protocols for communication across the +network. + +Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + +### 7. Additional Terms. + +"Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders +of that material) supplement the terms of this License with terms: + +- a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or +- b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or +- c) Prohibiting misrepresentation of the origin of that material, + or requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or +- d) Limiting the use for publicity purposes of names of licensors + or authors of the material; or +- e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or +- f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions + of it) with contractual assumptions of liability to the recipient, + for any liability that these contractual assumptions directly + impose on those licensors and authors. + +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; the +above requirements apply either way. + +### 8. Termination. + +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + +However, if you cease all violation of this License, then your license +from a particular copyright holder is reinstated (a) provisionally, +unless and until the copyright holder explicitly and finally +terminates your license, and (b) permanently, if the copyright holder +fails to notify you of the violation by some reasonable means prior to +60 days after the cessation. + +Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + +Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + +### 9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run +a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + +### 10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + +### 11. Patents. + +A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned +or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + +If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + +A patent license is "discriminatory" if it does not include within the +scope of its coverage, prohibits the exercise of, or is conditioned on +the non-exercise of one or more of the rights that are specifically +granted under this License. You may not convey a covered work if you +are a party to an arrangement with a third party that is in the +business of distributing software, under which you make payment to the +third party based on the extent of your activity of conveying the +work, and under which the third party grants, to any of the parties +who would receive the covered work from you, a discriminatory patent +license (a) in connection with copies of the covered work conveyed by +you (or copies made from those copies), or (b) primarily for and in +connection with specific products or compilations that contain the +covered work, unless you entered into that arrangement, or that patent +license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + +### 12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under +this License and any other pertinent obligations, then as a +consequence you may not convey it at all. For example, if you agree to +terms that obligate you to collect a royalty for further conveying +from those to whom you convey the Program, the only way you could +satisfy both those terms and this License would be to refrain entirely +from conveying the Program. + +### 13. Use with the GNU Affero General Public License. + +Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + +### 14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions +of the GNU 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 Program +specifies that a certain numbered version of the GNU General Public +License "or any later version" applies to it, you have the option of +following the terms and conditions either of that numbered version or +of any later version published by the Free Software Foundation. If the +Program does not specify a version number of the GNU General Public +License, you may choose any version ever published by the Free +Software Foundation. + +If the Program specifies that a proxy can decide which future versions +of the GNU General Public License can be used, that proxy's public +statement of acceptance of a version permanently authorizes you to +choose that version for the Program. + +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + +### 15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT +WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND +PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE +DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR +CORRECTION. + +### 16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR +CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES +ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT +NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR +LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM +TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER +PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +### 17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + +## How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these +terms. + +To do so, attach the following notices to the program. It is safest to +attach them to the start of each source file to most effectively state +the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 . + +Also add information on how to contact you by electronic and paper +mail. + +If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands \`show w' and \`show c' should show the +appropriate parts of the General Public License. Of course, your +program's commands might be different; for a GUI interface, you would +use an "about box". + +You should also get your employer (if you work as a programmer) or +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. For more information on this, and how to apply and follow +the GNU GPL, see . + +The GNU General Public License does not permit incorporating your +program into proprietary programs. If your program is a subroutine +library, you may consider it more useful to permit linking proprietary +applications with the library. If this is what you want to do, use the +GNU Lesser General Public License instead of this License. But first, +please read . diff --git a/TactilityC/CMakeLists.txt b/TactilityC/CMakeLists.txt index 97c81c4a..c8f82b3c 100644 --- a/TactilityC/CMakeLists.txt +++ b/TactilityC/CMakeLists.txt @@ -1,8 +1,5 @@ cmake_minimum_required(VERSION 3.20) -set(CMAKE_CXX_STANDARD 23) -set(CMAKE_CXX_STANDARD_REQUIRED ON) - if (DEFINED ENV{ESP_IDF_VERSION}) file(GLOB_RECURSE SOURCE_FILES Source/*.c*) diff --git a/TactilityC/LICENSE-Apache-2.0.md b/TactilityC/LICENSE-Apache-2.0.md new file mode 100644 index 00000000..f5f4b8b5 --- /dev/null +++ b/TactilityC/LICENSE-Apache-2.0.md @@ -0,0 +1,195 @@ +Apache License +============== + +_Version 2.0, January 2004_ +_<>_ + +### Terms and Conditions for use, reproduction, and distribution + +#### 1. Definitions + +“License” shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +“Licensor” shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + +“Legal Entity” shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, “control” means **(i)** the power, direct or +indirect, to cause the direction or management of such entity, whether by +contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the +outstanding shares, or **(iii)** beneficial ownership of such entity. + +“You” (or “Your”) shall mean an individual or Legal Entity exercising +permissions granted by this License. + +“Source” form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + +“Object” form shall mean any form resulting from mechanical transformation or +translation of a Source form, including but not limited to compiled object code, +generated documentation, and conversions to other media types. + +“Work” shall mean the work of authorship, whether in Source or Object form, made +available under the License, as indicated by a copyright notice that is included +in or attached to the work (an example is provided in the Appendix below). + +“Derivative Works” shall mean any work, whether in Source or Object form, that +is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative Works +shall not include works that remain separable from, or merely link (or bind by +name) to the interfaces of, the Work and Derivative Works thereof. + +“Contribution” shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative Works +thereof, that is intentionally submitted to Licensor for inclusion in the Work +by the copyright owner or by an individual or Legal Entity authorized to submit +on behalf of the copyright owner. For the purposes of this definition, +“submitted” means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for +the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as “Not a Contribution.” + +“Contributor” shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently +incorporated within the Work. + +#### 2. Grant of Copyright License + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +#### 3. Grant of Patent License + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this section) patent license to make, have +made, use, offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by combination +of their Contribution(s) with the Work to which such Contribution(s) was +submitted. If You institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work or a +Contribution incorporated within the Work constitutes direct or contributory +patent infringement, then any patent licenses granted to You under this License +for that Work shall terminate as of the date such litigation is filed. + +#### 4. Redistribution + +You may reproduce and distribute copies of the Work or Derivative Works thereof +in any medium, with or without modifications, and in Source or Object form, +provided that You meet the following conditions: + +* **(a)** You must give any other recipients of the Work or Derivative Works a copy of +this License; and +* **(b)** You must cause any modified files to carry prominent notices stating that You +changed the files; and +* **(c)** You must retain, in the Source form of any Derivative Works that You distribute, +all copyright, patent, trademark, and attribution notices from the Source form +of the Work, excluding those notices that do not pertain to any part of the +Derivative Works; and +* **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any +Derivative Works that You distribute must include a readable copy of the +attribution notices contained within such NOTICE file, excluding those notices +that do not pertain to any part of the Derivative Works, in at least one of the +following places: within a NOTICE text file distributed as part of the +Derivative Works; within the Source form or documentation, if provided along +with the Derivative Works; or, within a display generated by the Derivative +Works, if and wherever such third-party notices normally appear. The contents of +the NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative Works that +You distribute, alongside or as an addendum to the NOTICE text from the Work, +provided that such additional attribution notices cannot be construed as +modifying the License. + +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + +#### 5. Submission of Contributions + +Unless You explicitly state otherwise, any Contribution intentionally submitted +for inclusion in the Work by You to the Licensor shall be under the terms and +conditions of this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify the terms of +any separate license agreement you may have executed with Licensor regarding +such Contributions. + +#### 6. Trademarks + +This License does not grant permission to use the trade names, trademarks, +service marks, or product names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +#### 7. Disclaimer of Warranty + +Unless required by applicable law or agreed to in writing, Licensor provides the +Work (and each Contributor provides its Contributions) on an “AS IS” BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +including, without limitation, any warranties or conditions of TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your exercise of +permissions under this License. + +#### 8. Limitation of Liability + +In no event and under no legal theory, whether in tort (including negligence), +contract, or otherwise, unless required by applicable law (such as deliberate +and grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, incidental, +or consequential damages of any character arising as a result of this License or +out of the use or inability to use the Work (including but not limited to +damages for loss of goodwill, work stoppage, computer failure or malfunction, or +any and all other commercial damages or losses), even if such Contributor has +been advised of the possibility of such damages. + +#### 9. Accepting Warranty or Additional Liability + +While redistributing the Work or Derivative Works thereof, You may choose to +offer, and charge a fee for, acceptance of support, warranty, indemnity, or +other liability obligations and/or rights consistent with this License. However, +in accepting such obligations, You may act only on Your own behalf and on Your +sole responsibility, not on behalf of any other Contributor, and only if You +agree to indemnify, defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason of your +accepting any such warranty or additional liability. + +_END OF TERMS AND CONDITIONS_ + +### APPENDIX: How to apply the Apache License to your work + +To apply the Apache License to your work, attach the following boilerplate +notice, with the fields enclosed by brackets `[]` replaced with your own +identifying information. (Don't include the brackets!) The text should be +enclosed in the appropriate comment syntax for the file format. We also +recommend that a file or class name and description of purpose be included on +the same “printed page” as the copyright notice for easier identification within +third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/TactilityCore/CMakeLists.txt b/TactilityCore/CMakeLists.txt index b57398a1..b1c8891f 100644 --- a/TactilityCore/CMakeLists.txt +++ b/TactilityCore/CMakeLists.txt @@ -1,8 +1,5 @@ cmake_minimum_required(VERSION 3.20) -set(CMAKE_CXX_STANDARD 23) -set(CMAKE_CXX_STANDARD_REQUIRED ON) - if (DEFINED ENV{ESP_IDF_VERSION}) file(GLOB_RECURSE SOURCE_FILES Source/*.c*) @@ -24,9 +21,7 @@ else() PRIVATE ${SOURCES} ) - target_include_directories(TactilityCore SYSTEM - PUBLIC Include/ - ) + target_include_directories(TactilityCore PUBLIC Include/) add_definitions(-D_Nullable=) add_definitions(-D_Nonnull=) diff --git a/TactilityCore/Include/Tactility/LoggerAdapterGeneric.h b/TactilityCore/Include/Tactility/LoggerAdapterGeneric.h index 6ed0a26f..72b2aa5f 100644 --- a/TactilityCore/Include/Tactility/LoggerAdapterGeneric.h +++ b/TactilityCore/Include/Tactility/LoggerAdapterGeneric.h @@ -29,7 +29,7 @@ static const LoggerAdapter genericLoggerAdapter = [](LogLevel level, const char* constexpr auto COLOR_GREY = "\033[37m"; std::stringstream buffer; buffer << COLOR_GREY << getLogTimestamp() << ' ' << toTagColour(level) << toPrefix(level) << COLOR_GREY << " [" << COLOR_RESET << tag << COLOR_GREY << "] " << toMessageColour(level) << message << COLOR_RESET << std::endl; - printf(buffer.str().c_str()); + printf("%s", buffer.str().c_str()); }; } \ No newline at end of file diff --git a/TactilityCore/LICENSE-GPL-3.0.md b/TactilityCore/LICENSE-GPL-3.0.md new file mode 100644 index 00000000..496acdb2 --- /dev/null +++ b/TactilityCore/LICENSE-GPL-3.0.md @@ -0,0 +1,675 @@ +# GNU 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. + +## Preamble + +The GNU General Public License is a free, copyleft license for +software and other kinds of works. + +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom +to share and change all versions of a program--to make sure it remains +free software for all its users. We, the Free Software Foundation, use +the GNU General Public License for most of our software; it applies +also to any other work released this way by its authors. You can apply +it to your programs, too. + +When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you +have certain responsibilities if you distribute copies of the +software, or if you modify it: responsibilities to respect the freedom +of others. + +For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + +Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + +Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the +manufacturer can do so. This is fundamentally incompatible with the +aim of protecting users' freedom to change the software. The +systematic pattern of such abuse occurs in the area of products for +individuals to use, which is precisely where it is most unacceptable. +Therefore, we have designed this version of the GPL to prohibit the +practice for those products. If such problems arise substantially in +other domains, we stand ready to extend this provision to those +domains in future versions of the GPL, as needed to protect the +freedom of users. + +Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish +to avoid the special danger that patents applied to a free program +could make it effectively proprietary. To prevent this, the GPL +assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and +modification follow. + +## TERMS AND CONDITIONS + +### 0. Definitions. + +"This License" refers to version 3 of the GNU General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds +of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of +an exact copy. The resulting work is called a "modified version" of +the earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based +on the Program. + +To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user +through a computer network, with no transfer of a copy, is not +conveying. + +An interactive user interface displays "Appropriate Legal Notices" to +the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + +### 1. Source Code. + +The "source code" for a work means the preferred form of the work for +making modifications to it. "Object code" means any non-source form of +a work. + +A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can +regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same +work. + +### 2. Basic Permissions. + +All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, +without conditions so long as your license otherwise remains in force. +You may convey covered works to others for the sole purpose of having +them make modifications exclusively for you, or provide you with +facilities for running those works, provided that you comply with the +terms of this License in conveying all material for which you do not +control copyright. Those thus making or running the covered works for +you must do so exclusively on your behalf, under your direction and +control, on terms that prohibit them from making any copies of your +copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the +conditions stated below. Sublicensing is not allowed; section 10 makes +it unnecessary. + +### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such +circumvention is effected by exercising rights under this License with +respect to the covered work, and you disclaim any intention to limit +operation or modification of the work as a means of enforcing, against +the work's users, your or third parties' legal rights to forbid +circumvention of technological measures. + +### 4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + +### 5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these +conditions: + +- a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. +- b) The work must carry prominent notices stating that it is + released under this License and any conditions added under + section 7. This requirement modifies the requirement in section 4 + to "keep intact all notices". +- c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. +- d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + +A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + +### 6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms of +sections 4 and 5, provided that you also convey the machine-readable +Corresponding Source under the terms of this License, in one of these +ways: + +- a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. +- b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the Corresponding + Source from a network server at no charge. +- c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. +- d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. +- e) Convey the object code using peer-to-peer transmission, + provided you inform other peers where the object code and + Corresponding Source of the work are being offered to the general + public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, +family, or household purposes, or (2) anything designed or sold for +incorporation into a dwelling. In determining whether a product is a +consumer product, doubtful cases shall be resolved in favor of +coverage. For a particular product received by a particular user, +"normally used" refers to a typical or common use of that class of +product, regardless of the status of the particular user or of the way +in which the particular user actually uses, or expects or is expected +to use, the product. A product is a consumer product regardless of +whether the product has substantial commercial, industrial or +non-consumer uses, unless such uses represent the only significant +mode of use of the product. + +"Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to +install and execute modified versions of a covered work in that User +Product from a modified version of its Corresponding Source. The +information must suffice to ensure that the continued functioning of +the modified object code is in no case prevented or interfered with +solely because modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or +updates for a work that has been modified or installed by the +recipient, or for the User Product in which it has been modified or +installed. Access to a network may be denied when the modification +itself materially and adversely affects the operation of the network +or violates the rules and protocols for communication across the +network. + +Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + +### 7. Additional Terms. + +"Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders +of that material) supplement the terms of this License with terms: + +- a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or +- b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or +- c) Prohibiting misrepresentation of the origin of that material, + or requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or +- d) Limiting the use for publicity purposes of names of licensors + or authors of the material; or +- e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or +- f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions + of it) with contractual assumptions of liability to the recipient, + for any liability that these contractual assumptions directly + impose on those licensors and authors. + +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; the +above requirements apply either way. + +### 8. Termination. + +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + +However, if you cease all violation of this License, then your license +from a particular copyright holder is reinstated (a) provisionally, +unless and until the copyright holder explicitly and finally +terminates your license, and (b) permanently, if the copyright holder +fails to notify you of the violation by some reasonable means prior to +60 days after the cessation. + +Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + +Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + +### 9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run +a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + +### 10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + +### 11. Patents. + +A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned +or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + +If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + +A patent license is "discriminatory" if it does not include within the +scope of its coverage, prohibits the exercise of, or is conditioned on +the non-exercise of one or more of the rights that are specifically +granted under this License. You may not convey a covered work if you +are a party to an arrangement with a third party that is in the +business of distributing software, under which you make payment to the +third party based on the extent of your activity of conveying the +work, and under which the third party grants, to any of the parties +who would receive the covered work from you, a discriminatory patent +license (a) in connection with copies of the covered work conveyed by +you (or copies made from those copies), or (b) primarily for and in +connection with specific products or compilations that contain the +covered work, unless you entered into that arrangement, or that patent +license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + +### 12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under +this License and any other pertinent obligations, then as a +consequence you may not convey it at all. For example, if you agree to +terms that obligate you to collect a royalty for further conveying +from those to whom you convey the Program, the only way you could +satisfy both those terms and this License would be to refrain entirely +from conveying the Program. + +### 13. Use with the GNU Affero General Public License. + +Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + +### 14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions +of the GNU 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 Program +specifies that a certain numbered version of the GNU General Public +License "or any later version" applies to it, you have the option of +following the terms and conditions either of that numbered version or +of any later version published by the Free Software Foundation. If the +Program does not specify a version number of the GNU General Public +License, you may choose any version ever published by the Free +Software Foundation. + +If the Program specifies that a proxy can decide which future versions +of the GNU General Public License can be used, that proxy's public +statement of acceptance of a version permanently authorizes you to +choose that version for the Program. + +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + +### 15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT +WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND +PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE +DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR +CORRECTION. + +### 16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR +CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES +ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT +NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR +LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM +TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER +PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +### 17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + +## How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these +terms. + +To do so, attach the following notices to the program. It is safest to +attach them to the start of each source file to most effectively state +the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 . + +Also add information on how to contact you by electronic and paper +mail. + +If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands \`show w' and \`show c' should show the +appropriate parts of the General Public License. Of course, your +program's commands might be different; for a GUI interface, you would +use an "about box". + +You should also get your employer (if you work as a programmer) or +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. For more information on this, and how to apply and follow +the GNU GPL, see . + +The GNU General Public License does not permit incorporating your +program into proprietary programs. If your program is a subroutine +library, you may consider it more useful to permit linking proprietary +applications with the library. If this is what you want to do, use the +GNU Lesser General Public License instead of this License. But first, +please read . diff --git a/TactilityCore/LICENSE.md b/TactilityCore/LICENSE.md deleted file mode 100644 index 85c7c696..00000000 --- a/TactilityCore/LICENSE.md +++ /dev/null @@ -1,636 +0,0 @@ -# GNU GENERAL PUBLIC LICENSE -Version 3, 29 June 2007 - -Copyright (C) 2007 [Free Software Foundation, Inc.](http://fsf.org/) - -Everyone is permitted to copy and distribute verbatim copies of this license -document, but changing it is not allowed. - -## Preamble - -The GNU General Public License is a free, copyleft license for software and -other kinds of works. - -The licenses for most software and other practical works are designed to take -away your freedom to share and change the works. By contrast, the GNU General -Public License is intended to guarantee your freedom to share and change all -versions of a program--to make sure it remains free software for all its users. -We, the Free Software Foundation, use the GNU General Public License for most -of our software; it applies also to any other work released this way by its -authors. You can apply it to your programs, too. - -When we speak of free software, we are referring to freedom, not price. Our -General Public Licenses are designed to make sure that you have the freedom to -distribute copies of free software (and charge for them if you wish), that you -receive source code or can get it if you want it, that you can change the -software or use pieces of it in new free programs, and that you know you can do -these things. - -To protect your rights, we need to prevent others from denying you these rights -or asking you to surrender the rights. Therefore, you have certain -responsibilities if you distribute copies of the software, or if you modify it: -responsibilities to respect the freedom of others. - -For example, if you distribute copies of such a program, whether gratis or for -a fee, you must pass on to the recipients the same freedoms that you received. -You must make sure that they, too, receive or can get the source code. And you -must show them these terms so they know their rights. - -Developers that use the GNU GPL protect your rights with two steps: - - 1. assert copyright on the software, and - 2. offer you this License giving you legal permission to copy, distribute - and/or modify it. - -For the developers' and authors' protection, the GPL clearly explains that -there is no warranty for this free software. For both users' and authors' sake, -the GPL requires that modified versions be marked as changed, so that their -problems will not be attributed erroneously to authors of previous versions. - -Some devices are designed to deny users access to install or run modified -versions of the software inside them, although the manufacturer can do so. This -is fundamentally incompatible with the aim of protecting users' freedom to -change the software. The systematic pattern of such abuse occurs in the area of -products for individuals to use, which is precisely where it is most -unacceptable. Therefore, we have designed this version of the GPL to prohibit -the practice for those products. If such problems arise substantially in other -domains, we stand ready to extend this provision to those domains in future -versions of the GPL, as needed to protect the freedom of users. - -Finally, every program is threatened constantly by software patents. States -should not allow patents to restrict development and use of software on -general-purpose computers, but in those that do, we wish to avoid the special -danger that patents applied to a free program could make it effectively -proprietary. To prevent this, the GPL assures that patents cannot be used to -render the program non-free. - -The precise terms and conditions for copying, distribution and modification -follow. - -## TERMS AND CONDITIONS - -### 0. Definitions. - -*This License* refers to version 3 of the GNU General Public License. - -*Copyright* also means copyright-like laws that apply to other kinds of works, -such as semiconductor masks. - -*The Program* refers to any copyrightable work licensed under this License. -Each licensee is addressed as *you*. *Licensees* and *recipients* may be -individuals or organizations. - -To *modify* a work means to copy from or adapt all or part of the work in a -fashion requiring copyright permission, other than the making of an exact copy. -The resulting work is called a *modified version* of the earlier work or a work -*based on* the earlier work. - -A *covered work* means either the unmodified Program or a work based on the -Program. - -To *propagate* a work means to do anything with it that, without permission, -would make you directly or secondarily liable for infringement under applicable -copyright law, except executing it on a computer or modifying a private copy. -Propagation includes copying, distribution (with or without modification), -making available to the public, and in some countries other activities as well. - -To *convey* a work means any kind of propagation that enables other parties to -make or receive copies. Mere interaction with a user through a computer -network, with no transfer of a copy, is not conveying. - -An interactive user interface displays *Appropriate Legal Notices* to the -extent that it includes a convenient and prominently visible feature that - - 1. displays an appropriate copyright notice, and - 2. tells the user that there is no warranty for the work (except to the - extent that warranties are provided), that licensees may convey the work - under this License, and how to view a copy of this License. - -If the interface presents a list of user commands or options, such as a menu, a -prominent item in the list meets this criterion. - -### 1. Source Code. - -The *source code* for a work means the preferred form of the work for making -modifications to it. *Object code* means any non-source form of a work. - -A *Standard Interface* means an interface that either is an official standard -defined by a recognized standards body, or, in the case of interfaces specified -for a particular programming language, one that is widely used among developers -working in that language. - -The *System Libraries* of an executable work include anything, other than the -work as a whole, that (a) is included in the normal form of packaging a Major -Component, but which is not part of that Major Component, and (b) serves only -to enable use of the work with that Major Component, or to implement a Standard -Interface for which an implementation is available to the public in source code -form. A *Major Component*, in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system (if any) on -which the executable work runs, or a compiler used to produce the work, or an -object code interpreter used to run it. - -The *Corresponding Source* for a work in object code form means all the source -code needed to generate, install, and (for an executable work) run the object -code and to modify the work, including scripts to control those activities. -However, it does not include the work's System Libraries, or general-purpose -tools or generally available free programs which are used unmodified in -performing those activities but which are not part of the work. For example, -Corresponding Source includes interface definition files associated with source -files for the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, such as -by intimate data communication or control flow between those subprograms and -other parts of the work. - -The Corresponding Source need not include anything that users can regenerate -automatically from other parts of the Corresponding Source. - -The Corresponding Source for a work in source code form is that same work. - -### 2. Basic Permissions. - -All rights granted under this License are granted for the term of copyright on -the Program, and are irrevocable provided the stated conditions are met. This -License explicitly affirms your unlimited permission to run the unmodified -Program. The output from running a covered work is covered by this License only -if the output, given its content, constitutes a covered work. This License -acknowledges your rights of fair use or other equivalent, as provided by -copyright law. - -You may make, run and propagate covered works that you do not convey, without -conditions so long as your license otherwise remains in force. You may convey -covered works to others for the sole purpose of having them make modifications -exclusively for you, or provide you with facilities for running those works, -provided that you comply with the terms of this License in conveying all -material for which you do not control copyright. Those thus making or running -the covered works for you must do so exclusively on your behalf, under your -direction and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - -Conveying under any other circumstances is permitted solely under the -conditions stated below. Sublicensing is not allowed; section 10 makes it -unnecessary. - -### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - -No covered work shall be deemed part of an effective technological measure -under any applicable law fulfilling obligations under article 11 of the WIPO -copyright treaty adopted on 20 December 1996, or similar laws prohibiting or -restricting circumvention of such measures. - -When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention is -effected by exercising rights under this License with respect to the covered -work, and you disclaim any intention to limit operation or modification of the -work as a means of enforcing, against the work's users, your or third parties' -legal rights to forbid circumvention of technological measures. - -### 4. Conveying Verbatim Copies. - -You may convey verbatim copies of the Program's source code as you receive it, -in any medium, provided that you conspicuously and appropriately publish on -each copy an appropriate copyright notice; keep intact all notices stating that -this License and any non-permissive terms added in accord with section 7 apply -to the code; keep intact all notices of the absence of any warranty; and give -all recipients a copy of this License along with the Program. - -You may charge any price or no price for each copy that you convey, and you may -offer support or warranty protection for a fee. - -### 5. Conveying Modified Source Versions. - -You may convey a work based on the Program, or the modifications to produce it -from the Program, in the form of source code under the terms of section 4, -provided that you also meet all of these conditions: - - - a) The work must carry prominent notices stating that you modified it, and - giving a relevant date. - - b) The work must carry prominent notices stating that it is released under - this License and any conditions added under section 7. This requirement - modifies the requirement in section 4 to *keep intact all notices*. - - c) You must license the entire work, as a whole, under this License to - anyone who comes into possession of a copy. This License will therefore - apply, along with any applicable section 7 additional terms, to the whole - of the work, and all its parts, regardless of how they are packaged. This - License gives no permission to license the work in any other way, but it - does not invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your work need - not make them do so. - -A compilation of a covered work with other separate and independent works, -which are not by their nature extensions of the covered work, and which are not -combined with it such as to form a larger program, in or on a volume of a -storage or distribution medium, is called an *aggregate* if the compilation and -its resulting copyright are not used to limit the access or legal rights of the -compilation's users beyond what the individual works permit. Inclusion of a -covered work in an aggregate does not cause this License to apply to the other -parts of the aggregate. - -### 6. Conveying Non-Source Forms. - -You may convey a covered work in object code form under the terms of sections 4 -and 5, provided that you also convey the machine-readable Corresponding Source -under the terms of this License, in one of these ways: - - - a) Convey the object code in, or embodied in, a physical product (including - a physical distribution medium), accompanied by the Corresponding Source - fixed on a durable physical medium customarily used for software - interchange. - - b) Convey the object code in, or embodied in, a physical product (including - a physical distribution medium), accompanied by a written offer, valid for - at least three years and valid for as long as you offer spare parts or - customer support for that product model, to give anyone who possesses the - object code either - 1. a copy of the Corresponding Source for all the software in the product - that is covered by this License, on a durable physical medium - customarily used for software interchange, for a price no more than your - reasonable cost of physically performing this conveying of source, or - 2. access to copy the Corresponding Source from a network server at no - charge. - - c) Convey individual copies of the object code with a copy of the written - offer to provide the Corresponding Source. This alternative is allowed only - occasionally and noncommercially, and only if you received the object code - with such an offer, in accord with subsection 6b. - - d) Convey the object code by offering access from a designated place - (gratis or for a charge), and offer equivalent access to the Corresponding - Source in the same way through the same place at no further charge. You - need not require recipients to copy the Corresponding Source along with the - object code. If the place to copy the object code is a network server, the - Corresponding Source may be on a different server operated by you or a - third party) that supports equivalent copying facilities, provided you - maintain clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the Corresponding - Source, you remain obligated to ensure that it is available for as long as - needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided you - inform other peers where the object code and Corresponding Source of the - work are being offered to the general public at no charge under subsection - 6d. - -A separable portion of the object code, whose source code is excluded from the -Corresponding Source as a System Library, need not be included in conveying the -object code work. - -A *User Product* is either - - 1. a *consumer product*, which means any tangible personal property which is - normally used for personal, family, or household purposes, or - 2. anything designed or sold for incorporation into a dwelling. - -In determining whether a product is a consumer product, doubtful cases shall be -resolved in favor of coverage. For a particular product received by a -particular user, *normally used* refers to a typical or common use of that -class of product, regardless of the status of the particular user or of the way -in which the particular user actually uses, or expects or is expected to use, -the product. A product is a consumer product regardless of whether the product -has substantial commercial, industrial or non-consumer uses, unless such uses -represent the only significant mode of use of the product. - -*Installation Information* for a User Product means any methods, procedures, -authorization keys, or other information required to install and execute -modified versions of a covered work in that User Product from a modified -version of its Corresponding Source. The information must suffice to ensure -that the continued functioning of the modified object code is in no case -prevented or interfered with solely because modification has been made. - -If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as part of a -transaction in which the right of possession and use of the User Product is -transferred to the recipient in perpetuity or for a fixed term (regardless of -how the transaction is characterized), the Corresponding Source conveyed under -this section must be accompanied by the Installation Information. But this -requirement does not apply if neither you nor any third party retains the -ability to install modified object code on the User Product (for example, the -work has been installed in ROM). - -The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates for a -work that has been modified or installed by the recipient, or for the User -Product in which it has been modified or installed. Access to a network may be -denied when the modification itself materially and adversely affects the -operation of the network or violates the rules and protocols for communication -across the network. - -Corresponding Source conveyed, and Installation Information provided, in accord -with this section must be in a format that is publicly documented (and with an -implementation available to the public in source code form), and must require -no special password or key for unpacking, reading or copying. - -### 7. Additional Terms. - -*Additional permissions* are terms that supplement the terms of this License by -making exceptions from one or more of its conditions. Additional permissions -that are applicable to the entire Program shall be treated as though they were -included in this License, to the extent that they are valid under applicable -law. If additional permissions apply only to part of the Program, that part may -be used separately under those permissions, but the entire Program remains -governed by this License without regard to the additional permissions. - -When you convey a copy of a covered work, you may at your option remove any -additional permissions from that copy, or from any part of it. (Additional -permissions may be written to require their own removal in certain cases when -you modify the work.) You may place additional permissions on material, added -by you to a covered work, for which you have or can give appropriate copyright -permission. - -Notwithstanding any other provision of this License, for material you add to a -covered work, you may (if authorized by the copyright holders of that material) -supplement the terms of this License with terms: - - - a) Disclaiming warranty or limiting liability differently from the terms of - sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or author - attributions in that material or in the Appropriate Legal Notices displayed - by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in reasonable - ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or authors - of the material; or - - e) Declining to grant rights under trademark law for use of some trade - names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that material by - anyone who conveys the material (or modified versions of it) with - contractual assumptions of liability to the recipient, for any liability - that these contractual assumptions directly impose on those licensors and - authors. - -All other non-permissive additional terms are considered *further restrictions* -within the meaning of section 10. If the Program as you received it, or any -part of it, contains a notice stating that it is governed by this License along -with a term that is a further restriction, you may remove that term. If a -license document contains a further restriction but permits relicensing or -conveying under this License, you may add to a covered work material governed -by the terms of that license document, provided that the further restriction -does not survive such relicensing or conveying. - -If you add terms to a covered work in accord with this section, you must place, -in the relevant source files, a statement of the additional terms that apply to -those files, or a notice indicating where to find the applicable terms. - -Additional terms, permissive or non-permissive, may be stated in the form of a -separately written license, or stated as exceptions; the above requirements -apply either way. - -### 8. Termination. - -You may not propagate or modify a covered work except as expressly provided -under this License. Any attempt otherwise to propagate or modify it is void, -and will automatically terminate your rights under this License (including any -patent licenses granted under the third paragraph of section 11). - -However, if you cease all violation of this License, then your license from a -particular copyright holder is reinstated - - - a) provisionally, unless and until the copyright holder explicitly and - finally terminates your license, and - - b) permanently, if the copyright holder fails to notify you of the - violation by some reasonable means prior to 60 days after the cessation. - -Moreover, your license from a particular copyright holder is reinstated -permanently if the copyright holder notifies you of the violation by some -reasonable means, this is the first time you have received notice of violation -of this License (for any work) from that copyright holder, and you cure the -violation prior to 30 days after your receipt of the notice. - -Termination of your rights under this section does not terminate the licenses -of parties who have received copies or rights from you under this License. If -your rights have been terminated and not permanently reinstated, you do not -qualify to receive new licenses for the same material under section 10. - -### 9. Acceptance Not Required for Having Copies. - -You are not required to accept this License in order to receive or run a copy -of the Program. Ancillary propagation of a covered work occurring solely as a -consequence of using peer-to-peer transmission to receive a copy likewise does -not require acceptance. However, nothing other than this License grants you -permission to propagate or modify any covered work. These actions infringe -copyright if you do not accept this License. Therefore, by modifying or -propagating a covered work, you indicate your acceptance of this License to do -so. - -### 10. Automatic Licensing of Downstream Recipients. - -Each time you convey a covered work, the recipient automatically receives a -license from the original licensors, to run, modify and propagate that work, -subject to this License. You are not responsible for enforcing compliance by -third parties with this License. - -An *entity transaction* is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered work -results from an entity transaction, each party to that transaction who receives -a copy of the work also receives whatever licenses to the work the party's -predecessor in interest had or could give under the previous paragraph, plus a -right to possession of the Corresponding Source of the work from the -predecessor in interest, if the predecessor has it or can get it with -reasonable efforts. - -You may not impose any further restrictions on the exercise of the rights -granted or affirmed under this License. For example, you may not impose a -license fee, royalty, or other charge for exercise of rights granted under this -License, and you may not initiate litigation (including a cross-claim or -counterclaim in a lawsuit) alleging that any patent claim is infringed by -making, using, selling, offering for sale, or importing the Program or any -portion of it. - -### 11. Patents. - -A *contributor* is a copyright holder who authorizes use under this License of -the Program or a work on which the Program is based. The work thus licensed is -called the contributor's *contributor version*. - -A contributor's *essential patent claims* are all patent claims owned or -controlled by the contributor, whether already acquired or hereafter acquired, -that would be infringed by some manner, permitted by this License, of making, -using, or selling its contributor version, but do not include claims that would -be infringed only as a consequence of further modification of the contributor -version. For purposes of this definition, *control* includes the right to grant -patent sublicenses in a manner consistent with the requirements of this -License. - -Each contributor grants you a non-exclusive, worldwide, royalty-free patent -license under the contributor's essential patent claims, to make, use, sell, -offer for sale, import and otherwise run, modify and propagate the contents of -its contributor version. - -In the following three paragraphs, a *patent license* is any express agreement -or commitment, however denominated, not to enforce a patent (such as an express -permission to practice a patent or covenant not to sue for patent -infringement). To *grant* such a patent license to a party means to make such -an agreement or commitment not to enforce a patent against the party. - -If you convey a covered work, knowingly relying on a patent license, and the -Corresponding Source of the work is not available for anyone to copy, free of -charge and under the terms of this License, through a publicly available -network server or other readily accessible means, then you must either - - 1. cause the Corresponding Source to be so available, or - 2. arrange to deprive yourself of the benefit of the patent license for this - particular work, or - 3. arrange, in a manner consistent with the requirements of this License, to - extend the patent license to downstream recipients. - -*Knowingly relying* means you have actual knowledge that, but for the patent -license, your conveying the covered work in a country, or your recipient's use -of the covered work in a country, would infringe one or more identifiable -patents in that country that you have reason to believe are valid. - -If, pursuant to or in connection with a single transaction or arrangement, you -convey, or propagate by procuring conveyance of, a covered work, and grant a -patent license to some of the parties receiving the covered work authorizing -them to use, propagate, modify or convey a specific copy of the covered work, -then the patent license you grant is automatically extended to all recipients -of the covered work and works based on it. - -A patent license is *discriminatory* if it does not include within the scope of -its coverage, prohibits the exercise of, or is conditioned on the non-exercise -of one or more of the rights that are specifically granted under this License. -You may not convey a covered work if you are a party to an arrangement with a -third party that is in the business of distributing software, under which you -make payment to the third party based on the extent of your activity of -conveying the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory patent -license - - - a) in connection with copies of the covered work conveyed by you (or copies - made from those copies), or - - b) primarily for and in connection with specific products or compilations - that contain the covered work, unless you entered into that arrangement, or - that patent license was granted, prior to 28 March 2007. - -Nothing in this License shall be construed as excluding or limiting any implied -license or other defenses to infringement that may otherwise be available to -you under applicable patent law. - -### 12. No Surrender of Others' Freedom. - -If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not excuse -you from the conditions of this License. If you cannot convey a covered work so -as to satisfy simultaneously your obligations under this License and any other -pertinent obligations, then as a consequence you may not convey it at all. For -example, if you agree to terms that obligate you to collect a royalty for -further conveying from those to whom you convey the Program, the only way you -could satisfy both those terms and this License would be to refrain entirely -from conveying the Program. - -### 13. Use with the GNU Affero General Public License. - -Notwithstanding any other provision of this License, you have permission to -link or combine any covered work with a work licensed under version 3 of the -GNU Affero General Public License into a single combined work, and to convey -the resulting work. The terms of this License will continue to apply to the -part which is the covered work, but the special requirements of the GNU Affero -General Public License, section 13, concerning interaction through a network -will apply to the combination as such. - -### 14. Revised Versions of this License. - -The Free Software Foundation may publish revised and/or new versions of the GNU -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 Program specifies -that a certain numbered version of the GNU General Public License *or any later -version* applies to it, you have the option of following the terms and -conditions either of that numbered version or of any later version published by -the Free Software Foundation. If the Program does not specify a version number -of the GNU General Public License, you may choose any version ever published by -the Free Software Foundation. - -If the Program specifies that a proxy can decide which future versions of the -GNU General Public License can be used, that proxy's public statement of -acceptance of a version permanently authorizes you to choose that version for -the Program. - -Later license versions may give you additional or different permissions. -However, no additional obligations are imposed on any author or copyright -holder as a result of your choosing to follow a later version. - -### 15. Disclaimer of Warranty. - -THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE -LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER -PARTIES PROVIDE THE PROGRAM *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER -EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE -QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE -DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR -CORRECTION. - -### 16. Limitation of Liability. - -IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY -COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS -PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, -INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE -THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED -INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE -PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY -HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -### 17. Interpretation of Sections 15 and 16. - -If the disclaimer of warranty and limitation of liability provided above cannot -be given local legal effect according to their terms, reviewing courts shall -apply local law that most closely approximates an absolute waiver of all civil -liability in connection with the Program, unless a warranty or assumption of -liability accompanies a copy of the Program in return for a fee. - -## END OF TERMS AND CONDITIONS ### - -### How to Apply These Terms to Your New Programs - -If you develop a new program, and you want it to be of the greatest possible -use to the public, the best way to achieve this is to make it free software -which everyone can redistribute and change under these terms. - -To do so, attach the following notices to the program. It is safest to attach -them to the start of each source file to most effectively state the exclusion -of warranty; and each file should have at least the *copyright* line and a -pointer to where the full notice is found. - - - Copyright (C) - - 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 . - -Also add information on how to contact you by electronic and paper mail. - -If the program does terminal interaction, make it output a short notice like -this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w` and `show c` should show the appropriate -parts of the General Public License. Of course, your program's commands might -be different; for a GUI interface, you would use an *about box*. - -You should also get your employer (if you work as a programmer) or school, if -any, to sign a *copyright disclaimer* for the program, if necessary. For more -information on this, and how to apply and follow the GNU GPL, see -[http://www.gnu.org/licenses/](http://www.gnu.org/licenses/). - -The GNU General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may consider -it more useful to permit linking proprietary applications with the library. If -this is what you want to do, use the GNU Lesser General Public License instead -of this License. But first, please read -[http://www.gnu.org/philosophy/why-not-lgpl.html](http://www.gnu.org/philosophy/why-not-lgpl.html). diff --git a/TactilityFreeRtos/CMakeLists.txt b/TactilityFreeRtos/CMakeLists.txt index 072cb4f9..f23dce53 100644 --- a/TactilityFreeRtos/CMakeLists.txt +++ b/TactilityFreeRtos/CMakeLists.txt @@ -1,8 +1,5 @@ cmake_minimum_required(VERSION 3.20) -set(CMAKE_CXX_STANDARD 23) -set(CMAKE_CXX_STANDARD_REQUIRED ON) - if (DEFINED ENV{ESP_IDF_VERSION}) idf_component_register( diff --git a/TactilityFreeRtos/Include/Tactility/freertoscompat/Queue.h b/TactilityFreeRtos/Include/Tactility/freertoscompat/Queue.h index b8db380a..ef370454 100644 --- a/TactilityFreeRtos/Include/Tactility/freertoscompat/Queue.h +++ b/TactilityFreeRtos/Include/Tactility/freertoscompat/Queue.h @@ -1,3 +1,5 @@ +#pragma once + #ifdef ESP_PLATFORM #include #include diff --git a/TactilityFreeRtos/LICENSE-Apache-2.0.md b/TactilityFreeRtos/LICENSE-Apache-2.0.md new file mode 100644 index 00000000..f5f4b8b5 --- /dev/null +++ b/TactilityFreeRtos/LICENSE-Apache-2.0.md @@ -0,0 +1,195 @@ +Apache License +============== + +_Version 2.0, January 2004_ +_<>_ + +### Terms and Conditions for use, reproduction, and distribution + +#### 1. Definitions + +“License” shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +“Licensor” shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + +“Legal Entity” shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, “control” means **(i)** the power, direct or +indirect, to cause the direction or management of such entity, whether by +contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the +outstanding shares, or **(iii)** beneficial ownership of such entity. + +“You” (or “Your”) shall mean an individual or Legal Entity exercising +permissions granted by this License. + +“Source” form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + +“Object” form shall mean any form resulting from mechanical transformation or +translation of a Source form, including but not limited to compiled object code, +generated documentation, and conversions to other media types. + +“Work” shall mean the work of authorship, whether in Source or Object form, made +available under the License, as indicated by a copyright notice that is included +in or attached to the work (an example is provided in the Appendix below). + +“Derivative Works” shall mean any work, whether in Source or Object form, that +is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative Works +shall not include works that remain separable from, or merely link (or bind by +name) to the interfaces of, the Work and Derivative Works thereof. + +“Contribution” shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative Works +thereof, that is intentionally submitted to Licensor for inclusion in the Work +by the copyright owner or by an individual or Legal Entity authorized to submit +on behalf of the copyright owner. For the purposes of this definition, +“submitted” means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for +the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as “Not a Contribution.” + +“Contributor” shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently +incorporated within the Work. + +#### 2. Grant of Copyright License + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +#### 3. Grant of Patent License + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this section) patent license to make, have +made, use, offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by combination +of their Contribution(s) with the Work to which such Contribution(s) was +submitted. If You institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work or a +Contribution incorporated within the Work constitutes direct or contributory +patent infringement, then any patent licenses granted to You under this License +for that Work shall terminate as of the date such litigation is filed. + +#### 4. Redistribution + +You may reproduce and distribute copies of the Work or Derivative Works thereof +in any medium, with or without modifications, and in Source or Object form, +provided that You meet the following conditions: + +* **(a)** You must give any other recipients of the Work or Derivative Works a copy of +this License; and +* **(b)** You must cause any modified files to carry prominent notices stating that You +changed the files; and +* **(c)** You must retain, in the Source form of any Derivative Works that You distribute, +all copyright, patent, trademark, and attribution notices from the Source form +of the Work, excluding those notices that do not pertain to any part of the +Derivative Works; and +* **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any +Derivative Works that You distribute must include a readable copy of the +attribution notices contained within such NOTICE file, excluding those notices +that do not pertain to any part of the Derivative Works, in at least one of the +following places: within a NOTICE text file distributed as part of the +Derivative Works; within the Source form or documentation, if provided along +with the Derivative Works; or, within a display generated by the Derivative +Works, if and wherever such third-party notices normally appear. The contents of +the NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative Works that +You distribute, alongside or as an addendum to the NOTICE text from the Work, +provided that such additional attribution notices cannot be construed as +modifying the License. + +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + +#### 5. Submission of Contributions + +Unless You explicitly state otherwise, any Contribution intentionally submitted +for inclusion in the Work by You to the Licensor shall be under the terms and +conditions of this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify the terms of +any separate license agreement you may have executed with Licensor regarding +such Contributions. + +#### 6. Trademarks + +This License does not grant permission to use the trade names, trademarks, +service marks, or product names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +#### 7. Disclaimer of Warranty + +Unless required by applicable law or agreed to in writing, Licensor provides the +Work (and each Contributor provides its Contributions) on an “AS IS” BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +including, without limitation, any warranties or conditions of TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your exercise of +permissions under this License. + +#### 8. Limitation of Liability + +In no event and under no legal theory, whether in tort (including negligence), +contract, or otherwise, unless required by applicable law (such as deliberate +and grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, incidental, +or consequential damages of any character arising as a result of this License or +out of the use or inability to use the Work (including but not limited to +damages for loss of goodwill, work stoppage, computer failure or malfunction, or +any and all other commercial damages or losses), even if such Contributor has +been advised of the possibility of such damages. + +#### 9. Accepting Warranty or Additional Liability + +While redistributing the Work or Derivative Works thereof, You may choose to +offer, and charge a fee for, acceptance of support, warranty, indemnity, or +other liability obligations and/or rights consistent with this License. However, +in accepting such obligations, You may act only on Your own behalf and on Your +sole responsibility, not on behalf of any other Contributor, and only if You +agree to indemnify, defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason of your +accepting any such warranty or additional liability. + +_END OF TERMS AND CONDITIONS_ + +### APPENDIX: How to apply the Apache License to your work + +To apply the Apache License to your work, attach the following boilerplate +notice, with the fields enclosed by brackets `[]` replaced with your own +identifying information. (Don't include the brackets!) The text should be +enclosed in the appropriate comment syntax for the file format. We also +recommend that a file or class name and description of purpose be included on +the same “printed page” as the copyright notice for easier identification within +third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/TactilityKernel/Bindings/gpio-controller.yaml b/TactilityKernel/Bindings/gpio-controller.yaml new file mode 100644 index 00000000..e3a2f8bd --- /dev/null +++ b/TactilityKernel/Bindings/gpio-controller.yaml @@ -0,0 +1,6 @@ +properties: + gpio-count: + type: int + required: true + description: | + The number of available GPIOs. \ No newline at end of file diff --git a/TactilityKernel/Bindings/i2c-controller.yaml b/TactilityKernel/Bindings/i2c-controller.yaml new file mode 100644 index 00000000..5f14e180 --- /dev/null +++ b/TactilityKernel/Bindings/i2c-controller.yaml @@ -0,0 +1,10 @@ +bus: i2c + +properties: + clock-frequency: + type: int + description: Initial clock frequency in Hz + pin-sda: + type: phandle-array + pin-scl: + type: phandle-array diff --git a/TactilityKernel/Bindings/i2c-device.yaml b/TactilityKernel/Bindings/i2c-device.yaml new file mode 100644 index 00000000..cb1b52a5 --- /dev/null +++ b/TactilityKernel/Bindings/i2c-device.yaml @@ -0,0 +1,6 @@ +on-bus: i2c + +properties: + register: + required: true + description: device address on the bus \ No newline at end of file diff --git a/TactilityKernel/Bindings/root.yaml b/TactilityKernel/Bindings/root.yaml new file mode 100644 index 00000000..8db9050b --- /dev/null +++ b/TactilityKernel/Bindings/root.yaml @@ -0,0 +1,6 @@ +compatible: "root" + +properties: + model: + required: true + description: the name of hardware, usually vendor and model name diff --git a/TactilityKernel/CMakeLists.txt b/TactilityKernel/CMakeLists.txt new file mode 100644 index 00000000..5644a317 --- /dev/null +++ b/TactilityKernel/CMakeLists.txt @@ -0,0 +1,18 @@ +cmake_minimum_required(VERSION 3.20) + +file(GLOB_RECURSE SOURCES "Source/*.c**") + +if (DEFINED ENV{ESP_IDF_VERSION}) + + idf_component_register( + SRCS ${SOURCES} + INCLUDE_DIRS "Include/" + ) + +else () + + add_library(TactilityKernel OBJECT ${SOURCES}) + target_include_directories(TactilityKernel PUBLIC Include/) + target_link_libraries(TactilityKernel PUBLIC freertos_kernel) + +endif () diff --git a/TactilityKernel/Include/Tactility/Device.h b/TactilityKernel/Include/Tactility/Device.h new file mode 100644 index 00000000..f7618960 --- /dev/null +++ b/TactilityKernel/Include/Tactility/Device.h @@ -0,0 +1,183 @@ +#pragma once + +#include "Driver.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#include +#include +#include + +struct Driver; + +/** Enables discovering devices of the same type */ +struct DeviceType { + /* Placeholder because empty structs have a different size with C vs C++ compilers */ + uint8_t _; +}; + +/** Represents a piece of hardware */ +struct Device { + /** The name of the device. Valid characters: a-z a-Z 0-9 - _ . */ + const char* name; + /** The configuration data for the device's driver */ + const void* config; + /** The parent device that this device belongs to. Can be NULL, but only the root device should have a NULL parent. */ + struct Device* parent; + /** Internal data */ + struct { + /** Address of the API exposed by the device instance. */ + struct Driver* driver; + /** The driver data for this device (e.g. a mutex) */ + void* driver_data; + /** The mutex for device operations */ + struct Mutex mutex; + /** The device state */ + struct { + int start_result; + bool started : 1; + bool added : 1; + } state; + /** Private data */ + void* data; + } internal; +}; + +/** + * Initialize the properties of a device. + * + * @param[in] dev a device with all non-internal properties set + * @return the result code (0 for success) + */ +int device_construct(struct Device* device); + +/** + * Deinitialize the properties of a device. + * This fails when a device is busy or has children. + * + * @param[in] dev + * @return the result code (0 for success) + */ +int device_destruct(struct Device* device); + +/** + * Indicates whether the device is in a state where its API is available + * + * @param[in] dev non-null device pointer + * @return true if the device is ready for use + */ +static inline bool device_is_ready(const struct Device* device) { + return device->internal.state.started; +} + +/** + * Register a device to all relevant systems: + * - the global ledger + * - its parent (if any) + * - a bus (if any) + * + * @param[in] device non-null device pointer + * @return 0 on success + */ +int device_add(struct Device* device); + +/** + * Deregister a device. Remove it from all relevant systems: + * - the global ledger + * - its parent (if any) + * - a bus (if any) + * + * @param[in] device non-null device pointer + * @return 0 on success + */ +int device_remove(struct Device* device); + +/** + * Attach the driver. + * + * @warning must call device_construct() and device_add() first + * @param device + * @return ERROR_INVALID_STATE or otherwise the value of the driver binding result (0 on success) + */ +int device_start(struct Device* device); + +/** + * Detach the driver. + * + * @param device + * @return ERROR_INVALID_STATE or otherwise the value of the driver unbinding result (0 on success) + */ +int device_stop(struct Device* device); + +/** + * Set or unset a parent. + * @warning must call before device_add() + * @param device non-NULL device + * @param parent nullable parent device + */ +void device_set_parent(struct Device* device, struct Device* parent); + +static inline void device_set_driver(struct Device* device, struct Driver* driver) { + device->internal.driver = driver; +} + +static inline struct Driver* device_get_driver(struct Device* device) { + return device->internal.driver; +} + +static inline void device_set_driver_data(struct Device* device, void* driver_data) { + device->internal.driver_data = driver_data; +} + +static inline void* device_get_driver_data(struct Device* device) { + return device->internal.driver_data; +} + +static inline bool device_is_added(const struct Device* device) { + return device->internal.state.added; +} + +static inline void device_lock(struct Device* device) { + mutex_lock(&device->internal.mutex); +} + +static inline int device_try_lock(struct Device* device) { + return mutex_try_lock(&device->internal.mutex); +} + +static inline void device_unlock(struct Device* device) { + mutex_unlock(&device->internal.mutex); +} + +static inline const struct DeviceType* device_get_type(struct Device* device) { + return device->internal.driver ? device->internal.driver->device_type : NULL; +} +/** + * Iterate through all the known devices + * @param callback_context the parameter to pass to the callback. NULL is valid. + * @param on_device the function to call for each filtered device. return true to continue iterating or false to stop. + */ +void for_each_device(void* callback_context, bool(*on_device)(struct Device* device, void* context)); + +/** + * Iterate through all the child devices of the specified device + * @param callback_context the parameter to pass to the callback. NULL is valid. + * @param on_device the function to call for each filtered device. return true to continue iterating or false to stop. + */ +void for_each_device_child(struct Device* device, void* callback_context, bool(*on_device)(struct Device* device, void* context)); + +/** + * Iterate through all the known devices of a specific type + * @param type the type to filter + * @param callback_context the parameter to pass to the callback. NULL is valid. + * @param on_device the function to call for each filtered device. return true to continue iterating or false to stop. + */ +void for_each_device_of_type(const struct DeviceType* type, void* callback_context, bool(*on_device)(struct Device* device, void* context)); + +#ifdef __cplusplus +} +#endif diff --git a/TactilityKernel/Include/Tactility/Driver.h b/TactilityKernel/Include/Tactility/Driver.h new file mode 100644 index 00000000..ee0f88a3 --- /dev/null +++ b/TactilityKernel/Include/Tactility/Driver.h @@ -0,0 +1,50 @@ +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +struct Device; +struct DeviceType; + +struct Driver { + /** The driver name */ + const char* name; + /** Array of const char*, terminated by NULL */ + const char**compatible; + /** Function to initialize the driver for a device */ + int (*start_device)(struct Device* dev); + /** Function to deinitialize the driver for a device */ + int (*stop_device)(struct Device* dev); + /** Contains the driver's functions */ + const void* api; + /** Which type of devices this driver creates (can be NULL) */ + const struct DeviceType* device_type; + /** Internal data */ + struct { + /** Contains private data */ + void* data; + } internal; +}; + +int driver_construct(struct Driver* driver); + +int driver_destruct(struct Driver* driver); + +int driver_bind(struct Driver* driver, struct Device* device); + +int driver_unbind(struct Driver* driver, struct Device* device); + +bool driver_is_compatible(struct Driver* driver, const char* compatible); + +struct Driver* driver_find_compatible(const char* compatible); + +static inline const struct DeviceType* driver_get_device_type(struct Driver* driver) { + return driver->device_type; +} + +#ifdef __cplusplus +} +#endif diff --git a/TactilityKernel/Include/Tactility/Error.h b/TactilityKernel/Include/Tactility/Error.h new file mode 100644 index 00000000..fdfaaf45 --- /dev/null +++ b/TactilityKernel/Include/Tactility/Error.h @@ -0,0 +1,8 @@ +#pragma once + +#define ERROR_UNDEFINED 1 +#define ERROR_INVALID_STATE 2 +#define ERROR_INVALID_ARGUMENT 3 +#define ERROR_MISSING_PARAMETER 4 +#define ERROR_NOT_FOUND 5 + diff --git a/TactilityKernel/Include/Tactility/FreeRTOS/FreeRTOS.h b/TactilityKernel/Include/Tactility/FreeRTOS/FreeRTOS.h new file mode 100644 index 00000000..4d148d81 --- /dev/null +++ b/TactilityKernel/Include/Tactility/FreeRTOS/FreeRTOS.h @@ -0,0 +1,10 @@ +#pragma once + +#ifdef ESP_PLATFORM +#include +#else +#include +#endif + +// Custom port compatibility definitins, mainly for PC compatibility +#include "port.h" diff --git a/TactilityKernel/Include/Tactility/FreeRTOS/README.md b/TactilityKernel/Include/Tactility/FreeRTOS/README.md new file mode 100644 index 00000000..9b41539d --- /dev/null +++ b/TactilityKernel/Include/Tactility/FreeRTOS/README.md @@ -0,0 +1,3 @@ +Compatibility include files for FreeRTOS. +Custom FreeRTOS from ESP-IDF prefixes paths with "freertos/", +but this isn't the normal behaviour for the regular FreeRTOS project. diff --git a/TactilityKernel/Include/Tactility/FreeRTOS/event_groups.h b/TactilityKernel/Include/Tactility/FreeRTOS/event_groups.h new file mode 100644 index 00000000..665eeb64 --- /dev/null +++ b/TactilityKernel/Include/Tactility/FreeRTOS/event_groups.h @@ -0,0 +1,10 @@ +#pragma once + +#include "FreeRTOS.h" + +#ifdef ESP_PLATFORM +#include +#else +#include +#endif + diff --git a/TactilityKernel/Include/Tactility/FreeRTOS/port.h b/TactilityKernel/Include/Tactility/FreeRTOS/port.h new file mode 100644 index 00000000..d897dafc --- /dev/null +++ b/TactilityKernel/Include/Tactility/FreeRTOS/port.h @@ -0,0 +1,8 @@ +#pragma once + +#include "FreeRTOS.h" + +#ifndef ESP_PLATFORM +#define xPortInIsrContext(x) (false) +#define vPortAssertIfInISR() +#endif diff --git a/TactilityKernel/Include/Tactility/FreeRTOS/queue.h b/TactilityKernel/Include/Tactility/FreeRTOS/queue.h new file mode 100644 index 00000000..b22e3584 --- /dev/null +++ b/TactilityKernel/Include/Tactility/FreeRTOS/queue.h @@ -0,0 +1,10 @@ +#pragma once + +#include "FreeRTOS.h" + +#ifdef ESP_PLATFORM +#include +#else +#include +#endif + diff --git a/TactilityKernel/Include/Tactility/FreeRTOS/semphr.h b/TactilityKernel/Include/Tactility/FreeRTOS/semphr.h new file mode 100644 index 00000000..9aa7332b --- /dev/null +++ b/TactilityKernel/Include/Tactility/FreeRTOS/semphr.h @@ -0,0 +1,9 @@ +#pragma once + +#include "FreeRTOS.h" + +#ifdef ESP_PLATFORM +#include +#else +#include +#endif \ No newline at end of file diff --git a/TactilityKernel/Include/Tactility/FreeRTOS/task.h b/TactilityKernel/Include/Tactility/FreeRTOS/task.h new file mode 100644 index 00000000..cb01be7a --- /dev/null +++ b/TactilityKernel/Include/Tactility/FreeRTOS/task.h @@ -0,0 +1,10 @@ +#pragma once + +#include "FreeRTOS.h" + +#ifdef ESP_PLATFORM +#include +#else +#include +#endif + diff --git a/TactilityKernel/Include/Tactility/FreeRTOS/timers.h b/TactilityKernel/Include/Tactility/FreeRTOS/timers.h new file mode 100644 index 00000000..f1e60b47 --- /dev/null +++ b/TactilityKernel/Include/Tactility/FreeRTOS/timers.h @@ -0,0 +1,9 @@ +#pragma once + +#include "FreeRTOS.h" + +#ifdef ESP_PLATFORM +#include +#else +#include +#endif diff --git a/TactilityKernel/Include/Tactility/Log.h b/TactilityKernel/Include/Tactility/Log.h new file mode 100644 index 00000000..68939e20 --- /dev/null +++ b/TactilityKernel/Include/Tactility/Log.h @@ -0,0 +1,35 @@ +#pragma once + +#ifdef ESP_PLATFORM +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#define LOG_TAG(x) "\033[37m"#x"\033[0m" + +#ifndef ESP_PLATFORM + +void log_generic(const char* tag, const char* format, ...); + +#define LOG_E(x, ...) log_generic(x, ##__VA_ARGS__) +#define LOG_W(x, ...) log_generic(x, ##__VA_ARGS__) +#define LOG_I(x, ...) log_generic(x, ##__VA_ARGS__) +#define LOG_D(x, ...) log_generic(x, ##__VA_ARGS__) +#define LOG_V(x, ...) log_generic(x, ##__VA_ARGS__) + +#else + +#define LOG_E(x, ...) ESP_LOGE(x, ##__VA_ARGS__) +#define LOG_W(x, ...) ESP_LOGW(x, ##__VA_ARGS__) +#define LOG_I(x, ...) ESP_LOGI(x, ##__VA_ARGS__) +#define LOG_D(x, ...) ESP_LOGD(x, ##__VA_ARGS__) +#define LOG_V(x, ...) ESP_LOGV(x, ##__VA_ARGS__) + +#endif + +#ifdef __cplusplus +} +#endif diff --git a/TactilityKernel/Include/Tactility/bindings/bindings.h b/TactilityKernel/Include/Tactility/bindings/bindings.h new file mode 100644 index 00000000..8d46255a --- /dev/null +++ b/TactilityKernel/Include/Tactility/bindings/bindings.h @@ -0,0 +1,8 @@ +#pragma once + +/** + * Creates required aliases for the devicetree generation. + * @param compatible_name the "compatible" value for the related driver + * @param config_type the internal configuration type for a device + */ +#define DEFINE_DEVICETREE(compatible_name, config_type) typedef config_type compatible_name##_config_dt; diff --git a/TactilityKernel/Include/Tactility/bindings/gpio.h b/TactilityKernel/Include/Tactility/bindings/gpio.h new file mode 100644 index 00000000..836daf73 --- /dev/null +++ b/TactilityKernel/Include/Tactility/bindings/gpio.h @@ -0,0 +1,3 @@ +#pragma once + +#include diff --git a/TactilityKernel/Include/Tactility/bindings/root.h b/TactilityKernel/Include/Tactility/bindings/root.h new file mode 100644 index 00000000..f345b5c7 --- /dev/null +++ b/TactilityKernel/Include/Tactility/bindings/root.h @@ -0,0 +1,7 @@ +#pragma once + +#include +#include + +DEFINE_DEVICETREE(root, struct RootConfig) + diff --git a/TactilityKernel/Include/Tactility/concurrent/Mutex.h b/TactilityKernel/Include/Tactility/concurrent/Mutex.h new file mode 100644 index 00000000..0297ac0a --- /dev/null +++ b/TactilityKernel/Include/Tactility/concurrent/Mutex.h @@ -0,0 +1,45 @@ +#pragma once + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +struct Mutex { + QueueHandle_t handle; +}; + +inline static void mutex_construct(struct Mutex* mutex) { + assert(mutex->handle == NULL); + mutex->handle = xSemaphoreCreateMutex(); +} + +inline static void mutex_destruct(struct Mutex* mutex) { + assert(mutex->handle != NULL); + vPortAssertIfInISR(); + vSemaphoreDelete(mutex->handle); + mutex->handle = NULL; +} + +inline static void mutex_lock(struct Mutex* mutex) { + xSemaphoreTake(mutex->handle, portMAX_DELAY); +} + +inline static bool mutex_try_lock(struct Mutex* mutex) { + return xSemaphoreTake(mutex->handle, 0) == pdTRUE; +} + +inline static bool mutex_is_locked(struct Mutex* mutex) { + return xSemaphoreGetMutexHolder(mutex->handle) != NULL; +} + +inline static void mutex_unlock(struct Mutex* mutex) { + xSemaphoreGive(mutex->handle); +} + +#ifdef __cplusplus +} +#endif diff --git a/TactilityKernel/Include/Tactility/concurrent/RecursiveMutex.h b/TactilityKernel/Include/Tactility/concurrent/RecursiveMutex.h new file mode 100644 index 00000000..aba6e0da --- /dev/null +++ b/TactilityKernel/Include/Tactility/concurrent/RecursiveMutex.h @@ -0,0 +1,44 @@ +#pragma once + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +struct RecursiveMutex { + QueueHandle_t handle; +}; + +inline static void recursive_mutex_construct(struct RecursiveMutex* mutex) { + mutex->handle = xSemaphoreCreateRecursiveMutex(); +} + +inline static void recursive_mutex_destruct(struct RecursiveMutex* mutex) { + assert(mutex->handle != NULL); + vPortAssertIfInISR(); + vSemaphoreDelete(mutex->handle); + mutex->handle = NULL; +} + +inline static void recursive_mutex_lock(struct RecursiveMutex* mutex) { + xSemaphoreTakeRecursive(mutex->handle, portMAX_DELAY); +} + +inline static bool recursive_mutex_is_locked(struct RecursiveMutex* mutex) { + return xSemaphoreGetMutexHolder(mutex->handle) != NULL; +} + +inline static bool recursive_mutex_try_lock(struct RecursiveMutex* mutex) { + return xSemaphoreTakeRecursive(mutex->handle, 0) == pdTRUE; +} + +inline static void recursive_mutex_unlock(struct RecursiveMutex* mutex) { + xSemaphoreGiveRecursive(mutex->handle); +} + +#ifdef __cplusplus +} +#endif diff --git a/TactilityKernel/Include/Tactility/drivers/Gpio.h b/TactilityKernel/Include/Tactility/drivers/Gpio.h new file mode 100644 index 00000000..0e90f1df --- /dev/null +++ b/TactilityKernel/Include/Tactility/drivers/Gpio.h @@ -0,0 +1,90 @@ +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define GPIO_OPTIONS_MASK 0x1f + +#define GPIO_ACTIVE_HIGH (0 << 0) +#define GPIO_ACTIVE_LOW (1 << 0) + +#define GPIO_DIRECTION_INPUT (1 << 1) +#define GPIO_DIRECTION_OUTPUT (1 << 2) +#define GPIO_DIRECTION_INPUT_OUTPUT (GPIO_DIRECTION_INPUT | GPIO_DIRECTION_OUTPUT) + +#define GPIO_PULL_UP (0 << 3) +#define GPIO_PULL_DOWN (1 << 4) + +#define GPIO_INTERRUPT_BITMASK (0b111 << 5) // 3 bits to hold the values [0, 5] +#define GPIO_INTERRUPT_FROM_OPTIONS(options) (gpio_int_type_t)((options & GPIO_INTERRUPT_BITMASK) >> 5) +#define GPIO_INTERRUPT_TO_OPTIONS(options, interrupt) (options | (interrupt << 5)) + +typedef enum { + GPIO_INTERRUPT_DISABLE = 0, + GPIO_INTERRUPT_POS_EDGE = 1, + GPIO_INTERRUPT_NEG_EDGE = 2, + GPIO_INTERRUPT_ANY_EDGE = 3, + GPIO_INTERRUPT_LOW_LEVEL = 4, + GPIO_INTERRUPT_HIGH_LEVEL = 5, + GPIO__MAX, +} GpioInterruptType; + +/** + * @brief Provides a type to hold a GPIO pin index. + * + * This reduced-size type is sufficient to record a pin number, + * e.g. from a devicetree GPIOS property. + */ +typedef uint8_t gpio_pin_t; + +/** + * @brief Identifies a set of pins associated with a port. + * + * The pin with index n is present in the set if and only if the bit + * identified by (1U << n) is set. + */ +typedef uint32_t gpio_pinset_t; + +/** + * @brief Provides a type to hold GPIO devicetree flags. + * + * All GPIO flags that can be expressed in devicetree fit in the low 16 + * bits of the full flags field, so use a reduced-size type to record + * that part of a GPIOS property. + * + * The lower 8 bits are used for standard flags. The upper 8 bits are reserved + * for SoC specific flags. + */ +typedef uint16_t gpio_flags_t; + +/** + * @brief Container for GPIO pin information specified in dts files + * + * This type contains a pointer to a GPIO device, pin identifier for a pin + * controlled by that device, and the subset of pin configuration + * flags which may be given in devicetree. + */ +struct GpioPinConfig { + /** GPIO device controlling the pin */ + const struct Device* port; + /** The pin's number on the device */ + gpio_pin_t pin; + /** The pin's configuration flags as specified in devicetree */ + gpio_flags_t dt_flags; +}; + +/** + * Check if the pin is ready to be used. + * @param pin_config the specifications of the pin + * @return true if the pin is ready to be used + */ +static inline bool gpio_is_ready(const struct GpioPinConfig* pin_config) { + return device_is_ready(pin_config->port); +} + +#ifdef __cplusplus +} +#endif diff --git a/TactilityKernel/Include/Tactility/drivers/GpioController.h b/TactilityKernel/Include/Tactility/drivers/GpioController.h new file mode 100644 index 00000000..3d70923d --- /dev/null +++ b/TactilityKernel/Include/Tactility/drivers/GpioController.h @@ -0,0 +1,28 @@ +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include "Gpio.h" +#include + +struct GpioControllerApi { + bool (*set_level)(struct Device* device, gpio_pin_t pin, bool high); + bool (*get_level)(struct Device* device, gpio_pin_t pin, bool* high); + bool (*set_options)(struct Device* device, gpio_pin_t pin, gpio_flags_t options); + bool (*get_options)(struct Device* device, gpio_pin_t pin, gpio_flags_t* options); +}; + +bool gpio_controller_set_level(struct Device* device, gpio_pin_t pin, bool high); +bool gpio_controller_get_level(struct Device* device, gpio_pin_t pin, bool* high); +bool gpio_controller_set_options(struct Device* device, gpio_pin_t pin, gpio_flags_t options); +bool gpio_controller_get_options(struct Device* device, gpio_pin_t pin, gpio_flags_t* options); + +inline bool gpio_set_options_config(struct Device* device, struct GpioPinConfig* config) { + return gpio_controller_set_options(device, config->pin, config->dt_flags); +} + +#ifdef __cplusplus +} +#endif diff --git a/TactilityKernel/Include/Tactility/drivers/I2cController.h b/TactilityKernel/Include/Tactility/drivers/I2cController.h new file mode 100644 index 00000000..beb932a9 --- /dev/null +++ b/TactilityKernel/Include/Tactility/drivers/I2cController.h @@ -0,0 +1,28 @@ +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include "Gpio.h" +#include +#include +#include + +struct I2cControllerApi { + bool (*read)(struct Device* device, uint8_t address, uint8_t* data, size_t dataSize, TickType_t timeout); + bool (*write)(struct Device* device, uint8_t address, const uint8_t* data, uint16_t dataSize, TickType_t timeout); + bool (*write_read)(struct Device* device, uint8_t address, const uint8_t* write_data, size_t write_data_size, uint8_t* read_data, size_t read_data_size, TickType_t timeout); +}; + +bool i2c_controller_read(struct Device* device, uint8_t address, uint8_t* data, size_t dataSize, TickType_t timeout); + +bool i2c_controller_write(struct Device* device, uint8_t address, const uint8_t* data, uint16_t dataSize, TickType_t timeout); + +bool i2c_controller_write_read(struct Device* device, uint8_t address, const uint8_t* write_data, size_t write_data_size, uint8_t* read_data, size_t read_data_size, TickType_t timeout); + +extern const struct DeviceType I2C_CONTROLLER_TYPE; + +#ifdef __cplusplus +} +#endif diff --git a/TactilityKernel/Include/Tactility/drivers/Root.h b/TactilityKernel/Include/Tactility/drivers/Root.h new file mode 100644 index 00000000..00120801 --- /dev/null +++ b/TactilityKernel/Include/Tactility/drivers/Root.h @@ -0,0 +1,13 @@ +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +struct RootConfig { + const char* model; +}; + +#ifdef __cplusplus +} +#endif diff --git a/TactilityKernel/LICENSE-LGPL-3.0.md b/TactilityKernel/LICENSE-LGPL-3.0.md new file mode 100644 index 00000000..6fb6a01e --- /dev/null +++ b/TactilityKernel/LICENSE-LGPL-3.0.md @@ -0,0 +1,157 @@ +# 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. diff --git a/TactilityKernel/Source/Device.cpp b/TactilityKernel/Source/Device.cpp new file mode 100644 index 00000000..47d28f9e --- /dev/null +++ b/TactilityKernel/Source/Device.cpp @@ -0,0 +1,225 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#define TAG LOG_TAG(device) + +struct DeviceData { + std::vector children; +}; + +struct DeviceLedger { + std::vector devices; + Mutex mutex { 0 }; + + DeviceLedger() { + mutex_construct(&mutex); + } + + ~DeviceLedger() { + mutex_destruct(&mutex); + } +}; + +static DeviceLedger& get_ledger() { + static DeviceLedger ledger; + return ledger; +} + +#define ledger get_ledger() + +extern "C" { + +#define ledger_lock() mutex_lock(&ledger.mutex) +#define ledger_unlock() mutex_unlock(&ledger.mutex) + +#define get_device_data(device) static_cast(device->internal.data) + +int device_construct(Device* device) { + device->internal.data = new(std::nothrow) DeviceData; + if (device->internal.data == nullptr) { + return ENOMEM; + } + LOG_I(TAG, "construct %s", device->name); + mutex_construct(&device->internal.mutex); + return 0; +} + +int device_destruct(Device* device) { + if (device->internal.state.started || device->internal.state.added) { + return ERROR_INVALID_STATE; + } + if (!get_device_data(device)->children.empty()) { + return ERROR_INVALID_STATE; + } + LOG_I(TAG, "destruct %s", device->name); + mutex_destruct(&device->internal.mutex); + delete get_device_data(device); + device->internal.data = nullptr; + return 0; +} + +/** Add a child to the list of children */ +static void device_add_child(struct Device* device, struct Device* child) { + device_lock(device); + assert(device->internal.state.added); + get_device_data(device)->children.push_back(child); + device_unlock(device); +} + +/** Remove a child from the list of children */ +static void device_remove_child(struct Device* device, struct Device* child) { + device_lock(device); + auto* parent_data = get_device_data(device); + const auto iterator = std::ranges::find(parent_data->children, child); + if (iterator != parent_data->children.end()) { + parent_data->children.erase(iterator); + } + device_unlock(device); +} + +int device_add(Device* device) { + LOG_I(TAG, "add %s", device->name); + + // Already added + if (device->internal.state.started || device->internal.state.added) { + return ERROR_INVALID_STATE; + } + + // Add to ledger + ledger_lock(); + ledger.devices.push_back(device); + ledger_unlock(); + + // Add self to parent's children list + auto* parent = device->parent; + if (parent != nullptr) { + device_add_child(parent, device); + } + + device->internal.state.added = true; + return 0; +} + +int device_remove(Device* device) { + LOG_I(TAG, "remove %s", device->name); + + if (device->internal.state.started || !device->internal.state.added) { + return ERROR_INVALID_STATE; + } + + // Remove self from parent's children list + auto* parent = device->parent; + if (parent != nullptr) { + device_remove_child(parent, device); + } + + ledger_lock(); + const auto iterator = std::ranges::find(ledger.devices, device); + if (iterator == ledger.devices.end()) { + ledger_unlock(); + goto failed_ledger_lookup; + } + ledger.devices.erase(iterator); + ledger_unlock(); + + device->internal.state.added = false; + return 0; + +failed_ledger_lookup: + + // Re-add to parent + if (parent != nullptr) { + device_add_child(parent, device); + } + + return ERROR_NOT_FOUND; +} + +int device_start(Device* device) { + if (!device->internal.state.added) { + return ERROR_INVALID_STATE; + } + + if (device->internal.driver == nullptr) { + return ERROR_INVALID_STATE; + } + + // Already started + if (device->internal.state.started) { + return 0; + } + + int result = driver_bind(device->internal.driver, device); + device->internal.state.started = (result == 0); + device->internal.state.start_result = result; + return result; +} + +int device_stop(struct Device* device) { + if (!device->internal.state.added) { + return ERROR_INVALID_STATE; + } + + // Not started + if (!device->internal.state.started) { + return 0; + } + + int result = driver_unbind(device->internal.driver, device); + if (result != 0) { + return result; + } + + device->internal.state.started = false; + device->internal.state.start_result = 0; + return 0; +} + +void device_set_parent(Device* device, Device* parent) { + assert(!device->internal.state.started); + device->parent = parent; +} + +void for_each_device(void* callback_context, bool(*on_device)(Device* device, void* context)) { + ledger_lock(); + for (auto* device : ledger.devices) { + if (!on_device(device, callback_context)) { + break; + } + } + ledger_unlock(); +} + +void for_each_device_child(Device* device, void* callback_context, bool(*on_device)(struct Device* device, void* context)) { + auto* data = get_device_data(device); + for (auto* child_device : data->children) { + if (!on_device(child_device, callback_context)) { + break; + } + } +} + +void for_each_device_of_type(const DeviceType* type, void* callback_context, bool(*on_device)(Device* device, void* context)) { + ledger_lock(); + for (auto* device : ledger.devices) { + auto* driver = device->internal.driver; + if (driver != nullptr) { + if (driver->device_type == type) { + if (!on_device(device, callback_context)) { + break; + } + } + } + } + ledger_unlock(); +} + +} // extern "C" diff --git a/TactilityKernel/Source/Driver.cpp b/TactilityKernel/Source/Driver.cpp new file mode 100644 index 00000000..14c0d09d --- /dev/null +++ b/TactilityKernel/Source/Driver.cpp @@ -0,0 +1,188 @@ +#include +#include +#include + +#include +#include +#include +#include +#include + +#define TAG LOG_TAG(driver) + +struct DriverInternalData { + Mutex mutex { 0 }; + int use_count = 0; + + DriverInternalData() { + mutex_construct(&mutex); + } + + ~DriverInternalData() { + mutex_destruct(&mutex); + } +}; + +struct DriverLedger { + std::vector drivers; + Mutex mutex { 0 }; + + DriverLedger() { + mutex_construct(&mutex); + } + + ~DriverLedger() { + mutex_destruct(&mutex); + } + + void lock() { + mutex_lock(&mutex); + } + + void unlock() { + mutex_unlock(&mutex); + } +}; + +static DriverLedger& get_ledger() { + static DriverLedger ledger; + return ledger; +} + +#define ledger get_ledger() + +#define driver_internal_data(driver) static_cast(driver->internal.data) +#define driver_lock(driver) mutex_lock(&driver_internal_data(driver)->mutex); +#define driver_unlock(driver) mutex_unlock(&driver_internal_data(driver)->mutex); + +static void driver_add(Driver* driver) { + LOG_I(TAG, "add %s", driver->name); + ledger.lock(); + ledger.drivers.push_back(driver); + ledger.unlock(); +} + +static bool driver_remove(Driver* driver) { + LOG_I(TAG, "remove %s", driver->name); + + ledger.lock(); + const auto iterator = std::ranges::find(ledger.drivers, driver); + // check that there actually is a 3 in our vector + if (iterator == ledger.drivers.end()) { + ledger.unlock(); + return false; + } + ledger.drivers.erase(iterator); + ledger.unlock(); + + return true; +} + +extern "C" { + +int driver_construct(Driver* driver) { + driver->internal.data = new(std::nothrow) DriverInternalData; + if (driver->internal.data == nullptr) { + return ENOMEM; + } + driver_add(driver); + return 0; +} + +int driver_destruct(Driver* driver) { + // Check if in use + if (driver_internal_data(driver)->use_count != 0) { + return ERROR_INVALID_STATE; + } + + driver_remove(driver); + delete driver_internal_data(driver); + driver->internal.data = nullptr; + return 0; +} + +bool driver_is_compatible(Driver* driver, const char* compatible) { + if (compatible == nullptr || driver->compatible == nullptr) { + return false; + } + const char** compatible_iterator = driver->compatible; + while (*compatible_iterator != nullptr) { + if (strcmp(*compatible_iterator, compatible) == 0) { + return true; + } + compatible_iterator++; + } + return false; +} + +Driver* driver_find_compatible(const char* compatible) { + ledger.lock(); + Driver* result = nullptr; + for (auto* driver : ledger.drivers) { + if (driver_is_compatible(driver, compatible)) { + result = driver; + break; + } + } + ledger.unlock(); + return result; +} + +int driver_bind(Driver* driver, Device* device) { + driver_lock(driver); + + int err = 0; + if (!device_is_added(device)) { + err = ERROR_INVALID_STATE; + goto error; + } + + if (driver->start_device != nullptr) { + err = driver->start_device(device); + if (err != 0) { + goto error; + } + } + + driver_internal_data(driver)->use_count++; + driver_unlock(driver); + + LOG_I(TAG, "bound %s to %s", driver->name, device->name); + return 0; + +error: + + driver_unlock(driver); + return err; +} + +int driver_unbind(Driver* driver, Device* device) { + driver_lock(driver); + + int err = 0; + if (!device_is_added(device)) { + err = ERROR_INVALID_STATE; + goto error; + } + + if (driver->stop_device != nullptr) { + err = driver->stop_device(device); + if (err != 0) { + goto error; + } + } + + driver_internal_data(driver)->use_count--; + driver_unlock(driver); + + LOG_I(TAG, "unbound %s to %s", driver->name, device->name); + + return 0; + +error: + + driver_unlock(driver); + return err; +} + +} // extern "C" diff --git a/TactilityKernel/Source/Log.cpp b/TactilityKernel/Source/Log.cpp new file mode 100644 index 00000000..2d1c392c --- /dev/null +++ b/TactilityKernel/Source/Log.cpp @@ -0,0 +1,17 @@ +#ifndef ESP_PLATFORM + +#include + +#include +#include + +void log_generic(const char* tag, const char* format, ...) { + va_list args; + va_start(args, format); + printf("%s ", tag); + vprintf(format, args); + printf("\n"); + va_end(args); +} + +#endif \ No newline at end of file diff --git a/TactilityKernel/Source/drivers/GpioController.cpp b/TactilityKernel/Source/drivers/GpioController.cpp new file mode 100644 index 00000000..cd4e4971 --- /dev/null +++ b/TactilityKernel/Source/drivers/GpioController.cpp @@ -0,0 +1,28 @@ +#include +#include + +#define GPIO_DRIVER_API(driver) ((struct GpioControllerApi*)driver->api) + +extern "C" { + +bool gpio_controller_set_level(Device* device, gpio_pin_t pin, bool high) { + const auto* driver = device_get_driver(device); + return GPIO_DRIVER_API(driver)->set_level(device, pin, high); +} + +bool gpio_controller_get_level(Device* device, gpio_pin_t pin, bool* high) { + const auto* driver = device_get_driver(device); + return GPIO_DRIVER_API(driver)->get_level(device, pin, high); +} + +bool gpio_controller_set_options(Device* device, gpio_pin_t pin, gpio_flags_t options) { + const auto* driver = device_get_driver(device); + return GPIO_DRIVER_API(driver)->set_options(device, pin, options); +} + +bool gpio_controller_get_options(Device* device, gpio_pin_t pin, gpio_flags_t* options) { + const auto* driver = device_get_driver(device); + return GPIO_DRIVER_API(driver)->get_options(device, pin, options); +} + +} diff --git a/TactilityKernel/Source/drivers/I2cController.cpp b/TactilityKernel/Source/drivers/I2cController.cpp new file mode 100644 index 00000000..c6495534 --- /dev/null +++ b/TactilityKernel/Source/drivers/I2cController.cpp @@ -0,0 +1,25 @@ +#include +#include + +#define I2C_DRIVER_API(driver) ((struct I2cControllerApi*)driver->api) + +extern "C" { + +bool i2c_controller_read(Device* device, uint8_t address, uint8_t* data, size_t dataSize, TickType_t timeout) { + const auto* driver = device_get_driver(device); + return I2C_DRIVER_API(driver)->read(device, address, data, dataSize, timeout); +} + +bool i2c_controller_write(Device* device, uint8_t address, const uint8_t* data, uint16_t dataSize, TickType_t timeout) { + const auto* driver = device_get_driver(device); + return I2C_DRIVER_API(driver)->write(device, address, data, dataSize, timeout); +} + +bool i2c_controller_write_read(Device* device, uint8_t address, const uint8_t* write_data, size_t write_data_size, uint8_t* read_data, size_t read_data_size, TickType_t timeout) { + const auto* driver = device_get_driver(device); + return I2C_DRIVER_API(driver)->write_read(device, address, write_data, write_data_size, read_data, read_data_size, timeout); +} + +const struct DeviceType I2C_CONTROLLER_TYPE { 0 }; + +} diff --git a/TactilityKernel/Source/drivers/Register.cpp b/TactilityKernel/Source/drivers/Register.cpp new file mode 100644 index 00000000..4983fb49 --- /dev/null +++ b/TactilityKernel/Source/drivers/Register.cpp @@ -0,0 +1,10 @@ +#include + +extern "C" { + +extern void register_kernel_drivers() { + extern Driver root_driver; + driver_construct(&root_driver); +} + +} diff --git a/TactilityKernel/Source/drivers/Root.cpp b/TactilityKernel/Source/drivers/Root.cpp new file mode 100644 index 00000000..6afb64ce --- /dev/null +++ b/TactilityKernel/Source/drivers/Root.cpp @@ -0,0 +1,16 @@ +#include +#include + +extern "C" { + +Driver root_driver = { + .name = "root", + .compatible = (const char*[]) { "root", nullptr }, + .start_device = nullptr, + .stop_device = nullptr, + .api = nullptr, + .device_type = nullptr, + .internal = { 0 } +}; + +} diff --git a/TactilityKernel/devicetree.yaml b/TactilityKernel/devicetree.yaml new file mode 100644 index 00000000..6723f7af --- /dev/null +++ b/TactilityKernel/devicetree.yaml @@ -0,0 +1 @@ +bindings: Bindings diff --git a/Tests/CMakeLists.txt b/Tests/CMakeLists.txt index 3ab79bd1..5883c72c 100644 --- a/Tests/CMakeLists.txt +++ b/Tests/CMakeLists.txt @@ -5,9 +5,11 @@ set(DOCTESTINC ${PROJECT_SOURCE_DIR}/Include) enable_testing() add_subdirectory(TactilityCore) add_subdirectory(TactilityFreeRtos) +add_subdirectory(TactilityKernel) add_subdirectory(Tactility) add_custom_target(build-tests) add_dependencies(build-tests TactilityCoreTests) add_dependencies(build-tests TactilityFreeRtosTests) add_dependencies(build-tests TactilityTests) +add_dependencies(build-tests TactilityKernelTests) diff --git a/Tests/LICENSE-GPL-3.0.md b/Tests/LICENSE-GPL-3.0.md new file mode 100644 index 00000000..496acdb2 --- /dev/null +++ b/Tests/LICENSE-GPL-3.0.md @@ -0,0 +1,675 @@ +# GNU 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. + +## Preamble + +The GNU General Public License is a free, copyleft license for +software and other kinds of works. + +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom +to share and change all versions of a program--to make sure it remains +free software for all its users. We, the Free Software Foundation, use +the GNU General Public License for most of our software; it applies +also to any other work released this way by its authors. You can apply +it to your programs, too. + +When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you +have certain responsibilities if you distribute copies of the +software, or if you modify it: responsibilities to respect the freedom +of others. + +For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + +Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + +Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the +manufacturer can do so. This is fundamentally incompatible with the +aim of protecting users' freedom to change the software. The +systematic pattern of such abuse occurs in the area of products for +individuals to use, which is precisely where it is most unacceptable. +Therefore, we have designed this version of the GPL to prohibit the +practice for those products. If such problems arise substantially in +other domains, we stand ready to extend this provision to those +domains in future versions of the GPL, as needed to protect the +freedom of users. + +Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish +to avoid the special danger that patents applied to a free program +could make it effectively proprietary. To prevent this, the GPL +assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and +modification follow. + +## TERMS AND CONDITIONS + +### 0. Definitions. + +"This License" refers to version 3 of the GNU General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds +of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of +an exact copy. The resulting work is called a "modified version" of +the earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based +on the Program. + +To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user +through a computer network, with no transfer of a copy, is not +conveying. + +An interactive user interface displays "Appropriate Legal Notices" to +the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + +### 1. Source Code. + +The "source code" for a work means the preferred form of the work for +making modifications to it. "Object code" means any non-source form of +a work. + +A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can +regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same +work. + +### 2. Basic Permissions. + +All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, +without conditions so long as your license otherwise remains in force. +You may convey covered works to others for the sole purpose of having +them make modifications exclusively for you, or provide you with +facilities for running those works, provided that you comply with the +terms of this License in conveying all material for which you do not +control copyright. Those thus making or running the covered works for +you must do so exclusively on your behalf, under your direction and +control, on terms that prohibit them from making any copies of your +copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the +conditions stated below. Sublicensing is not allowed; section 10 makes +it unnecessary. + +### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such +circumvention is effected by exercising rights under this License with +respect to the covered work, and you disclaim any intention to limit +operation or modification of the work as a means of enforcing, against +the work's users, your or third parties' legal rights to forbid +circumvention of technological measures. + +### 4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + +### 5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these +conditions: + +- a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. +- b) The work must carry prominent notices stating that it is + released under this License and any conditions added under + section 7. This requirement modifies the requirement in section 4 + to "keep intact all notices". +- c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. +- d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + +A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + +### 6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms of +sections 4 and 5, provided that you also convey the machine-readable +Corresponding Source under the terms of this License, in one of these +ways: + +- a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. +- b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the Corresponding + Source from a network server at no charge. +- c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. +- d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. +- e) Convey the object code using peer-to-peer transmission, + provided you inform other peers where the object code and + Corresponding Source of the work are being offered to the general + public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, +family, or household purposes, or (2) anything designed or sold for +incorporation into a dwelling. In determining whether a product is a +consumer product, doubtful cases shall be resolved in favor of +coverage. For a particular product received by a particular user, +"normally used" refers to a typical or common use of that class of +product, regardless of the status of the particular user or of the way +in which the particular user actually uses, or expects or is expected +to use, the product. A product is a consumer product regardless of +whether the product has substantial commercial, industrial or +non-consumer uses, unless such uses represent the only significant +mode of use of the product. + +"Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to +install and execute modified versions of a covered work in that User +Product from a modified version of its Corresponding Source. The +information must suffice to ensure that the continued functioning of +the modified object code is in no case prevented or interfered with +solely because modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or +updates for a work that has been modified or installed by the +recipient, or for the User Product in which it has been modified or +installed. Access to a network may be denied when the modification +itself materially and adversely affects the operation of the network +or violates the rules and protocols for communication across the +network. + +Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + +### 7. Additional Terms. + +"Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders +of that material) supplement the terms of this License with terms: + +- a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or +- b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or +- c) Prohibiting misrepresentation of the origin of that material, + or requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or +- d) Limiting the use for publicity purposes of names of licensors + or authors of the material; or +- e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or +- f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions + of it) with contractual assumptions of liability to the recipient, + for any liability that these contractual assumptions directly + impose on those licensors and authors. + +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; the +above requirements apply either way. + +### 8. Termination. + +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + +However, if you cease all violation of this License, then your license +from a particular copyright holder is reinstated (a) provisionally, +unless and until the copyright holder explicitly and finally +terminates your license, and (b) permanently, if the copyright holder +fails to notify you of the violation by some reasonable means prior to +60 days after the cessation. + +Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + +Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + +### 9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run +a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + +### 10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + +### 11. Patents. + +A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned +or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + +If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + +A patent license is "discriminatory" if it does not include within the +scope of its coverage, prohibits the exercise of, or is conditioned on +the non-exercise of one or more of the rights that are specifically +granted under this License. You may not convey a covered work if you +are a party to an arrangement with a third party that is in the +business of distributing software, under which you make payment to the +third party based on the extent of your activity of conveying the +work, and under which the third party grants, to any of the parties +who would receive the covered work from you, a discriminatory patent +license (a) in connection with copies of the covered work conveyed by +you (or copies made from those copies), or (b) primarily for and in +connection with specific products or compilations that contain the +covered work, unless you entered into that arrangement, or that patent +license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + +### 12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under +this License and any other pertinent obligations, then as a +consequence you may not convey it at all. For example, if you agree to +terms that obligate you to collect a royalty for further conveying +from those to whom you convey the Program, the only way you could +satisfy both those terms and this License would be to refrain entirely +from conveying the Program. + +### 13. Use with the GNU Affero General Public License. + +Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + +### 14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions +of the GNU 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 Program +specifies that a certain numbered version of the GNU General Public +License "or any later version" applies to it, you have the option of +following the terms and conditions either of that numbered version or +of any later version published by the Free Software Foundation. If the +Program does not specify a version number of the GNU General Public +License, you may choose any version ever published by the Free +Software Foundation. + +If the Program specifies that a proxy can decide which future versions +of the GNU General Public License can be used, that proxy's public +statement of acceptance of a version permanently authorizes you to +choose that version for the Program. + +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + +### 15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT +WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND +PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE +DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR +CORRECTION. + +### 16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR +CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES +ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT +NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR +LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM +TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER +PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +### 17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + +## How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these +terms. + +To do so, attach the following notices to the program. It is safest to +attach them to the start of each source file to most effectively state +the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 . + +Also add information on how to contact you by electronic and paper +mail. + +If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands \`show w' and \`show c' should show the +appropriate parts of the General Public License. Of course, your +program's commands might be different; for a GUI interface, you would +use an "about box". + +You should also get your employer (if you work as a programmer) or +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. For more information on this, and how to apply and follow +the GNU GPL, see . + +The GNU General Public License does not permit incorporating your +program into proprietary programs. If your program is a subroutine +library, you may consider it more useful to permit linking proprietary +applications with the library. If this is what you want to do, use the +GNU Lesser General Public License instead of this License. But first, +please read . diff --git a/Tests/Tactility/Main.cpp b/Tests/Tactility/Main.cpp index cfa29e91..89eadd14 100644 --- a/Tests/Tactility/Main.cpp +++ b/Tests/Tactility/Main.cpp @@ -23,9 +23,7 @@ void test_task(void* parameter) { data->result = context.run(); - if (context.shouldExit()) { // important - query flags (and --exit) rely on the user doing this - vTaskEndScheduler(); - } + vTaskEndScheduler(); vTaskDelete(nullptr); } diff --git a/Tests/TactilityCore/Main.cpp b/Tests/TactilityCore/Main.cpp index 165c3d27..5866a9fe 100644 --- a/Tests/TactilityCore/Main.cpp +++ b/Tests/TactilityCore/Main.cpp @@ -23,9 +23,7 @@ void test_task(void* parameter) { data->result = context.run(); - if (context.shouldExit()) { // important - query flags (and --exit) rely on the user doing this - vTaskEndScheduler(); - } + vTaskEndScheduler(); vTaskDelete(nullptr); } diff --git a/Tests/TactilityFreeRtos/Main.cpp b/Tests/TactilityFreeRtos/Main.cpp index 165c3d27..5866a9fe 100644 --- a/Tests/TactilityFreeRtos/Main.cpp +++ b/Tests/TactilityFreeRtos/Main.cpp @@ -23,9 +23,7 @@ void test_task(void* parameter) { data->result = context.run(); - if (context.shouldExit()) { // important - query flags (and --exit) rely on the user doing this - vTaskEndScheduler(); - } + vTaskEndScheduler(); vTaskDelete(nullptr); } diff --git a/Tests/TactilityKernel/CMakeLists.txt b/Tests/TactilityKernel/CMakeLists.txt new file mode 100644 index 00000000..8c257f61 --- /dev/null +++ b/Tests/TactilityKernel/CMakeLists.txt @@ -0,0 +1,14 @@ +project(TactilityCoreTests) + +enable_language(C CXX ASM) + +set(CMAKE_CXX_COMPILER g++) + +file(GLOB_RECURSE TEST_SOURCES ${PROJECT_SOURCE_DIR}/*.cpp) +add_executable(TactilityKernelTests EXCLUDE_FROM_ALL ${TEST_SOURCES}) + +target_include_directories(TactilityKernelTests PRIVATE ${DOCTESTINC}) + +add_test(NAME TactilityKernelTests COMMAND TactilityKernelTests) + +target_link_libraries(TactilityKernelTests PUBLIC TactilityKernel) diff --git a/Tests/TactilityKernel/DeviceTest.cpp b/Tests/TactilityKernel/DeviceTest.cpp new file mode 100644 index 00000000..247af86d --- /dev/null +++ b/Tests/TactilityKernel/DeviceTest.cpp @@ -0,0 +1,190 @@ +#include "doctest.h" + +#include +#include + +#include + +TEST_CASE("device_construct and device_destruct should set and unset the correct fields") { + Device device = { 0 }; + + int error = device_construct(&device); + CHECK_EQ(error, 0); + + CHECK_NE(device.internal.data, nullptr); + CHECK_NE(device.internal.mutex.handle, nullptr); + + error = device_destruct(&device); + CHECK_EQ(error, 0); + + CHECK_EQ(device.internal.data, nullptr); + CHECK_EQ(device.internal.mutex.handle, nullptr); + + Device comparison_device = { 0 }; + comparison_device.internal.data = device.internal.data; + comparison_device.internal.mutex.handle = device.internal.mutex.handle; + + // Check that no other data was set + CHECK_EQ(memcmp(&device, &comparison_device, sizeof(Device)), 0); +} + +TEST_CASE("device_add should add the device to the list of all devices") { + Device device = { 0 }; + CHECK_EQ(device_construct(&device), 0); + CHECK_EQ(device_add(&device), 0); + + // Gather all devices + std::vector devices; + for_each_device(&devices, [](auto* device, auto* context) { + auto* devices_ptr = (std::vector*)context; + devices_ptr->push_back(device); + return true; + }); + + CHECK_EQ(devices.size(), 1); + CHECK_EQ(devices[0], &device); + + CHECK_EQ(device_remove(&device), 0); + CHECK_EQ(device_destruct(&device), 0); +} + +TEST_CASE("device_add should add the device to its parent") { + Device parent = { 0 }; + + Device child = { + .name = nullptr, + .config = nullptr, + .parent = &parent + }; + + CHECK_EQ(device_construct(&parent), 0); + CHECK_EQ(device_add(&parent), 0); + + CHECK_EQ(device_construct(&child), 0); + CHECK_EQ(device_add(&child), 0); + + // Gather all child devices + std::vector children; + for_each_device_child(&parent, &children, [](auto* child_device, auto* context) { + auto* children_ptr = (std::vector*)context; + children_ptr->push_back(child_device); + return true; + }); + + CHECK_EQ(children.size(), 1); + CHECK_EQ(children[0], &child); + + CHECK_EQ(device_remove(&child), 0); + CHECK_EQ(device_destruct(&child), 0); + + CHECK_EQ(device_remove(&parent), 0); + CHECK_EQ(device_destruct(&parent), 0); +} + +TEST_CASE("device_add should set the state to 'added'") { + Device device = { 0 }; + CHECK_EQ(device_construct(&device), 0); + + CHECK_EQ(device.internal.state.added, false); + CHECK_EQ(device_add(&device), 0); + CHECK_EQ(device.internal.state.added, true); + + CHECK_EQ(device_remove(&device), 0); + CHECK_EQ(device_destruct(&device), 0); +} + +TEST_CASE("device_remove should remove it from the list of all devices") { + Device device = { 0 }; + CHECK_EQ(device_construct(&device), 0); + CHECK_EQ(device_add(&device), 0); + CHECK_EQ(device_remove(&device), 0); + + // Gather all devices + std::vector devices; + for_each_device(&devices, [](auto* device, auto* context) { + auto* devices_ptr = (std::vector*)context; + devices_ptr->push_back(device); + return true; + }); + + CHECK_EQ(devices.size(), 0); + + CHECK_EQ(device_destruct(&device), 0); +} + +TEST_CASE("device_remove should remove the device from its parent") { + Device parent = { 0 }; + + Device child = { + .name = nullptr, + .config = nullptr, + .parent = &parent + }; + + CHECK_EQ(device_construct(&parent), 0); + CHECK_EQ(device_add(&parent), 0); + + CHECK_EQ(device_construct(&child), 0); + CHECK_EQ(device_add(&child), 0); + CHECK_EQ(device_remove(&child), 0); + + // Gather all child devices + std::vector children; + for_each_device_child(&parent, &children, [](auto* child_device, auto* context) { + auto* children_ptr = (std::vector*)context; + children_ptr->push_back(child_device); + return true; + }); + + CHECK_EQ(children.size(), 0); + + CHECK_EQ(device_destruct(&child), 0); + + CHECK_EQ(device_remove(&parent), 0); + CHECK_EQ(device_destruct(&parent), 0); +} + +TEST_CASE("device_remove should clear the state 'added'") { + Device device = { 0 }; + CHECK_EQ(device_construct(&device), 0); + + CHECK_EQ(device_add(&device), 0); + CHECK_EQ(device.internal.state.added, true); + CHECK_EQ(device_remove(&device), 0); + CHECK_EQ(device.internal.state.added, false); + + CHECK_EQ(device_destruct(&device), 0); +} + +TEST_CASE("device_is_ready should return true only when it is started") { + const char* compatible[] = { "test_compatible", nullptr }; + Driver driver = { + .name = "test_driver", + .compatible = compatible, + .start_device = nullptr, + .stop_device = nullptr, + .api = nullptr, + .device_type = nullptr, + .internal = { 0 } + }; + + Device device = { 0 }; + + CHECK_EQ(driver_construct(&driver), 0); + CHECK_EQ(device_construct(&device), 0); + + CHECK_EQ(device.internal.state.started, false); + device_set_driver(&device, &driver); + CHECK_EQ(device.internal.state.started, false); + CHECK_EQ(device_add(&device), 0); + CHECK_EQ(device.internal.state.started, false); + CHECK_EQ(device_start(&device), 0); + CHECK_EQ(device.internal.state.started, true); + CHECK_EQ(device_stop(&device), 0); + CHECK_EQ(device.internal.state.started, false); + CHECK_EQ(device_remove(&device), 0); + CHECK_EQ(device.internal.state.started, false); + + CHECK_EQ(driver_destruct(&driver), 0); + CHECK_EQ(device_destruct(&device), 0); +} diff --git a/Tests/TactilityKernel/DriverIntegrationTest.cpp b/Tests/TactilityKernel/DriverIntegrationTest.cpp new file mode 100644 index 00000000..f648cfff --- /dev/null +++ b/Tests/TactilityKernel/DriverIntegrationTest.cpp @@ -0,0 +1,64 @@ +#include "doctest.h" +#include +#include + +struct IntegrationDriverConfig { + int startResult; + int stopResult; +}; + +static int startCalled = 0; +static int stopCalled = 0; + +#define integration_data(device) static_cast(device_get_driver_data(device)) +#define integration_config(device) static_cast(device->config) + +static int start(Device* device) { + startCalled++; + return integration_config(device)->startResult; +} + +static int stop(Device* device) { + stopCalled++; + return integration_config(device)->stopResult; +} + +static Driver integration_driver = { + .name = "integration_test_driver", + .compatible = (const char*[]) { "integration", nullptr }, + .start_device = start, + .stop_device = stop, + .api = nullptr, + .device_type = nullptr, + .internal = { 0 } +}; + +TEST_CASE("driver with with start success and stop success should start and stop a device") { + startCalled = 0; + stopCalled = 0; + static const IntegrationDriverConfig config { + .startResult = 0, + .stopResult = 0 + }; + + static Device integration_device { + .name = "integration_device", + .config = &config, + .parent = nullptr, + }; + + CHECK_EQ(driver_construct(&integration_driver), 0); + + CHECK_EQ(device_construct(&integration_device), 0); + device_add(&integration_device); + CHECK_EQ(startCalled, 0); + CHECK_EQ(driver_bind(&integration_driver, &integration_device), 0); + CHECK_EQ(startCalled, 1); + CHECK_EQ(stopCalled, 0); + CHECK_EQ(driver_unbind(&integration_driver, &integration_device), 0); + CHECK_EQ(stopCalled, 1); + CHECK_EQ(device_remove(&integration_device), 0); + CHECK_EQ(device_destruct(&integration_device), 0); + + CHECK_EQ(driver_destruct(&integration_driver), 0); +} diff --git a/Tests/TactilityKernel/DriverTest.cpp b/Tests/TactilityKernel/DriverTest.cpp new file mode 100644 index 00000000..b85506a6 --- /dev/null +++ b/Tests/TactilityKernel/DriverTest.cpp @@ -0,0 +1,58 @@ +#include "doctest.h" +#include + +TEST_CASE("driver_construct and driver_destruct should set and unset the correct fields") { + Driver driver = { 0 }; + + int error = driver_construct(&driver); + CHECK_EQ(error, 0); + CHECK_NE(driver.internal.data, nullptr); + + error = driver_destruct(&driver); + CHECK_EQ(error, 0); + CHECK_EQ(driver.internal.data, nullptr); +} + +TEST_CASE("driver_is_compatible should return true if a compatible value is found") { + const char* compatible[] = { "test_compatible", nullptr }; + Driver driver = { + .name = "test_driver", + .compatible = compatible, + .start_device = nullptr, + .stop_device = nullptr, + .api = nullptr, + .device_type = nullptr, + .internal = { 0 } + }; + CHECK_EQ(driver_is_compatible(&driver, "test_compatible"), true); + CHECK_EQ(driver_is_compatible(&driver, "nope"), false); + CHECK_EQ(driver_is_compatible(&driver, nullptr), false); +} + +TEST_CASE("driver_find should only find a compatible driver when the driver was constructed") { + const char* compatible[] = { "test_compatible", nullptr }; + Driver driver = { + .name = "test_driver", + .compatible = compatible, + .start_device = nullptr, + .stop_device = nullptr, + .api = nullptr, + .device_type = nullptr, + .internal = { 0 } + }; + + Driver* found_driver = driver_find_compatible("test_compatible"); + CHECK_EQ(found_driver, nullptr); + + int error = driver_construct(&driver); + CHECK_EQ(error, 0); + + found_driver = driver_find_compatible("test_compatible"); + CHECK_EQ(found_driver, &driver); + + error = driver_destruct(&driver); + CHECK_EQ(error, 0); + + found_driver = driver_find_compatible("test_compatible"); + CHECK_EQ(found_driver, nullptr); +} diff --git a/Tests/TactilityKernel/Main.cpp b/Tests/TactilityKernel/Main.cpp new file mode 100644 index 00000000..6498121d --- /dev/null +++ b/Tests/TactilityKernel/Main.cpp @@ -0,0 +1,57 @@ +#define DOCTEST_CONFIG_IMPLEMENT +#include "doctest.h" +#include + +#include + +typedef struct { + int argc; + char** argv; + int result; +} TestTaskData; + +void test_task(void* parameter) { + auto* data = (TestTaskData*)parameter; + + doctest::Context context; + + context.applyCommandLine(data->argc, data->argv); + + // overrides + context.setOption("no-breaks", true); // don't break in the debugger when assertions fail + + data->result = context.run(); + + vTaskEndScheduler(); + + vTaskDelete(nullptr); +} + +int main(int argc, char** argv) { + TestTaskData data = { + .argc = argc, + .argv = argv, + .result = 0 + }; + + BaseType_t task_result = xTaskCreate( + test_task, + "test_task", + 8192, + &data, + 1, + nullptr + ); + assert(task_result == pdPASS); + + vTaskStartScheduler(); + + return data.result; +} + +extern "C" { + // Required for FreeRTOS + void vAssertCalled(unsigned long line, const char* const file) { + __assert_fail("assert failed", file, line, ""); + } +} From d3797abf4e4e2434131d0b4288897c7c7bd41081 Mon Sep 17 00:00:00 2001 From: Ken Van Hoeylandt Date: Sat, 24 Jan 2026 16:34:04 +0100 Subject: [PATCH 05/10] Update GitHub group references (#455) ByteWelder -> TactilityProject --- .github/FUNDING.yml | 2 +- .github/PULL_REQUEST_TEMPLATE/pull_request_template.md | 4 ++-- CONTRIBUTING.md | 2 +- Documentation/releasing.md | 8 ++++---- LICENSE.md | 2 +- THIRD-PARTY-NOTICES.md | 2 +- 6 files changed, 10 insertions(+), 10 deletions(-) diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index c6535e2d..0a31b5f4 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1,6 +1,6 @@ # These are supported funding model platforms -github: [ByteWelder] +github: [TactilityProject] patreon: # Replace with a single Patreon username open_collective: # Replace with a single Open Collective username ko_fi: # Replace with a single Ko-fi username diff --git a/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md b/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md index 3580d31f..914b08c4 100644 --- a/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md +++ b/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md @@ -1,7 +1,7 @@ ### Checklist -- [ ] I read [contribution guidelines](https://github.com/ByteWelder/Tactility/blob/main/CONTRIBUTING.md) -- [ ] Code adheres to the [coding style](https://github.com/ByteWelder/Tactility/blob/main/CODING_STYLE.md) +- [ ] I read [contribution guidelines](https://github.com/TactilityProject/Tactility/blob/main/CONTRIBUTING.md) +- [ ] Code adheres to the [coding style](https://github.com/TactilityProject/Tactility/blob/main/CODING_STYLE.md) ### Description diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9937bb78..b4314ba4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,7 +2,7 @@ ## New features and boards -Feel free to open an [issue](https://github.com/ByteWelder/Tactility/issues/new) +Feel free to open an [issue](https://github.com/TactilityProject/Tactility/issues/new) to discuss ideas you have regarding the implementation of new boards or features. Keep in mind that the internal APIs are changing rapidly. They might change considerably in a short timespan. diff --git a/Documentation/releasing.md b/Documentation/releasing.md index 11c8c8b0..ef4c24f9 100644 --- a/Documentation/releasing.md +++ b/Documentation/releasing.md @@ -6,8 +6,8 @@ 2. Merge the branch and wait for a build. 3. Upload the new Tactility SDK to the CDN 1. Upload it to the [CDN](https://dash.cloudflare.com) - 2. Update `sdk.json` from [TactilityTool](https://github.com/ByteWelder/TactilityTool) and upload it to [CDN](https://dash.cloudflare.com) -4. Update the [TactilityApps](https://github.com/ByteWelder/TactilityApps) with the new SDK and also release these to the CDN: + 2. Update `sdk.json` from [TactilityTool](https://github.com/TactilityProject/TactilityTool) and upload it to [CDN](https://dash.cloudflare.com) +4. Update the [TactilityApps](https://github.com/TactilityProject/TactilityApps) with the new SDK and also release these to the CDN: 1. Download the `cdn-files.zip` from the pipelines 2. Upload them to the CDN at `apps/x.y.z/` 3. Also upload them to the CDN for the upcoming version, because the upcoming a.b.c version will also need some basic apps to download @@ -18,8 +18,8 @@ 6. Test the firmwares on all devices with the local web installer 7. Push a tag e.g. `v1.2.3` - the `v` prefix is crucial for the pipelines 8. The pipelines should now kick off a build that releases the build to the stable channel of the Web Installer. Verify that. -9. Make a new version of the docs available at [TactilityDocs](https://github.com/ByteWelder/TactilityDocs) -10. Make a new [GitHub release](https://github.com/ByteWelder/Tactility/releases/new) +9. Make a new version of the docs available at [TactilityDocs](https://github.com/TactilityProject/TactilityDocs) +10. Make a new [GitHub release](https://github.com/TactilityProject/Tactility/releases/new) 11. Double-check that all CDN/TactilityApps/Tactility repository changes are merged. 12. Ensure that the CDN is not in development mode anymore. diff --git a/LICENSE.md b/LICENSE.md index 3a171c5d..c9f8c161 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -52,7 +52,7 @@ The Tactility logo copyrights are owned by Ken Van Hoeylandt. Logo usage is permitted in these scenarios: - News, blog posts, articles and documentation that write about the official Tactility project. -- Firmwares built with unmodified source code from [the official repository](https://github.com/ByteWelder/Tactility) can be redistributed with the Tactility logo. +- Firmwares built with unmodified source code from [the official repository](https://github.com/TactilityProject/Tactility) can be redistributed with the Tactility logo. - Personal use for local builds that contain Tactility source code (original or modified), and aren't re-distributed online. Logo usage is forbidden in all other scenarios unless an exception was granted by the author. diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md index 8fda14b6..8c94fb9e 100644 --- a/THIRD-PARTY-NOTICES.md +++ b/THIRD-PARTY-NOTICES.md @@ -59,7 +59,7 @@ License: [MIT](https://github.com/Xinyuan-LilyGO/T-Echo/blob/main/LICENSE) Website: https://github.com/UsefulElectronics/esp32s3-gc9a01-lvgl -License: [Explicitly granted by author](https://github.com/ByteWelder/Tactility/pull/295#discussion_r2226215423) +License: [Explicitly granted by author](https://github.com/TactilityProject/Tactility/pull/295#discussion_r2226215423) ### Other Dependencies From 51b9547e99c8bc8449376504175ddbda116a0b0b Mon Sep 17 00:00:00 2001 From: Ken Van Hoeylandt Date: Sat, 24 Jan 2026 16:38:59 +0100 Subject: [PATCH 06/10] Revert last change (#456) --- .github/FUNDING.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index 0a31b5f4..c6535e2d 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1,6 +1,6 @@ # These are supported funding model platforms -github: [TactilityProject] +github: [ByteWelder] patreon: # Replace with a single Patreon username open_collective: # Replace with a single Open Collective username ko_fi: # Replace with a single Ko-fi username From 2839ea4c35afe0252bd9e2a88ad77adb64ed1bdc Mon Sep 17 00:00:00 2001 From: Ken Van Hoeylandt Date: Sat, 24 Jan 2026 18:18:55 +0100 Subject: [PATCH 07/10] Update domain name and related URLs (#457) --- .github/ISSUE_TEMPLATE/bug_report.md | 2 +- CONTRIBUTING.md | 2 +- Documentation/releasing.md | 2 +- README.md | 2 +- Tactility/Source/app/apphub/AppHub.cpp | 2 +- Tactility/Source/app/crashdiagnostics/QrUrl.cpp | 2 +- sdkconfig.md | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 69bfbfcc..2077131d 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -30,4 +30,4 @@ If applicable, add screenshots to help explain your problem. **Additional context** Add any other context about the problem here. -Add your oops.tactility.one URL if you had a crash (scanned from QR). +Add your oops.tactilityproject.org URL if you had a crash (scanned from QR). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b4314ba4..f44a0d06 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -28,7 +28,7 @@ Some examples of non-serious issues include: ## Anything that doesn't fall in the above categories? -Please [contact me](https://tactility.one/#/support) first! +Please [contact me](https://tactilityproject.org/#/support) first! ## Pull Requests diff --git a/Documentation/releasing.md b/Documentation/releasing.md index ef4c24f9..9eb34581 100644 --- a/Documentation/releasing.md +++ b/Documentation/releasing.md @@ -11,7 +11,7 @@ 1. Download the `cdn-files.zip` from the pipelines 2. Upload them to the CDN at `apps/x.y.z/` 3. Also upload them to the CDN for the upcoming version, because the upcoming a.b.c version will also need some basic apps to download -5. Test the latest unstable version of Tactility on several devices using the [web installer](https://install.tactility.one). Pay special attention to: +5. Test the latest unstable version of Tactility on several devices using the [web installer](https://install.tactilityproject.org). Pay special attention to: 1. The version of the unstable channel (should be updated!) 2. App Hub 3. Wi-Fi diff --git a/README.md b/README.md index 7b40fd5b..87eab9de 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Tactility is an operating system that focuses on the ESP32 microcontroller family. -See [https://tactility.one](https://tactility.one) for more information. +See [https://tactilityproject.org](https://tactilityproject.org) for more information. ![photo of devices running Tactility](Documentation/pics/tactility-devices.webp)  ![screenshot of launcher app](Documentation/pics/screenshot-Launcher.png) diff --git a/Tactility/Source/app/apphub/AppHub.cpp b/Tactility/Source/app/apphub/AppHub.cpp index 82284e48..f1f82c27 100644 --- a/Tactility/Source/app/apphub/AppHub.cpp +++ b/Tactility/Source/app/apphub/AppHub.cpp @@ -4,7 +4,7 @@ namespace tt::app::apphub { -constexpr auto* BASE_URL = "https://cdn.tactility.one/apps"; +constexpr auto* BASE_URL = "https://cdn.tactilityproject.org/apps"; static std::string getVersionWithoutPostfix() { std::string version(TT_VERSION); diff --git a/Tactility/Source/app/crashdiagnostics/QrUrl.cpp b/Tactility/Source/app/crashdiagnostics/QrUrl.cpp index d2b65eb2..7a9475f5 100644 --- a/Tactility/Source/app/crashdiagnostics/QrUrl.cpp +++ b/Tactility/Source/app/crashdiagnostics/QrUrl.cpp @@ -35,7 +35,7 @@ std::string getUrlFromCrashData() { std::stringstream stream; - stream << "https://oops.tactility.one"; + stream << "https://oops.tactilityproject.org"; stream << "?v=" << TT_VERSION; // Version stream << "&a=" << CONFIG_IDF_TARGET; // Architecture stream << "&b=" << CONFIG_TT_DEVICE_ID; // Board identifier diff --git a/sdkconfig.md b/sdkconfig.md index ecc07593..a835cd21 100644 --- a/sdkconfig.md +++ b/sdkconfig.md @@ -1,6 +1,6 @@ # Get Started -See [https://docs.tactility.one] +See [https://docs.tactilityproject.org] # Useful Parameters From 96eccbdc8d7c4b9b52e44ce2eb706f829368f511 Mon Sep 17 00:00:00 2001 From: Ken Van Hoeylandt Date: Sat, 24 Jan 2026 21:33:44 +0100 Subject: [PATCH 08/10] Add tests and update licenses (#458) Replace LGPL from past commit with Apache License 2.0 for the newly created projects: - in Platforms/* - TactilityKernel Add license headers to source code in: - in Platforms/* - TactilityKernel - TactilityFreeRtos Updated LICENSE.md --- Documentation/LICENSE-LGPL-3.0.md | 157 -------------- Documentation/ideas.md | 2 +- LICENSE.md | 40 ++-- Platforms/LICENSE-Apache-2.0.md | 195 ++++++++++++++++++ Platforms/LICENSE-LGPL-3.0.md | 157 -------------- .../Include/Tactility/bindings/esp32_gpio.h | 1 + .../Include/Tactility/bindings/esp32_i2c.h | 1 + .../Include/Tactility/drivers/Esp32Gpio.h | 1 + .../Include/Tactility/drivers/Esp32I2c.h | 1 + Platforms/PlatformEsp32/Source/Esp32Gpio.cpp | 1 + Platforms/PlatformEsp32/Source/Esp32I2c.cpp | 1 + Platforms/PlatformEsp32/Source/Register.cpp | 1 + Platforms/PlatformPosix/Source/Register.cpp | 1 + .../Include/Tactility/Dispatcher.h | 1 + .../Include/Tactility/DispatcherThread.h | 1 + .../Include/Tactility/EventGroup.h | 1 + TactilityFreeRtos/Include/Tactility/Lock.h | 1 + .../Include/Tactility/MessageQueue.h | 1 + TactilityFreeRtos/Include/Tactility/Mutex.h | 1 + TactilityFreeRtos/Include/Tactility/PubSub.h | 1 + .../Include/Tactility/RecursiveMutex.h | 1 + .../Include/Tactility/Semaphore.h | 1 + TactilityFreeRtos/Include/Tactility/Thread.h | 1 + TactilityFreeRtos/Include/Tactility/Timer.h | 1 + .../Tactility/freertoscompat/EventGroups.h | 1 + .../Tactility/freertoscompat/PortCompat.h | 1 + .../Include/Tactility/freertoscompat/Queue.h | 1 + .../Include/Tactility/freertoscompat/RTOS.h | 1 + .../Tactility/freertoscompat/Semaphore.h | 1 + .../Include/Tactility/freertoscompat/Task.h | 1 + .../Include/Tactility/freertoscompat/Timers.h | 1 + .../Include/Tactility/kernel/Kernel.h | 1 + TactilityKernel/Include/Tactility/Device.h | 2 + TactilityKernel/Include/Tactility/Driver.h | 2 + TactilityKernel/Include/Tactility/Error.h | 2 + .../Include/Tactility/FreeRTOS/FreeRTOS.h | 2 + .../Include/Tactility/FreeRTOS/event_groups.h | 2 + .../Include/Tactility/FreeRTOS/port.h | 2 + .../Include/Tactility/FreeRTOS/queue.h | 2 + .../Include/Tactility/FreeRTOS/semphr.h | 2 + .../Include/Tactility/FreeRTOS/task.h | 2 + .../Include/Tactility/FreeRTOS/timers.h | 2 + TactilityKernel/Include/Tactility/Log.h | 2 + .../Include/Tactility/bindings/bindings.h | 2 + .../Include/Tactility/bindings/gpio.h | 2 + .../Include/Tactility/bindings/root.h | 2 + .../Include/Tactility/concurrent/Mutex.h | 2 + .../Tactility/concurrent/RecursiveMutex.h | 2 + .../Include/Tactility/drivers/Gpio.h | 2 + .../Tactility/drivers/GpioController.h | 2 + .../Include/Tactility/drivers/I2cController.h | 2 + .../Include/Tactility/drivers/Root.h | 2 + TactilityKernel/LICENSE-Apache-2.0.md | 195 ++++++++++++++++++ TactilityKernel/LICENSE-LGPL-3.0.md | 157 -------------- TactilityKernel/Source/Device.cpp | 2 + TactilityKernel/Source/Driver.cpp | 2 + TactilityKernel/Source/Log.cpp | 2 + .../Source/drivers/GpioController.cpp | 2 + .../Source/drivers/I2cController.cpp | 2 + TactilityKernel/Source/drivers/Register.cpp | 2 + TactilityKernel/Source/drivers/Root.cpp | 2 + Tests/TactilityKernel/MutexTest.cpp | 66 ++++++ Tests/TactilityKernel/RecursiveMutexTest.cpp | 86 ++++++++ 63 files changed, 639 insertions(+), 497 deletions(-) delete mode 100644 Documentation/LICENSE-LGPL-3.0.md create mode 100644 Platforms/LICENSE-Apache-2.0.md delete mode 100644 Platforms/LICENSE-LGPL-3.0.md create mode 100644 TactilityKernel/LICENSE-Apache-2.0.md delete mode 100644 TactilityKernel/LICENSE-LGPL-3.0.md create mode 100644 Tests/TactilityKernel/MutexTest.cpp create mode 100644 Tests/TactilityKernel/RecursiveMutexTest.cpp diff --git a/Documentation/LICENSE-LGPL-3.0.md b/Documentation/LICENSE-LGPL-3.0.md deleted file mode 100644 index 6fb6a01e..00000000 --- a/Documentation/LICENSE-LGPL-3.0.md +++ /dev/null @@ -1,157 +0,0 @@ -# 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. diff --git a/Documentation/ideas.md b/Documentation/ideas.md index 96d1ce27..2d14595e 100644 --- a/Documentation/ideas.md +++ b/Documentation/ideas.md @@ -2,7 +2,7 @@ ## Before release -- Add `// SPDX-License-Identifier: LGPL-3.0-only` and similar license mentions to individual files in the project +- Add `// SPDX-License-Identifier: GPL-3.0-only` and `// SPDX-License-Identifier: Apache-2.0` to individual files in the project - Change ButtonControl to work with interrupts and xQueue - TCA9534 keyboards should use interrupts - GT911 drivers should use interrupts if it's stable diff --git a/LICENSE.md b/LICENSE.md index c9f8c161..8340dbaa 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -7,40 +7,30 @@ These applications are not part of the Tactility operating system's main firmwar "end-users" refers to people who install and/or use Tactility software on their devices. -## Licensing Intent - -The main intention is to make sure forks of the operating system stay open source, -while external applications can have both open or closed source licenses. - -TactilitySDK combines several subprojects and should not have source code with a GPL licenses inside. - ## Past & Present Formerly, there was a mixed usage of [GPL v3.0](Documentation/LICENSE-GPL-3.0.md) for internal subprojects and [Apache License v2.0](Documentation/LICENSE-Apache-2.0.md) for subprojects that would be used in external apps. -For future subprojects, [LGPL v3.0](Documentation/LICENSE-LGPL-3.0.md) will be chosen for internal subprojects and -Apache License v2.0 will be chosen for header-only projects. -Existing GPL-licensed projects will retain this license, as it cannot be changed to LGPL. - -The reason is that LGPL allows for logic in header files, but it comes with limitations (e.g. limit of 10 lines of code in headers). -If we write C++ wrappers for C libraries then we want them to be usable for building external apps, without such LGPL limitations. +For future subprojects, [Apache License v2.0](Documentation/LICENSE-Apache-2.0.md) will be chosen for internal subproject. +Existing GPL-licensed projects will retain this license, as it cannot be changed to a more permissive license. ## Overview Below is an overview of the licenses of some of the subprojects. -| Project | License | -|--------------------|---------------------| -| Tactility | GPL v3.0 | -| TactilityCore | GPL v3.0 | -| TactilityC | Apache License v2.0 | -| TactilityFreeRTOS | Apache License v2.0 | -| TactilityKernel | LGPL v3.0 | -| Tests | GPL v3.0 | -| Devices/* | GPL v3.0 | -| Drivers/* | (varies) | -| DevicetreeCompiler | Apache License v2.0 | +| Project | License | +|--------------------|-------------------------| +| Tactility | GNU Public License v3.0 | +| TactilityCore | GNU Public License v3.0 | +| TactilityC | Apache License v2.0 | +| TactilityFreeRTOS | Apache License v2.0 | +| TactilityKernel | Apache License v2.0 | +| Tests | GNU Public License v3.0 | +| Devices/* | GNU Public License v3.0 | +| Drivers/* | (varies) | +| DevicetreeCompiler | Apache License v2.0 | +| Platforms/* | Apache License v2.0 | Subprojects and directories in this project can contain license files. @@ -69,4 +59,4 @@ Third-party licenses and copyrights are listed in [THIRD-PARTY-NOTICES.md](THIRD ## FAQ - Q: Can I build closed source applications? -- A: Yes, external apps can be closed source. All subprojects with an Apache License or LGPL license can be used in this manner. If you fork the project and make an internal app, it must be redistributed under the GPL v3.0 license. +- A: If the applications were built with the Tactility SDK, then they can have a proprietary license. Applications inside the Tactility firmware can't be released with a proprietary license. diff --git a/Platforms/LICENSE-Apache-2.0.md b/Platforms/LICENSE-Apache-2.0.md new file mode 100644 index 00000000..f5f4b8b5 --- /dev/null +++ b/Platforms/LICENSE-Apache-2.0.md @@ -0,0 +1,195 @@ +Apache License +============== + +_Version 2.0, January 2004_ +_<>_ + +### Terms and Conditions for use, reproduction, and distribution + +#### 1. Definitions + +“License” shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +“Licensor” shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + +“Legal Entity” shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, “control” means **(i)** the power, direct or +indirect, to cause the direction or management of such entity, whether by +contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the +outstanding shares, or **(iii)** beneficial ownership of such entity. + +“You” (or “Your”) shall mean an individual or Legal Entity exercising +permissions granted by this License. + +“Source” form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + +“Object” form shall mean any form resulting from mechanical transformation or +translation of a Source form, including but not limited to compiled object code, +generated documentation, and conversions to other media types. + +“Work” shall mean the work of authorship, whether in Source or Object form, made +available under the License, as indicated by a copyright notice that is included +in or attached to the work (an example is provided in the Appendix below). + +“Derivative Works” shall mean any work, whether in Source or Object form, that +is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative Works +shall not include works that remain separable from, or merely link (or bind by +name) to the interfaces of, the Work and Derivative Works thereof. + +“Contribution” shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative Works +thereof, that is intentionally submitted to Licensor for inclusion in the Work +by the copyright owner or by an individual or Legal Entity authorized to submit +on behalf of the copyright owner. For the purposes of this definition, +“submitted” means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for +the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as “Not a Contribution.” + +“Contributor” shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently +incorporated within the Work. + +#### 2. Grant of Copyright License + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +#### 3. Grant of Patent License + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this section) patent license to make, have +made, use, offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by combination +of their Contribution(s) with the Work to which such Contribution(s) was +submitted. If You institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work or a +Contribution incorporated within the Work constitutes direct or contributory +patent infringement, then any patent licenses granted to You under this License +for that Work shall terminate as of the date such litigation is filed. + +#### 4. Redistribution + +You may reproduce and distribute copies of the Work or Derivative Works thereof +in any medium, with or without modifications, and in Source or Object form, +provided that You meet the following conditions: + +* **(a)** You must give any other recipients of the Work or Derivative Works a copy of +this License; and +* **(b)** You must cause any modified files to carry prominent notices stating that You +changed the files; and +* **(c)** You must retain, in the Source form of any Derivative Works that You distribute, +all copyright, patent, trademark, and attribution notices from the Source form +of the Work, excluding those notices that do not pertain to any part of the +Derivative Works; and +* **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any +Derivative Works that You distribute must include a readable copy of the +attribution notices contained within such NOTICE file, excluding those notices +that do not pertain to any part of the Derivative Works, in at least one of the +following places: within a NOTICE text file distributed as part of the +Derivative Works; within the Source form or documentation, if provided along +with the Derivative Works; or, within a display generated by the Derivative +Works, if and wherever such third-party notices normally appear. The contents of +the NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative Works that +You distribute, alongside or as an addendum to the NOTICE text from the Work, +provided that such additional attribution notices cannot be construed as +modifying the License. + +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + +#### 5. Submission of Contributions + +Unless You explicitly state otherwise, any Contribution intentionally submitted +for inclusion in the Work by You to the Licensor shall be under the terms and +conditions of this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify the terms of +any separate license agreement you may have executed with Licensor regarding +such Contributions. + +#### 6. Trademarks + +This License does not grant permission to use the trade names, trademarks, +service marks, or product names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +#### 7. Disclaimer of Warranty + +Unless required by applicable law or agreed to in writing, Licensor provides the +Work (and each Contributor provides its Contributions) on an “AS IS” BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +including, without limitation, any warranties or conditions of TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your exercise of +permissions under this License. + +#### 8. Limitation of Liability + +In no event and under no legal theory, whether in tort (including negligence), +contract, or otherwise, unless required by applicable law (such as deliberate +and grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, incidental, +or consequential damages of any character arising as a result of this License or +out of the use or inability to use the Work (including but not limited to +damages for loss of goodwill, work stoppage, computer failure or malfunction, or +any and all other commercial damages or losses), even if such Contributor has +been advised of the possibility of such damages. + +#### 9. Accepting Warranty or Additional Liability + +While redistributing the Work or Derivative Works thereof, You may choose to +offer, and charge a fee for, acceptance of support, warranty, indemnity, or +other liability obligations and/or rights consistent with this License. However, +in accepting such obligations, You may act only on Your own behalf and on Your +sole responsibility, not on behalf of any other Contributor, and only if You +agree to indemnify, defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason of your +accepting any such warranty or additional liability. + +_END OF TERMS AND CONDITIONS_ + +### APPENDIX: How to apply the Apache License to your work + +To apply the Apache License to your work, attach the following boilerplate +notice, with the fields enclosed by brackets `[]` replaced with your own +identifying information. (Don't include the brackets!) The text should be +enclosed in the appropriate comment syntax for the file format. We also +recommend that a file or class name and description of purpose be included on +the same “printed page” as the copyright notice for easier identification within +third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/Platforms/LICENSE-LGPL-3.0.md b/Platforms/LICENSE-LGPL-3.0.md deleted file mode 100644 index 6fb6a01e..00000000 --- a/Platforms/LICENSE-LGPL-3.0.md +++ /dev/null @@ -1,157 +0,0 @@ -# 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. diff --git a/Platforms/PlatformEsp32/Include/Tactility/bindings/esp32_gpio.h b/Platforms/PlatformEsp32/Include/Tactility/bindings/esp32_gpio.h index 30102715..f11ecdb2 100644 --- a/Platforms/PlatformEsp32/Include/Tactility/bindings/esp32_gpio.h +++ b/Platforms/PlatformEsp32/Include/Tactility/bindings/esp32_gpio.h @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: Apache-2.0 #pragma once #include diff --git a/Platforms/PlatformEsp32/Include/Tactility/bindings/esp32_i2c.h b/Platforms/PlatformEsp32/Include/Tactility/bindings/esp32_i2c.h index e2826b74..0a02de04 100644 --- a/Platforms/PlatformEsp32/Include/Tactility/bindings/esp32_i2c.h +++ b/Platforms/PlatformEsp32/Include/Tactility/bindings/esp32_i2c.h @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: Apache-2.0 #pragma once #include diff --git a/Platforms/PlatformEsp32/Include/Tactility/drivers/Esp32Gpio.h b/Platforms/PlatformEsp32/Include/Tactility/drivers/Esp32Gpio.h index 04245c68..43b03a4c 100644 --- a/Platforms/PlatformEsp32/Include/Tactility/drivers/Esp32Gpio.h +++ b/Platforms/PlatformEsp32/Include/Tactility/drivers/Esp32Gpio.h @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifdef __cplusplus diff --git a/Platforms/PlatformEsp32/Include/Tactility/drivers/Esp32I2c.h b/Platforms/PlatformEsp32/Include/Tactility/drivers/Esp32I2c.h index 55b07b14..2e7de1c1 100644 --- a/Platforms/PlatformEsp32/Include/Tactility/drivers/Esp32I2c.h +++ b/Platforms/PlatformEsp32/Include/Tactility/drivers/Esp32I2c.h @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: Apache-2.0 #pragma once #include diff --git a/Platforms/PlatformEsp32/Source/Esp32Gpio.cpp b/Platforms/PlatformEsp32/Source/Esp32Gpio.cpp index 51bd2e94..adc4fa92 100644 --- a/Platforms/PlatformEsp32/Source/Esp32Gpio.cpp +++ b/Platforms/PlatformEsp32/Source/Esp32Gpio.cpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/Platforms/PlatformEsp32/Source/Esp32I2c.cpp b/Platforms/PlatformEsp32/Source/Esp32I2c.cpp index 4599f7db..b8948e8f 100644 --- a/Platforms/PlatformEsp32/Source/Esp32I2c.cpp +++ b/Platforms/PlatformEsp32/Source/Esp32I2c.cpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/Platforms/PlatformEsp32/Source/Register.cpp b/Platforms/PlatformEsp32/Source/Register.cpp index 1293e28a..133e01f9 100644 --- a/Platforms/PlatformEsp32/Source/Register.cpp +++ b/Platforms/PlatformEsp32/Source/Register.cpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: Apache-2.0 #include extern "C" { diff --git a/Platforms/PlatformPosix/Source/Register.cpp b/Platforms/PlatformPosix/Source/Register.cpp index 6453236e..b390c12f 100644 --- a/Platforms/PlatformPosix/Source/Register.cpp +++ b/Platforms/PlatformPosix/Source/Register.cpp @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: Apache-2.0 #include extern "C" { diff --git a/TactilityFreeRtos/Include/Tactility/Dispatcher.h b/TactilityFreeRtos/Include/Tactility/Dispatcher.h index 70677860..076acff0 100644 --- a/TactilityFreeRtos/Include/Tactility/Dispatcher.h +++ b/TactilityFreeRtos/Include/Tactility/Dispatcher.h @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: Apache-2.0 /** * Dispatcher is a thread-safe code execution queue. */ diff --git a/TactilityFreeRtos/Include/Tactility/DispatcherThread.h b/TactilityFreeRtos/Include/Tactility/DispatcherThread.h index 9e66a814..a6780915 100644 --- a/TactilityFreeRtos/Include/Tactility/DispatcherThread.h +++ b/TactilityFreeRtos/Include/Tactility/DispatcherThread.h @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: Apache-2.0 #pragma once #include "Dispatcher.h" diff --git a/TactilityFreeRtos/Include/Tactility/EventGroup.h b/TactilityFreeRtos/Include/Tactility/EventGroup.h index 2d80fe72..c016d5aa 100644 --- a/TactilityFreeRtos/Include/Tactility/EventGroup.h +++ b/TactilityFreeRtos/Include/Tactility/EventGroup.h @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: Apache-2.0 #pragma once #include "freertoscompat/EventGroups.h" diff --git a/TactilityFreeRtos/Include/Tactility/Lock.h b/TactilityFreeRtos/Include/Tactility/Lock.h index 46eaafb9..49c61d31 100644 --- a/TactilityFreeRtos/Include/Tactility/Lock.h +++ b/TactilityFreeRtos/Include/Tactility/Lock.h @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: Apache-2.0 #pragma once #include "kernel/Kernel.h" diff --git a/TactilityFreeRtos/Include/Tactility/MessageQueue.h b/TactilityFreeRtos/Include/Tactility/MessageQueue.h index 54fb020c..7dfc93eb 100644 --- a/TactilityFreeRtos/Include/Tactility/MessageQueue.h +++ b/TactilityFreeRtos/Include/Tactility/MessageQueue.h @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: Apache-2.0 /** * MessageQueue is a wrapper for FreeRTOS xQueue functionality. * There is no additional thread-safety on top of the xQueue functionality, diff --git a/TactilityFreeRtos/Include/Tactility/Mutex.h b/TactilityFreeRtos/Include/Tactility/Mutex.h index 759f3bb7..6b369ad4 100644 --- a/TactilityFreeRtos/Include/Tactility/Mutex.h +++ b/TactilityFreeRtos/Include/Tactility/Mutex.h @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: Apache-2.0 #pragma once #include "Lock.h" diff --git a/TactilityFreeRtos/Include/Tactility/PubSub.h b/TactilityFreeRtos/Include/Tactility/PubSub.h index 17b8b6e2..b7102cc5 100644 --- a/TactilityFreeRtos/Include/Tactility/PubSub.h +++ b/TactilityFreeRtos/Include/Tactility/PubSub.h @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: Apache-2.0 #pragma once #include "Mutex.h" diff --git a/TactilityFreeRtos/Include/Tactility/RecursiveMutex.h b/TactilityFreeRtos/Include/Tactility/RecursiveMutex.h index 5358351d..b1709aad 100644 --- a/TactilityFreeRtos/Include/Tactility/RecursiveMutex.h +++ b/TactilityFreeRtos/Include/Tactility/RecursiveMutex.h @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: Apache-2.0 #pragma once #include "Lock.h" diff --git a/TactilityFreeRtos/Include/Tactility/Semaphore.h b/TactilityFreeRtos/Include/Tactility/Semaphore.h index 64b25773..278c661d 100644 --- a/TactilityFreeRtos/Include/Tactility/Semaphore.h +++ b/TactilityFreeRtos/Include/Tactility/Semaphore.h @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: Apache-2.0 #pragma once #include "Lock.h" diff --git a/TactilityFreeRtos/Include/Tactility/Thread.h b/TactilityFreeRtos/Include/Tactility/Thread.h index d32d1bc3..552cc817 100644 --- a/TactilityFreeRtos/Include/Tactility/Thread.h +++ b/TactilityFreeRtos/Include/Tactility/Thread.h @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: Apache-2.0 #pragma once #include "freertoscompat/Task.h" diff --git a/TactilityFreeRtos/Include/Tactility/Timer.h b/TactilityFreeRtos/Include/Tactility/Timer.h index ff0f90f3..f77b2519 100644 --- a/TactilityFreeRtos/Include/Tactility/Timer.h +++ b/TactilityFreeRtos/Include/Tactility/Timer.h @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: Apache-2.0 #pragma once #include "Thread.h" diff --git a/TactilityFreeRtos/Include/Tactility/freertoscompat/EventGroups.h b/TactilityFreeRtos/Include/Tactility/freertoscompat/EventGroups.h index 49b52699..d8d09088 100644 --- a/TactilityFreeRtos/Include/Tactility/freertoscompat/EventGroups.h +++ b/TactilityFreeRtos/Include/Tactility/freertoscompat/EventGroups.h @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifdef ESP_PLATFORM diff --git a/TactilityFreeRtos/Include/Tactility/freertoscompat/PortCompat.h b/TactilityFreeRtos/Include/Tactility/freertoscompat/PortCompat.h index 6a43514f..3a3de3a3 100644 --- a/TactilityFreeRtos/Include/Tactility/freertoscompat/PortCompat.h +++ b/TactilityFreeRtos/Include/Tactility/freertoscompat/PortCompat.h @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: Apache-2.0 #pragma once #include "RTOS.h" diff --git a/TactilityFreeRtos/Include/Tactility/freertoscompat/Queue.h b/TactilityFreeRtos/Include/Tactility/freertoscompat/Queue.h index ef370454..ed80fbe1 100644 --- a/TactilityFreeRtos/Include/Tactility/freertoscompat/Queue.h +++ b/TactilityFreeRtos/Include/Tactility/freertoscompat/Queue.h @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifdef ESP_PLATFORM diff --git a/TactilityFreeRtos/Include/Tactility/freertoscompat/RTOS.h b/TactilityFreeRtos/Include/Tactility/freertoscompat/RTOS.h index 42481234..c42dcf5e 100644 --- a/TactilityFreeRtos/Include/Tactility/freertoscompat/RTOS.h +++ b/TactilityFreeRtos/Include/Tactility/freertoscompat/RTOS.h @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifdef ESP_PLATFORM diff --git a/TactilityFreeRtos/Include/Tactility/freertoscompat/Semaphore.h b/TactilityFreeRtos/Include/Tactility/freertoscompat/Semaphore.h index 4594a934..95604738 100644 --- a/TactilityFreeRtos/Include/Tactility/freertoscompat/Semaphore.h +++ b/TactilityFreeRtos/Include/Tactility/freertoscompat/Semaphore.h @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifdef ESP_PLATFORM diff --git a/TactilityFreeRtos/Include/Tactility/freertoscompat/Task.h b/TactilityFreeRtos/Include/Tactility/freertoscompat/Task.h index 59b5d65c..821c2dce 100644 --- a/TactilityFreeRtos/Include/Tactility/freertoscompat/Task.h +++ b/TactilityFreeRtos/Include/Tactility/freertoscompat/Task.h @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifdef ESP_PLATFORM diff --git a/TactilityFreeRtos/Include/Tactility/freertoscompat/Timers.h b/TactilityFreeRtos/Include/Tactility/freertoscompat/Timers.h index 45cf6c6e..d2cf08fa 100644 --- a/TactilityFreeRtos/Include/Tactility/freertoscompat/Timers.h +++ b/TactilityFreeRtos/Include/Tactility/freertoscompat/Timers.h @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifdef ESP_PLATFORM diff --git a/TactilityFreeRtos/Include/Tactility/kernel/Kernel.h b/TactilityFreeRtos/Include/Tactility/kernel/Kernel.h index 684d5a16..59830a6d 100644 --- a/TactilityFreeRtos/Include/Tactility/kernel/Kernel.h +++ b/TactilityFreeRtos/Include/Tactility/kernel/Kernel.h @@ -1,3 +1,4 @@ +// SPDX-License-Identifier: Apache-2.0 #pragma once #include "../freertoscompat/PortCompat.h" diff --git a/TactilityKernel/Include/Tactility/Device.h b/TactilityKernel/Include/Tactility/Device.h index f7618960..0b0983e6 100644 --- a/TactilityKernel/Include/Tactility/Device.h +++ b/TactilityKernel/Include/Tactility/Device.h @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 + #pragma once #include "Driver.h" diff --git a/TactilityKernel/Include/Tactility/Driver.h b/TactilityKernel/Include/Tactility/Driver.h index ee0f88a3..937f9f5d 100644 --- a/TactilityKernel/Include/Tactility/Driver.h +++ b/TactilityKernel/Include/Tactility/Driver.h @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 + #pragma once #ifdef __cplusplus diff --git a/TactilityKernel/Include/Tactility/Error.h b/TactilityKernel/Include/Tactility/Error.h index fdfaaf45..81ccc589 100644 --- a/TactilityKernel/Include/Tactility/Error.h +++ b/TactilityKernel/Include/Tactility/Error.h @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 + #pragma once #define ERROR_UNDEFINED 1 diff --git a/TactilityKernel/Include/Tactility/FreeRTOS/FreeRTOS.h b/TactilityKernel/Include/Tactility/FreeRTOS/FreeRTOS.h index 4d148d81..6c6608cf 100644 --- a/TactilityKernel/Include/Tactility/FreeRTOS/FreeRTOS.h +++ b/TactilityKernel/Include/Tactility/FreeRTOS/FreeRTOS.h @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 + #pragma once #ifdef ESP_PLATFORM diff --git a/TactilityKernel/Include/Tactility/FreeRTOS/event_groups.h b/TactilityKernel/Include/Tactility/FreeRTOS/event_groups.h index 665eeb64..18057781 100644 --- a/TactilityKernel/Include/Tactility/FreeRTOS/event_groups.h +++ b/TactilityKernel/Include/Tactility/FreeRTOS/event_groups.h @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 + #pragma once #include "FreeRTOS.h" diff --git a/TactilityKernel/Include/Tactility/FreeRTOS/port.h b/TactilityKernel/Include/Tactility/FreeRTOS/port.h index d897dafc..f78a0793 100644 --- a/TactilityKernel/Include/Tactility/FreeRTOS/port.h +++ b/TactilityKernel/Include/Tactility/FreeRTOS/port.h @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 + #pragma once #include "FreeRTOS.h" diff --git a/TactilityKernel/Include/Tactility/FreeRTOS/queue.h b/TactilityKernel/Include/Tactility/FreeRTOS/queue.h index b22e3584..aef05949 100644 --- a/TactilityKernel/Include/Tactility/FreeRTOS/queue.h +++ b/TactilityKernel/Include/Tactility/FreeRTOS/queue.h @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 + #pragma once #include "FreeRTOS.h" diff --git a/TactilityKernel/Include/Tactility/FreeRTOS/semphr.h b/TactilityKernel/Include/Tactility/FreeRTOS/semphr.h index 9aa7332b..b94ea2b0 100644 --- a/TactilityKernel/Include/Tactility/FreeRTOS/semphr.h +++ b/TactilityKernel/Include/Tactility/FreeRTOS/semphr.h @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 + #pragma once #include "FreeRTOS.h" diff --git a/TactilityKernel/Include/Tactility/FreeRTOS/task.h b/TactilityKernel/Include/Tactility/FreeRTOS/task.h index cb01be7a..b3bbda92 100644 --- a/TactilityKernel/Include/Tactility/FreeRTOS/task.h +++ b/TactilityKernel/Include/Tactility/FreeRTOS/task.h @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 + #pragma once #include "FreeRTOS.h" diff --git a/TactilityKernel/Include/Tactility/FreeRTOS/timers.h b/TactilityKernel/Include/Tactility/FreeRTOS/timers.h index f1e60b47..61ccd997 100644 --- a/TactilityKernel/Include/Tactility/FreeRTOS/timers.h +++ b/TactilityKernel/Include/Tactility/FreeRTOS/timers.h @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 + #pragma once #include "FreeRTOS.h" diff --git a/TactilityKernel/Include/Tactility/Log.h b/TactilityKernel/Include/Tactility/Log.h index 68939e20..452a1412 100644 --- a/TactilityKernel/Include/Tactility/Log.h +++ b/TactilityKernel/Include/Tactility/Log.h @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 + #pragma once #ifdef ESP_PLATFORM diff --git a/TactilityKernel/Include/Tactility/bindings/bindings.h b/TactilityKernel/Include/Tactility/bindings/bindings.h index 8d46255a..220ba53a 100644 --- a/TactilityKernel/Include/Tactility/bindings/bindings.h +++ b/TactilityKernel/Include/Tactility/bindings/bindings.h @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 + #pragma once /** diff --git a/TactilityKernel/Include/Tactility/bindings/gpio.h b/TactilityKernel/Include/Tactility/bindings/gpio.h index 836daf73..b7958b98 100644 --- a/TactilityKernel/Include/Tactility/bindings/gpio.h +++ b/TactilityKernel/Include/Tactility/bindings/gpio.h @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 + #pragma once #include diff --git a/TactilityKernel/Include/Tactility/bindings/root.h b/TactilityKernel/Include/Tactility/bindings/root.h index f345b5c7..063f0009 100644 --- a/TactilityKernel/Include/Tactility/bindings/root.h +++ b/TactilityKernel/Include/Tactility/bindings/root.h @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 + #pragma once #include diff --git a/TactilityKernel/Include/Tactility/concurrent/Mutex.h b/TactilityKernel/Include/Tactility/concurrent/Mutex.h index 0297ac0a..55b2d51c 100644 --- a/TactilityKernel/Include/Tactility/concurrent/Mutex.h +++ b/TactilityKernel/Include/Tactility/concurrent/Mutex.h @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 + #pragma once #include diff --git a/TactilityKernel/Include/Tactility/concurrent/RecursiveMutex.h b/TactilityKernel/Include/Tactility/concurrent/RecursiveMutex.h index aba6e0da..09dd9a9e 100644 --- a/TactilityKernel/Include/Tactility/concurrent/RecursiveMutex.h +++ b/TactilityKernel/Include/Tactility/concurrent/RecursiveMutex.h @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 + #pragma once #include diff --git a/TactilityKernel/Include/Tactility/drivers/Gpio.h b/TactilityKernel/Include/Tactility/drivers/Gpio.h index 0e90f1df..8aa08b35 100644 --- a/TactilityKernel/Include/Tactility/drivers/Gpio.h +++ b/TactilityKernel/Include/Tactility/drivers/Gpio.h @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 + #pragma once #ifdef __cplusplus diff --git a/TactilityKernel/Include/Tactility/drivers/GpioController.h b/TactilityKernel/Include/Tactility/drivers/GpioController.h index 3d70923d..149e601a 100644 --- a/TactilityKernel/Include/Tactility/drivers/GpioController.h +++ b/TactilityKernel/Include/Tactility/drivers/GpioController.h @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 + #pragma once #ifdef __cplusplus diff --git a/TactilityKernel/Include/Tactility/drivers/I2cController.h b/TactilityKernel/Include/Tactility/drivers/I2cController.h index beb932a9..d2b79cff 100644 --- a/TactilityKernel/Include/Tactility/drivers/I2cController.h +++ b/TactilityKernel/Include/Tactility/drivers/I2cController.h @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 + #pragma once #ifdef __cplusplus diff --git a/TactilityKernel/Include/Tactility/drivers/Root.h b/TactilityKernel/Include/Tactility/drivers/Root.h index 00120801..e2797b93 100644 --- a/TactilityKernel/Include/Tactility/drivers/Root.h +++ b/TactilityKernel/Include/Tactility/drivers/Root.h @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 + #pragma once #ifdef __cplusplus diff --git a/TactilityKernel/LICENSE-Apache-2.0.md b/TactilityKernel/LICENSE-Apache-2.0.md new file mode 100644 index 00000000..f5f4b8b5 --- /dev/null +++ b/TactilityKernel/LICENSE-Apache-2.0.md @@ -0,0 +1,195 @@ +Apache License +============== + +_Version 2.0, January 2004_ +_<>_ + +### Terms and Conditions for use, reproduction, and distribution + +#### 1. Definitions + +“License” shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +“Licensor” shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + +“Legal Entity” shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, “control” means **(i)** the power, direct or +indirect, to cause the direction or management of such entity, whether by +contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the +outstanding shares, or **(iii)** beneficial ownership of such entity. + +“You” (or “Your”) shall mean an individual or Legal Entity exercising +permissions granted by this License. + +“Source” form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + +“Object” form shall mean any form resulting from mechanical transformation or +translation of a Source form, including but not limited to compiled object code, +generated documentation, and conversions to other media types. + +“Work” shall mean the work of authorship, whether in Source or Object form, made +available under the License, as indicated by a copyright notice that is included +in or attached to the work (an example is provided in the Appendix below). + +“Derivative Works” shall mean any work, whether in Source or Object form, that +is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative Works +shall not include works that remain separable from, or merely link (or bind by +name) to the interfaces of, the Work and Derivative Works thereof. + +“Contribution” shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative Works +thereof, that is intentionally submitted to Licensor for inclusion in the Work +by the copyright owner or by an individual or Legal Entity authorized to submit +on behalf of the copyright owner. For the purposes of this definition, +“submitted” means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for +the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as “Not a Contribution.” + +“Contributor” shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently +incorporated within the Work. + +#### 2. Grant of Copyright License + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +#### 3. Grant of Patent License + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this section) patent license to make, have +made, use, offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by combination +of their Contribution(s) with the Work to which such Contribution(s) was +submitted. If You institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work or a +Contribution incorporated within the Work constitutes direct or contributory +patent infringement, then any patent licenses granted to You under this License +for that Work shall terminate as of the date such litigation is filed. + +#### 4. Redistribution + +You may reproduce and distribute copies of the Work or Derivative Works thereof +in any medium, with or without modifications, and in Source or Object form, +provided that You meet the following conditions: + +* **(a)** You must give any other recipients of the Work or Derivative Works a copy of +this License; and +* **(b)** You must cause any modified files to carry prominent notices stating that You +changed the files; and +* **(c)** You must retain, in the Source form of any Derivative Works that You distribute, +all copyright, patent, trademark, and attribution notices from the Source form +of the Work, excluding those notices that do not pertain to any part of the +Derivative Works; and +* **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any +Derivative Works that You distribute must include a readable copy of the +attribution notices contained within such NOTICE file, excluding those notices +that do not pertain to any part of the Derivative Works, in at least one of the +following places: within a NOTICE text file distributed as part of the +Derivative Works; within the Source form or documentation, if provided along +with the Derivative Works; or, within a display generated by the Derivative +Works, if and wherever such third-party notices normally appear. The contents of +the NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative Works that +You distribute, alongside or as an addendum to the NOTICE text from the Work, +provided that such additional attribution notices cannot be construed as +modifying the License. + +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + +#### 5. Submission of Contributions + +Unless You explicitly state otherwise, any Contribution intentionally submitted +for inclusion in the Work by You to the Licensor shall be under the terms and +conditions of this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify the terms of +any separate license agreement you may have executed with Licensor regarding +such Contributions. + +#### 6. Trademarks + +This License does not grant permission to use the trade names, trademarks, +service marks, or product names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +#### 7. Disclaimer of Warranty + +Unless required by applicable law or agreed to in writing, Licensor provides the +Work (and each Contributor provides its Contributions) on an “AS IS” BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +including, without limitation, any warranties or conditions of TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your exercise of +permissions under this License. + +#### 8. Limitation of Liability + +In no event and under no legal theory, whether in tort (including negligence), +contract, or otherwise, unless required by applicable law (such as deliberate +and grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, incidental, +or consequential damages of any character arising as a result of this License or +out of the use or inability to use the Work (including but not limited to +damages for loss of goodwill, work stoppage, computer failure or malfunction, or +any and all other commercial damages or losses), even if such Contributor has +been advised of the possibility of such damages. + +#### 9. Accepting Warranty or Additional Liability + +While redistributing the Work or Derivative Works thereof, You may choose to +offer, and charge a fee for, acceptance of support, warranty, indemnity, or +other liability obligations and/or rights consistent with this License. However, +in accepting such obligations, You may act only on Your own behalf and on Your +sole responsibility, not on behalf of any other Contributor, and only if You +agree to indemnify, defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason of your +accepting any such warranty or additional liability. + +_END OF TERMS AND CONDITIONS_ + +### APPENDIX: How to apply the Apache License to your work + +To apply the Apache License to your work, attach the following boilerplate +notice, with the fields enclosed by brackets `[]` replaced with your own +identifying information. (Don't include the brackets!) The text should be +enclosed in the appropriate comment syntax for the file format. We also +recommend that a file or class name and description of purpose be included on +the same “printed page” as the copyright notice for easier identification within +third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/TactilityKernel/LICENSE-LGPL-3.0.md b/TactilityKernel/LICENSE-LGPL-3.0.md deleted file mode 100644 index 6fb6a01e..00000000 --- a/TactilityKernel/LICENSE-LGPL-3.0.md +++ /dev/null @@ -1,157 +0,0 @@ -# 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. diff --git a/TactilityKernel/Source/Device.cpp b/TactilityKernel/Source/Device.cpp index 47d28f9e..ef8495cc 100644 --- a/TactilityKernel/Source/Device.cpp +++ b/TactilityKernel/Source/Device.cpp @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 + #include #include #include diff --git a/TactilityKernel/Source/Driver.cpp b/TactilityKernel/Source/Driver.cpp index 14c0d09d..52fd334a 100644 --- a/TactilityKernel/Source/Driver.cpp +++ b/TactilityKernel/Source/Driver.cpp @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 + #include #include #include diff --git a/TactilityKernel/Source/Log.cpp b/TactilityKernel/Source/Log.cpp index 2d1c392c..f02f9c22 100644 --- a/TactilityKernel/Source/Log.cpp +++ b/TactilityKernel/Source/Log.cpp @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 + #ifndef ESP_PLATFORM #include diff --git a/TactilityKernel/Source/drivers/GpioController.cpp b/TactilityKernel/Source/drivers/GpioController.cpp index cd4e4971..d97481dd 100644 --- a/TactilityKernel/Source/drivers/GpioController.cpp +++ b/TactilityKernel/Source/drivers/GpioController.cpp @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 + #include #include diff --git a/TactilityKernel/Source/drivers/I2cController.cpp b/TactilityKernel/Source/drivers/I2cController.cpp index c6495534..4dc16ce3 100644 --- a/TactilityKernel/Source/drivers/I2cController.cpp +++ b/TactilityKernel/Source/drivers/I2cController.cpp @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 + #include #include diff --git a/TactilityKernel/Source/drivers/Register.cpp b/TactilityKernel/Source/drivers/Register.cpp index 4983fb49..776c1996 100644 --- a/TactilityKernel/Source/drivers/Register.cpp +++ b/TactilityKernel/Source/drivers/Register.cpp @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 + #include extern "C" { diff --git a/TactilityKernel/Source/drivers/Root.cpp b/TactilityKernel/Source/drivers/Root.cpp index 6afb64ce..035c1f91 100644 --- a/TactilityKernel/Source/drivers/Root.cpp +++ b/TactilityKernel/Source/drivers/Root.cpp @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 + #include #include diff --git a/Tests/TactilityKernel/MutexTest.cpp b/Tests/TactilityKernel/MutexTest.cpp new file mode 100644 index 00000000..d84d10d4 --- /dev/null +++ b/Tests/TactilityKernel/MutexTest.cpp @@ -0,0 +1,66 @@ +#include "doctest.h" +#include + +TEST_CASE("mutex_construct and mutex_destruct should properly set the handle") { + Mutex mutex = { 0 }; + mutex_construct(&mutex); + CHECK_NE(mutex.handle, nullptr); + mutex_destruct(&mutex); + CHECK_EQ(mutex.handle, nullptr); +} + +TEST_CASE("mutex_is_locked should return true only when the mutex is locked") { + Mutex mutex = { 0 }; + mutex_construct(&mutex); + + CHECK_EQ(mutex_is_locked(&mutex), false); + mutex_lock(&mutex); + CHECK_EQ(mutex_is_locked(&mutex), true); + mutex_unlock(&mutex); + CHECK_EQ(mutex_is_locked(&mutex), false); + + mutex_destruct(&mutex); +} + +TEST_CASE("mutex_try_lock should succeed on first lock but not on second") { + Mutex mutex = { 0 }; + mutex_construct(&mutex); + + CHECK_EQ(mutex_try_lock(&mutex), true); + CHECK_EQ(mutex_try_lock(&mutex), false); + mutex_unlock(&mutex); + + mutex_destruct(&mutex); +} + +TEST_CASE("mutex_lock in another task should block when a lock is active") { + static int task_lock_counter = 0; + Mutex mutex = { 0 }; + task_lock_counter = 0; + + mutex_construct(&mutex); + mutex_lock(&mutex); + + TaskHandle_t task_handle; + auto task_create_result = xTaskCreate( + [](void* input) { + Mutex* mutex_ptr = static_cast(input); + mutex_lock(mutex_ptr); + task_lock_counter++; + vTaskDelete(nullptr); + }, + "mutex_test", + 2048, + &mutex, + 0, + &task_handle + ); + + CHECK_EQ(task_create_result, pdPASS); + CHECK_EQ(task_lock_counter, 0); + + mutex_unlock(&mutex); + vTaskDelay(1); + CHECK_EQ(task_lock_counter, 1); + mutex_destruct(&mutex); +} diff --git a/Tests/TactilityKernel/RecursiveMutexTest.cpp b/Tests/TactilityKernel/RecursiveMutexTest.cpp new file mode 100644 index 00000000..17c2d319 --- /dev/null +++ b/Tests/TactilityKernel/RecursiveMutexTest.cpp @@ -0,0 +1,86 @@ +#include "doctest.h" +#include + +TEST_CASE("recursive_mutex_construct and mutex_destruct should properly set the handle") { + RecursiveMutex mutex = { 0 }; + recursive_mutex_construct(&mutex); + CHECK_NE(mutex.handle, nullptr); + recursive_mutex_destruct(&mutex); + CHECK_EQ(mutex.handle, nullptr); +} + +TEST_CASE("recursive_mutex_is_locked should return true only when the mutex is locked") { + RecursiveMutex mutex = { 0 }; + recursive_mutex_construct(&mutex); + + CHECK_EQ(recursive_mutex_is_locked(&mutex), false); + recursive_mutex_lock(&mutex); + CHECK_EQ(recursive_mutex_is_locked(&mutex), true); + recursive_mutex_unlock(&mutex); + CHECK_EQ(recursive_mutex_is_locked(&mutex), false); + + recursive_mutex_destruct(&mutex); +} + +TEST_CASE("recursive_mutex_is_locked can lock twice from the same thread") { + RecursiveMutex mutex = { 0 }; + recursive_mutex_construct(&mutex); + + CHECK_EQ(recursive_mutex_is_locked(&mutex), false); + recursive_mutex_lock(&mutex); + CHECK_EQ(recursive_mutex_is_locked(&mutex), true); + recursive_mutex_lock(&mutex); + CHECK_EQ(recursive_mutex_is_locked(&mutex), true); + recursive_mutex_unlock(&mutex); + CHECK_EQ(recursive_mutex_is_locked(&mutex), true); + recursive_mutex_unlock(&mutex); + CHECK_EQ(recursive_mutex_is_locked(&mutex), false); + + recursive_mutex_destruct(&mutex); +} + +TEST_CASE("recursive_mutex_try_lock should lock multiple times from the same thread") { + RecursiveMutex mutex = { 0 }; + recursive_mutex_construct(&mutex); + + CHECK_EQ(recursive_mutex_try_lock(&mutex), true); + CHECK_EQ(recursive_mutex_try_lock(&mutex), true); + recursive_mutex_unlock(&mutex); + CHECK_EQ(recursive_mutex_is_locked(&mutex), true); + recursive_mutex_unlock(&mutex); + CHECK_EQ(recursive_mutex_is_locked(&mutex), false); + + recursive_mutex_destruct(&mutex); +} + +TEST_CASE("recursive_mutex_lock in another task should block when a lock is active") { + static int task_lock_counter = 0; + RecursiveMutex mutex = { 0 }; + task_lock_counter = 0; + + recursive_mutex_construct(&mutex); + recursive_mutex_lock(&mutex); + + TaskHandle_t task_handle; + auto task_create_result = xTaskCreate( + [](void* input) { + RecursiveMutex* mutex_ptr = static_cast(input); + recursive_mutex_lock(mutex_ptr); + task_lock_counter++; + vTaskDelete(nullptr); + }, + "mutex_test", + 2048, + &mutex, + 0, + &task_handle + ); + + CHECK_EQ(task_create_result, pdPASS); + CHECK_EQ(task_lock_counter, 0); + + recursive_mutex_unlock(&mutex); + vTaskDelay(1); + CHECK_EQ(task_lock_counter, 1); + recursive_mutex_destruct(&mutex); +} From dfe2c865d1d19daf87166445dbc7403fe2a971e7 Mon Sep 17 00:00:00 2001 From: Ken Van Hoeylandt Date: Sun, 25 Jan 2026 23:54:33 +0100 Subject: [PATCH 09/10] TactilityKernel improvements and more (#459) --- Devices/lilygo-tdeck/Source/Init.cpp | 4 + .../Source/drivers/TloraPager.cpp | 6 +- .../Include/Tactility/ErrorEsp32.h | 7 + .../Include/Tactility/drivers/Esp32Gpio.h | 2 +- .../Include/Tactility/drivers/Esp32I2c.h | 6 +- Platforms/PlatformEsp32/Source/ErrorEsp32.cpp | 16 ++ .../Source/{ => drivers}/Esp32Gpio.cpp | 49 +++--- .../Source/{ => drivers}/Esp32I2c.cpp | 41 ++--- .../Source/{ => drivers}/Register.cpp | 0 Tactility/Source/service/gui/GuiService.cpp | 2 +- Tactility/Source/service/wifi/WifiEsp.cpp | 8 +- .../Include/Tactility/Dispatcher.h | 5 +- .../Include/Tactility/EventGroup.h | 53 ++----- TactilityKernel/Include/Tactility/Device.h | 56 ++++--- TactilityKernel/Include/Tactility/Driver.h | 17 ++- TactilityKernel/Include/Tactility/Error.h | 11 +- .../Include/Tactility/concurrent/Dispatcher.h | 78 ++++++++++ .../Include/Tactility/concurrent/EventGroup.h | 78 ++++++++++ .../Include/Tactility/concurrent/Mutex.h | 15 +- .../Tactility/concurrent/RecursiveMutex.h | 14 +- .../Include/Tactility/drivers/Gpio.h | 45 ++---- .../Tactility/drivers/GpioController.h | 22 +-- .../Include/Tactility/drivers/I2cController.h | 20 +-- TactilityKernel/Source/Device.cpp | 52 +++---- TactilityKernel/Source/Driver.cpp | 65 ++++---- .../Source/concurrent/Dispatcher.cpp | 142 ++++++++++++++++++ .../Source/concurrent/EventGroup.cpp | 84 +++++++++++ .../Source/drivers/GpioController.cpp | 8 +- .../Source/drivers/I2cController.cpp | 9 +- TactilityKernel/Source/drivers/Root.cpp | 6 +- Tests/TactilityKernel/DeviceTest.cpp | 95 ++++++------ Tests/TactilityKernel/DispatcherTest.cpp | 25 +++ .../TactilityKernel/DriverIntegrationTest.cpp | 20 +-- Tests/TactilityKernel/DriverTest.cpp | 25 ++- Tests/TactilityKernel/MutexTest.cpp | 2 +- Tests/TactilityKernel/RecursiveMutexTest.cpp | 2 +- 36 files changed, 759 insertions(+), 331 deletions(-) create mode 100644 Platforms/PlatformEsp32/Include/Tactility/ErrorEsp32.h create mode 100644 Platforms/PlatformEsp32/Source/ErrorEsp32.cpp rename Platforms/PlatformEsp32/Source/{ => drivers}/Esp32Gpio.cpp (68%) rename Platforms/PlatformEsp32/Source/{ => drivers}/Esp32I2c.cpp (56%) rename Platforms/PlatformEsp32/Source/{ => drivers}/Register.cpp (100%) create mode 100644 TactilityKernel/Include/Tactility/concurrent/Dispatcher.h create mode 100644 TactilityKernel/Include/Tactility/concurrent/EventGroup.h create mode 100644 TactilityKernel/Source/concurrent/Dispatcher.cpp create mode 100644 TactilityKernel/Source/concurrent/EventGroup.cpp create mode 100644 Tests/TactilityKernel/DispatcherTest.cpp diff --git a/Devices/lilygo-tdeck/Source/Init.cpp b/Devices/lilygo-tdeck/Source/Init.cpp index 5646dac6..416bf830 100644 --- a/Devices/lilygo-tdeck/Source/Init.cpp +++ b/Devices/lilygo-tdeck/Source/Init.cpp @@ -3,6 +3,7 @@ #include "devices/TrackballDevice.h" #include +#include #include #include #include @@ -30,6 +31,9 @@ static bool powerOn() { return false; } + // Avoids crash when no SD card is inserted. It's unknown why, but likely is related to power draw. + tt::kernel::delayMillis(100); + return true; } diff --git a/Devices/lilygo-tlora-pager/Source/drivers/TloraPager.cpp b/Devices/lilygo-tlora-pager/Source/drivers/TloraPager.cpp index d1786e5a..9b2fea73 100644 --- a/Devices/lilygo-tlora-pager/Source/drivers/TloraPager.cpp +++ b/Devices/lilygo-tlora-pager/Source/drivers/TloraPager.cpp @@ -17,10 +17,10 @@ static int stop(Device* device) { Driver tlora_pager_driver = { .name = "T-Lora Pager", .compatible = (const char*[]) { "lilygo,tlora-pager", nullptr }, - .start_device = start, - .stop_device = stop, + .startDevice = start, + .stopDevice = stop, .api = nullptr, - .device_type = nullptr, + .deviceType = nullptr, .internal = { 0 } }; diff --git a/Platforms/PlatformEsp32/Include/Tactility/ErrorEsp32.h b/Platforms/PlatformEsp32/Include/Tactility/ErrorEsp32.h new file mode 100644 index 00000000..425478c8 --- /dev/null +++ b/Platforms/PlatformEsp32/Include/Tactility/ErrorEsp32.h @@ -0,0 +1,7 @@ +#pragma once + +#include + +#include + +error_t esp_err_to_error(esp_err_t error); diff --git a/Platforms/PlatformEsp32/Include/Tactility/drivers/Esp32Gpio.h b/Platforms/PlatformEsp32/Include/Tactility/drivers/Esp32Gpio.h index 43b03a4c..aa134c2e 100644 --- a/Platforms/PlatformEsp32/Include/Tactility/drivers/Esp32Gpio.h +++ b/Platforms/PlatformEsp32/Include/Tactility/drivers/Esp32Gpio.h @@ -8,7 +8,7 @@ extern "C" { #include struct Esp32GpioConfig { - uint8_t gpio_count; + uint8_t gpioCount; }; #ifdef __cplusplus diff --git a/Platforms/PlatformEsp32/Include/Tactility/drivers/Esp32I2c.h b/Platforms/PlatformEsp32/Include/Tactility/drivers/Esp32I2c.h index 2e7de1c1..c30a8325 100644 --- a/Platforms/PlatformEsp32/Include/Tactility/drivers/Esp32I2c.h +++ b/Platforms/PlatformEsp32/Include/Tactility/drivers/Esp32I2c.h @@ -9,9 +9,9 @@ extern "C" { #endif struct Esp32I2cConfig { - uint32_t clock_frequency; - struct GpioPinConfig pin_sda; - struct GpioPinConfig pin_scl; + uint32_t clockFrequency; + struct GpioPinConfig pinSda; + struct GpioPinConfig pinScl; const i2c_port_t port; }; diff --git a/Platforms/PlatformEsp32/Source/ErrorEsp32.cpp b/Platforms/PlatformEsp32/Source/ErrorEsp32.cpp new file mode 100644 index 00000000..5264fd59 --- /dev/null +++ b/Platforms/PlatformEsp32/Source/ErrorEsp32.cpp @@ -0,0 +1,16 @@ +#include + +error_t esp_err_to_error(esp_err_t error) { + switch (error) { + case ESP_OK: + return ERROR_NONE; + case ESP_ERR_INVALID_ARG: + return ERROR_INVALID_ARGUMENT; + case ESP_ERR_INVALID_STATE: + return ERROR_INVALID_STATE; + case ESP_ERR_TIMEOUT: + return ERROR_TIMEOUT; + default: + return ERROR_UNDEFINED; + } +} diff --git a/Platforms/PlatformEsp32/Source/Esp32Gpio.cpp b/Platforms/PlatformEsp32/Source/drivers/Esp32Gpio.cpp similarity index 68% rename from Platforms/PlatformEsp32/Source/Esp32Gpio.cpp rename to Platforms/PlatformEsp32/Source/drivers/Esp32Gpio.cpp index adc4fa92..119fc712 100644 --- a/Platforms/PlatformEsp32/Source/Esp32Gpio.cpp +++ b/Platforms/PlatformEsp32/Source/drivers/Esp32Gpio.cpp @@ -3,9 +3,11 @@ #include #include -#include -#include + +#include #include +#include +#include #define TAG LOG_TAG(esp32_gpio) @@ -13,20 +15,21 @@ extern "C" { -static bool set_level(Device* device, gpio_pin_t pin, bool high) { - return gpio_set_level(static_cast(pin), high) == ESP_OK; +static error_t set_level(Device* device, gpio_pin_t pin, bool high) { + auto esp_error = gpio_set_level(static_cast(pin), high); + return esp_err_to_error(esp_error); } -static bool get_level(Device* device, gpio_pin_t pin, bool* high) { +static error_t get_level(Device* device, gpio_pin_t pin, bool* high) { *high = gpio_get_level(static_cast(pin)) != 0; - return true; + return ERROR_NONE; } -static bool set_options(Device* device, gpio_pin_t pin, gpio_flags_t options) { +static error_t set_options(Device* device, gpio_pin_t pin, gpio_flags_t options) { const Esp32GpioConfig* config = GET_CONFIG(device); - if (pin >= config->gpio_count) { - return false; + if (pin >= config->gpioCount) { + return ERROR_INVALID_ARGUMENT; } gpio_mode_t mode; @@ -37,8 +40,7 @@ static bool set_options(Device* device, gpio_pin_t pin, gpio_flags_t options) { } else if (options & GPIO_DIRECTION_OUTPUT) { mode = GPIO_MODE_OUTPUT; } else { - ESP_LOGE(TAG, "set_options: no direction flag specified for pin %d", pin); - return false; + return ERROR_INVALID_ARGUMENT; } const gpio_config_t esp_config = { @@ -52,13 +54,14 @@ static bool set_options(Device* device, gpio_pin_t pin, gpio_flags_t options) { #endif }; - return gpio_config(&esp_config) == ESP_OK; + auto esp_error = gpio_config(&esp_config); + return esp_err_to_error(esp_error); } -static bool get_options(Device* device, gpio_pin_t pin, gpio_flags_t* options) { +static int get_options(Device* device, gpio_pin_t pin, gpio_flags_t* options) { gpio_io_config_t esp_config; - if (gpio_get_io_config((gpio_num_t)pin, &esp_config) != ESP_OK) { - return false; + if (gpio_get_io_config(static_cast(pin), &esp_config) != ESP_OK) { + return ERROR_RESOURCE; } gpio_flags_t output = 0; @@ -84,17 +87,17 @@ static bool get_options(Device* device, gpio_pin_t pin, gpio_flags_t* options) { } *options = output; - return true; + return ERROR_NONE; } -static int start(Device* device) { +static error_t start(Device* device) { ESP_LOGI(TAG, "start %s", device->name); - return 0; + return ERROR_NONE; } -static int stop(Device* device) { +static error_t stop(Device* device) { ESP_LOGI(TAG, "stop %s", device->name); - return 0; + return ERROR_NONE; } const static GpioControllerApi esp32_gpio_api = { @@ -107,10 +110,10 @@ const static GpioControllerApi esp32_gpio_api = { Driver esp32_gpio_driver = { .name = "esp32_gpio", .compatible = (const char*[]) { "espressif,esp32-gpio", nullptr }, - .start_device = start, - .stop_device = stop, + .startDevice = start, + .stopDevice = stop, .api = (void*)&esp32_gpio_api, - .device_type = nullptr, + .deviceType = nullptr, .internal = { 0 } }; diff --git a/Platforms/PlatformEsp32/Source/Esp32I2c.cpp b/Platforms/PlatformEsp32/Source/drivers/Esp32I2c.cpp similarity index 56% rename from Platforms/PlatformEsp32/Source/Esp32I2c.cpp rename to Platforms/PlatformEsp32/Source/drivers/Esp32I2c.cpp index b8948e8f..d8f0f19a 100644 --- a/Platforms/PlatformEsp32/Source/Esp32I2c.cpp +++ b/Platforms/PlatformEsp32/Source/drivers/Esp32I2c.cpp @@ -3,8 +3,11 @@ #include #include -#include + +#include "Tactility/ErrorEsp32.h" + #include +#include #define TAG LOG_TAG(esp32_i2c) @@ -28,41 +31,41 @@ struct InternalData { extern "C" { -static bool read(Device* device, uint8_t address, uint8_t* data, size_t data_size, TickType_t timeout) { +static int read(Device* device, uint8_t address, uint8_t* data, size_t data_size, TickType_t timeout) { vPortAssertIfInISR(); auto* driver_data = GET_DATA(device); lock(driver_data); - const esp_err_t result = i2c_master_read_from_device(GET_CONFIG(device)->port, address, data, data_size, timeout); + const esp_err_t esp_error = i2c_master_read_from_device(GET_CONFIG(device)->port, address, data, data_size, timeout); unlock(driver_data); - ESP_ERROR_CHECK_WITHOUT_ABORT(result); - return result == ESP_OK; + ESP_ERROR_CHECK_WITHOUT_ABORT(esp_error); + return esp_err_to_error(esp_error); } -static bool write(Device* device, uint8_t address, const uint8_t* data, uint16_t dataSize, TickType_t timeout) { +static int write(Device* device, uint8_t address, const uint8_t* data, uint16_t dataSize, TickType_t timeout) { vPortAssertIfInISR(); auto* driver_data = GET_DATA(device); lock(driver_data); - const esp_err_t result = i2c_master_write_to_device(GET_CONFIG(device)->port, address, data, dataSize, timeout); + const esp_err_t esp_error = i2c_master_write_to_device(GET_CONFIG(device)->port, address, data, dataSize, timeout); unlock(driver_data); - ESP_ERROR_CHECK_WITHOUT_ABORT(result); - return result == ESP_OK; + ESP_ERROR_CHECK_WITHOUT_ABORT(esp_error); + return esp_err_to_error(esp_error); } -static bool write_read(Device* device, uint8_t address, const uint8_t* write_data, size_t write_data_size, uint8_t* read_data, size_t read_data_size, TickType_t timeout) { +static int write_read(Device* device, uint8_t address, const uint8_t* write_data, size_t write_data_size, uint8_t* read_data, size_t read_data_size, TickType_t timeout) { vPortAssertIfInISR(); auto* driver_data = GET_DATA(device); lock(driver_data); - const esp_err_t result = i2c_master_write_read_device(GET_CONFIG(device)->port, address, write_data, write_data_size, read_data, read_data_size, timeout); + const esp_err_t esp_error = i2c_master_write_read_device(GET_CONFIG(device)->port, address, write_data, write_data_size, read_data, read_data_size, timeout); unlock(driver_data); - ESP_ERROR_CHECK_WITHOUT_ABORT(result); - return result == ESP_OK; + ESP_ERROR_CHECK_WITHOUT_ABORT(esp_error); + return esp_err_to_error(esp_error); } static int start(Device* device) { ESP_LOGI(TAG, "start %s", device->name); auto* data = new InternalData(); device_set_driver_data(device, data); - return 0; + return ERROR_NONE; } static int stop(Device* device) { @@ -70,10 +73,10 @@ static int stop(Device* device) { auto* driver_data = static_cast(device_get_driver_data(device)); device_set_driver_data(device, nullptr); delete driver_data; - return 0; + return ERROR_NONE; } -const I2cControllerApi esp32_i2c_api = { +const static I2cControllerApi esp32_i2c_api = { .read = read, .write = write, .write_read = write_read @@ -82,10 +85,10 @@ const I2cControllerApi esp32_i2c_api = { Driver esp32_i2c_driver = { .name = "esp32_i2c", .compatible = (const char*[]) { "espressif,esp32-i2c", nullptr }, - .start_device = start, - .stop_device = stop, + .startDevice = start, + .stopDevice = stop, .api = (void*)&esp32_i2c_api, - .device_type = &I2C_CONTROLLER_TYPE, + .deviceType = &I2C_CONTROLLER_TYPE, .internal = { 0 } }; diff --git a/Platforms/PlatformEsp32/Source/Register.cpp b/Platforms/PlatformEsp32/Source/drivers/Register.cpp similarity index 100% rename from Platforms/PlatformEsp32/Source/Register.cpp rename to Platforms/PlatformEsp32/Source/drivers/Register.cpp diff --git a/Tactility/Source/service/gui/GuiService.cpp b/Tactility/Source/service/gui/GuiService.cpp index 2a98df34..525c007e 100644 --- a/Tactility/Source/service/gui/GuiService.cpp +++ b/Tactility/Source/service/gui/GuiService.cpp @@ -31,7 +31,7 @@ int32_t GuiService::guiMain() { while (true) { uint32_t flags = 0; - if (service->threadFlags.wait(GUI_THREAD_FLAG_ALL, false, true, portMAX_DELAY, &flags)) { + if (service->threadFlags.wait(GUI_THREAD_FLAG_ALL, false, true, &flags, portMAX_DELAY)) { // When service not started or starting -> exit State service_state = getState(manifest.id); if (service_state != State::Started && service_state != State::Starting) { diff --git a/Tactility/Source/service/wifi/WifiEsp.cpp b/Tactility/Source/service/wifi/WifiEsp.cpp index 34c7d9dc..211bdb72 100644 --- a/Tactility/Source/service/wifi/WifiEsp.cpp +++ b/Tactility/Source/service/wifi/WifiEsp.cpp @@ -799,11 +799,11 @@ static void dispatchConnect(std::shared_ptr wifi) { /* Waiting until either the connection is established (WIFI_CONNECTED_BIT) * or connection failed for the maximum number of re-tries (WIFI_FAIL_BIT). * The bits are set by wifi_event_handler() */ - uint32_t bits; - if (wifi_singleton->connection_wait_flags.wait(WIFI_FAIL_BIT | WIFI_CONNECTED_BIT, false, true, kernel::MAX_TICKS, &bits)) { + uint32_t flags; + if (wifi_singleton->connection_wait_flags.wait(WIFI_FAIL_BIT | WIFI_CONNECTED_BIT, false, true, &flags, kernel::MAX_TICKS)) { LOGGER.info("Waiting for EventGroup by event_handler()"); - if (bits & WIFI_CONNECTED_BIT) { + if (flags & WIFI_CONNECTED_BIT) { wifi->setSecureConnection(config.sta.password[0] != 0x00U); wifi->setRadioState(RadioState::ConnectionActive); publish_event(wifi, WifiEvent::ConnectionSuccess); @@ -815,7 +815,7 @@ static void dispatchConnect(std::shared_ptr wifi) { LOGGER.info("Stored credentials"); } } - } else if (bits & WIFI_FAIL_BIT) { + } else if (flags & WIFI_FAIL_BIT) { wifi->setRadioState(RadioState::On); publish_event(wifi, WifiEvent::ConnectionFailed); LOGGER.info("Failed to connect to {}", wifi->connection_target.ssid.c_str()); diff --git a/TactilityFreeRtos/Include/Tactility/Dispatcher.h b/TactilityFreeRtos/Include/Tactility/Dispatcher.h index 076acff0..1fe6cbb2 100644 --- a/TactilityFreeRtos/Include/Tactility/Dispatcher.h +++ b/TactilityFreeRtos/Include/Tactility/Dispatcher.h @@ -67,6 +67,7 @@ public: } if (shutdown) { + mutex.unlock(); return false; } @@ -86,14 +87,14 @@ public: } /** - * Consume 1 or more dispatched function (if any) until the queue is empty. + * Consume 1 or more dispatched functions (if any) until the queue is empty. * @warning The timeout is only the wait time before consuming the message! It is not a limit to the total execution time when calling this method. * @param[in] timeout the ticks to wait for a message * @return the amount of messages that were consumed */ uint32_t consume(TickType_t timeout = kernel::MAX_TICKS) { // Wait for signal - if (!eventFlag.wait(WAIT_FLAG, false, true, timeout)) { + if (!eventFlag.wait(WAIT_FLAG, false, true, nullptr, timeout)) { return 0; } diff --git a/TactilityFreeRtos/Include/Tactility/EventGroup.h b/TactilityFreeRtos/Include/Tactility/EventGroup.h index c016d5aa..4b919a0a 100644 --- a/TactilityFreeRtos/Include/Tactility/EventGroup.h +++ b/TactilityFreeRtos/Include/Tactility/EventGroup.h @@ -33,42 +33,27 @@ public: } enum class Error { - Unknown, Timeout, - Resource, - Parameter, - IsrStatus + Resource }; /** * Set the flags. * @param[in] flags the flags to set - * @param[out] outFlags optional resulting flags: this is set when the return value is true - * @param[out] outError optional error output: this is set when the return value is false * @return true on success */ - bool set(uint32_t flags, uint32_t* outFlags = nullptr, Error* outError = nullptr) const { + bool set(uint32_t flags) const { assert(handle); if (xPortInIsrContext() == pdTRUE) { - uint32_t result; BaseType_t yield = pdFALSE; if (xEventGroupSetBitsFromISR(handle.get(), flags, &yield) == pdFAIL) { - if (outError != nullptr) { - *outError = Error::Resource; - } return false; } else { - if (outFlags != nullptr) { - *outFlags = flags; - } portYIELD_FROM_ISR(yield); return true; } } else { - auto result = xEventGroupSetBits(handle.get(), flags); - if (outFlags != nullptr) { - *outFlags = result; - } + xEventGroupSetBits(handle.get(), flags); return true; } } @@ -76,31 +61,19 @@ public: /** * Clear flags * @param[in] flags the flags to clear - * @param[out] outFlags optional resulting flags: this is set when the return value is true - * @param[out] outError optional error output: this is set when the return value is false * @return true on success */ - bool clear(uint32_t flags, uint32_t* outFlags = nullptr, Error* outError = nullptr) const { + bool clear(uint32_t flags) const { if (xPortInIsrContext() == pdTRUE) { uint32_t result = xEventGroupGetBitsFromISR(handle.get()); if (xEventGroupClearBitsFromISR(handle.get(), flags) == pdFAIL) { - if (outError != nullptr) { - *outError = Error::Resource; - } return false; } - if (outFlags != nullptr) { - *outFlags = result; - } portYIELD_FROM_ISR(pdTRUE); - return true; } else { - auto result = xEventGroupClearBits(handle.get(), flags); - if (outFlags != nullptr) { - *outFlags = result; - } - return true; + xEventGroupClearBits(handle.get(), flags); } + return true; } /** @@ -120,16 +93,14 @@ public: * @param[in] awaitAll If true, await for all bits to be set. Otherwise, await for any. * @param[in] clearOnExit If true, clears all the bits on exit, otherwise don't clear. * @param[in] timeout the maximum amount of ticks to wait for flags to be set - * @param[out] outFlags optional resulting flags: this is set when the return value is true - * @param[out] outError optional error output: this is set when the return value is false + * @param[out] outFlags optional resulting flags: this is set when the return value is true. Only set when return value is true. */ bool wait( uint32_t flags, bool awaitAll = false, bool clearOnExit = true, - TickType_t timeout = kernel::MAX_TICKS, uint32_t* outFlags = nullptr, - Error* outError = nullptr + TickType_t timeout = kernel::MAX_TICKS ) const { assert(xPortInIsrContext() == pdFALSE); @@ -144,14 +115,8 @@ public: auto invalid_flags = awaitAll ? ((flags & result_flags) != flags) // await all : ((flags & result_flags) == 0U); // await any + if (invalid_flags) { - if (outError != nullptr) { - if (timeout > 0U) { // assume time-out - *outError = Error::Timeout; - } else { - *outError = Error::Resource; - } - } return false; } diff --git a/TactilityKernel/Include/Tactility/Device.h b/TactilityKernel/Include/Tactility/Device.h index 0b0983e6..cb6104b4 100644 --- a/TactilityKernel/Include/Tactility/Device.h +++ b/TactilityKernel/Include/Tactility/Device.h @@ -8,12 +8,13 @@ extern "C" { #endif -#include - #include #include #include +#include "Error.h" +#include + struct Driver; /** Enables discovering devices of the same type */ @@ -52,24 +53,26 @@ struct Device { /** * Initialize the properties of a device. * - * @param[in] dev a device with all non-internal properties set - * @return the result code (0 for success) + * @param[in] device a device with all non-internal properties set + * @retval ERROR_OUT_OF_MEMORY + * @retval ERROR_NONE */ -int device_construct(struct Device* device); +error_t device_construct(struct Device* device); /** * Deinitialize the properties of a device. * This fails when a device is busy or has children. * - * @param[in] dev - * @return the result code (0 for success) + * @param[in] device + * @retval ERROR_INVALID_STATE + * @retval ERROR_NONE */ -int device_destruct(struct Device* device); +error_t device_destruct(struct Device* device); /** * Indicates whether the device is in a state where its API is available * - * @param[in] dev non-null device pointer + * @param[in] device non-null device pointer * @return true if the device is ready for use */ static inline bool device_is_ready(const struct Device* device) { @@ -83,9 +86,10 @@ static inline bool device_is_ready(const struct Device* device) { * - a bus (if any) * * @param[in] device non-null device pointer - * @return 0 on success + * @retval ERROR_INVALID_STATE + * @retval ERROR_NONE */ -int device_add(struct Device* device); +error_t device_add(struct Device* device); /** * Deregister a device. Remove it from all relevant systems: @@ -94,26 +98,32 @@ int device_add(struct Device* device); * - a bus (if any) * * @param[in] device non-null device pointer - * @return 0 on success + * @retval ERROR_INVALID_STATE + * @retval ERROR_NOT_FOUND + * @retval ERROR_NONE */ -int device_remove(struct Device* device); +error_t device_remove(struct Device* device); /** * Attach the driver. * * @warning must call device_construct() and device_add() first * @param device - * @return ERROR_INVALID_STATE or otherwise the value of the driver binding result (0 on success) + * @retval ERROR_INVALID_STATE + * @retval ERROR_RESOURCE when driver binding fails + * @retval ERROR_NONE */ -int device_start(struct Device* device); +error_t device_start(struct Device* device); /** * Detach the driver. * * @param device - * @return ERROR_INVALID_STATE or otherwise the value of the driver unbinding result (0 on success) + * @retval ERROR_INVALID_STATE + * @retval ERROR_RESOURCE when driver unbinding fails + * @retval ERROR_NONE */ -int device_stop(struct Device* device); +error_t device_stop(struct Device* device); /** * Set or unset a parent. @@ -147,7 +157,7 @@ static inline void device_lock(struct Device* device) { mutex_lock(&device->internal.mutex); } -static inline int device_try_lock(struct Device* device) { +static inline bool device_try_lock(struct Device* device) { return mutex_try_lock(&device->internal.mutex); } @@ -156,7 +166,7 @@ static inline void device_unlock(struct Device* device) { } static inline const struct DeviceType* device_get_type(struct Device* device) { - return device->internal.driver ? device->internal.driver->device_type : NULL; + return device->internal.driver ? device->internal.driver->deviceType : NULL; } /** * Iterate through all the known devices @@ -167,18 +177,18 @@ void for_each_device(void* callback_context, bool(*on_device)(struct Device* dev /** * Iterate through all the child devices of the specified device - * @param callback_context the parameter to pass to the callback. NULL is valid. + * @param callbackContext the parameter to pass to the callback. NULL is valid. * @param on_device the function to call for each filtered device. return true to continue iterating or false to stop. */ -void for_each_device_child(struct Device* device, void* callback_context, bool(*on_device)(struct Device* device, void* context)); +void for_each_device_child(struct Device* device, void* callbackContext, bool(*on_device)(struct Device* device, void* context)); /** * Iterate through all the known devices of a specific type * @param type the type to filter - * @param callback_context the parameter to pass to the callback. NULL is valid. + * @param callbackContext the parameter to pass to the callback. NULL is valid. * @param on_device the function to call for each filtered device. return true to continue iterating or false to stop. */ -void for_each_device_of_type(const struct DeviceType* type, void* callback_context, bool(*on_device)(struct Device* device, void* context)); +void for_each_device_of_type(const struct DeviceType* type, void* callbackContext, bool(*on_device)(struct Device* device, void* context)); #ifdef __cplusplus } diff --git a/TactilityKernel/Include/Tactility/Driver.h b/TactilityKernel/Include/Tactility/Driver.h index 937f9f5d..341def6f 100644 --- a/TactilityKernel/Include/Tactility/Driver.h +++ b/TactilityKernel/Include/Tactility/Driver.h @@ -7,6 +7,7 @@ extern "C" { #endif #include +#include "Error.h" struct Device; struct DeviceType; @@ -17,13 +18,13 @@ struct Driver { /** Array of const char*, terminated by NULL */ const char**compatible; /** Function to initialize the driver for a device */ - int (*start_device)(struct Device* dev); + error_t (*startDevice)(struct Device* dev); /** Function to deinitialize the driver for a device */ - int (*stop_device)(struct Device* dev); + error_t (*stopDevice)(struct Device* dev); /** Contains the driver's functions */ const void* api; /** Which type of devices this driver creates (can be NULL) */ - const struct DeviceType* device_type; + const struct DeviceType* deviceType; /** Internal data */ struct { /** Contains private data */ @@ -31,20 +32,20 @@ struct Driver { } internal; }; -int driver_construct(struct Driver* driver); +error_t driver_construct(struct Driver* driver); -int driver_destruct(struct Driver* driver); +error_t driver_destruct(struct Driver* driver); -int driver_bind(struct Driver* driver, struct Device* device); +error_t driver_bind(struct Driver* driver, struct Device* device); -int driver_unbind(struct Driver* driver, struct Device* device); +error_t driver_unbind(struct Driver* driver, struct Device* device); bool driver_is_compatible(struct Driver* driver, const char* compatible); struct Driver* driver_find_compatible(const char* compatible); static inline const struct DeviceType* driver_get_device_type(struct Driver* driver) { - return driver->device_type; + return driver->deviceType; } #ifdef __cplusplus diff --git a/TactilityKernel/Include/Tactility/Error.h b/TactilityKernel/Include/Tactility/Error.h index 81ccc589..000dba6c 100644 --- a/TactilityKernel/Include/Tactility/Error.h +++ b/TactilityKernel/Include/Tactility/Error.h @@ -2,9 +2,18 @@ #pragma once +// Avoid potential clash with bits/types/error_t.h +#ifndef __error_t_defined +typedef int error_t; +#endif + +#define ERROR_NONE 0 #define ERROR_UNDEFINED 1 #define ERROR_INVALID_STATE 2 #define ERROR_INVALID_ARGUMENT 3 #define ERROR_MISSING_PARAMETER 4 #define ERROR_NOT_FOUND 5 - +#define ERROR_ISR_STATUS 6 +#define ERROR_RESOURCE 7 // A problem with a resource/dependency +#define ERROR_TIMEOUT 8 +#define ERROR_OUT_OF_MEMORY 9 diff --git a/TactilityKernel/Include/Tactility/concurrent/Dispatcher.h b/TactilityKernel/Include/Tactility/concurrent/Dispatcher.h new file mode 100644 index 00000000..81fd014b --- /dev/null +++ b/TactilityKernel/Include/Tactility/concurrent/Dispatcher.h @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 + +/** +* Dispatcher is a thread-safe code execution queue. +*/ +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void (*DispatcherCallback)(void* context); +typedef void* DispatcherHandle_t; + +DispatcherHandle_t dispatcher_alloc(void); + +void dispatcher_free(DispatcherHandle_t dispatcher); + +/** + * Queue a function to be consumed elsewhere. + * + * @param[in] callbackContext the data to pass to the function upon execution + * @param[in] callback the function to execute elsewhere + * @param[in] timeout lock acquisition timeout + * @retval ERROR_TIMEOUT + * @retval ERROR_RESOURCE when failing to set event + * @retval ERROR_INVALID_STATE when the dispatcher is in the process of shutting down + * @retval ERROR_NONE + */ +error_t dispatcher_dispatch_timed(DispatcherHandle_t dispatcher, void* callbackContext, DispatcherCallback callback, TickType_t timeout); + +/** + * Queue a function to be consumed elsewhere. + * + * @param[in] callbackContext the data to pass to the function upon execution + * @param[in] callback the function to execute elsewhere + * @retval ERROR_RESOURCE when failing to set event + * @retval ERROR_TIMEOUT unlikely to occur unless there's an issue with the internal mutex + * @retval ERROR_INVALID_STATE when the dispatcher is in the process of shutting down + * @retval ERROR_NONE + */ +static inline error_t dispatcher_dispatch(DispatcherHandle_t dispatcher, void* callbackContext, DispatcherCallback callback) { + return dispatcher_dispatch_timed(dispatcher, callbackContext, callback, portMAX_DELAY); +} + +/** + * Consume 1 or more dispatched functions (if any) until the queue is empty. + * + * @warning The timeout is only the wait time before consuming the message! It is not a limit to the total execution time when calling this method. + * + * @param[in] timeout the ticks to wait for a message + * @retval ERROR_TIMEOUT + * @retval ERROR_RESOURCE failed to wait for event + * @retval ERROR_INVALID_STATE when the dispatcher is in the process of shutting down + * @retval ERROR_NONE + */ +error_t dispatcher_consume_timed(DispatcherHandle_t dispatcher, TickType_t timeout); + +/** + * Consume 1 or more dispatched functions (if any) until the queue is empty. + * + * @warning The timeout is only the wait time before consuming the message! It is not a limit to the total execution time when calling this method. + * + * @retval ERROR_TIMEOUT unlikely to occur unless there's an issue with the internal mutex + * @retval ERROR_RESOURCE failed to wait for event + * @retval ERROR_INVALID_STATE when the dispatcher is in the process of shutting down + * @retval ERROR_NONE + */ +static inline error_t dispatcher_consume(DispatcherHandle_t dispatcher) { + return dispatcher_consume_timed(dispatcher, portMAX_DELAY); +} + +#ifdef __cplusplus +} +#endif diff --git a/TactilityKernel/Include/Tactility/concurrent/EventGroup.h b/TactilityKernel/Include/Tactility/concurrent/EventGroup.h new file mode 100644 index 00000000..c5cd124f --- /dev/null +++ b/TactilityKernel/Include/Tactility/concurrent/EventGroup.h @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +#include +#include + +static inline void event_group_construct(EventGroupHandle_t* eventGroup) { + assert(xPortInIsrContext() == pdFALSE); + *eventGroup = xEventGroupCreate(); +} + +static inline void event_group_destruct(EventGroupHandle_t* eventGroup) { + assert(xPortInIsrContext() == pdFALSE); + assert(*eventGroup != NULL); + vEventGroupDelete(*eventGroup); + *eventGroup = NULL; +} + +/** + * Set the flags. + * + * @param[in] eventGroup the event group + * @param[in] flags the flags to set + * @retval ERROR_RESOURCE when setting failed + * @retval ERROR_NONE + */ +error_t event_group_set(EventGroupHandle_t eventGroup, uint32_t flags); + +/** + * Clear flags + * + * @param[in] eventGroup the event group + * @param[in] flags the flags to clear + * @retval ERROR_RESOURCE when clearing failed + * @retval ERROR_NONE + */ +error_t event_group_clear(EventGroupHandle_t eventGroup, uint32_t flags); + +/** + * @param[in] eventGroup the event group + * @return the bitset (always succeeds) + */ +uint32_t event_group_get(EventGroupHandle_t eventGroup); + +/** + * Wait for flags to be set + * + * @param[in] eventGroup the event group + * @param[in] inFlags the flags to await + * @param[in] awaitAll If true, await for all bits to be set. Otherwise, await for any. + * @param[in] clearOnExit If true, clears all the bits on exit, otherwise don't clear. + * @param[out] outFlags If set to non-NULL value, this will hold the resulting flags. Only set when return value is ERROR_NONE + * @param[in] timeout the maximum amount of ticks to wait for flags to be set + * @retval ERROR_ISR_STATUS when the function was called from an ISR context + * @retval ERROR_TIMEOUT + * @retval ERROR_RESOURCE when flags were triggered, but not in a way that was expected (e.g. waiting for all flags, but was only partially set) + * @retval ERROR_NONE + */ +error_t event_group_wait( + EventGroupHandle_t eventGroup, + uint32_t inFlags, + bool awaitAll, + bool clearOnExit, + uint32_t* outFlags, + TickType_t timeout +); + +#ifdef __cplusplus +} +#endif diff --git a/TactilityKernel/Include/Tactility/concurrent/Mutex.h b/TactilityKernel/Include/Tactility/concurrent/Mutex.h index 55b2d51c..eddc4e69 100644 --- a/TactilityKernel/Include/Tactility/concurrent/Mutex.h +++ b/TactilityKernel/Include/Tactility/concurrent/Mutex.h @@ -12,6 +12,7 @@ extern "C" { struct Mutex { QueueHandle_t handle; + // TODO: Debugging functionality }; inline static void mutex_construct(struct Mutex* mutex) { @@ -27,18 +28,30 @@ inline static void mutex_destruct(struct Mutex* mutex) { } inline static void mutex_lock(struct Mutex* mutex) { + assert(xPortInIsrContext() != pdTRUE); xSemaphoreTake(mutex->handle, portMAX_DELAY); } inline static bool mutex_try_lock(struct Mutex* mutex) { + assert(xPortInIsrContext() != pdTRUE); return xSemaphoreTake(mutex->handle, 0) == pdTRUE; } +inline static bool mutex_try_lock_timed(struct Mutex* mutex, TickType_t timeout) { + assert(xPortInIsrContext() != pdTRUE); + return xSemaphoreTake(mutex->handle, timeout) == pdTRUE; +} + inline static bool mutex_is_locked(struct Mutex* mutex) { - return xSemaphoreGetMutexHolder(mutex->handle) != NULL; + if (xPortInIsrContext() == pdTRUE) { + return xSemaphoreGetMutexHolderFromISR(mutex->handle) != NULL; + } else { + return xSemaphoreGetMutexHolder(mutex->handle) != NULL; + } } inline static void mutex_unlock(struct Mutex* mutex) { + assert(xPortInIsrContext() != pdTRUE); xSemaphoreGive(mutex->handle); } diff --git a/TactilityKernel/Include/Tactility/concurrent/RecursiveMutex.h b/TactilityKernel/Include/Tactility/concurrent/RecursiveMutex.h index 09dd9a9e..b2e451c4 100644 --- a/TactilityKernel/Include/Tactility/concurrent/RecursiveMutex.h +++ b/TactilityKernel/Include/Tactility/concurrent/RecursiveMutex.h @@ -26,18 +26,30 @@ inline static void recursive_mutex_destruct(struct RecursiveMutex* mutex) { } inline static void recursive_mutex_lock(struct RecursiveMutex* mutex) { + assert(xPortInIsrContext() != pdTRUE); xSemaphoreTakeRecursive(mutex->handle, portMAX_DELAY); } inline static bool recursive_mutex_is_locked(struct RecursiveMutex* mutex) { - return xSemaphoreGetMutexHolder(mutex->handle) != NULL; + if (xPortInIsrContext() == pdTRUE) { + return xSemaphoreGetMutexHolderFromISR(mutex->handle) != NULL; + } else { + return xSemaphoreGetMutexHolder(mutex->handle) != NULL; + } } inline static bool recursive_mutex_try_lock(struct RecursiveMutex* mutex) { + assert(xPortInIsrContext() != pdTRUE); return xSemaphoreTakeRecursive(mutex->handle, 0) == pdTRUE; } +inline static bool recursive_mutex_try_lock_timed(struct RecursiveMutex* mutex, TickType_t timeout) { + assert(xPortInIsrContext() != pdTRUE); + return xSemaphoreTakeRecursive(mutex->handle, timeout) == pdTRUE; +} + inline static void recursive_mutex_unlock(struct RecursiveMutex* mutex) { + assert(xPortInIsrContext() != pdTRUE); xSemaphoreGiveRecursive(mutex->handle); } diff --git a/TactilityKernel/Include/Tactility/drivers/Gpio.h b/TactilityKernel/Include/Tactility/drivers/Gpio.h index 8aa08b35..1e26ce1b 100644 --- a/TactilityKernel/Include/Tactility/drivers/Gpio.h +++ b/TactilityKernel/Include/Tactility/drivers/Gpio.h @@ -6,6 +6,8 @@ extern "C" { #endif +#include +#include #include #define GPIO_OPTIONS_MASK 0x1f @@ -34,57 +36,30 @@ typedef enum { GPIO__MAX, } GpioInterruptType; -/** - * @brief Provides a type to hold a GPIO pin index. - * - * This reduced-size type is sufficient to record a pin number, - * e.g. from a devicetree GPIOS property. - */ +/** The index of a GPIO pin on a GPIO Controller */ typedef uint8_t gpio_pin_t; -/** - * @brief Identifies a set of pins associated with a port. - * - * The pin with index n is present in the set if and only if the bit - * identified by (1U << n) is set. - */ -typedef uint32_t gpio_pinset_t; - -/** - * @brief Provides a type to hold GPIO devicetree flags. - * - * All GPIO flags that can be expressed in devicetree fit in the low 16 - * bits of the full flags field, so use a reduced-size type to record - * that part of a GPIOS property. - * - * The lower 8 bits are used for standard flags. The upper 8 bits are reserved - * for SoC specific flags. - */ +/** Specifies the configuration flags for a GPIO pin (or set of pins) */ typedef uint16_t gpio_flags_t; -/** - * @brief Container for GPIO pin information specified in dts files - * - * This type contains a pointer to a GPIO device, pin identifier for a pin - * controlled by that device, and the subset of pin configuration - * flags which may be given in devicetree. - */ +/** A configuration for a single GPIO pin */ struct GpioPinConfig { /** GPIO device controlling the pin */ const struct Device* port; /** The pin's number on the device */ gpio_pin_t pin; /** The pin's configuration flags as specified in devicetree */ - gpio_flags_t dt_flags; + gpio_flags_t flags; }; /** * Check if the pin is ready to be used. - * @param pin_config the specifications of the pin + * + * @param pinConfig the specifications of the pin * @return true if the pin is ready to be used */ -static inline bool gpio_is_ready(const struct GpioPinConfig* pin_config) { - return device_is_ready(pin_config->port); +static inline bool gpio_is_ready(const struct GpioPinConfig* pinConfig) { + return device_is_ready(pinConfig->port); } #ifdef __cplusplus diff --git a/TactilityKernel/Include/Tactility/drivers/GpioController.h b/TactilityKernel/Include/Tactility/drivers/GpioController.h index 149e601a..6b3e31ce 100644 --- a/TactilityKernel/Include/Tactility/drivers/GpioController.h +++ b/TactilityKernel/Include/Tactility/drivers/GpioController.h @@ -7,22 +7,22 @@ extern "C" { #endif #include "Gpio.h" -#include +#include struct GpioControllerApi { - bool (*set_level)(struct Device* device, gpio_pin_t pin, bool high); - bool (*get_level)(struct Device* device, gpio_pin_t pin, bool* high); - bool (*set_options)(struct Device* device, gpio_pin_t pin, gpio_flags_t options); - bool (*get_options)(struct Device* device, gpio_pin_t pin, gpio_flags_t* options); + error_t (*set_level)(struct Device* device, gpio_pin_t pin, bool high); + error_t (*get_level)(struct Device* device, gpio_pin_t pin, bool* high); + error_t (*set_options)(struct Device* device, gpio_pin_t pin, gpio_flags_t options); + error_t (*get_options)(struct Device* device, gpio_pin_t pin, gpio_flags_t* options); }; -bool gpio_controller_set_level(struct Device* device, gpio_pin_t pin, bool high); -bool gpio_controller_get_level(struct Device* device, gpio_pin_t pin, bool* high); -bool gpio_controller_set_options(struct Device* device, gpio_pin_t pin, gpio_flags_t options); -bool gpio_controller_get_options(struct Device* device, gpio_pin_t pin, gpio_flags_t* options); +error_t gpio_controller_set_level(struct Device* device, gpio_pin_t pin, bool high); +error_t gpio_controller_get_level(struct Device* device, gpio_pin_t pin, bool* high); +error_t gpio_controller_set_options(struct Device* device, gpio_pin_t pin, gpio_flags_t options); +error_t gpio_controller_get_options(struct Device* device, gpio_pin_t pin, gpio_flags_t* options); -inline bool gpio_set_options_config(struct Device* device, struct GpioPinConfig* config) { - return gpio_controller_set_options(device, config->pin, config->dt_flags); +static inline error_t gpio_set_options_config(struct Device* device, const struct GpioPinConfig* config) { + return gpio_controller_set_options(device, config->pin, config->flags); } #ifdef __cplusplus diff --git a/TactilityKernel/Include/Tactility/drivers/I2cController.h b/TactilityKernel/Include/Tactility/drivers/I2cController.h index d2b79cff..c33a8d2f 100644 --- a/TactilityKernel/Include/Tactility/drivers/I2cController.h +++ b/TactilityKernel/Include/Tactility/drivers/I2cController.h @@ -6,22 +6,24 @@ extern "C" { #endif -#include "Gpio.h" -#include -#include #include +#include "Gpio.h" + +#include +#include + struct I2cControllerApi { - bool (*read)(struct Device* device, uint8_t address, uint8_t* data, size_t dataSize, TickType_t timeout); - bool (*write)(struct Device* device, uint8_t address, const uint8_t* data, uint16_t dataSize, TickType_t timeout); - bool (*write_read)(struct Device* device, uint8_t address, const uint8_t* write_data, size_t write_data_size, uint8_t* read_data, size_t read_data_size, TickType_t timeout); + error_t (*read)(struct Device* device, uint8_t address, uint8_t* data, size_t dataSize, TickType_t timeout); + error_t (*write)(struct Device* device, uint8_t address, const uint8_t* data, uint16_t dataSize, TickType_t timeout); + error_t (*write_read)(struct Device* device, uint8_t address, const uint8_t* writeData, size_t writeDataSize, uint8_t* readData, size_t readDataSize, TickType_t timeout); }; -bool i2c_controller_read(struct Device* device, uint8_t address, uint8_t* data, size_t dataSize, TickType_t timeout); +error_t i2c_controller_read(struct Device* device, uint8_t address, uint8_t* data, size_t dataSize, TickType_t timeout); -bool i2c_controller_write(struct Device* device, uint8_t address, const uint8_t* data, uint16_t dataSize, TickType_t timeout); +error_t i2c_controller_write(struct Device* device, uint8_t address, const uint8_t* data, uint16_t dataSize, TickType_t timeout); -bool i2c_controller_write_read(struct Device* device, uint8_t address, const uint8_t* write_data, size_t write_data_size, uint8_t* read_data, size_t read_data_size, TickType_t timeout); +error_t i2c_controller_write_read(struct Device* device, uint8_t address, const uint8_t* writeData, size_t writeDataSize, uint8_t* readData, size_t readDataSize, TickType_t timeout); extern const struct DeviceType I2C_CONTROLLER_TYPE; diff --git a/TactilityKernel/Source/Device.cpp b/TactilityKernel/Source/Device.cpp index ef8495cc..d90e393d 100644 --- a/TactilityKernel/Source/Device.cpp +++ b/TactilityKernel/Source/Device.cpp @@ -44,17 +44,17 @@ extern "C" { #define get_device_data(device) static_cast(device->internal.data) -int device_construct(Device* device) { +error_t device_construct(Device* device) { device->internal.data = new(std::nothrow) DeviceData; if (device->internal.data == nullptr) { - return ENOMEM; + return ERROR_OUT_OF_MEMORY; } LOG_I(TAG, "construct %s", device->name); mutex_construct(&device->internal.mutex); - return 0; + return ERROR_NONE; } -int device_destruct(Device* device) { +error_t device_destruct(Device* device) { if (device->internal.state.started || device->internal.state.added) { return ERROR_INVALID_STATE; } @@ -65,7 +65,7 @@ int device_destruct(Device* device) { mutex_destruct(&device->internal.mutex); delete get_device_data(device); device->internal.data = nullptr; - return 0; + return ERROR_NONE; } /** Add a child to the list of children */ @@ -87,7 +87,7 @@ static void device_remove_child(struct Device* device, struct Device* child) { device_unlock(device); } -int device_add(Device* device) { +error_t device_add(Device* device) { LOG_I(TAG, "add %s", device->name); // Already added @@ -107,10 +107,10 @@ int device_add(Device* device) { } device->internal.state.added = true; - return 0; + return ERROR_NONE; } -int device_remove(Device* device) { +error_t device_remove(Device* device) { LOG_I(TAG, "remove %s", device->name); if (device->internal.state.started || !device->internal.state.added) { @@ -133,7 +133,7 @@ int device_remove(Device* device) { ledger_unlock(); device->internal.state.added = false; - return 0; + return ERROR_NONE; failed_ledger_lookup: @@ -145,7 +145,7 @@ failed_ledger_lookup: return ERROR_NOT_FOUND; } -int device_start(Device* device) { +error_t device_start(Device* device) { if (!device->internal.state.added) { return ERROR_INVALID_STATE; } @@ -156,33 +156,31 @@ int device_start(Device* device) { // Already started if (device->internal.state.started) { - return 0; + return ERROR_NONE; } - int result = driver_bind(device->internal.driver, device); - device->internal.state.started = (result == 0); - device->internal.state.start_result = result; - return result; + error_t bind_error = driver_bind(device->internal.driver, device); + device->internal.state.started = (bind_error == ERROR_NONE); + device->internal.state.start_result = bind_error; + return bind_error == ERROR_NONE ? ERROR_NONE : ERROR_RESOURCE; } -int device_stop(struct Device* device) { +error_t device_stop(struct Device* device) { if (!device->internal.state.added) { return ERROR_INVALID_STATE; } - // Not started if (!device->internal.state.started) { - return 0; + return ERROR_NONE; } - int result = driver_unbind(device->internal.driver, device); - if (result != 0) { - return result; + if (driver_unbind(device->internal.driver, device) != ERROR_NONE) { + return ERROR_RESOURCE; } device->internal.state.started = false; device->internal.state.start_result = 0; - return 0; + return ERROR_NONE; } void device_set_parent(Device* device, Device* parent) { @@ -200,22 +198,22 @@ void for_each_device(void* callback_context, bool(*on_device)(Device* device, vo ledger_unlock(); } -void for_each_device_child(Device* device, void* callback_context, bool(*on_device)(struct Device* device, void* context)) { +void for_each_device_child(Device* device, void* callbackContext, bool(*on_device)(struct Device* device, void* context)) { auto* data = get_device_data(device); for (auto* child_device : data->children) { - if (!on_device(child_device, callback_context)) { + if (!on_device(child_device, callbackContext)) { break; } } } -void for_each_device_of_type(const DeviceType* type, void* callback_context, bool(*on_device)(Device* device, void* context)) { +void for_each_device_of_type(const DeviceType* type, void* callbackContext, bool(*on_device)(Device* device, void* context)) { ledger_lock(); for (auto* device : ledger.devices) { auto* driver = device->internal.driver; if (driver != nullptr) { - if (driver->device_type == type) { - if (!on_device(device, callback_context)) { + if (driver->deviceType == type) { + if (!on_device(device, callbackContext)) { break; } } diff --git a/TactilityKernel/Source/Driver.cpp b/TactilityKernel/Source/Driver.cpp index 52fd334a..217eac3f 100644 --- a/TactilityKernel/Source/Driver.cpp +++ b/TactilityKernel/Source/Driver.cpp @@ -15,6 +15,7 @@ struct DriverInternalData { Mutex mutex { 0 }; int use_count = 0; + bool destroying = false; DriverInternalData() { mutex_construct(&mutex); @@ -64,7 +65,7 @@ static void driver_add(Driver* driver) { ledger.unlock(); } -static bool driver_remove(Driver* driver) { +static error_t driver_remove(Driver* driver) { LOG_I(TAG, "remove %s", driver->name); ledger.lock(); @@ -72,35 +73,41 @@ static bool driver_remove(Driver* driver) { // check that there actually is a 3 in our vector if (iterator == ledger.drivers.end()) { ledger.unlock(); - return false; + return ERROR_NOT_FOUND; } ledger.drivers.erase(iterator); ledger.unlock(); - return true; + return ERROR_NONE; } extern "C" { -int driver_construct(Driver* driver) { +error_t driver_construct(Driver* driver) { driver->internal.data = new(std::nothrow) DriverInternalData; if (driver->internal.data == nullptr) { - return ENOMEM; + return ERROR_OUT_OF_MEMORY; } driver_add(driver); - return 0; + return ERROR_NONE; } -int driver_destruct(Driver* driver) { - // Check if in use - if (driver_internal_data(driver)->use_count != 0) { +error_t driver_destruct(Driver* driver) { + driver_lock(driver); + if (driver_internal_data(driver)->use_count != 0 || driver_internal_data(driver)->destroying) { + driver_unlock(driver); return ERROR_INVALID_STATE; } + driver_internal_data(driver)->destroying = true; + driver_unlock(driver); + + if (driver_remove(driver) != ERROR_NONE) { + LOG_W(TAG, "Failed to remove driver from ledger: %s", driver->name); + } - driver_remove(driver); delete driver_internal_data(driver); driver->internal.data = nullptr; - return 0; + return ERROR_NONE; } bool driver_is_compatible(Driver* driver, const char* compatible) { @@ -130,18 +137,18 @@ Driver* driver_find_compatible(const char* compatible) { return result; } -int driver_bind(Driver* driver, Device* device) { +error_t driver_bind(Driver* driver, Device* device) { driver_lock(driver); - int err = 0; - if (!device_is_added(device)) { - err = ERROR_INVALID_STATE; + error_t error = ERROR_NONE; + if (driver_internal_data(driver)->destroying || !device_is_added(device)) { + error = ERROR_INVALID_STATE; goto error; } - if (driver->start_device != nullptr) { - err = driver->start_device(device); - if (err != 0) { + if (driver->startDevice != nullptr) { + error = driver->startDevice(device); + if (error != ERROR_NONE) { goto error; } } @@ -150,26 +157,26 @@ int driver_bind(Driver* driver, Device* device) { driver_unlock(driver); LOG_I(TAG, "bound %s to %s", driver->name, device->name); - return 0; + return ERROR_NONE; error: driver_unlock(driver); - return err; + return error; } -int driver_unbind(Driver* driver, Device* device) { +error_t driver_unbind(Driver* driver, Device* device) { driver_lock(driver); - int err = 0; - if (!device_is_added(device)) { - err = ERROR_INVALID_STATE; + error_t error = ERROR_NONE; + if (driver_internal_data(driver)->destroying || !device_is_added(device)) { + error = ERROR_INVALID_STATE; goto error; } - if (driver->stop_device != nullptr) { - err = driver->stop_device(device); - if (err != 0) { + if (driver->stopDevice != nullptr) { + error = driver->stopDevice(device); + if (error != ERROR_NONE) { goto error; } } @@ -179,12 +186,12 @@ int driver_unbind(Driver* driver, Device* device) { LOG_I(TAG, "unbound %s to %s", driver->name, device->name); - return 0; + return ERROR_NONE; error: driver_unlock(driver); - return err; + return error; } } // extern "C" diff --git a/TactilityKernel/Source/concurrent/Dispatcher.cpp b/TactilityKernel/Source/concurrent/Dispatcher.cpp new file mode 100644 index 00000000..ae72fb9d --- /dev/null +++ b/TactilityKernel/Source/concurrent/Dispatcher.cpp @@ -0,0 +1,142 @@ +// SPDX-License-Identifier: Apache-2.0 + +#include + +#include + +#include "Tactility/Error.h" + +#include +#include +#include +#include + +#define TAG LOG_TAG("Dispatcher") + +static constexpr EventBits_t BACKPRESSURE_WARNING_COUNT = 100U; +static constexpr EventBits_t WAIT_FLAG = 1U; + +struct QueuedItem { + DispatcherCallback callback; + void* context; +}; + +struct DispatcherData { + Mutex mutex = { 0 }; + std::queue queue = {}; + EventGroupHandle_t eventGroup = nullptr; + std::atomic shutdown{false}; // TODO: Use EventGroup + + DispatcherData() { + event_group_construct(&eventGroup); + mutex_construct(&mutex); + } + + ~DispatcherData() { + event_group_destruct(&eventGroup); + mutex_destruct(&mutex); + } +}; + +#define dispatcher_data(handle) static_cast(handle) + +extern "C" { + +DispatcherHandle_t dispatcher_alloc(void) { + return new DispatcherData(); +} + +void dispatcher_free(DispatcherHandle_t dispatcher) { + auto* data = dispatcher_data(dispatcher); + data->shutdown.store(true, std::memory_order_release); + mutex_lock(&data->mutex); + mutex_unlock(&data->mutex); + delete data; +} + +error_t dispatcher_dispatch_timed(DispatcherHandle_t dispatcher, void* callbackContext, DispatcherCallback callback, TickType_t timeout) { + auto* data = dispatcher_data(dispatcher); + + // Mutate + if (!mutex_try_lock_timed(&data->mutex, timeout)) { +#ifdef ESP_PLATFORM + LOG_E(TAG, "Mutex acquisition timeout"); +#endif + return ERROR_TIMEOUT; + } + + if (data->shutdown.load(std::memory_order_acquire)) { + mutex_unlock(&data->mutex); + return ERROR_INVALID_STATE; + } + + data->queue.push({ + .callback = callback, + .context = callbackContext + }); + + if (data->queue.size() == BACKPRESSURE_WARNING_COUNT) { +#ifdef ESP_PLATFORM + LOG_W(TAG, "Backpressure: You're not consuming fast enough (100 queued)"); +#endif + } + + mutex_unlock(&data->mutex); + + if (event_group_set(data->eventGroup, WAIT_FLAG) != ERROR_NONE) { +#ifdef ESP_PLATFORM + LOG_E(TAG, "Failed to set flag"); +#endif + return ERROR_RESOURCE; + } + + return ERROR_NONE; +} + +error_t dispatcher_consume_timed(DispatcherHandle_t dispatcher, TickType_t timeout) { + auto* data = dispatcher_data(dispatcher); + + // TODO: keep track of time and consider the timeout input as total timeout + + // Wait for signal + error_t error = event_group_wait(data->eventGroup, WAIT_FLAG, false, true, nullptr, timeout); + if (error != ERROR_NONE) { + if (error == ERROR_TIMEOUT) { + return ERROR_TIMEOUT; + } else { + return ERROR_RESOURCE; + } + } + + if (data->shutdown.load(std::memory_order_acquire)) { + return ERROR_INVALID_STATE; + } + + // Mutate + bool processing = true; + do { + if (mutex_try_lock_timed(&data->mutex, 10)) { + if (!data->queue.empty()) { + // Make a copy, so it's thread-safe when we unlock + auto entry = data->queue.front(); + data->queue.pop(); + processing = !data->queue.empty(); + // Don't keep lock as callback might be slow and we want to allow dispatch in the meanwhile + mutex_unlock(&data->mutex); + entry.callback(entry.context); + } else { + processing = false; + mutex_unlock(&data->mutex); + } + } else { +#ifdef ESP_PLATFORM + LOG_W(TAG, "Mutex acquisition timeout"); +#endif + } + + } while (processing && !data->shutdown.load(std::memory_order_acquire)); + + return ERROR_NONE; +} + +} \ No newline at end of file diff --git a/TactilityKernel/Source/concurrent/EventGroup.cpp b/TactilityKernel/Source/concurrent/EventGroup.cpp new file mode 100644 index 00000000..cab2f1fd --- /dev/null +++ b/TactilityKernel/Source/concurrent/EventGroup.cpp @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: Apache-2.0 + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +error_t event_group_set(EventGroupHandle_t eventGroup, uint32_t inFlags) { + if (xPortInIsrContext() == pdTRUE) { + BaseType_t yield = pdFALSE; + if (xEventGroupSetBitsFromISR(eventGroup, inFlags, &yield) == pdFAIL) { + return ERROR_RESOURCE; + } + portYIELD_FROM_ISR(yield); + } else { + xEventGroupSetBits(eventGroup, inFlags); + } + return ERROR_NONE; +} + +error_t event_group_clear(EventGroupHandle_t eventGroup, uint32_t flags) { + if (xPortInIsrContext() == pdTRUE) { + if (xEventGroupClearBitsFromISR(eventGroup, flags) == pdFAIL) { + return ERROR_RESOURCE; + } + portYIELD_FROM_ISR(pdTRUE); + } else { + xEventGroupClearBits(eventGroup, flags); + } + return ERROR_NONE; +} + +uint32_t event_group_get(EventGroupHandle_t eventGroup) { + if (xPortInIsrContext() == pdTRUE) { + return xEventGroupGetBitsFromISR(eventGroup); + } else { + return xEventGroupGetBits(eventGroup); + } +} + +error_t event_group_wait( + EventGroupHandle_t eventGroup, + uint32_t inFlags, + bool awaitAll, + bool clearOnExit, + uint32_t* outFlags, + TickType_t timeout +) { + if (xPortInIsrContext()) { + return ERROR_ISR_STATUS; + } + + uint32_t result_flags = xEventGroupWaitBits( + eventGroup, + inFlags, + clearOnExit ? pdTRUE : pdFALSE, + awaitAll ? pdTRUE : pdFALSE, + timeout + ); + + auto invalid_flags = awaitAll + ? ((inFlags & result_flags) != inFlags) // await all + : ((inFlags & result_flags) == 0U); // await any + + if (invalid_flags) { + const uint32_t matched = inFlags & result_flags; + if (matched == 0U) { + return ERROR_TIMEOUT; + } + return ERROR_RESOURCE; + } + + if (outFlags != nullptr) { + *outFlags = result_flags; + } + + return ERROR_NONE; +} + +#ifdef __cplusplus +} +#endif diff --git a/TactilityKernel/Source/drivers/GpioController.cpp b/TactilityKernel/Source/drivers/GpioController.cpp index d97481dd..4fbbd4d7 100644 --- a/TactilityKernel/Source/drivers/GpioController.cpp +++ b/TactilityKernel/Source/drivers/GpioController.cpp @@ -7,22 +7,22 @@ extern "C" { -bool gpio_controller_set_level(Device* device, gpio_pin_t pin, bool high) { +error_t gpio_controller_set_level(Device* device, gpio_pin_t pin, bool high) { const auto* driver = device_get_driver(device); return GPIO_DRIVER_API(driver)->set_level(device, pin, high); } -bool gpio_controller_get_level(Device* device, gpio_pin_t pin, bool* high) { +error_t gpio_controller_get_level(Device* device, gpio_pin_t pin, bool* high) { const auto* driver = device_get_driver(device); return GPIO_DRIVER_API(driver)->get_level(device, pin, high); } -bool gpio_controller_set_options(Device* device, gpio_pin_t pin, gpio_flags_t options) { +error_t gpio_controller_set_options(Device* device, gpio_pin_t pin, gpio_flags_t options) { const auto* driver = device_get_driver(device); return GPIO_DRIVER_API(driver)->set_options(device, pin, options); } -bool gpio_controller_get_options(Device* device, gpio_pin_t pin, gpio_flags_t* options) { +error_t gpio_controller_get_options(Device* device, gpio_pin_t pin, gpio_flags_t* options) { const auto* driver = device_get_driver(device); return GPIO_DRIVER_API(driver)->get_options(device, pin, options); } diff --git a/TactilityKernel/Source/drivers/I2cController.cpp b/TactilityKernel/Source/drivers/I2cController.cpp index 4dc16ce3..28a507f6 100644 --- a/TactilityKernel/Source/drivers/I2cController.cpp +++ b/TactilityKernel/Source/drivers/I2cController.cpp @@ -2,24 +2,25 @@ #include #include +#include #define I2C_DRIVER_API(driver) ((struct I2cControllerApi*)driver->api) extern "C" { -bool i2c_controller_read(Device* device, uint8_t address, uint8_t* data, size_t dataSize, TickType_t timeout) { +error_t i2c_controller_read(Device* device, uint8_t address, uint8_t* data, size_t dataSize, TickType_t timeout) { const auto* driver = device_get_driver(device); return I2C_DRIVER_API(driver)->read(device, address, data, dataSize, timeout); } -bool i2c_controller_write(Device* device, uint8_t address, const uint8_t* data, uint16_t dataSize, TickType_t timeout) { +error_t i2c_controller_write(Device* device, uint8_t address, const uint8_t* data, uint16_t dataSize, TickType_t timeout) { const auto* driver = device_get_driver(device); return I2C_DRIVER_API(driver)->write(device, address, data, dataSize, timeout); } -bool i2c_controller_write_read(Device* device, uint8_t address, const uint8_t* write_data, size_t write_data_size, uint8_t* read_data, size_t read_data_size, TickType_t timeout) { +error_t i2c_controller_write_read(Device* device, uint8_t address, const uint8_t* writeData, size_t writeDataSize, uint8_t* readData, size_t readDataSize, TickType_t timeout) { const auto* driver = device_get_driver(device); - return I2C_DRIVER_API(driver)->write_read(device, address, write_data, write_data_size, read_data, read_data_size, timeout); + return I2C_DRIVER_API(driver)->write_read(device, address, writeData, writeDataSize, readData, readDataSize, timeout); } const struct DeviceType I2C_CONTROLLER_TYPE { 0 }; diff --git a/TactilityKernel/Source/drivers/Root.cpp b/TactilityKernel/Source/drivers/Root.cpp index 035c1f91..7229b640 100644 --- a/TactilityKernel/Source/drivers/Root.cpp +++ b/TactilityKernel/Source/drivers/Root.cpp @@ -8,10 +8,10 @@ extern "C" { Driver root_driver = { .name = "root", .compatible = (const char*[]) { "root", nullptr }, - .start_device = nullptr, - .stop_device = nullptr, + .startDevice = nullptr, + .stopDevice = nullptr, .api = nullptr, - .device_type = nullptr, + .deviceType = nullptr, .internal = { 0 } }; diff --git a/Tests/TactilityKernel/DeviceTest.cpp b/Tests/TactilityKernel/DeviceTest.cpp index 247af86d..922066ad 100644 --- a/Tests/TactilityKernel/DeviceTest.cpp +++ b/Tests/TactilityKernel/DeviceTest.cpp @@ -8,14 +8,13 @@ TEST_CASE("device_construct and device_destruct should set and unset the correct fields") { Device device = { 0 }; - int error = device_construct(&device); - CHECK_EQ(error, 0); + error_t error = device_construct(&device); + CHECK_EQ(error, ERROR_NONE); CHECK_NE(device.internal.data, nullptr); CHECK_NE(device.internal.mutex.handle, nullptr); - error = device_destruct(&device); - CHECK_EQ(error, 0); + CHECK_EQ(device_destruct(&device), ERROR_NONE); CHECK_EQ(device.internal.data, nullptr); CHECK_EQ(device.internal.mutex.handle, nullptr); @@ -30,13 +29,13 @@ TEST_CASE("device_construct and device_destruct should set and unset the correct TEST_CASE("device_add should add the device to the list of all devices") { Device device = { 0 }; - CHECK_EQ(device_construct(&device), 0); - CHECK_EQ(device_add(&device), 0); + CHECK_EQ(device_construct(&device), ERROR_NONE); + CHECK_EQ(device_add(&device), ERROR_NONE); // Gather all devices std::vector devices; for_each_device(&devices, [](auto* device, auto* context) { - auto* devices_ptr = (std::vector*)context; + auto* devices_ptr = static_cast*>(context); devices_ptr->push_back(device); return true; }); @@ -44,8 +43,8 @@ TEST_CASE("device_add should add the device to the list of all devices") { CHECK_EQ(devices.size(), 1); CHECK_EQ(devices[0], &device); - CHECK_EQ(device_remove(&device), 0); - CHECK_EQ(device_destruct(&device), 0); + CHECK_EQ(device_remove(&device), ERROR_NONE); + CHECK_EQ(device_destruct(&device), ERROR_NONE); } TEST_CASE("device_add should add the device to its parent") { @@ -57,11 +56,11 @@ TEST_CASE("device_add should add the device to its parent") { .parent = &parent }; - CHECK_EQ(device_construct(&parent), 0); - CHECK_EQ(device_add(&parent), 0); + CHECK_EQ(device_construct(&parent), ERROR_NONE); + CHECK_EQ(device_add(&parent), ERROR_NONE); - CHECK_EQ(device_construct(&child), 0); - CHECK_EQ(device_add(&child), 0); + CHECK_EQ(device_construct(&child), ERROR_NONE); + CHECK_EQ(device_add(&child), ERROR_NONE); // Gather all child devices std::vector children; @@ -74,30 +73,30 @@ TEST_CASE("device_add should add the device to its parent") { CHECK_EQ(children.size(), 1); CHECK_EQ(children[0], &child); - CHECK_EQ(device_remove(&child), 0); - CHECK_EQ(device_destruct(&child), 0); + CHECK_EQ(device_remove(&child), ERROR_NONE); + CHECK_EQ(device_destruct(&child), ERROR_NONE); - CHECK_EQ(device_remove(&parent), 0); - CHECK_EQ(device_destruct(&parent), 0); + CHECK_EQ(device_remove(&parent), ERROR_NONE); + CHECK_EQ(device_destruct(&parent), ERROR_NONE); } TEST_CASE("device_add should set the state to 'added'") { Device device = { 0 }; - CHECK_EQ(device_construct(&device), 0); + CHECK_EQ(device_construct(&device), ERROR_NONE); CHECK_EQ(device.internal.state.added, false); - CHECK_EQ(device_add(&device), 0); + CHECK_EQ(device_add(&device), ERROR_NONE); CHECK_EQ(device.internal.state.added, true); - CHECK_EQ(device_remove(&device), 0); - CHECK_EQ(device_destruct(&device), 0); + CHECK_EQ(device_remove(&device), ERROR_NONE); + CHECK_EQ(device_destruct(&device), ERROR_NONE); } TEST_CASE("device_remove should remove it from the list of all devices") { Device device = { 0 }; - CHECK_EQ(device_construct(&device), 0); - CHECK_EQ(device_add(&device), 0); - CHECK_EQ(device_remove(&device), 0); + CHECK_EQ(device_construct(&device), ERROR_NONE); + CHECK_EQ(device_add(&device), ERROR_NONE); + CHECK_EQ(device_remove(&device), ERROR_NONE); // Gather all devices std::vector devices; @@ -109,7 +108,7 @@ TEST_CASE("device_remove should remove it from the list of all devices") { CHECK_EQ(devices.size(), 0); - CHECK_EQ(device_destruct(&device), 0); + CHECK_EQ(device_destruct(&device), ERROR_NONE); } TEST_CASE("device_remove should remove the device from its parent") { @@ -121,12 +120,12 @@ TEST_CASE("device_remove should remove the device from its parent") { .parent = &parent }; - CHECK_EQ(device_construct(&parent), 0); - CHECK_EQ(device_add(&parent), 0); + CHECK_EQ(device_construct(&parent), ERROR_NONE); + CHECK_EQ(device_add(&parent), ERROR_NONE); - CHECK_EQ(device_construct(&child), 0); - CHECK_EQ(device_add(&child), 0); - CHECK_EQ(device_remove(&child), 0); + CHECK_EQ(device_construct(&child), ERROR_NONE); + CHECK_EQ(device_add(&child), ERROR_NONE); + CHECK_EQ(device_remove(&child), ERROR_NONE); // Gather all child devices std::vector children; @@ -138,22 +137,22 @@ TEST_CASE("device_remove should remove the device from its parent") { CHECK_EQ(children.size(), 0); - CHECK_EQ(device_destruct(&child), 0); + CHECK_EQ(device_destruct(&child), ERROR_NONE); - CHECK_EQ(device_remove(&parent), 0); - CHECK_EQ(device_destruct(&parent), 0); + CHECK_EQ(device_remove(&parent), ERROR_NONE); + CHECK_EQ(device_destruct(&parent), ERROR_NONE); } TEST_CASE("device_remove should clear the state 'added'") { Device device = { 0 }; - CHECK_EQ(device_construct(&device), 0); + CHECK_EQ(device_construct(&device), ERROR_NONE); - CHECK_EQ(device_add(&device), 0); + CHECK_EQ(device_add(&device), ERROR_NONE); CHECK_EQ(device.internal.state.added, true); - CHECK_EQ(device_remove(&device), 0); + CHECK_EQ(device_remove(&device), ERROR_NONE); CHECK_EQ(device.internal.state.added, false); - CHECK_EQ(device_destruct(&device), 0); + CHECK_EQ(device_destruct(&device), ERROR_NONE); } TEST_CASE("device_is_ready should return true only when it is started") { @@ -161,30 +160,30 @@ TEST_CASE("device_is_ready should return true only when it is started") { Driver driver = { .name = "test_driver", .compatible = compatible, - .start_device = nullptr, - .stop_device = nullptr, + .startDevice = nullptr, + .stopDevice = nullptr, .api = nullptr, - .device_type = nullptr, + .deviceType = nullptr, .internal = { 0 } }; Device device = { 0 }; - CHECK_EQ(driver_construct(&driver), 0); - CHECK_EQ(device_construct(&device), 0); + CHECK_EQ(driver_construct(&driver), ERROR_NONE); + CHECK_EQ(device_construct(&device), ERROR_NONE); CHECK_EQ(device.internal.state.started, false); device_set_driver(&device, &driver); CHECK_EQ(device.internal.state.started, false); - CHECK_EQ(device_add(&device), 0); + CHECK_EQ(device_add(&device), ERROR_NONE); CHECK_EQ(device.internal.state.started, false); - CHECK_EQ(device_start(&device), 0); + CHECK_EQ(device_start(&device), ERROR_NONE); CHECK_EQ(device.internal.state.started, true); - CHECK_EQ(device_stop(&device), 0); + CHECK_EQ(device_stop(&device), ERROR_NONE); CHECK_EQ(device.internal.state.started, false); - CHECK_EQ(device_remove(&device), 0); + CHECK_EQ(device_remove(&device), ERROR_NONE); CHECK_EQ(device.internal.state.started, false); - CHECK_EQ(driver_destruct(&driver), 0); - CHECK_EQ(device_destruct(&device), 0); + CHECK_EQ(driver_destruct(&driver), ERROR_NONE); + CHECK_EQ(device_destruct(&device), ERROR_NONE); } diff --git a/Tests/TactilityKernel/DispatcherTest.cpp b/Tests/TactilityKernel/DispatcherTest.cpp new file mode 100644 index 00000000..8270e8d7 --- /dev/null +++ b/Tests/TactilityKernel/DispatcherTest.cpp @@ -0,0 +1,25 @@ +#include "doctest.h" +#include +#include + +TEST_CASE("dispatcher test") { + DispatcherHandle_t dispatcher = dispatcher_alloc(); + CHECK_NE(dispatcher, nullptr); + + int count = 0; + auto error = dispatcher_dispatch(dispatcher, &count, [](void* context) { + int* count_ptr = static_cast(context); + (*count_ptr)++; + }); + + CHECK_EQ(error, ERROR_NONE); + vTaskDelay(1); + + CHECK_EQ(count, 0); + + CHECK_EQ(dispatcher_consume(dispatcher), ERROR_NONE); + CHECK_EQ(count, 1); + + dispatcher_free(dispatcher); +} + diff --git a/Tests/TactilityKernel/DriverIntegrationTest.cpp b/Tests/TactilityKernel/DriverIntegrationTest.cpp index f648cfff..c97cfd75 100644 --- a/Tests/TactilityKernel/DriverIntegrationTest.cpp +++ b/Tests/TactilityKernel/DriverIntegrationTest.cpp @@ -26,10 +26,10 @@ static int stop(Device* device) { static Driver integration_driver = { .name = "integration_test_driver", .compatible = (const char*[]) { "integration", nullptr }, - .start_device = start, - .stop_device = stop, + .startDevice = start, + .stopDevice = stop, .api = nullptr, - .device_type = nullptr, + .deviceType = nullptr, .internal = { 0 } }; @@ -47,18 +47,18 @@ TEST_CASE("driver with with start success and stop success should start and stop .parent = nullptr, }; - CHECK_EQ(driver_construct(&integration_driver), 0); + CHECK_EQ(driver_construct(&integration_driver), ERROR_NONE); - CHECK_EQ(device_construct(&integration_device), 0); + CHECK_EQ(device_construct(&integration_device), ERROR_NONE); device_add(&integration_device); CHECK_EQ(startCalled, 0); - CHECK_EQ(driver_bind(&integration_driver, &integration_device), 0); + CHECK_EQ(driver_bind(&integration_driver, &integration_device), ERROR_NONE); CHECK_EQ(startCalled, 1); CHECK_EQ(stopCalled, 0); - CHECK_EQ(driver_unbind(&integration_driver, &integration_device), 0); + CHECK_EQ(driver_unbind(&integration_driver, &integration_device), ERROR_NONE); CHECK_EQ(stopCalled, 1); - CHECK_EQ(device_remove(&integration_device), 0); - CHECK_EQ(device_destruct(&integration_device), 0); + CHECK_EQ(device_remove(&integration_device), ERROR_NONE); + CHECK_EQ(device_destruct(&integration_device), ERROR_NONE); - CHECK_EQ(driver_destruct(&integration_driver), 0); + CHECK_EQ(driver_destruct(&integration_driver), ERROR_NONE); } diff --git a/Tests/TactilityKernel/DriverTest.cpp b/Tests/TactilityKernel/DriverTest.cpp index b85506a6..c5201b5c 100644 --- a/Tests/TactilityKernel/DriverTest.cpp +++ b/Tests/TactilityKernel/DriverTest.cpp @@ -4,12 +4,9 @@ TEST_CASE("driver_construct and driver_destruct should set and unset the correct fields") { Driver driver = { 0 }; - int error = driver_construct(&driver); - CHECK_EQ(error, 0); + CHECK_EQ(driver_construct(&driver), ERROR_NONE); CHECK_NE(driver.internal.data, nullptr); - - error = driver_destruct(&driver); - CHECK_EQ(error, 0); + CHECK_EQ(driver_destruct(&driver), ERROR_NONE); CHECK_EQ(driver.internal.data, nullptr); } @@ -18,10 +15,10 @@ TEST_CASE("driver_is_compatible should return true if a compatible value is foun Driver driver = { .name = "test_driver", .compatible = compatible, - .start_device = nullptr, - .stop_device = nullptr, + .startDevice = nullptr, + .stopDevice = nullptr, .api = nullptr, - .device_type = nullptr, + .deviceType = nullptr, .internal = { 0 } }; CHECK_EQ(driver_is_compatible(&driver, "test_compatible"), true); @@ -34,24 +31,22 @@ TEST_CASE("driver_find should only find a compatible driver when the driver was Driver driver = { .name = "test_driver", .compatible = compatible, - .start_device = nullptr, - .stop_device = nullptr, + .startDevice = nullptr, + .stopDevice = nullptr, .api = nullptr, - .device_type = nullptr, + .deviceType = nullptr, .internal = { 0 } }; Driver* found_driver = driver_find_compatible("test_compatible"); CHECK_EQ(found_driver, nullptr); - int error = driver_construct(&driver); - CHECK_EQ(error, 0); + CHECK_EQ(driver_construct(&driver), ERROR_NONE); found_driver = driver_find_compatible("test_compatible"); CHECK_EQ(found_driver, &driver); - error = driver_destruct(&driver); - CHECK_EQ(error, 0); + CHECK_EQ(driver_destruct(&driver), ERROR_NONE); found_driver = driver_find_compatible("test_compatible"); CHECK_EQ(found_driver, nullptr); diff --git a/Tests/TactilityKernel/MutexTest.cpp b/Tests/TactilityKernel/MutexTest.cpp index d84d10d4..a5eb8a1b 100644 --- a/Tests/TactilityKernel/MutexTest.cpp +++ b/Tests/TactilityKernel/MutexTest.cpp @@ -60,7 +60,7 @@ TEST_CASE("mutex_lock in another task should block when a lock is active") { CHECK_EQ(task_lock_counter, 0); mutex_unlock(&mutex); - vTaskDelay(1); + vTaskDelay(2); // 1 is sufficient most of the time, but not always CHECK_EQ(task_lock_counter, 1); mutex_destruct(&mutex); } diff --git a/Tests/TactilityKernel/RecursiveMutexTest.cpp b/Tests/TactilityKernel/RecursiveMutexTest.cpp index 17c2d319..1eda5a65 100644 --- a/Tests/TactilityKernel/RecursiveMutexTest.cpp +++ b/Tests/TactilityKernel/RecursiveMutexTest.cpp @@ -80,7 +80,7 @@ TEST_CASE("recursive_mutex_lock in another task should block when a lock is acti CHECK_EQ(task_lock_counter, 0); recursive_mutex_unlock(&mutex); - vTaskDelay(1); + vTaskDelay(2); // 1 is sufficient most of the time, but not always CHECK_EQ(task_lock_counter, 1); recursive_mutex_destruct(&mutex); } From 10381b10cdc9bec26f4b3c5f220ac9cc86e7bb60 Mon Sep 17 00:00:00 2001 From: Shadowtrance Date: Tue, 27 Jan 2026 02:32:57 +1000 Subject: [PATCH 10/10] Chat app update, EspNow v2 & GPS Info (#460) --- Documentation/chat.md | 192 ++++++++++++ .../Include/Tactility/service/espnow/EspNow.h | 10 + .../Tactility/service/gps/GpsService.h | 4 + .../Tactility/app/chat/ChatAppPrivate.h | 46 +++ .../Private/Tactility/app/chat/ChatProtocol.h | 97 ++++++ .../Private/Tactility/app/chat/ChatSettings.h | 34 ++ .../Private/Tactility/app/chat/ChatState.h | 59 ++++ .../Private/Tactility/app/chat/ChatView.h | 79 +++++ .../Tactility/service/espnow/EspNowService.h | 3 + Tactility/Source/app/chat/ChatApp.cpp | 260 ++++++++------- Tactility/Source/app/chat/ChatProtocol.cpp | 174 +++++++++++ Tactility/Source/app/chat/ChatSettings.cpp | 183 +++++++++++ Tactility/Source/app/chat/ChatState.cpp | 60 ++++ Tactility/Source/app/chat/ChatView.cpp | 295 ++++++++++++++++++ .../Source/app/gpssettings/GpsSettings.cpp | 112 ++++++- Tactility/Source/service/espnow/EspNow.cpp | 16 + .../Source/service/espnow/EspNowService.cpp | 22 +- Tactility/Source/service/gps/GpsService.cpp | 25 +- 18 files changed, 1547 insertions(+), 124 deletions(-) create mode 100644 Documentation/chat.md create mode 100644 Tactility/Private/Tactility/app/chat/ChatAppPrivate.h create mode 100644 Tactility/Private/Tactility/app/chat/ChatProtocol.h create mode 100644 Tactility/Private/Tactility/app/chat/ChatSettings.h create mode 100644 Tactility/Private/Tactility/app/chat/ChatState.h create mode 100644 Tactility/Private/Tactility/app/chat/ChatView.h create mode 100644 Tactility/Source/app/chat/ChatProtocol.cpp create mode 100644 Tactility/Source/app/chat/ChatSettings.cpp create mode 100644 Tactility/Source/app/chat/ChatState.cpp create mode 100644 Tactility/Source/app/chat/ChatView.cpp diff --git a/Documentation/chat.md b/Documentation/chat.md new file mode 100644 index 00000000..563d995e --- /dev/null +++ b/Documentation/chat.md @@ -0,0 +1,192 @@ +# Chat App + +ESP-NOW-based chat application with channel-based messaging. Devices with the same encryption key can communicate in real-time without requiring a WiFi access point or internet connection. + +## Features + +- **Channel-based messaging**: Join named channels (e.g. `#general`, `#random`) to organize conversations +- **Broadcast support**: Messages with empty target are visible in all channels +- **Configurable nickname**: Identify yourself with a custom name (max 23 characters) +- **Unique sender ID**: Each device gets a random 32-bit ID on first launch for future DM support +- **Encryption key**: Optional shared key for private group communication +- **Persistent settings**: Sender ID, nickname, key, and current chat channel are saved across reboots + +## Requirements + +- ESP32 with WiFi support (not available on ESP32-P4) +- ESP-NOW service enabled + +## UI Layout + +```text ++------------------------------------------+ +| [Back] Chat: #general [List] [Gear] | ++------------------------------------------+ +| alice: hello everyone | +| bob: hey alice! | +| You: hi there | +| (scrollable message list) | ++------------------------------------------+ +| [____input textarea____] [Send] | ++------------------------------------------+ +``` + +- **Toolbar title**: Shows `Chat: ` with the current channel name +- **List icon**: Opens channel selector to switch channels +- **Gear icon**: Opens settings panel (nickname, encryption key) +- **Message list**: Shows messages matching the current channel or broadcast messages +- **Input bar**: Type and send messages to the current channel + +## Channel Selector + +Tap the list icon to change channels. Enter a channel name (e.g. `#general`, `#team1`) and press OK. The message list refreshes to show only messages matching the new channel. + +Messages are sent with the current channel as the target. Only devices viewing the same channel will display the message. Broadcast messages (empty target) appear in all channels. + +## First Launch + +On first launch (when no settings file exists), the settings panel opens automatically so users can configure their nickname before chatting. A unique sender ID is also generated using the hardware RNG. + +## Settings + +Tap the gear icon to configure: + +| Setting | Description | Default | +|---------|-------------|---------| +| Nickname | Your display name (max 23 chars) | `Device` | +| Key | Encryption key as 32 hex characters (16 bytes) | All zeros (empty field) | + +Settings are stored in `/data/settings/chat.properties`. The encryption key is stored encrypted using AES-256-CBC. The sender ID is stored as a decimal number. + +When the key field is left empty, the default all-zeros key is used. All devices using the default key can communicate without configuration. + +Changing the encryption key causes ESP-NOW to restart with the new configuration. + +## Wire Protocol v2 + +Compact variable-length packets broadcast over ESP-NOW: + +### Header (16 bytes) + +```text +Offset Size Field +------ ---- ----- +0 4 magic (0x54435432 "TCT2") +4 2 protocol_version (2) +6 4 from (sender ID, random uint32) +10 4 to (recipient ID, 0 = broadcast/channel) +14 1 payload_type (1 = TextMessage) +15 1 payload_size (length of payload) +``` + +### Text Message Payload (variable) + +```text +[nickname\0][target\0][message bytes] +``` + +- `nickname`: Null-terminated sender display name (2-23 chars + null; single-letter names rejected) +- `target`: Null-terminated channel or empty for broadcast (0-23 chars + null) + - Empty string (`\0`): broadcast to all channels + - Channel name (e.g. `#general`): visible only when viewing that channel +- `message`: Remaining bytes, NOT null-terminated, minimum 1 byte (length = `payload_size - strlen(nickname) - 1 - strlen(target) - 1`) + +**Minimum packet size for TextMessage:** 16 (header) + 2 (min nickname) + 1 (null) + 0 (empty target) + 1 (null) + 1 (min message) = **21 bytes** + +**Example calculation:** If nickname is "Alice" (5 chars) and target is "#general" (8 chars): +- Overhead: 5 + 1 + 8 + 1 = 15 bytes +- Max message: 255 - 15 = 240 bytes + +### Example + +"Alice" sends "Hi!" to #general: +- Header: 16 bytes +- Payload: `Alice\0#general\0Hi!` = 18 bytes +- **Total: 34 bytes** + +### Size Limits + +| Constraint | Min | Max | +|------------|-----|-----| +| Header size | 16 bytes | 16 bytes | +| Payload (uint8_t) | 5 bytes | 255 bytes | +| Nickname | 2 characters | 23 characters | +| Channel/target | 0 (broadcast) | 23 characters | +| Message (wire) | 1 byte | up to 251 bytes (varies by overhead) | +| Message (UI) | 1 character | 200 characters | +| Total packet (TextMessage) | 21 bytes | 271 bytes | + +### Payload Types + +| Type | Value | Description | +|------|-------|-------------| +| TextMessage | 1 | Chat message with nickname, target, and text | +| (reserved) | 2+ | Future: Position, Telemetry, etc. | + +### Target Field Semantics + +| `to` Value | `target` Field | Meaning | +|------------|----------------|---------| +| 0 | `""` (empty) | Broadcast - visible in all channels | +| 0 | `#channel` | Channel message - visible only when viewing that channel | +| non-zero | `nickname` | Direct message (future - requires address discovery protocol) | + +Messages with incorrect magic/version or invalid payload are silently discarded. + +> **Note:** Direct messaging (non-zero `to`) will require an address discovery mechanism, such as periodic broadcasts announcing nickname→sender_id mappings, before devices can address each other directly. + +## Architecture + +```text +ChatApp - App lifecycle, ESP-NOW send/receive, settings management +ChatState - Message storage (deque, max 100), channel filtering, mutex-protected +ChatView - LVGL UI: toolbar, message list, input bar, settings/channel panels +ChatProtocol - MessageHeader struct, serialize/deserialize, PayloadType enum +ChatSettings - Properties file load/save with encrypted key storage, sender ID generation +``` + +All files are guarded with `#if defined(CONFIG_SOC_WIFI_SUPPORTED) && !defined(CONFIG_SLAVE_SOC_WIFI_SUPPORTED)` to exclude from P4 builds. + +## Message Flow + +### Sending + +1. User types message and taps Send +2. `serializeTextMessage()` builds compact packet with sender ID, nickname, channel, message +3. Broadcast via ESP-NOW to nearby devices +4. Own message stored and displayed locally + +### Receiving + +1. ESP-NOW callback fires with raw data +2. Validate packet: + - Minimum size: 21 bytes (16 header + 2 min nickname + 1 null + 0 min target + 1 null + 1 min message) + - Magic bytes: must be `0x54435432` ("TCT2") + - Protocol version: must be 2 + - Payload size: `header.payload_size` must equal `received_length - 16` +3. Parse null-terminated nickname and target from payload +4. Validate minimum lengths: nickname >= 2 chars, message >= 1 byte +5. Extract message from remaining bytes (length derived from payload_size) +6. Store in message deque with sender ID +7. Display if target matches current channel or is broadcast (empty) + +## Limitations + +- Maximum 100 stored messages (oldest discarded when full) +- Nickname: 23 characters max +- Channel name: 23 characters max +- Message text: 200 characters max (UI limit; actual wire limit varies by nickname/target length) +- No message persistence across app restarts (messages are in-memory only) +- All communication is broadcast; channel filtering is client-side only +- Sender ID collisions: 32-bit random IDs have ~50% collision probability at ~77,000 active devices (birthday paradox); no collision detection/resolution implemented + +## Security Considerations + +The chat protocol relies on ESP-NOW's built-in encryption (when configured) but has additional security limitations: + +- **No message authentication**: No MAC/HMAC to verify message integrity or sender authenticity beyond the sender ID +- **No replay protection**: No sequence numbers or timestamps; messages can be replayed +- **Sender ID spoofing**: Any device knowing the encryption key can forge messages with arbitrary sender IDs +- **No forward secrecy**: Compromise of the shared key exposes all past and future messages + +These tradeoffs are acceptable for casual local communication but should be understood before using for sensitive applications. diff --git a/Tactility/Include/Tactility/service/espnow/EspNow.h b/Tactility/Include/Tactility/service/espnow/EspNow.h index 429a5664..d29ef61d 100644 --- a/Tactility/Include/Tactility/service/espnow/EspNow.h +++ b/Tactility/Include/Tactility/service/espnow/EspNow.h @@ -16,6 +16,10 @@ namespace tt::service::espnow { typedef int ReceiverSubscription; constexpr ReceiverSubscription NO_SUBSCRIPTION = -1; +// ESP-NOW version payload limits +constexpr size_t MAX_DATA_LEN_V1 = 250; // ESP-NOW v1.0 max payload +constexpr size_t MAX_DATA_LEN_V2 = 1470; // ESP-NOW v2.0 max payload (requires ESP-IDF v5.4+) + enum class Mode { Station, AccessPoint @@ -54,6 +58,12 @@ ReceiverSubscription subscribeReceiver(std::function deviceRecords; @@ -58,6 +61,7 @@ public: bool hasCoordinates() const; bool getCoordinates(minmea_sentence_rmc& rmc) const; + bool getGga(minmea_sentence_gga& gga) const; /** @return GPS service pubsub that broadcasts State* objects */ std::shared_ptr> getStatePubsub() const { return statePubSub; } diff --git a/Tactility/Private/Tactility/app/chat/ChatAppPrivate.h b/Tactility/Private/Tactility/app/chat/ChatAppPrivate.h new file mode 100644 index 00000000..7d1f83e5 --- /dev/null +++ b/Tactility/Private/Tactility/app/chat/ChatAppPrivate.h @@ -0,0 +1,46 @@ +#pragma once + +#ifdef ESP_PLATFORM +#include +#endif + +#if defined(CONFIG_SOC_WIFI_SUPPORTED) && !defined(CONFIG_SLAVE_SOC_WIFI_SUPPORTED) + +#include "ChatState.h" +#include "ChatView.h" +#include "ChatSettings.h" + +#include +#include + +namespace tt::app::chat { + +class ChatApp final : public App { + + ChatState state; + ChatView view = ChatView(this, &state); + service::espnow::ReceiverSubscription receiveSubscription = -1; + ChatSettingsData settings; + bool isFirstLaunch = false; + + void onReceive(const esp_now_recv_info_t* receiveInfo, const uint8_t* data, int length); + void enableEspNow(); + void disableEspNow(); + +public: + void onCreate(AppContext& appContext) override; + void onDestroy(AppContext& appContext) override; + void onShow(AppContext& context, lv_obj_t* parent) override; + + void sendMessage(const std::string& text); + void applySettings(const std::string& nickname, const std::string& keyHex); + void switchChannel(const std::string& chatChannel); + + const ChatSettingsData& getSettings() const { return settings; } + + ~ChatApp() override = default; +}; + +} // namespace tt::app::chat + +#endif // CONFIG_SOC_WIFI_SUPPORTED && !CONFIG_SLAVE_SOC_WIFI_SUPPORTED diff --git a/Tactility/Private/Tactility/app/chat/ChatProtocol.h b/Tactility/Private/Tactility/app/chat/ChatProtocol.h new file mode 100644 index 00000000..d62812e9 --- /dev/null +++ b/Tactility/Private/Tactility/app/chat/ChatProtocol.h @@ -0,0 +1,97 @@ +#pragma once + +#ifdef ESP_PLATFORM +#include +#endif + +#if defined(CONFIG_SOC_WIFI_SUPPORTED) && !defined(CONFIG_SLAVE_SOC_WIFI_SUPPORTED) + +#include +#include +#include +#include + +namespace tt::app::chat { + +// Protocol identification +constexpr uint32_t CHAT_MAGIC_V2 = 0x54435432; // "TCT2" +constexpr uint16_t PROTOCOL_VERSION = 2; + +// Broadcast/channel target ID +constexpr uint32_t BROADCAST_ID = 0; + +// Payload types +enum class PayloadType : uint8_t { + TextMessage = 1, + // Future: Position = 2, Telemetry = 3, etc. +}; + +// Wire format header (16 bytes) +struct __attribute__((packed)) MessageHeader { + uint32_t magic; // CHAT_MAGIC_V2 + uint16_t protocol_version; // PROTOCOL_VERSION + uint32_t from; // Sender ID (random, stored in settings) + uint32_t to; // Recipient ID (0 = broadcast/channel) + uint8_t payload_type; // PayloadType enum + uint8_t payload_size; // Size of payload following header +}; + +static_assert(sizeof(MessageHeader) == 16, "MessageHeader must be 16 bytes"); + +// Size limits +constexpr size_t HEADER_SIZE = sizeof(MessageHeader); +constexpr size_t MAX_PAYLOAD_V1 = 250 - HEADER_SIZE; // 234 bytes for ESP-NOW v1 +constexpr size_t MAX_PAYLOAD_V2 = 1470 - HEADER_SIZE; // 1454 bytes for ESP-NOW v2 + +// Nickname constraints +constexpr size_t MIN_NICKNAME_LEN = 2; // Single-letter names not allowed +constexpr size_t MAX_NICKNAME_LEN = 23; // Max nickname length (excluding null) + +// Target/channel constraints (0 = broadcast allowed) +constexpr size_t MIN_TARGET_LEN = 0; // Empty = broadcast +constexpr size_t MAX_TARGET_LEN = 23; // Max target/channel length (excluding null) + +// Message constraints +constexpr size_t MIN_MESSAGE_LEN = 1; // At least 1 char (e.g. "?") + +// Max message length: 255 (uint8_t payload_size) - nickname - null - target - null +// Using max lengths: 255 - 23 - 1 - 23 - 1 = 207, rounded down for safety +constexpr size_t MAX_MESSAGE_LEN = 200; + +// Parsed message for application use +struct ParsedMessage { + uint32_t senderId; + uint32_t targetId; + std::string senderName; + std::string target; + std::string message; +}; + +/** Serialize a text message into wire format. + * @param senderId Sender's unique ID + * @param targetId Recipient ID (0 for broadcast/channel) + * @param senderName Sender's display name + * @param target Channel name (e.g. "#general") or empty for broadcast + * @param message The message text + * @param out Output buffer (will be resized to fit) + * @return true on success, false if inputs exceed limits + */ +bool serializeTextMessage(uint32_t senderId, uint32_t targetId, + const std::string& senderName, const std::string& target, + const std::string& message, std::vector& out); + +/** Deserialize a received buffer into a ParsedMessage. + * @param data Raw received data + * @param length Length of received data + * @param out Parsed message output + * @return true if valid (correct magic, version, and format) + */ +bool deserializeMessage(const uint8_t* data, size_t length, ParsedMessage& out); + +/** Get maximum message length for current ESP-NOW version. + * Accounts for header + nickname + target overhead. */ +size_t getMaxMessageLength(size_t nicknameLen, size_t targetLen); + +} // namespace tt::app::chat + +#endif // CONFIG_SOC_WIFI_SUPPORTED && !CONFIG_SLAVE_SOC_WIFI_SUPPORTED diff --git a/Tactility/Private/Tactility/app/chat/ChatSettings.h b/Tactility/Private/Tactility/app/chat/ChatSettings.h new file mode 100644 index 00000000..a504c9ac --- /dev/null +++ b/Tactility/Private/Tactility/app/chat/ChatSettings.h @@ -0,0 +1,34 @@ +#pragma once + +#ifdef ESP_PLATFORM +#include +#endif + +#if defined(CONFIG_SOC_WIFI_SUPPORTED) && !defined(CONFIG_SLAVE_SOC_WIFI_SUPPORTED) + +#include +#include +#include + +#include + +namespace tt::app::chat { + +constexpr auto* CHAT_SETTINGS_FILE = "/data/settings/chat.properties"; + +struct ChatSettingsData { + uint32_t senderId = 0; // Unique device ID (randomly generated on first launch) + std::string nickname = "Device"; + std::array encryptionKey = {}; + bool hasEncryptionKey = false; + std::string chatChannel = "#general"; +}; + +ChatSettingsData loadSettings(); +bool saveSettings(const ChatSettingsData& settings); +ChatSettingsData getDefaultSettings(); +bool settingsFileExists(); + +} // namespace tt::app::chat + +#endif // CONFIG_SOC_WIFI_SUPPORTED && !CONFIG_SLAVE_SOC_WIFI_SUPPORTED diff --git a/Tactility/Private/Tactility/app/chat/ChatState.h b/Tactility/Private/Tactility/app/chat/ChatState.h new file mode 100644 index 00000000..eb0d239d --- /dev/null +++ b/Tactility/Private/Tactility/app/chat/ChatState.h @@ -0,0 +1,59 @@ +#pragma once + +#ifdef ESP_PLATFORM +#include +#endif + +#if defined(CONFIG_SOC_WIFI_SUPPORTED) && !defined(CONFIG_SLAVE_SOC_WIFI_SUPPORTED) + +#include + +#include +#include +#include +#include + +namespace tt::app::chat { + +constexpr size_t MAX_MESSAGES = 100; + +struct StoredMessage { + std::string displayText; + std::string target; // for channel filtering + bool isOwn; +}; + +/** Thread safety: All public methods are mutex-protected. + * LVGL sync lock must be held separately when updating UI. */ +class ChatState { + + mutable RecursiveMutex mutex; + + std::deque messages; + std::string currentChannel = "#general"; + std::string localNickname = "Device"; + +public: + ChatState() = default; + ~ChatState() = default; + + ChatState(const ChatState&) = delete; + ChatState& operator=(const ChatState&) = delete; + ChatState(ChatState&&) = delete; + ChatState& operator=(ChatState&&) = delete; + + void setLocalNickname(const std::string& nickname); + std::string getLocalNickname() const; + + void setCurrentChannel(const std::string& channel); + std::string getCurrentChannel() const; + + void addMessage(const StoredMessage& msg); + + /** Returns messages matching the current channel (or broadcast). */ + std::vector getFilteredMessages() const; +}; + +} // namespace tt::app::chat + +#endif // CONFIG_SOC_WIFI_SUPPORTED && !CONFIG_SLAVE_SOC_WIFI_SUPPORTED diff --git a/Tactility/Private/Tactility/app/chat/ChatView.h b/Tactility/Private/Tactility/app/chat/ChatView.h new file mode 100644 index 00000000..e246aaf0 --- /dev/null +++ b/Tactility/Private/Tactility/app/chat/ChatView.h @@ -0,0 +1,79 @@ +#pragma once + +#ifdef ESP_PLATFORM +#include +#endif + +#if defined(CONFIG_SOC_WIFI_SUPPORTED) && !defined(CONFIG_SLAVE_SOC_WIFI_SUPPORTED) + +#include "ChatState.h" +#include "ChatSettings.h" + +#include + +#include +#include + +namespace tt::app::chat { + +class ChatApp; + +class ChatView { + + ChatApp* app; + ChatState* state; + + lv_obj_t* toolbar = nullptr; + lv_obj_t* msgList = nullptr; + lv_obj_t* inputWrapper = nullptr; + lv_obj_t* inputField = nullptr; + + // Settings panel widgets + lv_obj_t* settingsPanel = nullptr; + lv_obj_t* nicknameInput = nullptr; + lv_obj_t* keyInput = nullptr; + + // Channel selector panel widgets + lv_obj_t* channelPanel = nullptr; + lv_obj_t* channelInput = nullptr; + + void createInputBar(lv_obj_t* parent); + void createSettingsPanel(lv_obj_t* parent); + void createChannelPanel(lv_obj_t* parent); + + void updateToolbarTitle(); + + static void addMessageToList(lv_obj_t* msgList, const StoredMessage& msg); + + static void onSendClicked(lv_event_t* e); + static void onSettingsClicked(lv_event_t* e); + static void onSettingsSave(lv_event_t* e); + static void onSettingsCancel(lv_event_t* e); + static void onChannelClicked(lv_event_t* e); + static void onChannelSave(lv_event_t* e); + static void onChannelCancel(lv_event_t* e); + +public: + ChatView(ChatApp* app, ChatState* state) : app(app), state(state) {} + ~ChatView() = default; + + ChatView(const ChatView&) = delete; + ChatView& operator=(const ChatView&) = delete; + ChatView(ChatView&&) = delete; + ChatView& operator=(ChatView&&) = delete; + + void init(AppContext& appContext, lv_obj_t* parent); + + void displayMessage(const StoredMessage& msg); + void refreshMessageList(); + + void showSettings(const ChatSettingsData& current); + void hideSettings(); + + void showChannelSelector(); + void hideChannelSelector(); +}; + +} // namespace tt::app::chat + +#endif // CONFIG_SOC_WIFI_SUPPORTED && !CONFIG_SLAVE_SOC_WIFI_SUPPORTED diff --git a/Tactility/Private/Tactility/service/espnow/EspNowService.h b/Tactility/Private/Tactility/service/espnow/EspNowService.h index d3478240..c54ec35d 100644 --- a/Tactility/Private/Tactility/service/espnow/EspNowService.h +++ b/Tactility/Private/Tactility/service/espnow/EspNowService.h @@ -31,6 +31,7 @@ class EspNowService final : public Service { std::vector subscriptions; ReceiverSubscription lastSubscriptionId = 0; bool enabled = false; + uint32_t espnowVersion = 0; // Dispatcher calls this and forwards to non-static function void enableFromDispatcher(const EspNowConfig& config); @@ -65,6 +66,8 @@ public: void unsubscribeReceiver(ReceiverSubscription subscription); + uint32_t getVersion() const; + // region Internal API }; diff --git a/Tactility/Source/app/chat/ChatApp.cpp b/Tactility/Source/app/chat/ChatApp.cpp index aa349748..20355c41 100644 --- a/Tactility/Source/app/chat/ChatApp.cpp +++ b/Tactility/Source/app/chat/ChatApp.cpp @@ -4,141 +4,179 @@ #if defined(CONFIG_SOC_WIFI_SUPPORTED) && !defined(CONFIG_SLAVE_SOC_WIFI_SUPPORTED) +#include +#include + #include -#include #include #include -#include +#include -#include "Tactility/lvgl/LvglSync.h" - -#include -#include -#include -#include +#include +#include +#include +#include namespace tt::app::chat { static const auto LOGGER = Logger("ChatApp"); -constexpr uint8_t BROADCAST_ADDRESS[ESP_NOW_ETH_ALEN] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; +static constexpr uint8_t BROADCAST_ADDRESS[ESP_NOW_ETH_ALEN] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; -class ChatApp : public App { +void ChatApp::enableEspNow() { + static uint8_t defaultKey[ESP_NOW_KEY_LEN] = {}; + auto config = service::espnow::EspNowConfig( + settings.hasEncryptionKey ? settings.encryptionKey.data() : defaultKey, + service::espnow::Mode::Station, + 1, // Channel 1 default; actual channel determined by WiFi if connected + false, + settings.hasEncryptionKey + ); + service::espnow::enable(config); +} - lv_obj_t* msg_list = nullptr; - lv_obj_t* input_field = nullptr; - service::espnow::ReceiverSubscription receiveSubscription; - - void addMessage(const char* message) { - lv_obj_t* msg_label = lv_label_create(msg_list); - lv_label_set_text(msg_label, message); - lv_obj_set_width(msg_label, lv_pct(100)); - lv_label_set_long_mode(msg_label, LV_LABEL_LONG_WRAP); - lv_obj_set_style_text_align(msg_label, LV_TEXT_ALIGN_LEFT, 0); - lv_obj_set_style_pad_all(msg_label, 2, 0); - lv_obj_scroll_to_y(msg_list, lv_obj_get_scroll_y(msg_list) + 20, LV_ANIM_ON); +void ChatApp::disableEspNow() { + if (service::espnow::isEnabled()) { + service::espnow::disable(); } +} - static void onSendClicked(lv_event_t* e) { - auto* self = static_cast(lv_event_get_user_data(e)); - auto* msg = lv_textarea_get_text(self->input_field); - const auto msg_len = strlen(msg); - - if (self->msg_list && msg && msg_len) { - self->addMessage(msg); - - if (!service::espnow::send(BROADCAST_ADDRESS, reinterpret_cast(msg), msg_len)) { - LOGGER.error("Failed to send message"); - } - - lv_textarea_set_text(self->input_field, ""); - } +void ChatApp::onCreate(AppContext& appContext) { + isFirstLaunch = !settingsFileExists(); + settings = loadSettings(); + state.setLocalNickname(settings.nickname); + if (!settings.chatChannel.empty()) { + state.setCurrentChannel(settings.chatChannel); } + enableEspNow(); - void onReceive(const esp_now_recv_info_t* receiveInfo, const uint8_t* data, int length) { - // Append \0 to make it a string - auto buffer = static_cast(malloc(length + 1)); - memcpy(buffer, data, length); - buffer[length] = 0x00; - const std::string message_prefixed = std::string("Received: ") + buffer; - - lvgl::getSyncLock()->lock(); - addMessage(message_prefixed.c_str()); - lvgl::getSyncLock()->unlock(); - - free(buffer); - } - -public: - - void onCreate(AppContext& appContext) override { - // TODO: Move this to a configuration screen/app - static const uint8_t key[ESP_NOW_KEY_LEN] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - auto config = service::espnow::EspNowConfig( - const_cast(key), - service::espnow::Mode::Station, - 1, - false, - false - ); - - service::espnow::enable(config); - - receiveSubscription = service::espnow::subscribeReceiver([this](const esp_now_recv_info_t* receiveInfo, const uint8_t* data, int length) { + receiveSubscription = service::espnow::subscribeReceiver( + [this](const esp_now_recv_info_t* receiveInfo, const uint8_t* data, int length) { onReceive(receiveInfo, data, length); - }); - } - - void onDestroy(AppContext& appContext) override { - service::espnow::unsubscribeReceiver(receiveSubscription); - - if (service::espnow::isEnabled()) { - service::espnow::disable(); } + ); +} + +void ChatApp::onDestroy(AppContext& appContext) { + service::espnow::unsubscribeReceiver(receiveSubscription); + disableEspNow(); +} + +void ChatApp::onShow(AppContext& context, lv_obj_t* parent) { + view.init(context, parent); + if (isFirstLaunch) { + view.showSettings(settings); + } +} + +void ChatApp::onReceive(const esp_now_recv_info_t* receiveInfo, const uint8_t* data, int length) { + if (length <= 0) return; + + ParsedMessage parsed; + if (!deserializeMessage(data, static_cast(length), parsed)) { + return; } - void onShow(AppContext& context, lv_obj_t* parent) override { - lv_obj_set_flex_flow(parent, LV_FLEX_FLOW_COLUMN); - lv_obj_set_style_pad_row(parent, 0, LV_STATE_DEFAULT); + StoredMessage msg; + msg.displayText = parsed.senderName + ": " + parsed.message; + msg.target = parsed.target; + msg.isOwn = false; - lvgl::toolbar_create(parent, context); + state.addMessage(msg); - // Message list - msg_list = lv_list_create(parent); - lv_obj_set_flex_grow(msg_list, 1); - lv_obj_set_width(msg_list, LV_PCT(100)); - lv_obj_set_flex_grow(msg_list, 1); - lv_obj_set_style_bg_color(msg_list, lv_color_hex(0x262626), 0); - lv_obj_set_style_border_width(msg_list, 1, 0); - lv_obj_set_style_pad_ver(msg_list, 0, 0); - lv_obj_set_style_pad_hor(msg_list, 4, 0); + { + auto lock = lvgl::getSyncLock()->asScopedLock(); + lock.lock(); + view.displayMessage(msg); + } +} - // Input panel - auto* bottom_wrapper = lv_obj_create(parent); - lv_obj_set_flex_flow(bottom_wrapper, LV_FLEX_FLOW_ROW); - lv_obj_set_size(bottom_wrapper, LV_PCT(100), LV_SIZE_CONTENT); - lv_obj_set_style_pad_all(bottom_wrapper, 0, 0); - lv_obj_set_style_pad_column(bottom_wrapper, 4, 0); - lv_obj_set_style_border_opa(bottom_wrapper, 0, LV_STATE_DEFAULT); +void ChatApp::sendMessage(const std::string& text) { + if (text.empty()) return; - // Input field - input_field = lv_textarea_create(bottom_wrapper); - lv_obj_set_flex_grow(input_field, 1); - lv_textarea_set_placeholder_text(input_field, "Type a message..."); - lv_textarea_set_one_line(input_field, true); + std::string nickname = state.getLocalNickname(); + std::string channel = state.getCurrentChannel(); - // Send button - auto* send_btn = lv_button_create(bottom_wrapper); - lv_obj_set_style_margin_all(send_btn, 0, LV_STATE_DEFAULT); - lv_obj_set_style_margin_top(send_btn, 2, LV_STATE_DEFAULT); // Hack to fix alignment - lv_obj_add_event_cb(send_btn, onSendClicked, LV_EVENT_CLICKED, this); - - auto* btn_label = lv_label_create(send_btn); - lv_label_set_text(btn_label, "Send"); - lv_obj_center(btn_label); + std::vector wireMsg; + if (!serializeTextMessage(settings.senderId, BROADCAST_ID, nickname, channel, text, wireMsg)) { + LOGGER.error("Failed to serialize message"); + return; } - ~ChatApp() override = default; -}; + if (!service::espnow::send(BROADCAST_ADDRESS, wireMsg.data(), wireMsg.size())) { + LOGGER.error("Failed to send message"); + return; + } + + StoredMessage msg; + msg.displayText = nickname + ": " + text; + msg.target = channel; + msg.isOwn = true; + + state.addMessage(msg); + + { + auto lock = lvgl::getSyncLock()->asScopedLock(); + lock.lock(); + view.displayMessage(msg); + } +} + +void ChatApp::applySettings(const std::string& nickname, const std::string& keyHex) { + bool needRestart = false; + + // Trim nickname to protocol limit + settings.nickname = nickname.substr(0, MAX_NICKNAME_LEN); + + // Parse hex key + if (keyHex.size() == ESP_NOW_KEY_LEN * 2) { + bool validHex = std::all_of(keyHex.begin(), keyHex.end(), [](unsigned char c) { return std::isxdigit(c); }); + if (validHex) { + uint8_t newKey[ESP_NOW_KEY_LEN]; + for (int i = 0; i < ESP_NOW_KEY_LEN; i++) { + char hex[3] = { keyHex[i * 2], keyHex[i * 2 + 1], 0 }; + newKey[i] = static_cast(strtoul(hex, nullptr, 16)); + } + // Restart if key changed OR if encryption is being enabled + bool wasEnabled = settings.hasEncryptionKey; + if (!wasEnabled || !std::equal(newKey, newKey + ESP_NOW_KEY_LEN, settings.encryptionKey.begin())) { + std::copy(newKey, newKey + ESP_NOW_KEY_LEN, settings.encryptionKey.begin()); + needRestart = true; + } + settings.hasEncryptionKey = true; + } else { + LOGGER.warn("Invalid hex characters in encryption key"); + } + } else if (keyHex.empty()) { + if (settings.hasEncryptionKey) { + settings.encryptionKey.fill(0); + settings.hasEncryptionKey = false; + needRestart = true; + } + } else { + LOGGER.warn("Key must be exactly {} hex characters, got {}", ESP_NOW_KEY_LEN * 2, keyHex.size()); + } + + state.setLocalNickname(settings.nickname); + saveSettings(settings); + + if (needRestart) { + disableEspNow(); + enableEspNow(); + } +} + +void ChatApp::switchChannel(const std::string& chatChannel) { + const auto trimmedChannel = chatChannel.substr(0, MAX_TARGET_LEN); + state.setCurrentChannel(trimmedChannel); + settings.chatChannel = trimmedChannel; + saveSettings(settings); + + { + auto lock = lvgl::getSyncLock()->asScopedLock(); + lock.lock(); + view.refreshMessageList(); + } +} extern const AppManifest manifest = { .appId = "Chat", @@ -147,6 +185,6 @@ extern const AppManifest manifest = { .createApp = create }; -} +} // namespace tt::app::chat #endif // CONFIG_SOC_WIFI_SUPPORTED && !CONFIG_SLAVE_SOC_WIFI_SUPPORTED diff --git a/Tactility/Source/app/chat/ChatProtocol.cpp b/Tactility/Source/app/chat/ChatProtocol.cpp new file mode 100644 index 00000000..e3cc1803 --- /dev/null +++ b/Tactility/Source/app/chat/ChatProtocol.cpp @@ -0,0 +1,174 @@ +#ifdef ESP_PLATFORM +#include +#endif + +#if defined(CONFIG_SOC_WIFI_SUPPORTED) && !defined(CONFIG_SLAVE_SOC_WIFI_SUPPORTED) + +#include +#include + +#include +#include + +namespace tt::app::chat { + +bool serializeTextMessage(uint32_t senderId, uint32_t targetId, + const std::string& senderName, const std::string& target, + const std::string& message, std::vector& out) { + // Validate input lengths (min and max) + if (senderName.size() < MIN_NICKNAME_LEN || senderName.size() > MAX_NICKNAME_LEN) { + return false; + } + if (target.size() > MAX_TARGET_LEN) { + return false; // MIN_TARGET_LEN is 0, so empty (broadcast) is allowed + } + if (message.size() < MIN_MESSAGE_LEN) { + return false; + } + + // Calculate payload size: nickname + null + target + null + message + size_t payloadSize = senderName.size() + 1 + target.size() + 1 + message.size(); + + // Check against ESP-NOW limits (guard against underflow if getMaxDataLength < HEADER_SIZE) + size_t maxData = service::espnow::getMaxDataLength(); + if (maxData <= HEADER_SIZE) { + return false; + } + size_t maxPayload = maxData - HEADER_SIZE; + if (payloadSize > maxPayload || payloadSize > 255) { + return false; // payload_size is uint8_t + } + + // Build header + MessageHeader header = { + .magic = CHAT_MAGIC_V2, + .protocol_version = PROTOCOL_VERSION, + .from = senderId, + .to = targetId, + .payload_type = static_cast(PayloadType::TextMessage), + .payload_size = static_cast(payloadSize) + }; + + // Allocate output buffer + out.resize(HEADER_SIZE + payloadSize); + + // Copy header to output + memcpy(out.data(), &header, HEADER_SIZE); + + // Build payload: nickname\0 + target\0 + message + uint8_t* payload = out.data() + HEADER_SIZE; + size_t offset = 0; + + memcpy(payload + offset, senderName.c_str(), senderName.size() + 1); + offset += senderName.size() + 1; + + memcpy(payload + offset, target.c_str(), target.size() + 1); + offset += target.size() + 1; + + memcpy(payload + offset, message.c_str(), message.size()); + // Note: message is NOT null-terminated in wire format (length is implicit) + + return true; +} + +bool deserializeMessage(const uint8_t* data, size_t length, ParsedMessage& out) { + // Minimum: header + min_nickname + null + min_target + null + min_message + // = 16 + 2 + 1 + 0 + 1 + 1 = 21 bytes + constexpr size_t MIN_PACKET_SIZE = HEADER_SIZE + MIN_NICKNAME_LEN + 1 + MIN_TARGET_LEN + 1 + MIN_MESSAGE_LEN; + if (length < MIN_PACKET_SIZE) { + return false; + } + + // Copy header to aligned struct + MessageHeader header; + memcpy(&header, data, HEADER_SIZE); + + // Validate header + if (header.magic != CHAT_MAGIC_V2) { + return false; + } + + if (header.protocol_version != PROTOCOL_VERSION) { + return false; + } + + // Validate payload size + if (header.payload_size != length - HEADER_SIZE) { + return false; + } + + // Only handle text messages for now + if (header.payload_type != static_cast(PayloadType::TextMessage)) { + return false; + } + + // Parse payload + const uint8_t* payload = data + HEADER_SIZE; + size_t payloadLen = header.payload_size; + + // Find nickname (null-terminated) + const char* nicknameStart = reinterpret_cast(payload); + size_t nicknameLen = strnlen(nicknameStart, payloadLen); + if (nicknameLen >= payloadLen) { + return false; // No null terminator found + } + + size_t offset = nicknameLen + 1; + size_t remaining = payloadLen - offset; + + // Find target (null-terminated) + const char* targetStart = reinterpret_cast(payload + offset); + size_t targetLen = strnlen(targetStart, remaining); + if (targetLen >= remaining) { + return false; // No null terminator found + } + + offset += targetLen + 1; + remaining = payloadLen - offset; + + // Rest is the message (not null-terminated) + const char* messageStart = reinterpret_cast(payload + offset); + + // Validate field lengths (min and max) + if (nicknameLen < MIN_NICKNAME_LEN || nicknameLen > MAX_NICKNAME_LEN) { + return false; + } + if (targetLen > MAX_TARGET_LEN) { + return false; + } + if (remaining < MIN_MESSAGE_LEN) { + return false; + } + + // Populate output + out.senderId = header.from; + out.targetId = header.to; + out.senderName = std::string(nicknameStart, nicknameLen); + out.target = std::string(targetStart, targetLen); + out.message = std::string(messageStart, remaining); + + return true; +} + +size_t getMaxMessageLength(size_t nicknameLen, size_t targetLen) { + // Guard against underflow if getMaxDataLength < HEADER_SIZE + size_t maxData = service::espnow::getMaxDataLength(); + if (maxData <= HEADER_SIZE) { + return 0; + } + size_t maxPayload = maxData - HEADER_SIZE; + + // Payload: nickname + null + target + null + message + size_t overhead = nicknameLen + 1 + targetLen + 1; + if (overhead >= maxPayload || overhead > 255) { + return 0; + } + // Cap at 255 since payload_size is uint8_t + size_t maxFromEspNow = maxPayload - overhead; + size_t maxFromPayloadSize = 255 - overhead; + return std::min(maxFromEspNow, maxFromPayloadSize); +} + +} // namespace tt::app::chat + +#endif // CONFIG_SOC_WIFI_SUPPORTED && !CONFIG_SLAVE_SOC_WIFI_SUPPORTED diff --git a/Tactility/Source/app/chat/ChatSettings.cpp b/Tactility/Source/app/chat/ChatSettings.cpp new file mode 100644 index 00000000..f4ac8417 --- /dev/null +++ b/Tactility/Source/app/chat/ChatSettings.cpp @@ -0,0 +1,183 @@ +#ifdef ESP_PLATFORM +#include +#endif + +#if defined(CONFIG_SOC_WIFI_SUPPORTED) && !defined(CONFIG_SLAVE_SOC_WIFI_SUPPORTED) + +#include +#include + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace tt::app::chat { + +static const auto LOGGER = Logger("ChatSettings"); + +constexpr auto* KEY_SENDER_ID = "senderId"; +constexpr auto* KEY_NICKNAME = "nickname"; +constexpr auto* KEY_ENCRYPTION_KEY = "encryptionKey"; +constexpr auto* KEY_CHAT_CHANNEL = "chatChannel"; + +// IV_SEED provides basic obfuscation for stored encryption keys, not strong encryption. +// The device master key (from crypt::getIv) provides the actual security. +static constexpr auto* IV_SEED = "chat_key"; + +static std::string toHexString(const uint8_t* data, size_t length) { + std::stringstream stream; + stream << std::hex; + for (size_t i = 0; i < length; ++i) { + stream << std::setw(2) << std::setfill('0') << static_cast(data[i]); + } + return stream.str(); +} + +static bool readHex(const std::string& input, uint8_t* buffer, size_t length) { + if (input.size() != length * 2) { + LOGGER.error("readHex() length mismatch"); + return false; + } + + char hex[3] = { 0 }; + for (size_t i = 0; i < length; i++) { + hex[0] = input[i * 2]; + hex[1] = input[i * 2 + 1]; + char* endptr; + unsigned long val = strtoul(hex, &endptr, 16); + if (endptr != hex + 2) { + LOGGER.error("readHex() invalid hex character"); + return false; + } + buffer[i] = static_cast(val); + } + return true; +} + +static bool encryptKey(const uint8_t key[ESP_NOW_KEY_LEN], std::string& hexOutput) { + uint8_t iv[16]; + crypt::getIv(IV_SEED, std::strlen(IV_SEED), iv); + + uint8_t encrypted[ESP_NOW_KEY_LEN]; + if (crypt::encrypt(iv, key, encrypted, ESP_NOW_KEY_LEN) != 0) { + LOGGER.error("Failed to encrypt key"); + return false; + } + + hexOutput = toHexString(encrypted, ESP_NOW_KEY_LEN); + return true; +} + +static bool decryptKey(const std::string& hexInput, uint8_t key[ESP_NOW_KEY_LEN]) { + if (hexInput.size() != ESP_NOW_KEY_LEN * 2) { + return false; + } + + uint8_t encrypted[ESP_NOW_KEY_LEN]; + if (!readHex(hexInput, encrypted, ESP_NOW_KEY_LEN)) { + return false; + } + + uint8_t iv[16]; + crypt::getIv(IV_SEED, std::strlen(IV_SEED), iv); + + if (crypt::decrypt(iv, encrypted, key, ESP_NOW_KEY_LEN) != 0) { + LOGGER.error("Failed to decrypt key"); + return false; + } + return true; +} + +/** Generate a non-zero random sender ID using hardware RNG. */ +static uint32_t generateSenderId() { + uint32_t id; + do { + id = esp_random(); + } while (id == 0); + return id; +} + +ChatSettingsData getDefaultSettings() { + return ChatSettingsData{ + .senderId = 0, + .nickname = "Device", + .encryptionKey = {}, + .hasEncryptionKey = false, + .chatChannel = "#general" + }; +} + +ChatSettingsData loadSettings() { + ChatSettingsData settings = getDefaultSettings(); + + std::map map; + if (!file::loadPropertiesFile(CHAT_SETTINGS_FILE, map)) { + settings.senderId = generateSenderId(); + return settings; + } + + auto it = map.find(KEY_SENDER_ID); + if (it != map.end() && !it->second.empty()) { + settings.senderId = static_cast(strtoul(it->second.c_str(), nullptr, 10)); + } + // Generate sender ID if missing or zero + if (settings.senderId == 0) { + settings.senderId = generateSenderId(); + } + + it = map.find(KEY_NICKNAME); + if (it != map.end() && !it->second.empty()) { + settings.nickname = it->second.substr(0, MAX_NICKNAME_LEN); + } + + it = map.find(KEY_ENCRYPTION_KEY); + if (it != map.end() && !it->second.empty()) { + if (decryptKey(it->second, settings.encryptionKey.data())) { + settings.hasEncryptionKey = true; + } + } + + it = map.find(KEY_CHAT_CHANNEL); + if (it != map.end() && !it->second.empty()) { + settings.chatChannel = it->second.substr(0, MAX_TARGET_LEN); + } + + return settings; +} + +bool saveSettings(const ChatSettingsData& settings) { + std::map map; + + map[KEY_SENDER_ID] = std::to_string(settings.senderId); + map[KEY_NICKNAME] = settings.nickname; + map[KEY_CHAT_CHANNEL] = settings.chatChannel; + + if (settings.hasEncryptionKey) { + std::string encryptedHex; + if (!encryptKey(settings.encryptionKey.data(), encryptedHex)) { + return false; + } + map[KEY_ENCRYPTION_KEY] = encryptedHex; + } else { + map[KEY_ENCRYPTION_KEY] = ""; + } + + return file::savePropertiesFile(CHAT_SETTINGS_FILE, map); +} + +bool settingsFileExists() { + return access(CHAT_SETTINGS_FILE, F_OK) == 0; +} + +} // namespace tt::app::chat + +#endif // CONFIG_SOC_WIFI_SUPPORTED && !CONFIG_SLAVE_SOC_WIFI_SUPPORTED diff --git a/Tactility/Source/app/chat/ChatState.cpp b/Tactility/Source/app/chat/ChatState.cpp new file mode 100644 index 00000000..100650e2 --- /dev/null +++ b/Tactility/Source/app/chat/ChatState.cpp @@ -0,0 +1,60 @@ +#ifdef ESP_PLATFORM +#include +#endif + +#if defined(CONFIG_SOC_WIFI_SUPPORTED) && !defined(CONFIG_SLAVE_SOC_WIFI_SUPPORTED) + +#include + +namespace tt::app::chat { + +void ChatState::setLocalNickname(const std::string& nickname) { + auto lock = mutex.asScopedLock(); + lock.lock(); + localNickname = nickname; +} + +std::string ChatState::getLocalNickname() const { + auto lock = mutex.asScopedLock(); + lock.lock(); + return localNickname; +} + +void ChatState::setCurrentChannel(const std::string& channel) { + auto lock = mutex.asScopedLock(); + lock.lock(); + currentChannel = channel; +} + +std::string ChatState::getCurrentChannel() const { + auto lock = mutex.asScopedLock(); + lock.lock(); + return currentChannel; +} + +void ChatState::addMessage(const StoredMessage& msg) { + auto lock = mutex.asScopedLock(); + lock.lock(); + if (messages.size() >= MAX_MESSAGES) { + messages.pop_front(); + } + messages.push_back(msg); +} + +std::vector ChatState::getFilteredMessages() const { + auto lock = mutex.asScopedLock(); + lock.lock(); + std::vector result; + result.reserve(messages.size()); // Avoid reallocations; may over-allocate slightly + for (const auto& msg : messages) { + // Show if broadcast (empty target) or matches current channel + if (msg.target.empty() || msg.target == currentChannel) { + result.push_back(msg); + } + } + return result; +} + +} // namespace tt::app::chat + +#endif // CONFIG_SOC_WIFI_SUPPORTED && !CONFIG_SLAVE_SOC_WIFI_SUPPORTED diff --git a/Tactility/Source/app/chat/ChatView.cpp b/Tactility/Source/app/chat/ChatView.cpp new file mode 100644 index 00000000..6372800b --- /dev/null +++ b/Tactility/Source/app/chat/ChatView.cpp @@ -0,0 +1,295 @@ +#ifdef ESP_PLATFORM +#include +#endif + +#if defined(CONFIG_SOC_WIFI_SUPPORTED) && !defined(CONFIG_SLAVE_SOC_WIFI_SUPPORTED) + +#include +#include +#include + +#include + +#include +#include + +namespace tt::app::chat { + +void ChatView::addMessageToList(lv_obj_t* list, const StoredMessage& msg) { + auto* label = lv_label_create(list); + lv_label_set_text(label, msg.displayText.c_str()); + lv_obj_set_width(label, lv_pct(100)); + lv_label_set_long_mode(label, LV_LABEL_LONG_WRAP); + lv_obj_set_style_text_align(label, LV_TEXT_ALIGN_LEFT, 0); + lv_obj_set_style_pad_all(label, 2, 0); + + if (msg.isOwn) { + lv_obj_set_style_text_color(label, lv_color_hex(0x80C0FF), 0); + } +} + +void ChatView::updateToolbarTitle() { + if (!state || !toolbar) return; + std::string channel = state->getCurrentChannel(); + std::string title = "Chat: " + channel; + lvgl::toolbar_set_title(toolbar, title); +} + +void ChatView::createInputBar(lv_obj_t* parent) { + inputWrapper = lv_obj_create(parent); + auto* wrapper = inputWrapper; + lv_obj_set_flex_flow(wrapper, LV_FLEX_FLOW_ROW); + lv_obj_set_size(wrapper, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_style_pad_all(wrapper, 0, 0); + lv_obj_set_style_pad_column(wrapper, 4, 0); + lv_obj_set_style_border_opa(wrapper, 0, LV_STATE_DEFAULT); + + inputField = lv_textarea_create(wrapper); + lv_obj_set_flex_grow(inputField, 1); + lv_textarea_set_placeholder_text(inputField, "Type a message..."); + lv_textarea_set_one_line(inputField, true); + lv_textarea_set_max_length(inputField, MAX_MESSAGE_LEN); + + auto* sendBtn = lv_button_create(wrapper); + lv_obj_set_style_margin_all(sendBtn, 0, LV_STATE_DEFAULT); + lv_obj_set_style_margin_top(sendBtn, 2, LV_STATE_DEFAULT); + lv_obj_add_event_cb(sendBtn, onSendClicked, LV_EVENT_CLICKED, this); + + auto* btnLabel = lv_label_create(sendBtn); + lv_label_set_text(btnLabel, "Send"); + lv_obj_center(btnLabel); +} + +void ChatView::createSettingsPanel(lv_obj_t* parent) { + settingsPanel = lv_obj_create(parent); + lv_obj_set_width(settingsPanel, LV_PCT(100)); + lv_obj_set_flex_grow(settingsPanel, 1); + lv_obj_set_flex_flow(settingsPanel, LV_FLEX_FLOW_COLUMN); + lv_obj_set_style_pad_all(settingsPanel, 8, 0); + lv_obj_set_style_pad_row(settingsPanel, 6, 0); + lv_obj_add_flag(settingsPanel, LV_OBJ_FLAG_HIDDEN); + + // Nickname + auto* nickLabel = lv_label_create(settingsPanel); + lv_label_set_text(nickLabel, "Nickname (max 23):"); + + nicknameInput = lv_textarea_create(settingsPanel); + lv_obj_set_width(nicknameInput, LV_PCT(100)); + lv_textarea_set_one_line(nicknameInput, true); + lv_textarea_set_max_length(nicknameInput, MAX_NICKNAME_LEN); + + // Encryption key + auto* keyLabel = lv_label_create(settingsPanel); + lv_label_set_text(keyLabel, "Key (32 hex chars):"); + + keyInput = lv_textarea_create(settingsPanel); + lv_obj_set_width(keyInput, LV_PCT(100)); + lv_textarea_set_one_line(keyInput, true); + lv_textarea_set_max_length(keyInput, ESP_NOW_KEY_LEN * 2); + lv_textarea_set_placeholder_text(keyInput, "empty = all zeros"); + + // Buttons + auto* btnRow = lv_obj_create(settingsPanel); + lv_obj_set_flex_flow(btnRow, LV_FLEX_FLOW_ROW); + lv_obj_set_size(btnRow, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_style_pad_all(btnRow, 0, 0); + lv_obj_set_style_pad_column(btnRow, 8, 0); + lv_obj_set_style_border_opa(btnRow, 0, 0); + + auto* saveBtn = lv_button_create(btnRow); + lv_obj_add_event_cb(saveBtn, onSettingsSave, LV_EVENT_CLICKED, this); + auto* saveLbl = lv_label_create(saveBtn); + lv_label_set_text(saveLbl, "Save"); + + auto* cancelBtn = lv_button_create(btnRow); + lv_obj_add_event_cb(cancelBtn, onSettingsCancel, LV_EVENT_CLICKED, this); + auto* cancelLbl = lv_label_create(cancelBtn); + lv_label_set_text(cancelLbl, "Cancel"); +} + +void ChatView::createChannelPanel(lv_obj_t* parent) { + channelPanel = lv_obj_create(parent); + lv_obj_set_width(channelPanel, LV_PCT(100)); + lv_obj_set_flex_grow(channelPanel, 1); + lv_obj_set_flex_flow(channelPanel, LV_FLEX_FLOW_COLUMN); + lv_obj_set_style_pad_all(channelPanel, 8, 0); + lv_obj_set_style_pad_row(channelPanel, 6, 0); + lv_obj_add_flag(channelPanel, LV_OBJ_FLAG_HIDDEN); + + auto* label = lv_label_create(channelPanel); + lv_label_set_text(label, "Channel (e.g. #general):"); + + channelInput = lv_textarea_create(channelPanel); + lv_obj_set_width(channelInput, LV_PCT(100)); + lv_textarea_set_one_line(channelInput, true); + lv_textarea_set_max_length(channelInput, MAX_TARGET_LEN); + + auto* btnRow = lv_obj_create(channelPanel); + lv_obj_set_flex_flow(btnRow, LV_FLEX_FLOW_ROW); + lv_obj_set_size(btnRow, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_style_pad_all(btnRow, 0, 0); + lv_obj_set_style_pad_column(btnRow, 8, 0); + lv_obj_set_style_border_opa(btnRow, 0, 0); + + auto* okBtn = lv_button_create(btnRow); + lv_obj_add_event_cb(okBtn, onChannelSave, LV_EVENT_CLICKED, this); + auto* okLbl = lv_label_create(okBtn); + lv_label_set_text(okLbl, "OK"); + + auto* cancelBtn = lv_button_create(btnRow); + lv_obj_add_event_cb(cancelBtn, onChannelCancel, LV_EVENT_CLICKED, this); + auto* cancelLbl = lv_label_create(cancelBtn); + lv_label_set_text(cancelLbl, "Cancel"); +} + +void ChatView::init(AppContext& appContext, lv_obj_t* parent) { + lv_obj_set_flex_flow(parent, LV_FLEX_FLOW_COLUMN); + lv_obj_set_style_pad_row(parent, 0, LV_STATE_DEFAULT); + + toolbar = lvgl::toolbar_create(parent, appContext); + lvgl::toolbar_add_text_button_action(toolbar, LV_SYMBOL_LIST, onChannelClicked, this); + lvgl::toolbar_add_text_button_action(toolbar, LV_SYMBOL_SETTINGS, onSettingsClicked, this); + updateToolbarTitle(); + + // Message list + msgList = lv_list_create(parent); + lv_obj_set_flex_grow(msgList, 1); + lv_obj_set_width(msgList, LV_PCT(100)); + lv_obj_set_style_bg_color(msgList, lv_color_hex(0x262626), 0); + lv_obj_set_style_border_width(msgList, 0, 0); + lv_obj_set_style_pad_ver(msgList, 2, 0); + lv_obj_set_style_pad_hor(msgList, 4, 0); + + // Input bar + createInputBar(parent); + + // Overlay panels (hidden by default) + createSettingsPanel(parent); + createChannelPanel(parent); +} + +void ChatView::displayMessage(const StoredMessage& msg) { + if (!msgList || !state) return; + + // Only show if matches current channel or broadcast + std::string channel = state->getCurrentChannel(); + if (!msg.target.empty() && msg.target != channel) { + return; + } + addMessageToList(msgList, msg); + lv_obj_scroll_to_y(msgList, LV_COORD_MAX, LV_ANIM_ON); +} + +void ChatView::refreshMessageList() { + if (!msgList || !state) return; + + lv_obj_clean(msgList); + auto filtered = state->getFilteredMessages(); + for (const auto& msg : filtered) { + addMessageToList(msgList, msg); + } + lv_obj_scroll_to_y(msgList, LV_COORD_MAX, LV_ANIM_OFF); + updateToolbarTitle(); +} + +void ChatView::showSettings(const ChatSettingsData& current) { + if (!settingsPanel) return; + + lv_textarea_set_text(nicknameInput, current.nickname.c_str()); + + if (current.hasEncryptionKey) { + char hexStr[ESP_NOW_KEY_LEN * 2 + 1] = {}; + for (size_t i = 0; i < ESP_NOW_KEY_LEN; i++) { + snprintf(hexStr + i * 2, 3, "%02x", current.encryptionKey[i]); + } + lv_textarea_set_text(keyInput, hexStr); + } else { + lv_textarea_set_text(keyInput, ""); + } + + lv_obj_add_flag(msgList, LV_OBJ_FLAG_HIDDEN); + lv_obj_add_flag(inputWrapper, LV_OBJ_FLAG_HIDDEN); + lv_obj_remove_flag(settingsPanel, LV_OBJ_FLAG_HIDDEN); +} + +void ChatView::hideSettings() { + if (!settingsPanel || !msgList || !inputWrapper) return; + lv_obj_add_flag(settingsPanel, LV_OBJ_FLAG_HIDDEN); + lv_obj_remove_flag(msgList, LV_OBJ_FLAG_HIDDEN); + lv_obj_remove_flag(inputWrapper, LV_OBJ_FLAG_HIDDEN); +} + +void ChatView::showChannelSelector() { + if (!channelPanel || !state) return; + + std::string current = state->getCurrentChannel(); + lv_textarea_set_text(channelInput, current.c_str()); + + lv_obj_add_flag(msgList, LV_OBJ_FLAG_HIDDEN); + lv_obj_add_flag(inputWrapper, LV_OBJ_FLAG_HIDDEN); + lv_obj_remove_flag(channelPanel, LV_OBJ_FLAG_HIDDEN); +} + +void ChatView::hideChannelSelector() { + if (!channelPanel || !msgList || !inputWrapper) return; + lv_obj_add_flag(channelPanel, LV_OBJ_FLAG_HIDDEN); + lv_obj_remove_flag(msgList, LV_OBJ_FLAG_HIDDEN); + lv_obj_remove_flag(inputWrapper, LV_OBJ_FLAG_HIDDEN); +} + +void ChatView::onSendClicked(lv_event_t* e) { + auto* self = static_cast(lv_event_get_user_data(e)); + auto* text = lv_textarea_get_text(self->inputField); + if (text && strlen(text) > 0) { + self->app->sendMessage(std::string(text)); + lv_textarea_set_text(self->inputField, ""); + } +} + +void ChatView::onSettingsClicked(lv_event_t* e) { + auto* self = static_cast(lv_event_get_user_data(e)); + self->showSettings(self->app->getSettings()); +} + +void ChatView::onSettingsSave(lv_event_t* e) { + auto* self = static_cast(lv_event_get_user_data(e)); + + auto* nickname = lv_textarea_get_text(self->nicknameInput); + auto* keyHex = lv_textarea_get_text(self->keyInput); + + if (nickname && strlen(nickname) > 0) { + self->app->applySettings( + std::string(nickname), + keyHex ? std::string(keyHex) : std::string() + ); + } + self->hideSettings(); +} + +void ChatView::onSettingsCancel(lv_event_t* e) { + auto* self = static_cast(lv_event_get_user_data(e)); + self->hideSettings(); +} + +void ChatView::onChannelClicked(lv_event_t* e) { + auto* self = static_cast(lv_event_get_user_data(e)); + self->showChannelSelector(); +} + +void ChatView::onChannelSave(lv_event_t* e) { + auto* self = static_cast(lv_event_get_user_data(e)); + auto* text = lv_textarea_get_text(self->channelInput); + if (text && strlen(text) > 0) { + self->app->switchChannel(std::string(text)); + } + self->hideChannelSelector(); +} + +void ChatView::onChannelCancel(lv_event_t* e) { + auto* self = static_cast(lv_event_get_user_data(e)); + self->hideChannelSelector(); +} + +} // namespace tt::app::chat + +#endif // CONFIG_SOC_WIFI_SUPPORTED && !CONFIG_SLAVE_SOC_WIFI_SUPPORTED diff --git a/Tactility/Source/app/gpssettings/GpsSettings.cpp b/Tactility/Source/app/gpssettings/GpsSettings.cpp index 2316648b..cbcceb1b 100644 --- a/Tactility/Source/app/gpssettings/GpsSettings.cpp +++ b/Tactility/Source/app/gpssettings/GpsSettings.cpp @@ -30,6 +30,12 @@ class GpsSettingsApp final : public App { std::shared_ptr appReference = std::make_shared(this); lv_obj_t* statusWrapper = nullptr; lv_obj_t* statusLabelWidget = nullptr; + lv_obj_t* statusLatitudeValue = nullptr; + lv_obj_t* statusLongitudeValue = nullptr; + lv_obj_t* statusAltitudeValue = nullptr; + lv_obj_t* statusSpeedValue = nullptr; + lv_obj_t* statusHeadingValue = nullptr; + lv_obj_t* statusSatellitesValue = nullptr; lv_obj_t* switchWidget = nullptr; lv_obj_t* spinnerWidget = nullptr; lv_obj_t* infoContainerWidget = nullptr; @@ -203,14 +209,79 @@ class GpsSettingsApp final : public App { } minmea_sentence_rmc rmc; + char buffer[64]; if (service->getCoordinates(rmc)) { + lv_label_set_text(statusLabelWidget, "Lock acquired"); + lv_obj_set_style_text_color(statusLabelWidget, lv_color_hex(0x00ff00), 0); + minmea_float latitude = { rmc.latitude.value, rmc.latitude.scale }; minmea_float longitude = { rmc.longitude.value, rmc.longitude.scale }; - auto label_text = std::format("LAT {}\nLON {}", minmea_tocoord(&latitude), minmea_tocoord(&longitude)); - lv_label_set_text(statusLabelWidget, label_text.c_str()); + + double latCoord = minmea_tocoord(&latitude); + double lonCoord = minmea_tocoord(&longitude); + if (isnan(latCoord) || isnan(lonCoord)) { + lv_label_set_text(statusLatitudeValue, "--"); + lv_label_set_text(statusLongitudeValue, "--"); + } else { + const char* latDir = (latCoord >= 0) ? "N" : "S"; + const char* lonDir = (lonCoord >= 0) ? "E" : "W"; + + snprintf(buffer, sizeof(buffer), "%.6f %s", std::abs(latCoord), latDir); + lv_label_set_text(statusLatitudeValue, buffer); + + snprintf(buffer, sizeof(buffer), "%.6f %s", std::abs(lonCoord), lonDir); + lv_label_set_text(statusLongitudeValue, buffer); + } + + float speedKnots = minmea_tofloat(&rmc.speed); + if (!isnan(speedKnots)) { + float speedKmh = speedKnots * 1.852f; + snprintf(buffer, sizeof(buffer), "%.1f km/h", speedKmh); + lv_label_set_text(statusSpeedValue, buffer); + } else { + lv_label_set_text(statusSpeedValue, "--"); + } + + float heading = minmea_tofloat(&rmc.course); + if (!isnan(heading)) { + // Normalize heading to [0, 360) range + heading = fmodf(heading, 360.0f); + if (heading < 0) heading += 360.0f; + const char* dirs[] = {"N", "NE", "E", "SE", "S", "SW", "W", "NW"}; + // Calculate cardinal direction index (0-7) + int idx = (int)((heading + 22.5f) / 45.0f) % 8; + snprintf(buffer, sizeof(buffer), "%.0f° %s", heading, dirs[idx]); + lv_label_set_text(statusHeadingValue, buffer); + } else { + lv_label_set_text(statusHeadingValue, "--"); + } + } else { lv_label_set_text(statusLabelWidget, "Acquiring lock..."); + lv_obj_set_style_text_color(statusLabelWidget, lv_color_hex(0xffaa00), 0); + lv_label_set_text(statusLatitudeValue, "--"); + lv_label_set_text(statusLongitudeValue, "--"); + lv_label_set_text(statusSpeedValue, "--"); + lv_label_set_text(statusHeadingValue, "--"); } + + minmea_sentence_gga gga; + if (service->getGga(gga)) { + float altitude = minmea_tofloat(&gga.altitude); + if (!isnan(altitude)) { + snprintf(buffer, sizeof(buffer), "%.1f m", altitude); + lv_label_set_text(statusAltitudeValue, buffer); + } else { + lv_label_set_text(statusAltitudeValue, "--"); + } + + snprintf(buffer, sizeof(buffer), "%d", gga.satellites_tracked); + lv_label_set_text(statusSatellitesValue, buffer); + } else { + lv_label_set_text(statusAltitudeValue, "--"); + lv_label_set_text(statusSatellitesValue, "--"); + } + lv_obj_remove_flag(statusLabelWidget, LV_OBJ_FLAG_HIDDEN); } else { if (hasSetInfo) { @@ -266,6 +337,28 @@ class GpsSettingsApp final : public App { } } + lv_obj_t* createInfoRow(lv_obj_t* parent, const char* labelText, lv_color_t color) { + lv_obj_t* row = lv_obj_create(parent); + lv_obj_set_size(row, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_flex_flow(row, LV_FLEX_FLOW_ROW); + lv_obj_set_flex_align(row, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_START); + + lv_obj_set_style_pad_all(row, 0, 0); + lv_obj_set_style_pad_right(row, 10, 0); + lv_obj_set_style_border_width(row, 0, 0); + lv_obj_set_style_bg_opa(row, LV_OPA_TRANSP, 0); + + lv_obj_t* label = lv_label_create(row); + lv_label_set_text(label, labelText); + lv_obj_set_style_text_color(label, lv_palette_lighten(LV_PALETTE_GREY, 5), 0); + + lv_obj_t* value = lv_label_create(row); + lv_label_set_text(value, "--"); + lv_obj_set_style_text_color(value, color, 0); + + return value; + } + public: GpsSettingsApp() { @@ -297,20 +390,29 @@ public: statusWrapper = lv_obj_create(main_wrapper); lv_obj_set_width(statusWrapper, LV_PCT(100)); lv_obj_set_height(statusWrapper, LV_SIZE_CONTENT); + lv_obj_set_flex_flow(statusWrapper, LV_FLEX_FLOW_COLUMN); + lv_obj_set_flex_align(statusWrapper, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); lv_obj_set_style_pad_all(statusWrapper, 0, 0); + lv_obj_set_style_pad_row(statusWrapper, 8, 0); lv_obj_set_style_border_width(statusWrapper, 0, 0); statusLabelWidget = lv_label_create(statusWrapper); - lv_obj_align(statusLabelWidget, LV_ALIGN_TOP_LEFT, 0, 0); infoContainerWidget = lv_obj_create(statusWrapper); - lv_obj_align_to(infoContainerWidget, statusLabelWidget, LV_ALIGN_OUT_BOTTOM_LEFT, 0, 20); lv_obj_set_size(infoContainerWidget, LV_PCT(100), LV_SIZE_CONTENT); lv_obj_set_flex_flow(infoContainerWidget, LV_FLEX_FLOW_COLUMN); lv_obj_set_style_border_width(infoContainerWidget, 0, 0); - lv_obj_set_style_pad_all(infoContainerWidget, 0, 0); + lv_obj_set_style_pad_row(infoContainerWidget, 5, 0); + lv_obj_set_style_pad_hor(infoContainerWidget, 10, 0); hasSetInfo = false; + statusLatitudeValue = createInfoRow(infoContainerWidget, "Latitude", lv_color_hex(0x00ff00)); + statusLongitudeValue = createInfoRow(infoContainerWidget, "Longitude", lv_color_hex(0x00ff00)); + statusAltitudeValue = createInfoRow(infoContainerWidget, "Altitude", lv_color_hex(0x00ffff)); + statusSpeedValue = createInfoRow(infoContainerWidget, "Speed", lv_color_hex(0xffff00)); + statusHeadingValue = createInfoRow(infoContainerWidget, "Heading", lv_color_hex(0xff88ff)); + statusSatellitesValue = createInfoRow(infoContainerWidget, "Satellites", lv_color_hex(0xffffff)); + serviceStateSubscription = service->getStatePubsub()->subscribe([this](auto) { onServiceStateChanged(); }); diff --git a/Tactility/Source/service/espnow/EspNow.cpp b/Tactility/Source/service/espnow/EspNow.cpp index 42c934e3..2fd1a06a 100644 --- a/Tactility/Source/service/espnow/EspNow.cpp +++ b/Tactility/Source/service/espnow/EspNow.cpp @@ -36,6 +36,7 @@ bool isEnabled() { if (service != nullptr) { return service->isEnabled(); } else { + LOGGER.error("Service not found"); return false; } } @@ -79,6 +80,21 @@ void unsubscribeReceiver(ReceiverSubscription subscription) { } } +uint32_t getVersion() { + auto service = findService(); + if (service != nullptr) { + return service->getVersion(); + } + LOGGER.error("Service not found"); + return 0; +} + +size_t getMaxDataLength() { + auto v = getVersion(); + if (v == 0) return 0; + return v >= 2 ? MAX_DATA_LEN_V2 : MAX_DATA_LEN_V1; +} + } #endif // CONFIG_SOC_WIFI_SUPPORTED && !CONFIG_SLAVE_SOC_WIFI_SUPPORTED diff --git a/Tactility/Source/service/espnow/EspNowService.cpp b/Tactility/Source/service/espnow/EspNowService.cpp index 476b1b7c..432f3344 100644 --- a/Tactility/Source/service/espnow/EspNowService.cpp +++ b/Tactility/Source/service/espnow/EspNowService.cpp @@ -74,16 +74,23 @@ void EspNowService::enableFromDispatcher(const EspNowConfig& config) { return; } -//#if CONFIG_ESPNOW_ENABLE_POWER_SAVE -// ESP_ERROR_CHECK( esp_now_set_wake_window(CONFIG_ESPNOW_WAKE_WINDOW) ); -// ESP_ERROR_CHECK( esp_wifi_connectionless_module_set_wake_interval(CONFIG_ESPNOW_WAKE_INTERVAL) ); -//#endif + //#if CONFIG_ESPNOW_ENABLE_POWER_SAVE + // ESP_ERROR_CHECK( esp_now_set_wake_window(CONFIG_ESPNOW_WAKE_WINDOW) ); + // ESP_ERROR_CHECK( esp_wifi_connectionless_module_set_wake_interval(CONFIG_ESPNOW_WAKE_INTERVAL) ); + //#endif if (esp_now_set_pmk(config.masterKey) != ESP_OK) { LOGGER.error("esp_now_set_pmk() failed"); return; } + espnowVersion = 0; + if (esp_now_get_version(&espnowVersion) == ESP_OK) { + LOGGER.info("ESP-NOW version: {}.0", espnowVersion); + } else { + LOGGER.warn("Failed to get ESP-NOW version"); + } + // Add default unencrypted broadcast peer esp_now_peer_info_t broadcast_peer; memset(&broadcast_peer, 0, sizeof(esp_now_peer_info_t)); @@ -119,6 +126,7 @@ void EspNowService::disableFromDispatcher() { LOGGER.error("deinitWifi() failed"); } + espnowVersion = 0; enabled = false; } @@ -195,6 +203,12 @@ void EspNowService::unsubscribeReceiver(ReceiverSubscription subscriptionId) { std::erase_if(subscriptions, [subscriptionId](auto& subscription) { return subscription.id == subscriptionId; }); } +uint32_t EspNowService::getVersion() const { + auto lock = mutex.asScopedLock(); + lock.lock(); + return espnowVersion; +} + std::shared_ptr findService() { return std::static_pointer_cast( findServiceById(manifest.id) diff --git a/Tactility/Source/service/gps/GpsService.cpp b/Tactility/Source/service/gps/GpsService.cpp index 69cc251c..359b0269 100644 --- a/Tactility/Source/service/gps/GpsService.cpp +++ b/Tactility/Source/service/gps/GpsService.cpp @@ -37,7 +37,7 @@ void GpsService::addGpsDevice(const std::shared_ptr& device) { GpsDeviceRecord record = {.device = device}; - if (getState() == State::On) { // Ignore during OnPending due to risk of data corruptiohn + if (getState() == State::On) { // Ignore during OnPending due to risk of data corruption startGpsDevice(record); } @@ -50,7 +50,7 @@ void GpsService::removeGpsDevice(const std::shared_ptr& device) { GpsDeviceRecord* record = findGpsRecord(device); - if (getState() == State::On) { // Ignore during OnPending due to risk of data corruptiohn + if (getState() == State::On) { // Ignore during OnPending due to risk of data corruption stopGpsDevice(*record); } @@ -87,6 +87,10 @@ bool GpsService::startGpsDevice(GpsDeviceRecord& record) { record.satelliteSubscriptionId = device->subscribeGga([this](hal::Device::Id deviceId, auto& record) { mutex.lock(); + if (record.fix_quality > 0) { + ggaRecord = record; + ggaTime = kernel::getTicks(); + } onGgaSentence(deviceId, record); mutex.unlock(); }); @@ -156,14 +160,16 @@ bool GpsService::startReceiving() { addGpsDevice(device); } + // Reset times before starting devices to avoid race with incoming data + rmcTime = 0; + ggaTime = 0; + bool started_one_or_more = false; for (auto& record: deviceRecords) { started_one_or_more |= startGpsDevice(record); } - rmcTime = 0; - if (started_one_or_more) { setState(State::On); return true; @@ -186,6 +192,7 @@ void GpsService::stopReceiving() { } rmcTime = 0; + ggaTime = 0; setState(State::Off); } @@ -227,6 +234,16 @@ bool GpsService::getCoordinates(minmea_sentence_rmc& rmc) const { } } +bool GpsService::getGga(minmea_sentence_gga& gga) const { + auto lock = mutex.asScopedLock(); + lock.lock(); + if (getState() == State::On && ggaTime != 0 && !hasTimeElapsed(kernel::getTicks(), ggaTime, kernel::secondsToTicks(10))) { + gga = ggaRecord; + return true; + } + return false; +} + std::shared_ptr findGpsService() { auto service = findServiceById(manifest.id); assert(service != nullptr);