Compare commits
29 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| dcfd4e9bcc | |||
| 982bba70b2 | |||
| 9630707b41 | |||
| fd82efe08f | |||
| 72089f74f3 | |||
| 89e8baf517 | |||
| 2060095028 | |||
| 620d56e19a | |||
| a0583e3a30 | |||
| 054d1286b2 | |||
| 85da419a98 | |||
| 87c82f5314 | |||
| 4b7f82c38f | |||
| 6d55f0b200 | |||
| 61fc67cf4c | |||
| c8ee763f3d | |||
| 8556103eb1 | |||
| 9e3dc3dc15 | |||
| 2496dea5c2 | |||
| a321bfeb4c | |||
| f95cd7df4c | |||
| 1b16184a72 | |||
| a0b2ee7ebc | |||
| 643cbc3806 | |||
| d3656bcd3d | |||
| 7a81b525ed | |||
| 6e5e35610b | |||
| 64fb1a9f52 | |||
| 19b11eb9a8 |
@@ -63,3 +63,7 @@ Strong success criteria let you loop independently. Weak criteria ("make it work
|
||||
---
|
||||
|
||||
**These guidelines are working if:** fewer unnecessary changes in diffs, fewer rewrites due to overcomplication, and clarifying questions come before implementation rather than after mistakes.
|
||||
|
||||
For current-firmware merges, board customization retention, ESP-IDF build/flash,
|
||||
and external-app compatibility verification, also follow
|
||||
`.claude/skills/tactility-firmware-development/SKILL.md`.
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
---
|
||||
name: tactility-firmware-development
|
||||
description: Use when merging current Tactility firmware, preserving local ES3C28P/ES3C35P customizations, building/flashing ESP32 firmware, or validating external apps against it.
|
||||
---
|
||||
|
||||
# Tactility firmware development
|
||||
|
||||
## Scope and success criteria
|
||||
|
||||
Use this skill for firmware upgrades, especially when upstream changes the app
|
||||
loader, dashboard API, SDK export, or device model. Before editing, record the
|
||||
active branch, `git status --short`, selected `Devices/<id>`, serial port, and
|
||||
the expected device identity. Preserve user work and local board
|
||||
customizations; do not reset or overwrite a dirty tree.
|
||||
|
||||
Success is not merely a successful flash: the board must boot, mount storage,
|
||||
return `/api/sysinfo`, expose required internal apps, and accept an external
|
||||
app rebuilt against this exact firmware.
|
||||
|
||||
## Upgrade and customization audit
|
||||
|
||||
1. Fetch and compare the intended upstream branch before merging. Treat
|
||||
`upstream/main` as distinct from experimental release/IDF branches unless
|
||||
the task explicitly asks for one of those branches.
|
||||
2. Merge without discarding local work (for example, `git merge --autostash
|
||||
upstream/main` after inspecting status). Resolve conflicts by preserving
|
||||
required ES3C28P and ES3C35P device definitions, partition selection,
|
||||
display/font customizations, and product features.
|
||||
3. Compare the pre-upgrade customization commit against the resulting worktree.
|
||||
Check new app registrations, CMake/source inclusion, settings pages,
|
||||
web-server endpoints, and board-specific `sdkconfig` entries—not just files
|
||||
that happen to conflict.
|
||||
4. Commit the resulting firmware customization as a focused, reviewable
|
||||
commit after `git diff --check`.
|
||||
|
||||
## Multi-binary external-app compatibility
|
||||
|
||||
Upstream app packaging changed to `bin/<platform>/<binary>.elf`. The old
|
||||
`elf/<platform>.elf` archive layout produces a loader `Not executable` error.
|
||||
|
||||
- Manifest v0.2: `bin/esp32s3/app.elf`
|
||||
- Manifest v0.3: `bin/esp32s3/<app.0.binary>.elf`
|
||||
|
||||
When this change arrives, update the companion app tool and rebuild every app
|
||||
from a fresh SDK exported from this firmware. Do not attempt to repair a
|
||||
packaged ELF on the SD card: its layout and ABI must both be regenerated.
|
||||
|
||||
## Build and flash
|
||||
|
||||
Use the installed IDF 5.5 environment; host virtual environments can corrupt
|
||||
both Python dependencies and IDF tooling:
|
||||
|
||||
```zsh
|
||||
unset VIRTUAL_ENV PYTHONPATH PYTHONHOME
|
||||
export IDF_PYTHON_ENV_PATH=/Users/adolforeyna/.espressif/python_env/idf5.5_py3.9_env
|
||||
source /Users/adolforeyna/esp/esp-idf/export.sh
|
||||
|
||||
# Select/check the intended board before this step.
|
||||
python device.py <device-id>
|
||||
idf.py build
|
||||
idf.py -p /dev/cu.usbmodemXXXX flash
|
||||
```
|
||||
|
||||
`Tactility/CMakeLists.txt` uses a non-configure-dependent source glob. After
|
||||
adding a new `.c`/`.cpp` file, run `idf.py reconfigure build`; otherwise a
|
||||
linker error for a newly referenced symbol may only mean CMake has not
|
||||
discovered the source file yet.
|
||||
|
||||
## Boot and feature acceptance
|
||||
|
||||
Capture serial at 115200 after flash or reset. Confirm the board name, SD-card
|
||||
mount, HTTP-server start, Wi-Fi address, and any feature-specific startup logs.
|
||||
Then query the resolved device:
|
||||
|
||||
```zsh
|
||||
curl -fsS http://<ip>/api/sysinfo
|
||||
curl -fsS http://<ip>/api/apps
|
||||
```
|
||||
|
||||
For MCP settings, verify the `McpSettings` internal app appears in `/api/apps`.
|
||||
When enabled, verify MCP stream startup logs. For a feature restored from an
|
||||
older customization, validate its registration path and persisted settings,
|
||||
not only its source files.
|
||||
|
||||
## External-app acceptance gate
|
||||
|
||||
Use the companion app skill's exact-firmware wrapper:
|
||||
|
||||
```zsh
|
||||
cd /path/to/tactility_apps
|
||||
scripts/build_current_firmware_app.sh Apps/MyApp --firmware /path/to/tactility
|
||||
```
|
||||
|
||||
Inspect the resulting tar member path, install through port-80 dashboard API,
|
||||
launch it, and read serial. Required evidence is the loader's `Loading
|
||||
.../bin/...`, an ELF entry address, `Task started`, and app-specific startup
|
||||
logs. HTTP 200 or a package simply appearing in `/api/apps` is insufficient.
|
||||
|
||||
## Host simulator (buildsim) + web viewer
|
||||
|
||||
The POSIX simulator runs the real firmware (LVGL, services, web server) on
|
||||
macOS/Linux with an SDL backend. On current firmware, `Main.cpp` runs SDL's
|
||||
event loop on the process main thread while FreeRTOS runs on a separate thread.
|
||||
This is required by AppKit and supports a native macOS window as well as the
|
||||
web viewer. `SDL_VIDEODRIVER=dummy` remains useful for headless automation.
|
||||
|
||||
Code locations:
|
||||
|
||||
- `Devices/simulator/Source/module.cpp` — display resolution + `SIM_DISPLAY_W/H`
|
||||
- `Devices/simulator/Source/drivers/sdl_display.{h,cpp}` — SDL backend
|
||||
- `Devices/simulator/Source/drivers/sdl_input.{h,cpp}` — pointer/key state +
|
||||
web touch-injection override
|
||||
- `Tactility/Source/service/webserver/WebServerService.cpp` — `/sim` viewer,
|
||||
`/sim/api/*` aliases, `POST /api/sim/touch`, `GET /api/screenshot?fast=`
|
||||
- `Tactility/Private/Tactility/service/webserver/WebServerService.h` — handler decls
|
||||
|
||||
### Build and run
|
||||
|
||||
```zsh
|
||||
# one-time host deps (outside any ESP-IDF env)
|
||||
mkdir -p /tmp/simbin && ln -sf "$(which python3)" /tmp/simbin/python
|
||||
pip3 install --break-system-packages lark pyyaml # devicetree compiler
|
||||
|
||||
cd /path/to/tactility
|
||||
export PATH="/tmp/simbin:$PATH"
|
||||
env -u ESP_IDF_VERSION -u IDF_PATH cmake -S . -B buildsim -DCMAKE_BUILD_TYPE=Release
|
||||
env -u ESP_IDF_VERSION -u IDF_PATH cmake --build buildsim --target Tactility -j "$(sysctl -n hw.ncpu)"
|
||||
|
||||
# POSIX SDK for host apps (arm64)
|
||||
env -u ESP_IDF_VERSION -u IDF_PATH cmake --build buildsim --target TactilityKernel lvgl minitar minmea \
|
||||
app-module crypt-module gps-module http-module lvgl-module lvgl-window-manager-module service-module
|
||||
env -u ESP_IDF_VERSION -u IDF_PATH python3 Buildscripts/release-sdk-posix.py /tmp/sim-sdk
|
||||
|
||||
# release (MUST run from the firmware root: release-simulator.sh uses relative
|
||||
# version.txt / Data paths)
|
||||
sh Buildscripts/release-simulator.sh buildsim /tmp/simrun
|
||||
# Native macOS window + web API. Run this from the release directory because
|
||||
# data/ and system/ are relative to the process working directory.
|
||||
(cd /tmp/simrun && SIM_DISPLAY_W=480 SIM_DISPLAY_H=320 \
|
||||
nohup ./Tactility > /tmp/sim_gui.log 2>&1 &)
|
||||
# For CI/headless operation, set SDL_VIDEODRIVER=dummy instead.
|
||||
curl -s --max-time 5 http://127.0.0.1/api/sysinfo | head -c 120
|
||||
```
|
||||
|
||||
Display resolution: `SIM_DISPLAY_W/H` env (default **480x320 landscape**,
|
||||
matching on-device screenshots). ES3C35P panel is 320x480 portrait in DTS but
|
||||
presents 480x320 landscape; ES3C28P is 320x240. The chosen geometry is logged
|
||||
as `Simulator Sim display WxH`. `SDL_VIDEODRIVER=dummy` is expected to log one
|
||||
`SdlDisplay Failed to create SDL window: Couldn't find matching render
|
||||
driver` line — LVGL still renders and screenshots work. A native macOS launch
|
||||
must not emit that line.
|
||||
|
||||
### Web viewer, touch, screenshots
|
||||
|
||||
- `GET /sim` → 301 to `/sim/` (trailing slash required so the page's relative
|
||||
`api/` URLs resolve under `/sim/`). Viewer polls `api/screenshot?fast=1`
|
||||
every 500 ms, footer shows live `naturalWidth×naturalHeight`, click/tap
|
||||
POSTs `api/sim/touch?x=&y=`.
|
||||
- `POST /api/sim/touch?x=123&y=456[&down=0|1]` (also `/sim/api/sim/touch` via
|
||||
alias). Coordinates are LVGL logical pixels. `down=1` (default) presses and
|
||||
**auto-releases after 1500 ms** (`SIM_TOUCH_HOLD_MS` in `sdl_input.cpp`),
|
||||
long enough for LVGL indev polls to register a click. Simulator-only: 404 on
|
||||
ESP32 (`#ifndef ESP_PLATFORM`).
|
||||
- `GET /api/screenshot?fast=1` (default): `lv_snapshot_take` (RGB888) → in-place
|
||||
BGR→RGB swap → `lodepng_encode24` **to memory** → chunked HTTP. No filesystem
|
||||
touch, ~8 ms/shot. `?fast=0` keeps the legacy `webscreenshotN.png` file path
|
||||
(slot scan + accumulation — avoid for viewer loops).
|
||||
- lodepng include in `.cpp`: `#define LODEPNG_NO_COMPILE_CPP` before
|
||||
`#include "src/libs/lodepng/lodepng.h"`, otherwise its C++ `std::vector`
|
||||
overloads collide with the C declarations (`conflicting types for 'encode'`).
|
||||
- MCP includes and `settings::mcp` reads are `#ifdef ESP_PLATFORM`-gated; the
|
||||
sim has no `McpSystem`.
|
||||
|
||||
### Tailscale viewer
|
||||
|
||||
```zsh
|
||||
tailscale serve --bg --set-path=/simagent http://127.0.0.1:80/
|
||||
# open: https://<node>/simagent/sim/
|
||||
```
|
||||
|
||||
The serve target must be `/` (not `/sim`): the page resolves `api/` against
|
||||
its own directory, so at `/simagent/sim/` fetches go to `/simagent/sim/api/…`,
|
||||
which tailscale strips to `/sim/api/…` and the firmware's `/sim/api/*`
|
||||
aliases (GET+POST, registered in `startServer()`) handle. Absolute `/api/…`
|
||||
URLs would 404 at the edge (no `/api` mount there).
|
||||
|
||||
### Simulator pitfalls
|
||||
|
||||
- **Rebuild ≠ redeploy.** `cmake --build buildsim` updates `buildsim/` only.
|
||||
Re-run `release-simulator.sh`, restart the process, then retest. A stale
|
||||
`/tmp/simrun/Tactility` serves old handlers with new logs nowhere to be found.
|
||||
- **One simulator owns port 80.** Do not launch a second instance while another
|
||||
simulator is listening: it will initialize LVGL but fail `bind/listen`, so its
|
||||
app API and viewer target the other process. Identify the listener with
|
||||
`lsof -nP -iTCP:80 -sTCP:LISTEN`, stop only the intended simulator, then
|
||||
release/restart it before installing or running POSIX apps.
|
||||
- **Input is cross-thread on macOS.** SDL event pumping occurs on the real main
|
||||
thread; LVGL and web touch injection run elsewhere. Keep all shared pointer,
|
||||
key-queue, and touch-override state under `sdl_input.cpp`'s mutex.
|
||||
- **C array `sizeof` decay.** A helper like
|
||||
`f(HttpServerRequest*, char uri[256])` sees `sizeof(uri) == 8`, truncating
|
||||
`get_uri` output to 7 chars (`/api/sy`, `/sim/ap` 404s). Pass the size
|
||||
explicitly: `f(request, buf, sizeof(buf))`.
|
||||
- **Log truncation.** `LOG_QUEUE_MESSAGE_MAX_LENGTH` is 256 (`TactilityKernel/
|
||||
private/tactility/log_queue.h`), including color/timestamp prefix. Long URIs
|
||||
and messages truncate — don't over-interpret a short path in the log.
|
||||
- **Auth.** The viewer and API handlers enforce `validateRequestAuth` like any
|
||||
other endpoint; failures surface as 401/404, not viewer bugs.
|
||||
@@ -0,0 +1,41 @@
|
||||
name: Build
|
||||
|
||||
runs:
|
||||
using: "composite"
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
submodules: recursive
|
||||
persist-credentials: false
|
||||
- name: 'Detect architecture'
|
||||
id: arch
|
||||
shell: bash
|
||||
run: echo "value=$(uname -m)" >> "$GITHUB_OUTPUT"
|
||||
- name: 'Configure'
|
||||
shell: bash
|
||||
run: cmake -S ./ -B buildsim
|
||||
- name: 'Build'
|
||||
shell: bash
|
||||
run: cmake --build buildsim --target TactilityKernel lvgl minitar minmea $(cat Buildscripts/release-sdk-modules.txt)
|
||||
- name: 'Release'
|
||||
shell: bash
|
||||
run: python Buildscripts/release-sdk-posix.py release/TactilitySDK
|
||||
- name: 'Test Integration Prep'
|
||||
shell: bash
|
||||
env:
|
||||
TACTILITY_ARCH: ${{ steps.arch.outputs.value }}
|
||||
run: |
|
||||
TACTILITY_SDK_NAME="$(cat version.txt)-posix-$TACTILITY_ARCH"
|
||||
mkdir -p test_sdk/$TACTILITY_SDK_NAME
|
||||
cp -r release/TactilitySDK test_sdk/$TACTILITY_SDK_NAME
|
||||
- name: 'Test Integration'
|
||||
shell: bash
|
||||
env:
|
||||
TACTILITY_ARCH: ${{ steps.arch.outputs.value }}
|
||||
run: cd Tests/SdkIntegration && TACTILITY_SDK_PATH=../../test_sdk python tactility.py build -a posix-$TACTILITY_ARCH --local-sdk
|
||||
- name: 'Upload Artifact'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: TactilitySDK-posix-${{ steps.arch.outputs.value }}
|
||||
path: release/TactilitySDK
|
||||
retention-days: 30
|
||||
@@ -29,13 +29,13 @@ runs:
|
||||
env:
|
||||
# NOTE: Update with ESP-IDF!
|
||||
ESP_IDF_VERSION: '5.5.2'
|
||||
run: python Buildscripts/release-sdk.py release/TactilitySDK
|
||||
run: python Buildscripts/release-sdk-esp32.py release/TactilitySDK
|
||||
- name: 'Test Integration Prep'
|
||||
shell: bash
|
||||
# The manifest.properties of our integration test uses version 0.0.0 to indicate that it is not using a normal SDK
|
||||
# This way, it only works with our custom build. That means we have to create a copy of the SDK with the correct folder structure:
|
||||
run: |
|
||||
TACTILITY_SDK_NAME="0.0.0-${{ inputs.arch }}"
|
||||
TACTILITY_SDK_NAME="$(cat version.txt)-${{ inputs.arch }}"
|
||||
mkdir -p test_sdk/$TACTILITY_SDK_NAME
|
||||
cp -r release/TactilitySDK test_sdk/$TACTILITY_SDK_NAME
|
||||
- name: 'Test Integration'
|
||||
@@ -43,7 +43,7 @@ runs:
|
||||
with:
|
||||
esp_idf_version: v5.5.2
|
||||
target: ${{ inputs.arch }}
|
||||
command: export TACTILITY_SDK_PATH=../../test_sdk && cd Tests/SdkIntegration && python tactility.py build ${{ inputs.arch }} --local-sdk
|
||||
command: export TACTILITY_SDK_PATH=../../test_sdk && cd Tests/SdkIntegration && python tactility.py build -a ${{ inputs.arch }} --local-sdk
|
||||
- name: 'Upload Artifact'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
|
||||
@@ -4,11 +4,8 @@ inputs:
|
||||
os_name:
|
||||
description: A descriptive name for the operating system (e.g. linux, windows)
|
||||
required: true
|
||||
platform_name:
|
||||
description: A descriptive name for the target platform (e.g. amd64, aarch64, etc.)
|
||||
required: true
|
||||
publish:
|
||||
description: A boolean that enables publishing of artifacts
|
||||
architecture:
|
||||
description: A descriptive name for the target architecture (e.g. x86_64, aarch64, etc.)
|
||||
required: true
|
||||
|
||||
runs:
|
||||
@@ -45,14 +42,13 @@ runs:
|
||||
run: cmake -S ./ -B buildsim
|
||||
- name: "Build Tests"
|
||||
shell: bash
|
||||
run: cmake --build buildsim --target FirmwareSim
|
||||
run: cmake --build buildsim --target Tactility
|
||||
- name: 'Release'
|
||||
shell: bash
|
||||
run: Buildscripts/release-simulator.sh buildsim release/Simulator-${{ inputs.os_name }}-${{ inputs.platform_name }}
|
||||
run: Buildscripts/release-simulator.sh buildsim release/Simulator-${{ inputs.os_name }}-${{ inputs.architecture }}
|
||||
- name: 'Upload Artifact'
|
||||
uses: actions/upload-artifact@v4
|
||||
if: ${{ inputs.publish == 'true' }}
|
||||
with:
|
||||
name: Simulator-${{ inputs.os_name }}-${{ inputs.platform_name }}
|
||||
path: release/Simulator-${{ inputs.os_name }}-${{ inputs.platform_name }}
|
||||
name: Simulator-${{ inputs.os_name }}-${{ inputs.architecture }}
|
||||
path: release/Simulator-${{ inputs.os_name }}-${{ inputs.architecture }}
|
||||
retention-days: 30
|
||||
|
||||
@@ -17,8 +17,7 @@ jobs:
|
||||
uses: ./.github/actions/build-simulator
|
||||
with:
|
||||
os_name: linux
|
||||
platform_name: amd64
|
||||
publish: true
|
||||
architecture: x86_64
|
||||
macOS:
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
@@ -29,6 +28,4 @@ jobs:
|
||||
uses: ./.github/actions/build-simulator
|
||||
with:
|
||||
os_name: macos
|
||||
platform_name: aarch64
|
||||
# macOS simulator currently fails due to main thread requirement for rendering
|
||||
publish: false
|
||||
architecture: aarch64
|
||||
|
||||
@@ -11,7 +11,7 @@ on:
|
||||
permissions: read-all
|
||||
|
||||
jobs:
|
||||
BuildSdk:
|
||||
BuildSdkEsp32:
|
||||
strategy:
|
||||
matrix:
|
||||
board: [
|
||||
@@ -30,9 +30,17 @@ jobs:
|
||||
with:
|
||||
board_id: ${{ matrix.board.id }}
|
||||
arch: ${{ matrix.board.arch }}
|
||||
BuildSdkPosix:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: "Build SDK"
|
||||
uses: ./.github/actions/build-sdk-posix
|
||||
GenerateDeviceMatrix:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [ BuildSdk ]
|
||||
needs: [ BuildSdkEsp32 ]
|
||||
outputs:
|
||||
matrix: ${{ steps.set-matrix.outputs.matrix }}
|
||||
steps:
|
||||
@@ -57,7 +65,7 @@ jobs:
|
||||
arch: ${{ matrix.board.arch }}
|
||||
BundleArtifacts:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [ BuildFirmware ]
|
||||
needs: [ BuildFirmware, BuildSdkPosix ]
|
||||
if: |
|
||||
(github.event_name == 'push' && github.ref == 'refs/heads/main') ||
|
||||
(github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v'))
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
.DS_Store
|
||||
|
||||
build*/
|
||||
!.github/actions/build*/
|
||||
!Buildscripts/
|
||||
!Buildscripts/release-simulator-macos-app.sh
|
||||
cmake*/
|
||||
CMakeCache.txt
|
||||
*.cbp
|
||||
@@ -25,3 +28,5 @@ sdkconfig.board.*.dev
|
||||
|
||||
.caveman.json
|
||||
.ai/mcp
|
||||
|
||||
__pycache__
|
||||
|
||||
@@ -311,11 +311,39 @@ def test_compile_missing_config():
|
||||
print("PASSED")
|
||||
return True
|
||||
|
||||
|
||||
def test_es3c35p_uses_current_runtime_contract():
|
||||
print("Running test_es3c35p_uses_current_runtime_contract...")
|
||||
repository_root = os.path.abspath(os.path.join(SCRIPT_DIR, "..", "..", ".."))
|
||||
device_dir = os.path.join(repository_root, "Devices", "es3c35p")
|
||||
with open(os.path.join(device_dir, "device.properties")) as f:
|
||||
properties = f.read()
|
||||
with open(os.path.join(device_dir, "es3c35p.dts")) as f:
|
||||
devicetree = f.read()
|
||||
|
||||
requirements = [
|
||||
("apps.launcherAppId=tactility.launcher" in properties, "current launcher app id"),
|
||||
("hardware.tinyUsb=" not in properties, "no obsolete hardware.tinyUsb property"),
|
||||
('wifi0 {\n\t\tcompatible = "espressif,esp32-wifi-pinned";\n\t};' in devicetree,
|
||||
"Wi-Fi enabled for web server and MCP"),
|
||||
('ble0 {\n\t\tcompatible = "espressif,esp32-ble";\n\t};' in devicetree,
|
||||
"BLE node matches hardware.bluetooth=true"),
|
||||
]
|
||||
missing = [description for condition, description in requirements if not condition]
|
||||
if missing:
|
||||
print("FAILED: " + ", ".join(missing))
|
||||
return False
|
||||
|
||||
print("PASSED")
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
tests = [
|
||||
test_compile_success,
|
||||
test_compile_invalid_dts,
|
||||
test_compile_missing_config,
|
||||
test_es3c35p_uses_current_runtime_contract,
|
||||
test_minmax_within_range_succeeds,
|
||||
test_minmax_below_minimum_fails,
|
||||
test_minmax_above_maximum_fails,
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
idf_component_register(
|
||||
INCLUDE_DIRS
|
||||
"Libraries/TactilityC/include"
|
||||
"Libraries/TactilityKernel/include"
|
||||
"Libraries/TactilityFreeRtos/Include"
|
||||
"Libraries/lvgl/include"
|
||||
@@ -11,13 +10,11 @@ idf_component_register(
|
||||
)
|
||||
|
||||
# Regular and core features
|
||||
add_prebuilt_library(TactilityC Libraries/TactilityC/binary/libTactilityC.a)
|
||||
add_prebuilt_library(TactilityKernel Libraries/TactilityKernel/binary/libTactilityKernel.a)
|
||||
add_prebuilt_library(lvgl Libraries/lvgl/binary/liblvgl.a)
|
||||
add_prebuilt_library(minmea Libraries/minmea/binary/libminmea.a)
|
||||
add_prebuilt_library(minitar Libraries/minitar/binary/libminitar.a)
|
||||
|
||||
target_link_libraries(${COMPONENT_LIB} INTERFACE TactilityC)
|
||||
target_link_libraries(${COMPONENT_LIB} INTERFACE TactilityKernel)
|
||||
target_link_libraries(${COMPONENT_LIB} INTERFACE lvgl)
|
||||
target_link_libraries(${COMPONENT_LIB} INTERFACE minmea)
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
function(tactility_project)
|
||||
endfunction()
|
||||
|
||||
function(_tactility_project)
|
||||
endfunction()
|
||||
|
||||
macro(tactility_project project_name)
|
||||
set(TACTILITY_SKIP_SPIFFS 1)
|
||||
|
||||
include("${TACTILITY_SDK_PATH}/Libraries/elf_loader/elf_loader.cmake")
|
||||
project_elf($project_name)
|
||||
|
||||
file(READ ${TACTILITY_SDK_PATH}/idf-version.txt TACTILITY_SDK_IDF_VERSION)
|
||||
string(REGEX REPLACE "^([0-9]+\\.[0-9]+).*" "\\1" TACTILITY_SDK_IDF_MAJOR_MINOR "${TACTILITY_SDK_IDF_VERSION}")
|
||||
string(REGEX REPLACE "^([0-9]+\\.[0-9]+).*" "\\1" CURRENT_IDF_MAJOR_MINOR "$ENV{ESP_IDF_VERSION}")
|
||||
if (NOT "${CURRENT_IDF_MAJOR_MINOR}" STREQUAL "${TACTILITY_SDK_IDF_MAJOR_MINOR}")
|
||||
message(FATAL_ERROR "ESP-IDF version of Tactility SDK (${TACTILITY_SDK_IDF_VERSION}) does not match current ESP-IDF version ($ENV{ESP_IDF_VERSION})")
|
||||
endif()
|
||||
|
||||
set(EXTRA_COMPONENT_DIRS
|
||||
"${TACTILITY_SDK_PATH}/Libraries/TactilityFreeRtos"
|
||||
"${TACTILITY_SDK_PATH}/Modules"
|
||||
)
|
||||
|
||||
set(COMPONENTS
|
||||
TactilityFreeRtos
|
||||
app-module
|
||||
crypt-module
|
||||
gps-module
|
||||
lvgl-module
|
||||
lvgl-window-manager-module
|
||||
service-module
|
||||
)
|
||||
|
||||
endmacro()
|
||||
@@ -0,0 +1,62 @@
|
||||
function(tactility_project)
|
||||
endfunction()
|
||||
|
||||
function(_tactility_project)
|
||||
endfunction()
|
||||
|
||||
macro(tactility_project_pre project_name)
|
||||
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||
set(EXTRA_COMPONENT_DIRS ${TACTILITY_SDK_PATH} ${TACTILITY_SDK_PATH}/Modules)
|
||||
endmacro()
|
||||
|
||||
macro(tactility_project_post project_name)
|
||||
set(TACTILITY_SKIP_SPIFFS 1)
|
||||
|
||||
# Tactility's PanicHandler.cpp needs s0 to stay a frame pointer to capture a callstack for
|
||||
# a RISC-V app's crashes, which GCC does not guarantee without this flag. The firmware sets the
|
||||
# same flag for its own code, but a crash usually happens in app code, built separately here.
|
||||
# Gated to RISC-V since Xtensa never reads s0 this way. idf_build_set_property(), not
|
||||
# add_compile_options(): the app's code compiles as an idf_component_register() component
|
||||
# (Apps/*/main/CMakeLists.txt), which reads ESP-IDF's own COMPILE_OPTIONS build property rather
|
||||
# than plain directory-scoped flags. project_elf() below uses the same property for its own
|
||||
# flags for the same reason.
|
||||
if(CONFIG_IDF_TARGET_ARCH_RISCV)
|
||||
idf_build_set_property(COMPILE_OPTIONS "-fno-omit-frame-pointer" APPEND)
|
||||
endif()
|
||||
|
||||
include("${TACTILITY_SDK_PATH}/Libraries/elf_loader/elf_loader.cmake")
|
||||
project_elf($project_name)
|
||||
|
||||
file(READ ${TACTILITY_SDK_PATH}/idf-version.txt TACTILITY_SDK_IDF_VERSION)
|
||||
string(REGEX REPLACE "^([0-9]+\\.[0-9]+).*" "\\1" TACTILITY_SDK_IDF_MAJOR_MINOR "${TACTILITY_SDK_IDF_VERSION}")
|
||||
string(REGEX REPLACE "^([0-9]+\\.[0-9]+).*" "\\1" CURRENT_IDF_MAJOR_MINOR "$ENV{ESP_IDF_VERSION}")
|
||||
if (NOT "${CURRENT_IDF_MAJOR_MINOR}" STREQUAL "${TACTILITY_SDK_IDF_MAJOR_MINOR}")
|
||||
message(FATAL_ERROR "ESP-IDF version of Tactility SDK (${TACTILITY_SDK_IDF_VERSION}) does not match current ESP-IDF version ($ENV{ESP_IDF_VERSION})")
|
||||
endif()
|
||||
|
||||
set(EXTRA_COMPONENT_DIRS
|
||||
"${TACTILITY_SDK_PATH}/Libraries/TactilityFreeRtos"
|
||||
"${TACTILITY_SDK_PATH}/Modules"
|
||||
)
|
||||
|
||||
set(COMPONENTS
|
||||
TactilityFreeRtos
|
||||
app-module
|
||||
crypt-module
|
||||
gps-module
|
||||
lvgl-module
|
||||
lvgl-window-manager-module
|
||||
service-module
|
||||
)
|
||||
|
||||
endmacro()
|
||||
|
||||
macro(tactility_component_register)
|
||||
cmake_parse_arguments(TT_COMPONENT "" "" "SRCS;INCLUDE_DIRS;REQUIRES;PRIV_REQUIRES" ${ARGN})
|
||||
idf_component_register(
|
||||
SRCS ${TT_COMPONENT_SRCS}
|
||||
INCLUDE_DIRS ${TT_COMPONENT_INCLUDE_DIRS}
|
||||
REQUIRES TactilitySDK ${TT_COMPONENT_REQUIRES}
|
||||
PRIV_REQUIRES ${TT_COMPONENT_PRIV_REQUIRES}
|
||||
)
|
||||
endmacro()
|
||||
@@ -0,0 +1,51 @@
|
||||
function(tactility_project)
|
||||
endfunction()
|
||||
|
||||
function(_tactility_project)
|
||||
endfunction()
|
||||
|
||||
macro(tactility_project_pre project_name)
|
||||
endmacro()
|
||||
|
||||
macro(tactility_project_post project_name)
|
||||
# The app's own library target is defined in a subdirectory (e.g. "main"); without this it
|
||||
# would land nested under that subdirectory instead of directly in the build dir.
|
||||
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR})
|
||||
|
||||
# Mirrors the ESP-IDF "TactilitySDK" component (Buildscripts/TactilitySDK/CMakeLists.txt):
|
||||
# apps link against this single target instead of listing SDK include dirs themselves.
|
||||
# Posix apps are dlopen()ed into a running Tactility process (see app-posix-module) and
|
||||
# resolve symbols against Tactility's own copies at load time, so headers are all they need
|
||||
# at compile time - no libraries to link.
|
||||
add_library(TactilitySDK INTERFACE)
|
||||
target_include_directories(TactilitySDK INTERFACE
|
||||
${TACTILITY_SDK_PATH}/Modules/app-module/include
|
||||
${TACTILITY_SDK_PATH}/Modules/crypt-module/include
|
||||
${TACTILITY_SDK_PATH}/Modules/gps-module/include
|
||||
${TACTILITY_SDK_PATH}/Modules/lvgl-module/include
|
||||
${TACTILITY_SDK_PATH}/Modules/lvgl-window-manager-module/include
|
||||
${TACTILITY_SDK_PATH}/Modules/service-module/include
|
||||
${TACTILITY_SDK_PATH}/Libraries/TactilityKernel/include
|
||||
${TACTILITY_SDK_PATH}/Libraries/lvgl/include
|
||||
${TACTILITY_SDK_PATH}/Libraries/FreeRTOS-Kernel/include
|
||||
${TACTILITY_SDK_PATH}/Libraries/FreeRTOS-Kernel/portable/ThirdParty/GCC/Posix
|
||||
${TACTILITY_SDK_PATH}/Libraries/FreeRTOS-Kernel/portable/ThirdParty/GCC/Posix/utils
|
||||
)
|
||||
target_compile_definitions(TactilitySDK INTERFACE LV_LVGL_H_INCLUDE_SIMPLE)
|
||||
|
||||
# ESP-IDF's project() auto-discovers the "main" component; plain CMake doesn't.
|
||||
add_subdirectory(main)
|
||||
endmacro()
|
||||
|
||||
macro(tactility_component_register)
|
||||
cmake_parse_arguments(TT_COMPONENT "" "" "SRCS;INCLUDE_DIRS;REQUIRES;PRIV_REQUIRES" ${ARGN})
|
||||
# Must be a SHARED object, not a -pie executable: glibc's dlopen() unconditionally refuses
|
||||
# any ET_DYN carrying the DF_1_PIE flag ("cannot dynamically load position-independent
|
||||
# executable"), regardless of whether it has a dynamic-linker segment - verified empirically.
|
||||
add_library(${PROJECT_NAME} SHARED ${TT_COMPONENT_SRCS})
|
||||
target_link_libraries(${PROJECT_NAME} PRIVATE TactilitySDK)
|
||||
set_target_properties(${PROJECT_NAME} PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
||||
if (TT_COMPONENT_INCLUDE_DIRS)
|
||||
target_include_directories(${PROJECT_NAME} PRIVATE ${TT_COMPONENT_INCLUDE_DIRS})
|
||||
endif ()
|
||||
endmacro()
|
||||
@@ -5,7 +5,6 @@ import time
|
||||
|
||||
def build(device: str) -> bool:
|
||||
print(f"Building {device}...")
|
||||
shutil.rmtree(os.path.join('Firmware', 'Generated'), ignore_errors=True)
|
||||
result = subprocess.run(['python', 'device.py', device], capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
print(f"Failed to select device {device}")
|
||||
|
||||
Executable
+87
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
"""Convert an image to an uncompressed LVGL RGB565 launcher background."""
|
||||
|
||||
import argparse
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
LV_IMAGE_HEADER_MAGIC = 0x19
|
||||
LV_COLOR_FORMAT_RGB565 = 0x12
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(
|
||||
description=(
|
||||
"Create an uncompressed LVGL .bin image for "
|
||||
"/sdcard/tactility/launcher/background.bin. Use a square image sized "
|
||||
"to the display's longest edge to support both orientations without scaling "
|
||||
"(for example, 320x320 for a 320x240 display)."
|
||||
)
|
||||
)
|
||||
parser.add_argument("input", type=Path, help="Source image")
|
||||
parser.add_argument("output", type=Path, help="Destination .bin file")
|
||||
parser.add_argument("--width", type=int, required=True, help="Output width")
|
||||
parser.add_argument("--height", type=int, required=True, help="Output height")
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = parse_args()
|
||||
if args.width <= 0 or args.width > 65535 or args.height <= 0 or args.height > 65535:
|
||||
raise SystemExit("width and height must be between 1 and 65535")
|
||||
|
||||
magick = shutil.which("magick")
|
||||
if magick is None:
|
||||
raise SystemExit("ImageMagick is required (the 'magick' command was not found)")
|
||||
|
||||
command = [
|
||||
magick,
|
||||
str(args.input),
|
||||
"-resize",
|
||||
f"{args.width}x{args.height}^",
|
||||
"-gravity",
|
||||
"center",
|
||||
"-extent",
|
||||
f"{args.width}x{args.height}",
|
||||
"-depth",
|
||||
"8",
|
||||
"rgb:-",
|
||||
]
|
||||
rgb888 = subprocess.run(command, check=True, stdout=subprocess.PIPE).stdout
|
||||
expected_size = args.width * args.height * 3
|
||||
if len(rgb888) != expected_size:
|
||||
raise SystemExit(f"unexpected ImageMagick output: {len(rgb888)} bytes, expected {expected_size}")
|
||||
|
||||
rgb565 = bytearray(args.width * args.height * 2)
|
||||
for source_offset in range(0, len(rgb888), 3):
|
||||
r, g, b = rgb888[source_offset : source_offset + 3]
|
||||
pixel = ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3)
|
||||
destination_offset = (source_offset // 3) * 2
|
||||
struct.pack_into("<H", rgb565, destination_offset, pixel)
|
||||
|
||||
stride = args.width * 2
|
||||
header = struct.pack(
|
||||
"<BBHHHHH",
|
||||
LV_IMAGE_HEADER_MAGIC,
|
||||
LV_COLOR_FORMAT_RGB565,
|
||||
0,
|
||||
args.width,
|
||||
args.height,
|
||||
stride,
|
||||
0,
|
||||
)
|
||||
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.output.write_bytes(header + rgb565)
|
||||
print(
|
||||
f"Wrote {args.output} ({args.width}x{args.height}, "
|
||||
f"{len(header) + len(rgb565)} bytes, uncompressed RGB565)"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -2,6 +2,8 @@ if (COMMAND tactility_add_module)
|
||||
return()
|
||||
endif()
|
||||
|
||||
cmake_minimum_required(VERSION 3.24)
|
||||
|
||||
macro(tactility_get_module_name NAME OUT_NAME)
|
||||
if (DEFINED ENV{ESP_IDF_VERSION})
|
||||
set(${OUT_NAME} ${COMPONENT_LIB})
|
||||
@@ -16,8 +18,7 @@ macro(tactility_add_module NAME)
|
||||
# undefined reference to. Needed when this module provides symbols a component it depends on
|
||||
# (e.g. lvgl__lvgl's custom-allocator hooks) calls back into - a reverse reference a normal
|
||||
# single-pass static-archive link can't resolve, since that component is scanned after this
|
||||
# one's archive has already been passed once. POSIX builds link everything as plain OBJECT
|
||||
# libraries (no archive-pruning to begin with), so this is a no-op there.
|
||||
# one's archive has already been passed once.
|
||||
set(options WHOLE_ARCHIVE)
|
||||
set(oneValueArgs)
|
||||
set(multiValueArgs SRCS INCLUDE_DIRS PRIV_INCLUDE_DIRS REQUIRES PRIV_REQUIRES)
|
||||
@@ -40,7 +41,7 @@ macro(tactility_add_module NAME)
|
||||
${whole_archive_arg}
|
||||
)
|
||||
else()
|
||||
add_library(${NAME} OBJECT)
|
||||
add_library(${NAME} STATIC)
|
||||
target_sources(${NAME} PRIVATE ${ARG_SRCS})
|
||||
target_include_directories(${NAME}
|
||||
PRIVATE ${ARG_PRIV_INCLUDE_DIRS}
|
||||
@@ -48,5 +49,12 @@ macro(tactility_add_module NAME)
|
||||
)
|
||||
target_link_libraries(${NAME} PUBLIC ${ARG_REQUIRES})
|
||||
target_link_libraries(${NAME} PRIVATE ${ARG_PRIV_REQUIRES})
|
||||
if (ARG_WHOLE_ARCHIVE)
|
||||
# A static archive only pulls in object files that already have a pending undefined
|
||||
# reference at the point the archive is scanned, so a plain link drops ${NAME}'s
|
||||
# reverse dependencies (see WHOLE_ARCHIVE comment above). Make whoever links ${NAME}
|
||||
# whole-archive it instead of just archive-pruning it.
|
||||
set_property(TARGET ${NAME} APPEND PROPERTY INTERFACE_LINK_LIBRARIES $<LINK_LIBRARY:WHOLE_ARCHIVE,${NAME}>)
|
||||
endif()
|
||||
endif()
|
||||
endmacro()
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import os
|
||||
import platform
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -17,42 +18,53 @@ def get_idf_target():
|
||||
return None
|
||||
return None
|
||||
|
||||
def main():
|
||||
# 1. Get idf_target
|
||||
idf_target = get_idf_target()
|
||||
if not idf_target:
|
||||
print("Could not determine IDF target from sdkconfig")
|
||||
sys.exit(1)
|
||||
|
||||
# 2. Get version
|
||||
def get_version():
|
||||
try:
|
||||
with open("version.txt", "r") as f:
|
||||
version = f.read().strip()
|
||||
return f.read().strip()
|
||||
except FileNotFoundError:
|
||||
print("version.txt not found")
|
||||
sys.exit(1)
|
||||
|
||||
# 3. Construct sdk_path
|
||||
# release/TactilitySDK/${version}-${idf_target}/TactilitySDK
|
||||
sdk_path = os.path.join("release", "TactilitySDK", f"{version}-{idf_target}", "TactilitySDK")
|
||||
|
||||
# 4. Cleanup sdk_path
|
||||
def run_release_script(script_name, sdk_path):
|
||||
# Cleanup sdk_path
|
||||
if os.path.exists(sdk_path):
|
||||
print(f"Cleaning up {sdk_path}")
|
||||
shutil.rmtree(sdk_path)
|
||||
|
||||
|
||||
os.makedirs(sdk_path, exist_ok=True)
|
||||
|
||||
# 5. Call release-sdk.py
|
||||
# Note: Using sys.executable to ensure we use the same python interpreter
|
||||
script_path = os.path.join("Buildscripts", "release-sdk.py")
|
||||
script_path = os.path.join("Buildscripts", script_name)
|
||||
print(f"Running {script_path} {sdk_path}")
|
||||
|
||||
|
||||
result = subprocess.run([sys.executable, script_path, sdk_path])
|
||||
|
||||
|
||||
if result.returncode != 0:
|
||||
print(f"Error: {script_path} failed with return code {result.returncode}")
|
||||
sys.exit(result.returncode)
|
||||
|
||||
def main():
|
||||
version = get_version()
|
||||
|
||||
# ESP_IDF_VERSION is only set once an ESP-IDF environment has been activated (export.sh /
|
||||
# the Windows PowerShell profile - see building.md); same check release-sdk-esp32.py and
|
||||
# release-sdk-posix.py themselves use to tell the two builds apart.
|
||||
esp_idf_version = os.environ.get("ESP_IDF_VERSION", "")
|
||||
|
||||
if esp_idf_version:
|
||||
idf_target = get_idf_target()
|
||||
if not idf_target:
|
||||
print("Could not determine IDF target from sdkconfig")
|
||||
sys.exit(1)
|
||||
# release/TactilitySDK/${version}-${idf_target}/TactilitySDK
|
||||
sdk_path = os.path.join("release", "TactilitySDK", f"{version}-{idf_target}", "TactilitySDK")
|
||||
run_release_script("release-sdk-esp32.py", sdk_path)
|
||||
else:
|
||||
# release/TactilitySDK/${version}-posix-${arch}/TactilitySDK
|
||||
arch = platform.machine()
|
||||
sdk_path = os.path.join("release", "TactilitySDK", f"{version}-posix-{arch}", "TactilitySDK")
|
||||
run_release_script("release-sdk-posix.py", sdk_path)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -1,66 +1,16 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import glob
|
||||
import subprocess
|
||||
import sys
|
||||
import importlib.util
|
||||
from textwrap import dedent
|
||||
|
||||
def map_copy(mappings, target_base):
|
||||
"""
|
||||
Helper function to map input files/directories to output files/directories.
|
||||
mappings: list of dicts with 'src' (glob pattern) and 'dst' (relative to target_base or absolute)
|
||||
'src' can be a single file or a directory (if it ends with /).
|
||||
"""
|
||||
for mapping in mappings:
|
||||
src_pattern = mapping['src']
|
||||
dst_rel = mapping['dst']
|
||||
dst_path = os.path.join(target_base, dst_rel)
|
||||
_shared_spec = importlib.util.spec_from_file_location("release_sdk_shared", os.path.join("Buildscripts", "release-sdk-shared.py"))
|
||||
shared = importlib.util.module_from_spec(_shared_spec)
|
||||
_shared_spec.loader.exec_module(shared)
|
||||
|
||||
# To preserve directory structure, we need to know where the wildcard starts
|
||||
# or have a way to determine the "base" of the search.
|
||||
# We'll split the pattern into a fixed base and a pattern part.
|
||||
|
||||
# Simple heuristic: find the first occurrence of '*' or '?'
|
||||
wildcard_idx = -1
|
||||
for i, char in enumerate(src_pattern):
|
||||
if char in '*?':
|
||||
wildcard_idx = i
|
||||
break
|
||||
|
||||
if wildcard_idx != -1:
|
||||
# Found a wildcard. The base is the directory containing it.
|
||||
pattern_base = os.path.dirname(src_pattern[:wildcard_idx])
|
||||
else:
|
||||
# No wildcard. If it's a directory, we might want to preserve its name?
|
||||
# For now, let's treat no-wildcard as no relative structure needed.
|
||||
pattern_base = None
|
||||
|
||||
src_files = glob.glob(src_pattern, recursive=True)
|
||||
if not src_files:
|
||||
continue
|
||||
|
||||
for src in src_files:
|
||||
if os.path.isdir(src):
|
||||
continue
|
||||
|
||||
if pattern_base and src.startswith(pattern_base):
|
||||
# Calculate relative path from the base of the glob pattern
|
||||
rel_src = os.path.relpath(src, pattern_base)
|
||||
# If dst_rel ends with /, it's a target directory
|
||||
if dst_rel.endswith('/') or os.path.isdir(dst_path):
|
||||
final_dst = os.path.join(dst_path, rel_src)
|
||||
else:
|
||||
# If dst_rel is a file, we can't really preserve structure
|
||||
# unless we join it. But usually it's a dir if structure is preserved.
|
||||
final_dst = dst_path
|
||||
else:
|
||||
final_dst = dst_path if not (dst_rel.endswith('/') or os.path.isdir(dst_path)) else os.path.join(dst_path, os.path.basename(src))
|
||||
|
||||
os.makedirs(os.path.dirname(final_dst), exist_ok=True)
|
||||
shutil.copy2(src, final_dst)
|
||||
|
||||
def get_driver_mappings(driver_name):
|
||||
return [
|
||||
{'src': f'Drivers/{driver_name}/include/**', 'dst': f'Drivers/{driver_name}/include/'},
|
||||
@@ -82,11 +32,7 @@ def create_module_cmakelists(module_name):
|
||||
INCLUDE_DIRS "include"
|
||||
)
|
||||
add_prebuilt_library({module_name} "binary/lib{module_name}.a")
|
||||
'''.format(module_name=module_name))
|
||||
|
||||
def write_module_cmakelists(path, content):
|
||||
with open(path, 'w') as f:
|
||||
f.write(content)
|
||||
''')
|
||||
|
||||
def driver_is_available(driver_name):
|
||||
"""
|
||||
@@ -101,28 +47,25 @@ def driver_is_available(driver_name):
|
||||
|
||||
def add_driver(target_path, driver_name):
|
||||
mappings = get_driver_mappings(driver_name)
|
||||
map_copy(mappings, target_path)
|
||||
shared.map_copy(mappings, target_path)
|
||||
cmakelists_content = create_module_cmakelists(driver_name)
|
||||
write_module_cmakelists(os.path.join(target_path, f"Drivers/{driver_name}/CMakeLists.txt"), cmakelists_content)
|
||||
shared.write_module_cmakelists(os.path.join(target_path, f"Drivers/{driver_name}/CMakeLists.txt"), cmakelists_content)
|
||||
|
||||
def add_module(target_path, module_name):
|
||||
mappings = get_module_mappings(module_name)
|
||||
map_copy(mappings, target_path)
|
||||
shared.map_copy(mappings, target_path)
|
||||
cmakelists_content = create_module_cmakelists(module_name)
|
||||
write_module_cmakelists(os.path.join(target_path, f"Modules/{module_name}/CMakeLists.txt"), cmakelists_content)
|
||||
|
||||
def generate_tactility_sdk_cmake(target_path):
|
||||
src = os.path.join('Buildscripts', 'TactilitySDK', 'TactilitySDK.cmake')
|
||||
shutil.copy2(src, os.path.join(target_path, 'TactilitySDK.cmake'))
|
||||
|
||||
def generate_tactility_sdk_top_cmakelists(target_path):
|
||||
src = os.path.join('Buildscripts', 'TactilitySDK', 'CMakeLists.txt')
|
||||
shutil.copy2(src, os.path.join(target_path, 'CMakeLists.txt'))
|
||||
shared.write_module_cmakelists(os.path.join(target_path, f"Modules/{module_name}/CMakeLists.txt"), cmakelists_content)
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
print("Usage: release-sdk.py [target_path]")
|
||||
print("Example: release-sdk.py release/TactilitySDK")
|
||||
print("Usage: release-sdk-esp32.py [target_path]")
|
||||
print("Example: release-sdk-esp32.py release/TactilitySDK")
|
||||
sys.exit(1)
|
||||
|
||||
esp_idf_version = os.environ.get("ESP_IDF_VERSION", "")
|
||||
if not esp_idf_version:
|
||||
print("Error: ESP_IDF_VERSION environment variable is not set")
|
||||
sys.exit(1)
|
||||
|
||||
target_path = os.path.abspath(sys.argv[1])
|
||||
@@ -131,11 +74,6 @@ def main():
|
||||
# Mapping logic
|
||||
mappings = [
|
||||
{'src': 'version.txt', 'dst': ''},
|
||||
# TactilityC
|
||||
{'src': 'build/esp-idf/TactilityC/libTactilityC.a', 'dst': 'Libraries/TactilityC/binary/'},
|
||||
{'src': 'TactilityC/Include/*', 'dst': 'Libraries/TactilityC/include/'},
|
||||
{'src': 'TactilityC/CMakeLists.txt', 'dst': 'Libraries/TactilityC/'},
|
||||
{'src': 'TactilityC/LICENSE*.*', 'dst': 'Libraries/TactilityC/'},
|
||||
# TactilityFreeRtos
|
||||
{'src': 'TactilityFreeRtos/Include/**', 'dst': 'Libraries/TactilityFreeRtos/Include/'},
|
||||
{'src': 'TactilityFreeRtos/CMakeLists.txt', 'dst': 'Libraries/TactilityFreeRtos/'},
|
||||
@@ -153,8 +91,9 @@ def main():
|
||||
{'src': 'Libraries/lvgl/src/lv_conf_kconfig.h', 'dst': 'Libraries/lvgl/include/lv_conf.h'},
|
||||
{'src': 'Libraries/lvgl/src/**/*.h', 'dst': 'Libraries/lvgl/include/src/'},
|
||||
# elf_loader
|
||||
{'src': 'Libraries/elf_loader/elf_loader.cmake', 'dst': 'Libraries/elf_loader/'},
|
||||
{'src': 'Libraries/elf_loader/license.txt', 'dst': 'Libraries/elf_loader/'},
|
||||
{'src': 'managed_components/espressif__elf_loader/*.cmake', 'dst': 'Libraries/elf_loader/'},
|
||||
{'src': 'managed_components/espressif__elf_loader/*.lf', 'dst': 'Libraries/elf_loader/'},
|
||||
{'src': 'managed_components/espressif__elf_loader/license.txt', 'dst': 'Libraries/elf_loader/'},
|
||||
# minitar
|
||||
{'src': 'build/esp-idf/minitar/libminitar.a', 'dst': 'Libraries/minitar/binary/'},
|
||||
{'src': 'Libraries/minitar/minitar/minitar.h', 'dst': 'Libraries/minitar/include/'},
|
||||
@@ -168,23 +107,18 @@ def main():
|
||||
{'src': 'Libraries/minmea/COPYING', 'dst': 'Libraries/minmea/'},
|
||||
]
|
||||
|
||||
map_copy(mappings, target_path)
|
||||
shared.map_copy(mappings, target_path)
|
||||
|
||||
# Modules
|
||||
add_module(target_path, "app-module")
|
||||
add_module(target_path, "crypt-module")
|
||||
add_module(target_path, "gps-module")
|
||||
add_module(target_path, "http-module")
|
||||
add_module(target_path, "lvgl-module")
|
||||
add_module(target_path, "lvgl-window-manager-module")
|
||||
add_module(target_path, "service-module")
|
||||
module_names = shared.read_module_list(os.path.join('Buildscripts', 'release-sdk-modules.txt'))
|
||||
for module_name in module_names:
|
||||
add_module(target_path, module_name)
|
||||
|
||||
# Final scripts - copied verbatim
|
||||
generate_tactility_sdk_cmake(target_path)
|
||||
generate_tactility_sdk_top_cmakelists(target_path)
|
||||
shared.generate_tactility_sdk_cmake(target_path, 'esp32')
|
||||
shared.generate_tactility_sdk_top_cmakelists(target_path)
|
||||
|
||||
# Output ESP-IDF SDK version to file
|
||||
esp_idf_version = os.environ.get("ESP_IDF_VERSION", "")
|
||||
with open(os.path.join(target_path, "idf-version.txt"), "a") as f:
|
||||
f.write(esp_idf_version)
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
app-module
|
||||
crypt-module
|
||||
gps-module
|
||||
http-module
|
||||
lvgl-module
|
||||
lvgl-window-manager-module
|
||||
service-module
|
||||
Executable
+101
@@ -0,0 +1,101 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import os
|
||||
import sys
|
||||
import importlib.util
|
||||
from textwrap import dedent
|
||||
|
||||
_shared_spec = importlib.util.spec_from_file_location("release_sdk_shared", os.path.join("Buildscripts", "release-sdk-shared.py"))
|
||||
shared = importlib.util.module_from_spec(_shared_spec)
|
||||
_shared_spec.loader.exec_module(shared)
|
||||
|
||||
def get_module_mappings(module_name):
|
||||
return [
|
||||
{'src': f'Modules/{module_name}/include/**', 'dst': f'Modules/{module_name}/include/'},
|
||||
{'src': f'Modules/{module_name}/*.md', 'dst': f'Modules/{module_name}/'},
|
||||
{'src': f'buildsim/Modules/{module_name}/lib{module_name}.a', 'dst': f'Modules/{module_name}/binary/lib{module_name}.a'},
|
||||
]
|
||||
|
||||
def create_module_cmakelists(module_name):
|
||||
return dedent(f'''
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
add_library({module_name} STATIC IMPORTED)
|
||||
set_target_properties({module_name} PROPERTIES
|
||||
IMPORTED_LOCATION "${{CMAKE_CURRENT_LIST_DIR}}/binary/lib{module_name}.a"
|
||||
INTERFACE_INCLUDE_DIRECTORIES "${{CMAKE_CURRENT_LIST_DIR}}/include"
|
||||
)
|
||||
''')
|
||||
|
||||
def add_module(target_path, module_name):
|
||||
mappings = get_module_mappings(module_name)
|
||||
shared.map_copy(mappings, target_path)
|
||||
cmakelists_content = create_module_cmakelists(module_name)
|
||||
shared.write_module_cmakelists(os.path.join(target_path, f"Modules/{module_name}/CMakeLists.txt"), cmakelists_content)
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
print("Usage: release-sdk-posix.py [target_path]")
|
||||
print("Example: release-sdk-posix.py release/TactilitySDK")
|
||||
sys.exit(1)
|
||||
|
||||
esp_idf_version = os.environ.get("ESP_IDF_VERSION", "")
|
||||
if esp_idf_version:
|
||||
print("Error: ESP_IDF_VERSION environment variable is set - this script packages the POSIX/simulator build, run it outside an ESP-IDF environment")
|
||||
sys.exit(1)
|
||||
|
||||
target_path = os.path.abspath(sys.argv[1])
|
||||
os.makedirs(target_path, exist_ok=True)
|
||||
|
||||
# Mapping logic
|
||||
mappings = [
|
||||
{'src': 'version.txt', 'dst': ''},
|
||||
# TactilityFreeRtos
|
||||
{'src': 'TactilityFreeRtos/Include/**', 'dst': 'Libraries/TactilityFreeRtos/Include/'},
|
||||
{'src': 'TactilityFreeRtos/CMakeLists.txt', 'dst': 'Libraries/TactilityFreeRtos/'},
|
||||
{'src': 'TactilityFreeRtos/LICENSE*.*', 'dst': 'Libraries/TactilityFreeRtos/'},
|
||||
# TactilityKernel
|
||||
{'src': 'buildsim/TactilityKernel/libTactilityKernel.a', 'dst': 'Libraries/TactilityKernel/binary/'},
|
||||
{'src': 'TactilityKernel/include/**', 'dst': 'Libraries/TactilityKernel/include/'},
|
||||
{'src': 'TactilityKernel/CMakeLists.txt', 'dst': 'Libraries/TactilityKernel/'},
|
||||
{'src': 'TactilityKernel/*.md', 'dst': 'Libraries/TactilityKernel/'},
|
||||
# FreeRTOS-Kernel - TactilityKernel's public headers (tactility/freertos/*.h) include the
|
||||
# real FreeRTOS.h/task.h/etc directly, unlike ESP32 where ESP-IDF's own "freertos"
|
||||
# component and Kconfig-generated FreeRTOSConfig.h are already part of every project.
|
||||
{'src': 'Libraries/FreeRTOS-Kernel/include/**', 'dst': 'Libraries/FreeRTOS-Kernel/include/'},
|
||||
{'src': 'Libraries/FreeRTOS-Kernel/portable/ThirdParty/GCC/Posix/*.h', 'dst': 'Libraries/FreeRTOS-Kernel/portable/ThirdParty/GCC/Posix/'},
|
||||
{'src': 'Libraries/FreeRTOS-Kernel/portable/ThirdParty/GCC/Posix/utils/*.h', 'dst': 'Libraries/FreeRTOS-Kernel/portable/ThirdParty/GCC/Posix/utils/'},
|
||||
{'src': 'Libraries/FreeRTOS-Kernel/LICENSE*.*', 'dst': 'Libraries/FreeRTOS-Kernel/'},
|
||||
{'src': 'Devices/simulator/Source/FreeRTOSConfig.h', 'dst': 'Libraries/FreeRTOS-Kernel/include/'},
|
||||
# lvgl (basics)
|
||||
{'src': 'buildsim/Libraries/lvgl/lib/liblvgl.a', 'dst': 'Libraries/lvgl/binary/liblvgl.a'},
|
||||
{'src': 'Libraries/lvgl/lvgl.h', 'dst': 'Libraries/lvgl/include/'},
|
||||
{'src': 'Libraries/lvgl/lv_version.h', 'dst': 'Libraries/lvgl/include/'},
|
||||
{'src': 'Libraries/lvgl/LICENCE*.*', 'dst': 'Libraries/lvgl/'},
|
||||
{'src': 'lv_conf.h', 'dst': 'Libraries/lvgl/include/'},
|
||||
{'src': 'Libraries/lvgl/src/**/*.h', 'dst': 'Libraries/lvgl/include/src/'},
|
||||
# minitar
|
||||
{'src': 'buildsim/Libraries/minitar/libminitar.a', 'dst': 'Libraries/minitar/binary/'},
|
||||
{'src': 'Libraries/minitar/minitar/minitar.h', 'dst': 'Libraries/minitar/include/'},
|
||||
{'src': 'Libraries/minitar/minitar/LICENSE*', 'dst': 'Libraries/minitar/'},
|
||||
# minmea
|
||||
{'src': 'buildsim/Libraries/minmea/libminmea.a', 'dst': 'Libraries/minmea/binary/'},
|
||||
{'src': 'Libraries/minmea/Include/**', 'dst': 'Libraries/minmea/include/'},
|
||||
{'src': 'Libraries/minmea/CMakeLists.txt', 'dst': 'Libraries/minmea/'},
|
||||
{'src': 'Libraries/minmea/README.md', 'dst': 'Libraries/minmea/'},
|
||||
{'src': 'Libraries/minmea/LICENSE*.*', 'dst': 'Libraries/minmea/'},
|
||||
{'src': 'Libraries/minmea/COPYING', 'dst': 'Libraries/minmea/'},
|
||||
]
|
||||
|
||||
shared.map_copy(mappings, target_path)
|
||||
|
||||
# Modules
|
||||
module_names = shared.read_module_list(os.path.join('Buildscripts', 'release-sdk-modules.txt'))
|
||||
for module_name in module_names:
|
||||
add_module(target_path, module_name)
|
||||
|
||||
# Final scripts - copied verbatim
|
||||
shared.generate_tactility_sdk_cmake(target_path, 'posix')
|
||||
shared.generate_tactility_sdk_top_cmakelists(target_path)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# Functions shared between release-sdk-esp32.py and release-sdk-posix.py. Not runnable on its
|
||||
# own; loaded by those scripts via importlib (its hyphenated filename isn't a valid Python
|
||||
# module name for a plain "import").
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import glob
|
||||
import sys
|
||||
|
||||
def map_copy(mappings, target_base):
|
||||
"""
|
||||
Helper function to map input files/directories to output files/directories.
|
||||
mappings: list of dicts with 'src' (glob pattern) and 'dst' (relative to target_base or absolute)
|
||||
'src' can be a single file or a directory (if it ends with /).
|
||||
"""
|
||||
for mapping in mappings:
|
||||
src_pattern = mapping['src']
|
||||
dst_rel = mapping['dst']
|
||||
dst_path = os.path.join(target_base, dst_rel)
|
||||
|
||||
# To preserve directory structure, we need to know where the wildcard starts
|
||||
# or have a way to determine the "base" of the search.
|
||||
# We'll split the pattern into a fixed base and a pattern part.
|
||||
|
||||
# Simple heuristic: find the first occurrence of '*' or '?'
|
||||
wildcard_idx = -1
|
||||
for i, char in enumerate(src_pattern):
|
||||
if char in '*?':
|
||||
wildcard_idx = i
|
||||
break
|
||||
|
||||
if wildcard_idx != -1:
|
||||
# Found a wildcard. The base is the directory containing it.
|
||||
pattern_base = os.path.dirname(src_pattern[:wildcard_idx])
|
||||
else:
|
||||
# No wildcard. If it's a directory, we might want to preserve its name?
|
||||
# For now, let's treat no-wildcard as no relative structure needed.
|
||||
pattern_base = None
|
||||
|
||||
src_files = glob.glob(src_pattern, recursive=True)
|
||||
if not src_files:
|
||||
continue
|
||||
|
||||
for src in src_files:
|
||||
if os.path.isdir(src):
|
||||
continue
|
||||
|
||||
if pattern_base and src.startswith(pattern_base):
|
||||
# Calculate relative path from the base of the glob pattern
|
||||
rel_src = os.path.relpath(src, pattern_base)
|
||||
# If dst_rel ends with /, it's a target directory
|
||||
if dst_rel.endswith('/') or os.path.isdir(dst_path):
|
||||
final_dst = os.path.join(dst_path, rel_src)
|
||||
else:
|
||||
# If dst_rel is a file, we can't really preserve structure
|
||||
# unless we join it. But usually it's a dir if structure is preserved.
|
||||
final_dst = dst_path
|
||||
else:
|
||||
final_dst = dst_path if not (dst_rel.endswith('/') or os.path.isdir(dst_path)) else os.path.join(dst_path, os.path.basename(src))
|
||||
|
||||
os.makedirs(os.path.dirname(final_dst), exist_ok=True)
|
||||
shutil.copy2(src, final_dst)
|
||||
|
||||
def write_module_cmakelists(path, content):
|
||||
with open(path, 'w') as f:
|
||||
f.write(content)
|
||||
|
||||
def read_module_list(path):
|
||||
"""Reads a newline-separated module name list, skipping empty lines, and checks that each
|
||||
named module actually exists under Modules/ - exits the process with an error if not."""
|
||||
with open(path, 'r') as f:
|
||||
module_names = [line.strip() for line in f if line.strip()]
|
||||
|
||||
for module_name in module_names:
|
||||
if not os.path.isdir(os.path.join('Modules', module_name)):
|
||||
print(f"Error: Modules/{module_name} does not exist (listed in {path})")
|
||||
sys.exit(1)
|
||||
|
||||
return module_names
|
||||
|
||||
def generate_tactility_sdk_cmake(target_path, variant):
|
||||
"""variant selects Buildscripts/TactilitySDK/TactilitySDK.{variant}.cmake (e.g. "esp32" or
|
||||
"posix") - always copied into the SDK as the platform-neutral name TactilitySDK.cmake."""
|
||||
src = os.path.join('Buildscripts', 'TactilitySDK', f'TactilitySDK.{variant}.cmake')
|
||||
shutil.copy2(src, os.path.join(target_path, 'TactilitySDK.cmake'))
|
||||
|
||||
def generate_tactility_sdk_top_cmakelists(target_path):
|
||||
src = os.path.join('Buildscripts', 'TactilitySDK', 'CMakeLists.txt')
|
||||
shutil.copy2(src, os.path.join(target_path, 'CMakeLists.txt'))
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/bin/sh
|
||||
|
||||
# Usage: release-simulator-macos-app.sh [builddir] [Tactility.app]
|
||||
# Example: release-simulator-macos-app.sh buildsim release/Tactility.app
|
||||
|
||||
set -eu
|
||||
|
||||
build_path=$1
|
||||
bundle_path=$2
|
||||
|
||||
if [ -e "$bundle_path" ]; then
|
||||
echo "Refusing to overwrite existing bundle: $bundle_path" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
contents_path="$bundle_path/Contents"
|
||||
resources_path="$contents_path/Resources"
|
||||
macos_path="$contents_path/MacOS"
|
||||
|
||||
mkdir -p "$resources_path" "$macos_path"
|
||||
|
||||
cp "$build_path/Tactility/Tactility" "$resources_path/Tactility-bin"
|
||||
cp version.txt "$resources_path/"
|
||||
cp -R Data/data "$resources_path/"
|
||||
cp -R Data/system "$resources_path/"
|
||||
|
||||
cat > "$contents_path/Info.plist" <<'EOF'
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>en</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>Tactility</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>org.tactilityproject.simulator</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>Tactility</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>0.8.0-dev</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>NSMicrophoneUsageDescription</key>
|
||||
<string>Tactility uses the microphone when a simulator app records audio.</string>
|
||||
</dict>
|
||||
</plist>
|
||||
EOF
|
||||
|
||||
cat > "$macos_path/Tactility" <<'EOF'
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
resources_path="$(CDPATH= cd -- "$(dirname -- "$0")/../Resources" && pwd)"
|
||||
cd "$resources_path"
|
||||
exec "$resources_path/Tactility-bin" "$@"
|
||||
EOF
|
||||
|
||||
chmod +x "$macos_path/Tactility" "$resources_path/Tactility-bin"
|
||||
@@ -9,9 +9,9 @@
|
||||
build_path=$1
|
||||
target_path=$2
|
||||
|
||||
mkdir -p $target_path
|
||||
mkdir -p "$target_path"
|
||||
|
||||
cp version.txt $target_path
|
||||
cp $build_path/Firmware/FirmwareSim $target_path/
|
||||
cp -r Data/data $target_path/
|
||||
cp -r Data/system $target_path/
|
||||
cp version.txt "$target_path"
|
||||
cp "$build_path/Tactility/Tactility" "$target_path/"
|
||||
cp -r Data/data "$target_path/"
|
||||
cp -r Data/system "$target_path/"
|
||||
|
||||
+46
-15
@@ -33,19 +33,22 @@ 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)
|
||||
|
||||
set(COMPONENTS Firmware)
|
||||
set(COMPONENTS Tactility)
|
||||
set(EXTRA_COMPONENT_DIRS
|
||||
"Firmware"
|
||||
# Tactility must be discovered first: its CMakeLists.txt calls init_tactility_globals(),
|
||||
# which other components' CMakeLists.txt (e.g. lvgl-module) rely on having already run to
|
||||
# read back TACTILITY_DEVICE_ID/TACTILITY_DEVICE_PROJECT via get_property(). ESP-IDF's
|
||||
# requirements-discovery pass processes EXTRA_COMPONENT_DIRS in an isolated sub-process, in
|
||||
# the order listed here, so this must stay first now that Firmware no longer exists as a
|
||||
# separate component.
|
||||
"Tactility"
|
||||
"Devices/${TACTILITY_DEVICE_PROJECT}"
|
||||
"Drivers"
|
||||
"Modules"
|
||||
"Platforms/platform-esp32"
|
||||
"TactilityKernel"
|
||||
"TactilityKernelCpp"
|
||||
"Tactility"
|
||||
"TactilityC"
|
||||
"TactilityFreeRtos"
|
||||
"Libraries/elf_loader"
|
||||
"Libraries/esp_epaper"
|
||||
"Libraries/lv_screenshot"
|
||||
"Libraries/minitar"
|
||||
@@ -55,10 +58,17 @@ if (DEFINED ENV{ESP_IDF_VERSION})
|
||||
|
||||
set(EXCLUDE_COMPONENTS "Simulator")
|
||||
|
||||
# Panic handler wrapping is only available on Xtensa architecture
|
||||
if (CONFIG_IDF_TARGET_ARCH_XTENSA)
|
||||
idf_build_set_property(LINK_OPTIONS "-Wl,--wrap=esp_panic_handler" APPEND)
|
||||
endif ()
|
||||
# panic_info_t is architecture-independent (esp_private/panic_internal.h) so this wrap applies
|
||||
# to every target; PanicHandler.cpp branches internally per architecture.
|
||||
idf_build_set_property(LINK_OPTIONS "-Wl,--wrap=esp_panic_handler" APPEND)
|
||||
|
||||
# Wraps newlib's reentrant syscall stubs, not the plain read()/write()/close() newlib itself
|
||||
# implements as thin wrappers around them. newlib's own stdio (fflush()'s buffer-flush path in particular)
|
||||
# calls these _r stubs directly, bypassing the plain names entirely.
|
||||
# See Modules/app-module/source/stdio_wrap.cpp's own comment for the exact call chain.
|
||||
idf_build_set_property(LINK_OPTIONS "-Wl,--wrap=_read_r" APPEND)
|
||||
idf_build_set_property(LINK_OPTIONS "-Wl,--wrap=_write_r" APPEND)
|
||||
idf_build_set_property(LINK_OPTIONS "-Wl,--wrap=_close_r" APPEND)
|
||||
|
||||
idf_build_set_property(LINK_OPTIONS "-Wl,--wrap=lv_button_create" APPEND)
|
||||
idf_build_set_property(LINK_OPTIONS "-Wl,--wrap=lv_dropdown_create" APPEND)
|
||||
@@ -71,9 +81,7 @@ if (DEFINED ENV{ESP_IDF_VERSION})
|
||||
|
||||
else ()
|
||||
message("Building for sim target")
|
||||
# Devices/simulator/Source/Simulator.cpp always defines its own hardwareConfiguration; without
|
||||
# this, Firmware/Source/Main.cpp's #else branch also defines an empty one (its ESP32-only
|
||||
# fallback for devices migrated off the deprecated HAL), causing a duplicate-definition link error.
|
||||
# eps-idf generates these from Kconfig, but posix build isn't set up with Kconfig.
|
||||
add_compile_definitions(CONFIG_TT_DEVICE_ID="simulator")
|
||||
add_compile_definitions(CONFIG_TT_DEVICE_NAME="Simulator")
|
||||
add_compile_definitions(CONFIG_TT_DEVICE_VENDOR="")
|
||||
@@ -85,8 +93,26 @@ endif ()
|
||||
|
||||
project(Tactility)
|
||||
|
||||
if (DEFINED ENV{ESP_IDF_VERSION})
|
||||
# PanicHandler.cpp's RISC-V callstack walker requires s0 to stay a frame pointer, which GCC
|
||||
# does not guarantee without this flag. CONFIG_ESP_SYSTEM_USE_FRAME_POINTER does not add it
|
||||
# (it only selects which ESP-IDF backtrace-printing function gets compiled), and can't be used
|
||||
# instead: the bootloader shares this project's sdkconfig with no per-subproject override, and
|
||||
# enabling it there overflows the bootloader's fixed partition budget. Setting the flag here via
|
||||
# idf_build_set_property() only affects this project's own configure, not the bootloader's
|
||||
# separate one, so it's naturally excluded. Gated to RISC-V since Xtensa never reads s0 this way.
|
||||
# Must run after project(Tactility) above - project() initializes default build specifications
|
||||
# that would otherwise overwrite this.
|
||||
if(CONFIG_IDF_TARGET_ARCH_RISCV)
|
||||
idf_build_set_property(COMPILE_OPTIONS "-fno-omit-frame-pointer" APPEND)
|
||||
endif()
|
||||
endif ()
|
||||
|
||||
# Defined as regular project for PC and component for ESP
|
||||
if (NOT DEFINED ENV{ESP_IDF_VERSION})
|
||||
if (APPLE)
|
||||
enable_language(OBJC OBJCXX)
|
||||
endif ()
|
||||
add_subdirectory(Tactility)
|
||||
add_subdirectory(TactilityFreeRtos)
|
||||
add_subdirectory(TactilityKernel)
|
||||
@@ -99,14 +125,22 @@ if (NOT DEFINED ENV{ESP_IDF_VERSION})
|
||||
add_subdirectory(Libraries/minitar)
|
||||
add_subdirectory(Libraries/minmea)
|
||||
add_subdirectory(Modules/lvgl-module)
|
||||
add_subdirectory(Modules/c-symbols-module)
|
||||
add_subdirectory(Modules/cpp-symbols-module)
|
||||
add_subdirectory(Modules/crypt-module)
|
||||
add_subdirectory(Modules/freertos-module)
|
||||
add_subdirectory(Modules/gps-module)
|
||||
add_subdirectory(Modules/http-module)
|
||||
add_subdirectory(Modules/mbedtls-module)
|
||||
add_subdirectory(Modules/posix-symbols-module)
|
||||
add_subdirectory(Modules/pthread-module)
|
||||
add_subdirectory(Modules/service-module)
|
||||
add_subdirectory(Modules/app-module)
|
||||
add_subdirectory(Modules/app-posix-module)
|
||||
add_subdirectory(Modules/lvgl-window-manager-module)
|
||||
add_subdirectory(Drivers/gps-generic-module)
|
||||
add_subdirectory(Drivers/gps-meshtastic-module)
|
||||
add_subdirectory(Drivers/audio-stream-module)
|
||||
|
||||
# FreeRTOS
|
||||
set(FREERTOS_CONFIG_FILE_DIRECTORY ${PROJECT_SOURCE_DIR}/Devices/simulator/Source CACHE STRING "")
|
||||
@@ -130,9 +164,6 @@ if (NOT DEFINED ENV{ESP_IDF_VERSION})
|
||||
add_subdirectory(Libraries/lvgl) # Added as idf component for ESP and as library for other targets
|
||||
target_link_libraries(lvgl PRIVATE SDL2-static)
|
||||
|
||||
# Sim app
|
||||
add_subdirectory(Firmware)
|
||||
|
||||
# Tests
|
||||
add_subdirectory(Tests)
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ apOpenNetwork=0
|
||||
apChannel=1
|
||||
|
||||
# Web Server Settings
|
||||
webServerEnabled=0
|
||||
webServerEnabled=1
|
||||
webServerPort=80
|
||||
|
||||
# HTTP Basic Authentication (optional)
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 298 KiB |
@@ -19,3 +19,8 @@ display.dpi=143
|
||||
lvgl.colorDepth=16
|
||||
|
||||
storage.userDataLocation=SD
|
||||
|
||||
# Launcher clock and full-screen wallpaper
|
||||
sdkconfig.CONFIG_LV_FONT_MONTSERRAT_48=y
|
||||
sdkconfig.CONFIG_LV_CACHE_DEF_SIZE=1048576
|
||||
sdkconfig.CONFIG_LV_IMAGE_HEADER_CACHE_DEF_CNT=16
|
||||
|
||||
@@ -90,6 +90,7 @@
|
||||
compatible = "everest,es8311";
|
||||
reg = <0x18>;
|
||||
i2s = <&i2s0>;
|
||||
input-gain-percent = <100>;
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
idf_component_register(
|
||||
SRCS "source/module.cpp"
|
||||
REQUIRES TactilityKernel
|
||||
)
|
||||
@@ -0,0 +1,28 @@
|
||||
general.vendor=LCDWIKI/Hosyond
|
||||
general.name=ES3C35P
|
||||
|
||||
apps.launcherAppId=tactility.launcher
|
||||
|
||||
hardware.target=ESP32S3
|
||||
hardware.flashSize=16MB
|
||||
hardware.spiRam=true
|
||||
hardware.spiRamMode=OCT
|
||||
hardware.spiRamSpeed=120M
|
||||
hardware.esptoolFlashFreq=120M
|
||||
hardware.bluetooth=true
|
||||
|
||||
display.size=3.5"
|
||||
display.shape=rectangle
|
||||
display.dpi=165
|
||||
|
||||
lvgl.colorDepth=16
|
||||
lvgl.fontSize=16
|
||||
|
||||
storage.userDataLocation=SD
|
||||
|
||||
dependencies.useDeprecatedHal=false
|
||||
|
||||
# Launcher clock and full-screen wallpaper
|
||||
sdkconfig.CONFIG_LV_FONT_MONTSERRAT_48=y
|
||||
sdkconfig.CONFIG_LV_CACHE_DEF_SIZE=1048576
|
||||
sdkconfig.CONFIG_LV_IMAGE_HEADER_CACHE_DEF_CNT=16
|
||||
@@ -0,0 +1,6 @@
|
||||
dependencies:
|
||||
- Platforms/platform-esp32
|
||||
- Drivers/st77922-module
|
||||
- Drivers/es8311-module
|
||||
- Drivers/audio-stream-module
|
||||
dts: es3c35p.dts
|
||||
@@ -0,0 +1,142 @@
|
||||
/dts-v1/;
|
||||
|
||||
#include <tactility/bindings/root.h>
|
||||
#include <tactility/bindings/esp32_adc_oneshot.h>
|
||||
#include <tactility/bindings/esp32_ble.h>
|
||||
#include <tactility/bindings/esp32_gpio.h>
|
||||
#include <tactility/bindings/esp32_i2c.h>
|
||||
#include <tactility/bindings/esp32_i2s.h>
|
||||
#include <tactility/bindings/esp32_pwm_ledc.h>
|
||||
#include <tactility/bindings/esp32_sdmmc.h>
|
||||
#include <tactility/bindings/esp32_spi.h>
|
||||
#include <tactility/bindings/esp32_wifi_pinned.h>
|
||||
#include <tactility/bindings/battery_sense.h>
|
||||
#include <tactility/bindings/gpio_hog.h>
|
||||
#include <tactility/bindings/pwm_backlight.h>
|
||||
#include <bindings/st77922.h>
|
||||
#include <bindings/st77922_touch.h>
|
||||
#include <bindings/es8311.h>
|
||||
|
||||
/ {
|
||||
compatible = "root";
|
||||
model = "LCDWIKI/Hosyond ES3C35P";
|
||||
|
||||
wifi0 {
|
||||
compatible = "espressif,esp32-wifi-pinned";
|
||||
};
|
||||
|
||||
ble0 {
|
||||
compatible = "espressif,esp32-ble";
|
||||
};
|
||||
|
||||
gpio0 {
|
||||
compatible = "espressif,esp32-gpio";
|
||||
gpio-count = <49>;
|
||||
};
|
||||
|
||||
/* FM8002E speaker amplifier enable, active-low on GPIO1. */
|
||||
amp_enable {
|
||||
compatible = "gpio-hog";
|
||||
pin = <&gpio0 1 GPIO_FLAG_NONE>;
|
||||
mode = <GPIO_HOG_MODE_OUTPUT_LOW>;
|
||||
};
|
||||
|
||||
adc0 {
|
||||
compatible = "espressif,esp32-adc-oneshot";
|
||||
unit-id = <ADC_UNIT_1>;
|
||||
clk-src = <ADC_RTC_CLK_SRC_DEFAULT>;
|
||||
channels = <ADC_CHANNEL_7 ADC_ATTEN_DB_12 ADC_BITWIDTH_DEFAULT>;
|
||||
};
|
||||
|
||||
/* BAT+ through a 200K/200K divider into GPIO8 / ADC1_CH7. */
|
||||
battery-sense {
|
||||
compatible = "battery-sense";
|
||||
io-channel = <&adc0 0>;
|
||||
reference-voltage-mv = <3300>;
|
||||
multiplier = <2000>;
|
||||
};
|
||||
|
||||
i2s0 {
|
||||
compatible = "espressif,esp32-i2s";
|
||||
port = <I2S_NUM_0>;
|
||||
pin-bclk = <&gpio0 18 GPIO_FLAG_NONE>;
|
||||
pin-ws = <&gpio0 21 GPIO_FLAG_NONE>;
|
||||
pin-data-out = <&gpio0 15 GPIO_FLAG_NONE>;
|
||||
pin-data-in = <&gpio0 16 GPIO_FLAG_NONE>;
|
||||
pin-mclk = <&gpio0 17 GPIO_FLAG_NONE>;
|
||||
};
|
||||
|
||||
i2c0 {
|
||||
compatible = "espressif,esp32-i2c";
|
||||
port = <I2C_NUM_0>;
|
||||
clock-frequency = <400000>;
|
||||
pin-sda = <&gpio0 38 GPIO_FLAG_NONE>;
|
||||
pin-scl = <&gpio0 39 GPIO_FLAG_NONE>;
|
||||
|
||||
touch@55 {
|
||||
compatible = "sitronix,st77922-touch";
|
||||
reg = <0x55>;
|
||||
x-max = <320>;
|
||||
y-max = <480>;
|
||||
pin-reset = <&gpio0 48 GPIO_FLAG_NONE>;
|
||||
pin-interrupt = <&gpio0 47 GPIO_FLAG_NONE>;
|
||||
};
|
||||
|
||||
es8311: es8311@18 {
|
||||
compatible = "everest,es8311";
|
||||
reg = <0x18>;
|
||||
i2s = <&i2s0>;
|
||||
input-gain-percent = <100>;
|
||||
};
|
||||
};
|
||||
|
||||
display_backlight_pwm {
|
||||
compatible = "espressif,esp32-pwm-ledc";
|
||||
pin = <&gpio0 41 GPIO_FLAG_NONE>;
|
||||
period-ns = <200000>;
|
||||
ledc-timer = <0>;
|
||||
ledc-channel = <0>;
|
||||
};
|
||||
|
||||
display_backlight {
|
||||
compatible = "pwm-backlight";
|
||||
status = "disabled";
|
||||
pwm = <&display_backlight_pwm>;
|
||||
};
|
||||
|
||||
spi0 {
|
||||
compatible = "espressif,esp32-spi";
|
||||
host = <SPI2_HOST>;
|
||||
pin-sclk = <&gpio0 12 GPIO_FLAG_NONE>;
|
||||
pin-mosi = <&gpio0 11 GPIO_FLAG_NONE>;
|
||||
pin-miso = <&gpio0 13 GPIO_FLAG_NONE>;
|
||||
pin-wp = <&gpio0 14 GPIO_FLAG_NONE>;
|
||||
pin-hd = <&gpio0 9 GPIO_FLAG_NONE>;
|
||||
cs-gpios = <&gpio0 10 GPIO_FLAG_NONE>;
|
||||
/* Accommodate the driver's 1/10-frame DMA staging transfers, matching
|
||||
* the vendor LVGL port's full-frame refresh path. */
|
||||
max-transfer-size = <65536>;
|
||||
|
||||
display@0 {
|
||||
compatible = "sitronix,st77922";
|
||||
horizontal-resolution = <320>;
|
||||
vertical-resolution = <480>;
|
||||
/* 80 MHz works in the vendor demo, but produces visible QSPI corruption on
|
||||
* some modules/cables. The component's 40 MHz default is reliably clean. */
|
||||
pixel-clock-hz = <40000000>;
|
||||
backlight = <&display_backlight>;
|
||||
};
|
||||
};
|
||||
|
||||
sdmmc0 {
|
||||
compatible = "espressif,esp32-sdmmc";
|
||||
pin-clk = <&gpio0 5 GPIO_FLAG_NONE>;
|
||||
pin-cmd = <&gpio0 4 GPIO_FLAG_NONE>;
|
||||
pin-d0 = <&gpio0 6 GPIO_FLAG_NONE>;
|
||||
pin-d1 = <&gpio0 7 GPIO_FLAG_NONE>;
|
||||
pin-d2 = <&gpio0 2 GPIO_FLAG_NONE>;
|
||||
pin-d3 = <&gpio0 3 GPIO_FLAG_NONE>;
|
||||
slot = <SDMMC_HOST_SLOT_1>;
|
||||
bus-width = <4>;
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,9 @@
|
||||
#include <tactility/module.h>
|
||||
|
||||
extern "C" {
|
||||
|
||||
Module es3c35p_module = {
|
||||
.name = "es3c35p"
|
||||
};
|
||||
|
||||
}
|
||||
@@ -10,10 +10,13 @@ properties:
|
||||
type: int
|
||||
default: 20
|
||||
description: Ambient temperature in °C, used for waveform timing compensation
|
||||
draw-mode:
|
||||
quality-draw-mode:
|
||||
type: int
|
||||
default: MODE_DU
|
||||
description: Default EpdDrawMode waveform used for screen updates (e.g. MODE_DU, MODE_GC16)
|
||||
default: MODE_GC16
|
||||
description: >
|
||||
EpdDrawMode waveform used for full-quality refreshes (e.g. MODE_GC16, MODE_GL16).
|
||||
Fast partial updates always use MODE_DU internally and are not configurable - see
|
||||
driver comments.
|
||||
rotation:
|
||||
type: int
|
||||
default: EPD_ROT_PORTRAIT
|
||||
|
||||
@@ -7,7 +7,7 @@ apps.launcherAppId=tactility.launcher
|
||||
hardware.target=esp32s3
|
||||
hardware.flashSize=16MB
|
||||
hardware.spiRam=true
|
||||
hardware.spiRamMode=OPI
|
||||
hardware.spiRamMode=OCT
|
||||
hardware.spiRamSpeed=80M
|
||||
hardware.esptoolFlashFreq=80M
|
||||
hardware.tinyUsbMsc=true
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
/**
|
||||
* Board definition for M5Stack PaperS3.
|
||||
*
|
||||
* Kept out-of-tree (see epd_board_m5papers3.h) instead of forking epdiy: this file only
|
||||
* uses epdiy's public API, so it builds as an ordinary consumer of the upstream component.
|
||||
*
|
||||
* Pin mapping from M5GFX source code (authoritative reference):
|
||||
* https://github.com/m5stack/M5GFX/blob/master/src/M5GFX.cpp
|
||||
*
|
||||
* Data bus: DB0-DB7 on GPIO 6,14,7,12,9,11,8,10
|
||||
* Control: STH=13, LEH=15, STV=17, CKV=18, CKH=16
|
||||
* Power: PWR=46, OE=45
|
||||
*/
|
||||
|
||||
#include "epd_board_m5papers3.h"
|
||||
|
||||
#include <stdint.h>
|
||||
#include "epdiy.h"
|
||||
|
||||
#include <output_lcd/lcd_driver.h>
|
||||
#include "esp_log.h"
|
||||
|
||||
#include <driver/gpio.h>
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
|
||||
#ifndef CONFIG_IDF_TARGET_ESP32S3
|
||||
#error "M5Paper S3 board only supports ESP32-S3"
|
||||
#endif
|
||||
|
||||
static const char* TAG = "m5paper_s3";
|
||||
|
||||
/* Data Lines - from M5GFX source */
|
||||
#define D0 GPIO_NUM_6
|
||||
#define D1 GPIO_NUM_14
|
||||
#define D2 GPIO_NUM_7
|
||||
#define D3 GPIO_NUM_12
|
||||
#define D4 GPIO_NUM_9
|
||||
#define D5 GPIO_NUM_11
|
||||
#define D6 GPIO_NUM_8
|
||||
#define D7 GPIO_NUM_10
|
||||
|
||||
/* Control Lines - from M5GFX source */
|
||||
#define STH GPIO_NUM_13 /* Start pulse horizontal (active low) */
|
||||
#define LEH GPIO_NUM_15 /* Latch enable horizontal */
|
||||
#define STV GPIO_NUM_17 /* Start vertical */
|
||||
#define CKV GPIO_NUM_18 /* Clock vertical */
|
||||
#define CKH GPIO_NUM_16 /* Clock horizontal - LCD peripheral clock output */
|
||||
|
||||
/* Power control - from M5GFX source */
|
||||
#define PWR_PIN GPIO_NUM_46 /* Main power enable */
|
||||
#define OE_PIN GPIO_NUM_45 /* Output enable */
|
||||
|
||||
|
||||
static lcd_bus_config_t lcd_config = {
|
||||
.clock = CKH,
|
||||
.ckv = CKV,
|
||||
.leh = LEH,
|
||||
.start_pulse = STH,
|
||||
.stv = STV,
|
||||
.data[0] = D0,
|
||||
.data[1] = D1,
|
||||
.data[2] = D2,
|
||||
.data[3] = D3,
|
||||
.data[4] = D4,
|
||||
.data[5] = D5,
|
||||
.data[6] = D6,
|
||||
.data[7] = D7,
|
||||
};
|
||||
|
||||
static void epd_board_init(uint32_t epd_row_width, const EpdInitConfig* init_config) {
|
||||
(void)init_config;
|
||||
ESP_LOGI(TAG, "Initializing M5Paper S3 board");
|
||||
|
||||
/* Configure power pin - start with power off */
|
||||
gpio_reset_pin(PWR_PIN);
|
||||
gpio_set_direction(PWR_PIN, GPIO_MODE_OUTPUT);
|
||||
gpio_set_level(PWR_PIN, 0);
|
||||
|
||||
/* Configure output enable pin - active high */
|
||||
gpio_reset_pin(OE_PIN);
|
||||
gpio_set_direction(OE_PIN, GPIO_MODE_OUTPUT);
|
||||
gpio_set_level(OE_PIN, 0);
|
||||
|
||||
const EpdDisplay_t* display = epd_get_display();
|
||||
|
||||
LcdEpdConfig_t config = {
|
||||
.pixel_clock = display->bus_speed * 1000 * 1000,
|
||||
.ckv_high_time = 60,
|
||||
.line_front_porch = 4,
|
||||
.le_high_time = 4,
|
||||
.bus_width = display->bus_width,
|
||||
.bus = lcd_config,
|
||||
};
|
||||
|
||||
epd_lcd_init(&config, display->width, display->height);
|
||||
|
||||
ESP_LOGI(TAG, "Board initialized: %dx%d @ %dMHz",
|
||||
display->width, display->height, display->bus_speed);
|
||||
}
|
||||
|
||||
static void epd_board_deinit() {
|
||||
ESP_LOGI(TAG, "Deinitializing M5Paper S3 board");
|
||||
|
||||
/* Disable output first */
|
||||
gpio_set_level(OE_PIN, 0);
|
||||
|
||||
/* Power off display */
|
||||
gpio_set_level(PWR_PIN, 0);
|
||||
|
||||
epd_lcd_deinit();
|
||||
}
|
||||
|
||||
static void epd_board_set_ctrl(epd_ctrl_state_t* state, const epd_ctrl_state_t* const mask) {
|
||||
/* Handle output enable changes */
|
||||
if (mask->ep_output_enable) {
|
||||
gpio_set_level(OE_PIN, state->ep_output_enable ? 1 : 0);
|
||||
}
|
||||
}
|
||||
|
||||
static void epd_board_poweron(epd_ctrl_state_t* state) {
|
||||
ESP_LOGI(TAG, "Powering on display");
|
||||
|
||||
/* Enable main power first */
|
||||
gpio_set_level(PWR_PIN, 1);
|
||||
|
||||
/* Wait for power to stabilize */
|
||||
vTaskDelay(pdMS_TO_TICKS(100));
|
||||
|
||||
/* Enable output */
|
||||
gpio_set_level(OE_PIN, 1);
|
||||
|
||||
/* Update state */
|
||||
state->ep_stv = true;
|
||||
state->ep_mode = false;
|
||||
state->ep_output_enable = true;
|
||||
state->ep_sth = true;
|
||||
}
|
||||
|
||||
static void epd_board_poweroff(epd_ctrl_state_t* state) {
|
||||
ESP_LOGI(TAG, "Powering off display");
|
||||
|
||||
/* Disable output first */
|
||||
gpio_set_level(OE_PIN, 0);
|
||||
|
||||
state->ep_stv = false;
|
||||
state->ep_output_enable = false;
|
||||
state->ep_mode = false;
|
||||
state->ep_sth = false;
|
||||
|
||||
/* Small delay before cutting power */
|
||||
vTaskDelay(pdMS_TO_TICKS(10));
|
||||
|
||||
/* Cut main power */
|
||||
gpio_set_level(PWR_PIN, 0);
|
||||
}
|
||||
|
||||
static float epd_board_ambient_temperature() {
|
||||
/* TODO: Could read from BMI270 temperature sensor */
|
||||
return 20.0f;
|
||||
}
|
||||
|
||||
const EpdBoardDefinition epd_board_m5papers3 = {
|
||||
.init = epd_board_init,
|
||||
.deinit = epd_board_deinit,
|
||||
.set_ctrl = epd_board_set_ctrl,
|
||||
.poweron = epd_board_poweron,
|
||||
.poweroff = epd_board_poweroff,
|
||||
.get_temperature = epd_board_ambient_temperature,
|
||||
// No hardware VCOM control path on this board yet - a non-null callback that doesn't touch
|
||||
// hardware would let epd_set_vcom() complete without changing anything on the panel.
|
||||
.set_vcom = NULL,
|
||||
.gpio_set_direction = NULL,
|
||||
.gpio_read = NULL,
|
||||
.gpio_write = NULL,
|
||||
};
|
||||
@@ -0,0 +1,20 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
/**
|
||||
* @file "epd_board_m5papers3.h"
|
||||
* @brief Board definition for M5Stack PaperS3, kept out-of-tree because upstream epdiy
|
||||
* (https://github.com/vroland/epdiy) does not support this board.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <epd_board.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
extern const EpdBoardDefinition epd_board_m5papers3;
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -7,8 +7,10 @@
|
||||
#include <tactility/error.h>
|
||||
#include <tactility/log.h>
|
||||
#include <tactility/module.h>
|
||||
#include <tactility/time.h>
|
||||
|
||||
#include "epd_board_m5papers3.h"
|
||||
|
||||
#include <epd_board.h>
|
||||
#include <epdiy.h>
|
||||
|
||||
#include <esp_heap_caps.h>
|
||||
@@ -19,6 +21,70 @@
|
||||
#define TAG "Papers3Display"
|
||||
#define GET_CONFIG(device) (static_cast<const Papers3DisplayConfig*>((device)->config))
|
||||
|
||||
// Fast partial updates are always MODE_DU (strict black/white); config->quality_draw_mode is
|
||||
// only used for the periodic full-quality pass.
|
||||
static constexpr EpdDrawMode FAST_DRAW_MODE = MODE_DU;
|
||||
|
||||
// A partial update covering at least this fraction of the panel is a full-screen content change
|
||||
// (e.g. an app switch rebuilding the whole window, see lvgl.md) rather than a small widget
|
||||
// redraw, and is promoted to a quality refresh immediately.
|
||||
static constexpr float FULL_AREA_QUALITY_THRESHOLD = 0.6f;
|
||||
|
||||
// Bounds worst-case ghost accumulation during sustained fast-mode interaction (e.g. scrolling),
|
||||
// regardless of idle time. LVGL's PARTIAL-mode draw buffer covers vres/10 rows (see
|
||||
// lvgl-module/source/devices/devices.cpp's buffer_height), so a single full-screen redraw is
|
||||
// already ~10 tiles - this must clear a full sweep comfortably, or a normal full-screen redraw
|
||||
// gets promoted to slow GC16 partway through.
|
||||
static constexpr uint32_t QUALITY_REFRESH_PARTIAL_COUNT = 20;
|
||||
|
||||
// Cleans up ghosting left behind after interaction stops, since nothing else triggers a refresh
|
||||
// once draw_bitmap() calls stop arriving. Matches the M5Stack official demo's timer.
|
||||
static constexpr uint32_t QUALITY_REFRESH_IDLE_SECONDS = 10;
|
||||
|
||||
// LVGL's PARTIAL render mode flushes one draw_bitmap() call per still-unjoined dirty rect, so
|
||||
// one visual refresh is usually several back-to-back calls, not one; this holds quality mode
|
||||
// across a sibling rect's near-zero gap so they don't end up on inconsistent modes. Must stay
|
||||
// well under a GC16 draw's own duration (400ms+), or it also bridges the much larger gap between
|
||||
// separate real frames and pins a whole multi-frame interaction to GC16.
|
||||
static constexpr uint32_t QUALITY_HOLD_MS = 50;
|
||||
|
||||
// epd_fullclear() (white fill + GC16 draw + 3-cycle black/white flash, see epdiy's
|
||||
// highlevel.c/render.c) only runs once, at boot (papers3_display_init()), never periodically:
|
||||
// it wipes the whole panel, and this driver has no way to force LVGL to redraw everything
|
||||
// afterward - only whatever rect is drawn next gets restored, leaving the rest blank.
|
||||
|
||||
// 4x4 ordered (Bayer) dither thresholds, spread evenly across a 0-15 nibble range.
|
||||
static constexpr uint8_t BAYER_4X4[4][4] = {
|
||||
{ 0, 8, 2, 10 },
|
||||
{ 12, 4, 14, 6 },
|
||||
{ 3, 11, 1, 9 },
|
||||
{ 15, 7, 13, 5 },
|
||||
};
|
||||
|
||||
// Dithers an 8-bit luminance sample (0x00=black..0xFF=white) down to a 4-bit nibble
|
||||
// (0x0=black..0xF=white, matching EPDiy's MODE_PACKING_2PPB), spreading the rounding error
|
||||
// spatially instead of truncating every pixel the same way - this is what turns flat/banded
|
||||
// output into something that reads as smooth grayscale.
|
||||
static inline uint8_t dither_to_nibble(uint8_t luminance, int32_t x, int32_t y) {
|
||||
// BAYER_4X4 is 0-15; scaled by 17 it spans a full 0-255 quantization step (one increment of
|
||||
// luminance*15), so the dither bias is actually comparable to the rounding it perturbs
|
||||
// instead of a few percent of one step.
|
||||
const uint32_t threshold = BAYER_4X4[y & 3][x & 3] * 17U;
|
||||
const uint32_t level = (static_cast<uint32_t>(luminance) * 15U + threshold) / 255U;
|
||||
return static_cast<uint8_t>(level > 15U ? 15U : level);
|
||||
}
|
||||
|
||||
// Binary variant for MODE_DU, which only supports pure black/white (see epdiy.h) - dithering
|
||||
// still applies so a partial-update area doesn't look coarser than the quality pass that
|
||||
// preceded it.
|
||||
static inline uint8_t dither_to_bw_nibble(uint8_t luminance, int32_t x, int32_t y) {
|
||||
// *16 (not 17) keeps the max threshold at 240, strictly below 255 - otherwise luminance 0xFF
|
||||
// (pure white) would tie the top Bayer cell's threshold and the strict ">" would misclassify
|
||||
// it as black.
|
||||
const uint32_t threshold = BAYER_4X4[y & 3][x & 3] * 16U;
|
||||
return luminance > threshold ? 0xF : 0x0;
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
|
||||
extern Module m5stack_papers3_module;
|
||||
@@ -34,6 +100,15 @@ struct Papers3DisplayInternal {
|
||||
// Scratch buffer for the grayscale8->EPDiy(4bpp packed, 2px/byte) conversion in draw_bitmap().
|
||||
uint8_t* packed_buffer;
|
||||
bool powered;
|
||||
uint32_t panel_pixel_count;
|
||||
// Fast (MODE_DU) partial updates since the last quality refresh; see
|
||||
// QUALITY_REFRESH_PARTIAL_COUNT.
|
||||
uint32_t partial_count_since_quality;
|
||||
// get_ticks() at the last quality refresh; see QUALITY_REFRESH_IDLE_SECONDS.
|
||||
TickType_t last_quality_refresh_tick;
|
||||
// While get_ticks() < this, every draw_bitmap() call uses quality mode regardless of the
|
||||
// other triggers; see QUALITY_HOLD_MS.
|
||||
TickType_t quality_hold_until_tick;
|
||||
};
|
||||
|
||||
static void power_on(Papers3DisplayInternal* internal) {
|
||||
@@ -64,9 +139,48 @@ static error_t papers3_display_init(Device* device) {
|
||||
// pass, leaving a faint ghost. Run a full clear now, before LVGL's first flush ever reaches
|
||||
// draw_bitmap(), so it never has to undo content LVGL already put on screen.
|
||||
epd_fullclear(&internal->hl_state, config->temperature_celsius);
|
||||
internal->partial_count_since_quality = 0;
|
||||
internal->last_quality_refresh_tick = get_ticks();
|
||||
internal->quality_hold_until_tick = 0;
|
||||
return ERROR_NONE;
|
||||
}
|
||||
|
||||
// Decides whether this update should be a full-quality (config->quality_draw_mode) refresh or
|
||||
// a fast MODE_DU one. Read-only - see commit_quality_mode_decision() for the state this decision
|
||||
// leads to.
|
||||
static bool should_use_quality_mode(Papers3DisplayInternal* internal, int32_t width, int32_t height) {
|
||||
const TickType_t now = get_ticks();
|
||||
|
||||
const uint32_t area = static_cast<uint32_t>(width) * static_cast<uint32_t>(height);
|
||||
const bool is_full_screen_change = area >= static_cast<uint32_t>(
|
||||
static_cast<float>(internal->panel_pixel_count) * FULL_AREA_QUALITY_THRESHOLD
|
||||
);
|
||||
const bool partial_count_exceeded = internal->partial_count_since_quality >= QUALITY_REFRESH_PARTIAL_COUNT;
|
||||
// Idle refresh is too problematic to worth the possible gains. So it isn't done on purpose.
|
||||
// Ghosting is very minimal now anyway (it's still around but way less bad)
|
||||
const bool idle_exceeded = now - internal->last_quality_refresh_tick >= seconds_to_ticks(QUALITY_REFRESH_IDLE_SECONDS);
|
||||
const bool within_hold = now < internal->quality_hold_until_tick;
|
||||
|
||||
return is_full_screen_change || partial_count_exceeded || idle_exceeded || within_hold;
|
||||
}
|
||||
|
||||
// Applies should_use_quality_mode()'s decision, but only commits the quality-mode reset once the
|
||||
// draw actually succeeded - a failed quality refresh must not make a still-ghosting panel look
|
||||
// freshly cleaned to every trigger above. A failed fast update still counts toward the partial
|
||||
// count, since it was still MODE_DU content, not a clean slate.
|
||||
static void commit_quality_mode_decision(Papers3DisplayInternal* internal, bool used_quality, bool draw_succeeded) {
|
||||
if (used_quality) {
|
||||
if (draw_succeeded) {
|
||||
const TickType_t now = get_ticks();
|
||||
internal->partial_count_since_quality = 0;
|
||||
internal->last_quality_refresh_tick = now;
|
||||
internal->quality_hold_until_tick = now + millis_to_ticks(QUALITY_HOLD_MS);
|
||||
}
|
||||
} else {
|
||||
internal->partial_count_since_quality++;
|
||||
}
|
||||
}
|
||||
|
||||
// Reports GRAYSCALE8 (not MONOCHROME) so LVGL uses partial/tile updates instead of forcing
|
||||
// full-frame - the bridge hardcodes full-frame for MONOCHROME/I1 regardless of capability flags.
|
||||
// So draw_bitmap is called once per changed tile, not necessarily the whole panel.
|
||||
@@ -76,11 +190,12 @@ static error_t papers3_display_draw_bitmap(Device* device, int32_t x_start, int3
|
||||
|
||||
const int32_t width = x_end - x_start;
|
||||
const int32_t height = y_end - y_start;
|
||||
const bool use_quality = should_use_quality_mode(internal, width, height);
|
||||
|
||||
// color_data is DISPLAY_COLOR_FORMAT_GRAYSCALE8: row-major, 1 byte/pixel luminance
|
||||
// (0x00=black..0xFF=white, matching LVGL's L8). EPDiy wants 4bpp packed (2px/byte, 0x0=black,
|
||||
// 0xF=white) - a plain >>4 truncation preserves all 16 real gray levels the panel supports
|
||||
// (this panel is not B/W-only; see MODE_GC16/GL16 in papers3-display.yaml's draw-mode doc).
|
||||
// 0xF=white); Bayer dithering (full 16-level for the quality pass, binary for MODE_DU)
|
||||
// spreads the rounding error instead of a flat truncation.
|
||||
const auto* src = static_cast<const uint8_t*>(color_data);
|
||||
const size_t src_stride = static_cast<size_t>(width);
|
||||
const size_t packed_stride = static_cast<size_t>(width + 1) / 2;
|
||||
@@ -90,12 +205,18 @@ static error_t papers3_display_draw_bitmap(Device* device, int32_t x_start, int3
|
||||
uint8_t* dst_row = internal->packed_buffer + static_cast<size_t>(row) * packed_stride;
|
||||
int32_t col = 0;
|
||||
for (; col + 2 <= width; col += 2) {
|
||||
const uint8_t p0 = src_row[col] >> 4U;
|
||||
const uint8_t p1 = src_row[col + 1] >> 4U;
|
||||
const uint8_t p0 = use_quality
|
||||
? dither_to_nibble(src_row[col], x_start + col, y_start + row)
|
||||
: dither_to_bw_nibble(src_row[col], x_start + col, y_start + row);
|
||||
const uint8_t p1 = use_quality
|
||||
? dither_to_nibble(src_row[col + 1], x_start + col + 1, y_start + row)
|
||||
: dither_to_bw_nibble(src_row[col + 1], x_start + col + 1, y_start + row);
|
||||
dst_row[col / 2] = static_cast<uint8_t>((p1 << 4U) | p0);
|
||||
}
|
||||
if (col < width) { // odd width: last column has no pair, low nibble unused
|
||||
dst_row[col / 2] = static_cast<uint8_t>(src_row[col] >> 4U);
|
||||
dst_row[col / 2] = use_quality
|
||||
? dither_to_nibble(src_row[col], x_start + col, y_start + row)
|
||||
: dither_to_bw_nibble(src_row[col], x_start + col, y_start + row);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,13 +229,15 @@ static error_t papers3_display_draw_bitmap(Device* device, int32_t x_start, int3
|
||||
|
||||
power_on(internal);
|
||||
epd_draw_rotated_image(update_area, internal->packed_buffer, internal->framebuffer);
|
||||
const auto draw_mode = use_quality ? config->quality_draw_mode : FAST_DRAW_MODE;
|
||||
auto draw_result = epd_hl_update_area(
|
||||
&internal->hl_state,
|
||||
static_cast<EpdDrawMode>(config->draw_mode | MODE_PACKING_2PPB),
|
||||
static_cast<EpdDrawMode>(draw_mode | MODE_PACKING_2PPB),
|
||||
config->temperature_celsius,
|
||||
update_area
|
||||
);
|
||||
|
||||
commit_quality_mode_decision(internal, use_quality, draw_result == EPD_DRAW_SUCCESS);
|
||||
return draw_result == EPD_DRAW_SUCCESS ? ERROR_NONE : ERROR_RESOURCE;
|
||||
}
|
||||
|
||||
@@ -133,13 +256,11 @@ static DisplayColorFormat papers3_display_get_color_format(Device*) {
|
||||
return DISPLAY_COLOR_FORMAT_GRAYSCALE8;
|
||||
}
|
||||
|
||||
// epd_width()/epd_height() are the panel's native, unrotated dimensions (display->width/height in
|
||||
// epdiy.c) - epd_rotated_display_width()/height() swap them for EPD_ROT_PORTRAIT/INVERTED_PORTRAIT.
|
||||
// epd_draw_rotated_image() clamps its input rect against the *rotated* dims and epd_draw_pixel()
|
||||
// applies the rotation transform on top of that (see _rotate() in epdiy.c), so both LVGL's canvas
|
||||
// size and draw_bitmap()'s rect must be in rotated-space, not native-space - using the native
|
||||
// epd_width()/epd_height() here fed rotated-space code a landscape-sized canvas, which produced
|
||||
// exactly the "rotated + landscape" symptom this was fixed for.
|
||||
// epd_width()/epd_height() are the panel's native, unrotated dimensions; epd_rotated_display_
|
||||
// width()/height() swap them for EPD_ROT_PORTRAIT/INVERTED_PORTRAIT. epd_draw_rotated_image()
|
||||
// clamps its input rect against the rotated dims and epd_draw_pixel() applies the rotation
|
||||
// transform on top of that (see _rotate() in epdiy.c), so both LVGL's canvas size and
|
||||
// draw_bitmap()'s rect must be in rotated-space, not native-space.
|
||||
static uint16_t papers3_display_get_resolution_x(Device*) {
|
||||
return static_cast<uint16_t>(epd_rotated_display_width());
|
||||
}
|
||||
@@ -232,6 +353,11 @@ static error_t start(Device* device) {
|
||||
return ERROR_OUT_OF_MEMORY;
|
||||
}
|
||||
|
||||
internal->panel_pixel_count = static_cast<uint32_t>(epd_rotated_display_width()) * static_cast<uint32_t>(epd_rotated_display_height());
|
||||
internal->partial_count_since_quality = 0;
|
||||
internal->last_quality_refresh_tick = get_ticks();
|
||||
internal->quality_hold_until_tick = 0;
|
||||
|
||||
device_set_driver_data(device, internal);
|
||||
|
||||
LOG_I(TAG, "EPDiy initialized (%dx%d native, %dx%d rotated)", epd_width(), epd_height(), epd_rotated_display_width(), epd_rotated_display_height());
|
||||
|
||||
@@ -10,7 +10,7 @@ extern "C" {
|
||||
|
||||
struct Papers3DisplayConfig {
|
||||
int temperature_celsius;
|
||||
enum EpdDrawMode draw_mode;
|
||||
enum EpdDrawMode quality_draw_mode;
|
||||
enum EpdRotation rotation;
|
||||
};
|
||||
|
||||
|
||||
@@ -29,8 +29,8 @@ static constexpr uint8_t I2C_ADDRESS = 0x6D;
|
||||
static constexpr uint32_t REPEAT_INITIAL_MS = 400;
|
||||
static constexpr uint32_t REPEAT_RATE_MS = 80;
|
||||
|
||||
// I2C event-poll interval - mirrors the old deprecated-HAL's 20ms Timer period. Drives both
|
||||
// REG_INT_STAT polling (when no IRQ pin) and software key-repeat ticking.
|
||||
// I2C event-poll interval
|
||||
// Drives both REG_INT_STAT polling (when no IRQ pin) and software key-repeat ticking.
|
||||
static constexpr uint32_t POLL_INTERVAL_MS = 20;
|
||||
|
||||
// Upper bound on events consumed per drain_events() call. Since the loop re-reads REG_EVENT_NUM
|
||||
@@ -193,6 +193,7 @@ static uint32_t now_ms() {
|
||||
// the event - and software key-repeat replays this same struct, so a held chord keeps its modifiers.
|
||||
struct Tab5KeyEvent {
|
||||
uint32_t key;
|
||||
bool pressed;
|
||||
bool ctrl;
|
||||
bool alt;
|
||||
uint8_t hid_keycode;
|
||||
@@ -216,11 +217,20 @@ struct Tab5KeyboardInternal {
|
||||
gpio_num_t irq_pin;
|
||||
|
||||
// Poll throttling (real-time based, since read_key() is called at whatever rate LVGL's indev
|
||||
// timer and its own drain-loop - via continue_reading - happen to run at, unlike the old
|
||||
// deprecated-HAL's fixed 20ms Timer)
|
||||
// timer and its own drain-loop, via continue_reading, happen to run at).
|
||||
uint32_t last_poll_ms;
|
||||
|
||||
// Software key-repeat state (tracked by position to survive modifier changes)
|
||||
// Original press event for every currently-held key, indexed by matrix position (row*14+col),
|
||||
// so a release can recover the exact event its press queued (modifiers captured at press
|
||||
// time) even when another key was pressed and released in between. held_event[i].key can
|
||||
// legitimately be 0 (e.g. F1-F12, see drain_events()), so held[i] tracks validity separately
|
||||
// rather than using a sentinel key value.
|
||||
Tab5KeyEvent held_event[70];
|
||||
bool held[70];
|
||||
|
||||
// Software key-repeat state: tracks only the most recently pressed key, independent of the
|
||||
// per-position storage above (repeats stop as soon as a different key is pressed, matching
|
||||
// typical keyboard behavior, and don't need to survive that key's release).
|
||||
Tab5KeyEvent repeat_event;
|
||||
uint8_t repeat_row;
|
||||
uint8_t repeat_col;
|
||||
@@ -258,15 +268,17 @@ bool tab5_keyboard_is_attached(Device* device) {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// LED helpers - LED0 = Sym indicator (green), LED1 = Aa indicator (red)
|
||||
// LED helpers - LED0 = Sym indicator (blue), LED1 = Aa indicator (red)
|
||||
// RGB register layout: [B, G, R] per LED, stride 4 (byte 3 reserved)
|
||||
// ---------------------------------------------------------------------------
|
||||
static void update_leds(Device* device, const Tab5KeyboardInternal* internal) {
|
||||
static constexpr uint8_t LED_SYM_ON_BLUE = 0xC0;
|
||||
static constexpr uint8_t LED_AA_ON_RED = 0x90;
|
||||
|
||||
static void update_leds(Device* device, Tab5KeyboardInternal* internal) {
|
||||
auto* parent = device_get_parent(device);
|
||||
// [LED0: B,G,R, reserved, LED1: B,G,R]
|
||||
uint8_t buf[7] = {
|
||||
0x00, internal->sym_active ? uint8_t(0xA0) : uint8_t(0x00), 0x00, 0x00,
|
||||
0x00, 0x00, internal->aa_sticky ? uint8_t(0xA0) : uint8_t(0x00),
|
||||
internal->sym_active ? LED_SYM_ON_BLUE : uint8_t(0x00), 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, internal->aa_sticky ? LED_AA_ON_RED : uint8_t(0x00),
|
||||
};
|
||||
i2c_controller_write_register(parent, I2C_ADDRESS, REG_RGB_BASE, buf, 7, pdMS_TO_TICKS(50));
|
||||
}
|
||||
@@ -389,9 +401,14 @@ static void drain_events(Device* device, Tab5KeyboardInternal* internal) {
|
||||
// no business reaching into, so ESC is now just queued as a normal key
|
||||
// like everything else (LVGL/app code already handles ESC via focus/group
|
||||
// navigation the same way a dedicated ESC key on any other keyboard would).
|
||||
const Tab5KeyEvent event = { lv_key, internal->ctrl_held, internal->alt_held,
|
||||
const Tab5KeyEvent event = { lv_key, true, internal->ctrl_held, internal->alt_held,
|
||||
m.keycode, modifier };
|
||||
xQueueSend(internal->queue, &event, 0);
|
||||
// Remember this key's press event by position so its release (whenever it
|
||||
// comes, regardless of what else is pressed in between) reports the same value.
|
||||
const uint8_t idx = row * 14U + col;
|
||||
internal->held_event[idx] = event;
|
||||
internal->held[idx] = true;
|
||||
// Arm software repeat tracking by row/col to survive modifier changes
|
||||
const uint32_t now = now_ms();
|
||||
internal->repeat_event = event;
|
||||
@@ -405,9 +422,31 @@ static void drain_events(Device* device, Tab5KeyboardInternal* internal) {
|
||||
internal->aa_held = false;
|
||||
update_leds(device, internal);
|
||||
}
|
||||
} else if (row == internal->repeat_row && col == internal->repeat_col) {
|
||||
// Match release by position, not translated value — survives sticky Aa clear
|
||||
internal->repeat_event.key = 0;
|
||||
} else {
|
||||
// Always queue the release: callers key their own "is this held" state off
|
||||
// (key, pressed) pairs, and a dropped release leaves that key stuck down forever.
|
||||
//
|
||||
// Reuse the matching press's key/modifier (via held_event, tracked by matrix
|
||||
// position) rather than recomputing from current modifier state: aa_active
|
||||
// above is read fresh, but sticky Aa is consumed right after the press fires
|
||||
// (above), so recomputing here would give the release a different key value
|
||||
// than its press whenever Aa was sticky (e.g. shifted vs unshifted). Only
|
||||
// recompute as a fallback for the case where no press was ever recorded for
|
||||
// this position (e.g. driver just started while the key was already held).
|
||||
const uint8_t idx = row * 14U + col;
|
||||
Tab5KeyEvent event;
|
||||
if (internal->held[idx]) {
|
||||
event = internal->held_event[idx];
|
||||
internal->held[idx] = false;
|
||||
} else {
|
||||
event = { lv_key, false, internal->ctrl_held, internal->alt_held, m.keycode, modifier };
|
||||
}
|
||||
event.pressed = false;
|
||||
xQueueSend(internal->queue, &event, 0);
|
||||
|
||||
if (row == internal->repeat_row && col == internal->repeat_col) {
|
||||
internal->repeat_event.key = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -429,7 +468,7 @@ void tab5_keyboard_reinit(Device* device) {
|
||||
write_reg_fast(device, REG_EVENT_NUM, 0x00); // flush event queue
|
||||
write_reg_fast(device, REG_INT_STAT, 0x00); // clear pending INT
|
||||
write_reg_fast(device, REG_RGB_MODE, 0x01); // Custom RGB mode (manual LED control)
|
||||
write_reg_fast(device, REG_BRIGHTNESS, 50); // 50% brightness
|
||||
write_reg_fast(device, REG_BRIGHTNESS, 30); // 30% brightness
|
||||
update_leds(device, internal); // restore current LED state
|
||||
|
||||
if (internal->irq_configured) {
|
||||
@@ -437,9 +476,39 @@ void tab5_keyboard_reinit(Device* device) {
|
||||
}
|
||||
}
|
||||
|
||||
void tab5_keyboard_reset_state(Device* device) {
|
||||
auto* internal = static_cast<Tab5KeyboardInternal*>(device_get_driver_data(device));
|
||||
|
||||
for (uint8_t idx = 0; idx < 70U; idx++) {
|
||||
if (internal->held[idx]) {
|
||||
Tab5KeyEvent event = internal->held_event[idx];
|
||||
event.pressed = false;
|
||||
// This runs under lvgl_lock() (apply_state()'s caller), and the consumer that drains
|
||||
// this queue is LVGL's own indev read callback - blocking here for queue space could
|
||||
// deadlock against that consumer needing the same lock. Best-effort send only, same as
|
||||
// drain_events()'s hot path; internal->held[idx] is still cleared on a dropped send so
|
||||
// this reset doesn't get stuck retrying a release that already lost its only chance to
|
||||
// be delivered before the state it referred to (an unplugged keyboard) is gone anyway.
|
||||
xQueueSend(internal->queue, &event, 0);
|
||||
internal->held[idx] = false;
|
||||
}
|
||||
}
|
||||
|
||||
internal->repeat_event.key = 0;
|
||||
internal->repeat_row = 0xFF;
|
||||
internal->repeat_col = 0xFF;
|
||||
|
||||
internal->sym_active = false;
|
||||
internal->aa_sticky = false;
|
||||
internal->aa_held = false;
|
||||
internal->aa_tapped = false;
|
||||
internal->ctrl_held = false;
|
||||
internal->alt_held = false;
|
||||
update_leds(device, internal);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// poll_if_due - the closest equivalent to the old deprecated-HAL's 20ms-Timer-driven
|
||||
// processKeyboard(): drains new key events (IRQ-gated or polled) and ticks software key-repeat.
|
||||
// poll_if_due - drains new key events (IRQ-gated or polled) and ticks software key-repeat.
|
||||
// Called from read_key(), throttled to real elapsed time rather than call count, since read_key()
|
||||
// can be called back-to-back multiple times per LVGL indev timer tick while draining an
|
||||
// already-queued burst (continue_reading). Hot-plug attach detection lives outside the driver -
|
||||
@@ -566,7 +635,7 @@ static error_t tab5_keyboard_read_key(Device* device, KeyboardKeyData* data) {
|
||||
Tab5KeyEvent event = {};
|
||||
if (xQueueReceive(internal->queue, &event, 0) == pdTRUE) {
|
||||
data->key = event.key;
|
||||
data->pressed = true;
|
||||
data->pressed = event.pressed;
|
||||
data->continue_reading = uxQueueMessagesWaiting(internal->queue) > 0;
|
||||
data->ctrl = event.ctrl;
|
||||
data->alt = event.alt;
|
||||
|
||||
@@ -37,6 +37,12 @@ bool tab5_keyboard_is_attached(struct Device* device);
|
||||
// tab5_keyboard_attach_detect.cpp).
|
||||
void tab5_keyboard_reinit(struct Device* device);
|
||||
|
||||
// Emits a release for every currently-held key (a hardware release can't arrive once the keyboard
|
||||
// is unplugged), then clears held-key/software-repeat/modifier state. Callers must call this on
|
||||
// confirmed detach (see tab5_keyboard_attach_detect.cpp) so a key held across an unplug doesn't
|
||||
// leave consumers with a stuck key or spurious repeats/modifiers after reattach.
|
||||
void tab5_keyboard_reset_state(struct Device* device);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -63,6 +63,11 @@ static bool apply_state(Device* keyboard_device, bool attached) {
|
||||
lv_display_set_rotation(display, LV_DISPLAY_ROTATION_90);
|
||||
}
|
||||
} else {
|
||||
// A key held at the moment of unplug can never get its hardware release - reset tracked
|
||||
// state so it doesn't read as stuck or feed stale modifiers into whatever's pressed next
|
||||
// after reattach.
|
||||
tab5_keyboard_reset_state(keyboard_device);
|
||||
|
||||
// Only restore if rotation is still what we set it to - if the user manually changed it
|
||||
// since attaching, respect their choice instead.
|
||||
if (rotation_override_active && lv_display_get_rotation(display) == LV_DISPLAY_ROTATION_90) {
|
||||
@@ -84,13 +89,24 @@ static void attach_detect_callback(TimerHandle_t /*timer*/) {
|
||||
// LVGL restarting is a distinct event from the keyboard physically attaching/detaching: the
|
||||
// accessory may never have moved, but whatever apply_state() last set (rotation) may have
|
||||
// been reset in the meantime by the restart. Forcing was_attached false makes the block below
|
||||
// see a fresh "attached" transition (still going through the normal 2-check debounce) so
|
||||
// see a fresh "attached" transition, still going through the normal two-check debounce, so
|
||||
// apply_state() re-announces the current state instead of staying silent forever, waiting for
|
||||
// an edge that will never come because the keyboard was never actually unplugged.
|
||||
// lvgl_is_running() is safe to call unlocked (unlike lv_display_get_default(), resolved inside
|
||||
// the lock in apply_state() instead).
|
||||
const bool lvgl_ready = lvgl_is_running();
|
||||
if (lvgl_ready && !was_lvgl_ready) {
|
||||
// If the keyboard is (and, per was_attached, already was) physically detached, forcing
|
||||
// was_attached false below means the detach transition below will never fire again for
|
||||
// this unplug - it already happened before this restart. Reset software state here
|
||||
// instead, since apply_state()'s own detach path may never have run: it could have bailed
|
||||
// out early (LVGL lock busy, or display not ready yet) before reaching its
|
||||
// tab5_keyboard_reset_state() call, and now never will, because that transition is about
|
||||
// to be erased. This reset doesn't touch LVGL/display state, so it doesn't need
|
||||
// apply_state()'s lock/display gating.
|
||||
if (was_attached && !tab5_keyboard_is_attached(keyboard_device)) {
|
||||
tab5_keyboard_reset_state(keyboard_device);
|
||||
}
|
||||
was_attached = false;
|
||||
pending_attach_confirm_count = 0;
|
||||
}
|
||||
@@ -98,7 +114,7 @@ static void attach_detect_callback(TimerHandle_t /*timer*/) {
|
||||
|
||||
const bool attached = tab5_keyboard_is_attached(keyboard_device);
|
||||
if (attached != was_attached) {
|
||||
// Require the new state to be confirmed on a second consecutive check before acting - a
|
||||
// Require the new state to be confirmed on a second consecutive check before acting: a
|
||||
// single probe on a floating/half-connected bus (e.g. mid-unplug) can false-positive.
|
||||
if (attached != pending_attach_state || pending_attach_confirm_count == 0) {
|
||||
pending_attach_state = attached;
|
||||
@@ -108,7 +124,7 @@ static void attach_detect_callback(TimerHandle_t /*timer*/) {
|
||||
if (apply_state(keyboard_device, attached)) {
|
||||
was_attached = attached;
|
||||
}
|
||||
// else: not handled yet (e.g. LVGL lock busy) - retry on the next confirmed check
|
||||
// else: not handled yet (e.g. LVGL lock busy); retry on the next confirmed check
|
||||
}
|
||||
} else {
|
||||
pending_attach_confirm_count = 0;
|
||||
|
||||
@@ -174,7 +174,7 @@
|
||||
i2c_keyboard: i2c2 {
|
||||
compatible = "espressif,esp32-i2c-master";
|
||||
port = <LP_I2C_NUM_0>;
|
||||
clock-frequency = <100000>;
|
||||
clock-frequency = <400000>;
|
||||
clock-source = <LP_I2C_SCLK_DEFAULT>;
|
||||
pin-sda = <&gpio0 0 GPIO_FLAG_PULL_UP>;
|
||||
pin-scl = <&gpio0 1 GPIO_FLAG_PULL_UP>;
|
||||
|
||||
@@ -13,11 +13,21 @@ if (NOT DEFINED ENV{ESP_IDF_VERSION})
|
||||
)
|
||||
|
||||
target_link_libraries(simulator
|
||||
PRIVATE Tactility
|
||||
PRIVATE TactilityKernel
|
||||
PRIVATE TactilityFreeRtos
|
||||
PRIVATE lvgl
|
||||
PRIVATE SDL2-static
|
||||
)
|
||||
|
||||
target_link_libraries(simulator PRIVATE ${SDL2_LIBRARIES})
|
||||
|
||||
if (APPLE)
|
||||
target_sources(simulator PRIVATE Source/drivers/sdl_audio_permission.mm)
|
||||
target_link_libraries(simulator PRIVATE "-framework AVFoundation" "-framework Foundation")
|
||||
# The developer executable can also request recording outside an .app bundle.
|
||||
target_link_options(simulator INTERFACE
|
||||
"LINKER:-sectcreate,__TEXT,__info_plist,${CMAKE_CURRENT_SOURCE_DIR}/macos-info.plist")
|
||||
set_property(TARGET Tactility APPEND PROPERTY LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/macos-info.plist")
|
||||
endif ()
|
||||
|
||||
endif()
|
||||
|
||||
@@ -10,13 +10,13 @@ constexpr auto* TAG = "FreeRTOS";
|
||||
|
||||
namespace simulator {
|
||||
|
||||
MainFunction mainFunction = nullptr;
|
||||
static MainFunction mainFunction = nullptr;
|
||||
|
||||
void setMain(MainFunction newMainFunction) {
|
||||
mainFunction = newMainFunction;
|
||||
}
|
||||
|
||||
static void freertosMainTask(void* parameter) {
|
||||
static void freertosMainTask(void*) {
|
||||
LOG_I(TAG, "starting app_main()");
|
||||
assert(simulator::mainFunction);
|
||||
mainFunction();
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
#pragma once
|
||||
|
||||
#include "Main.h"
|
||||
#include "drivers/sdl_bridge.h"
|
||||
|
||||
#include <csignal>
|
||||
#include <pthread.h>
|
||||
#include <thread>
|
||||
|
||||
namespace simulator {
|
||||
/** Set the function pointer of the real app_main() */
|
||||
@@ -14,8 +19,23 @@ void app_main(); // ESP-IDF's main function, implemented in the application
|
||||
}
|
||||
|
||||
int main() {
|
||||
// Actual main function that passes on app_main() (to be executed in a FreeRTOS task) and bootstraps FreeRTOS
|
||||
// The FreeRTOS POSIX port arms a process-wide SIGALRM timer for its tick and expects every one
|
||||
// of its task pthreads to have all signals but SIGINT blocked.
|
||||
// (see prvSetupSignalsAndSchedulerPolicy() in FreeRTOS-Kernel's Posix port.c)
|
||||
// A signal-generated SIGALRM can land on any thread in the process that doesn't block it.
|
||||
// This thread stays a plain OS thread (running the SDL loop below, never a FreeRTOS task),
|
||||
// so without this it's eligible to catch a tick SIGALRM and freeze inside the scheduler's handler.
|
||||
// Block the same set here, before anything else, so it never can.
|
||||
sigset_t all_signals_except_sigint;
|
||||
sigfillset(&all_signals_except_sigint);
|
||||
sigdelset(&all_signals_except_sigint, SIGINT);
|
||||
pthread_sigmask(SIG_SETMASK, &all_signals_except_sigint, nullptr);
|
||||
|
||||
// FreeRTOS and app_main() run on a separate thread: macOS requires SDL/Cocoa window creation,
|
||||
// event pumping and rendering to happen on the real OS main thread, which sdl_bridge_run_main_loop()
|
||||
// below takes over. freertosMain() never returns, so this thread is detached rather than joined.
|
||||
simulator::setMain(app_main);
|
||||
simulator::freertosMain();
|
||||
std::thread(simulator::freertosMain).detach();
|
||||
sdl_bridge_run_main_loop();
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
#include "sdl_audio.h"
|
||||
#include "sdl_audio_buffer.h"
|
||||
|
||||
#include <tactility/device.h>
|
||||
#include <tactility/driver.h>
|
||||
#include <tactility/freertos/task.h>
|
||||
#include <tactility/log.h>
|
||||
#include <tactility/module.h>
|
||||
|
||||
#include <SDL2/SDL.h>
|
||||
#include <atomic>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <new>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr auto* TAG = "SdlAudio";
|
||||
constexpr uint32_t SAMPLE_RATE = 48000;
|
||||
|
||||
struct AudioData {
|
||||
SdlAudioBuffer buffer;
|
||||
SemaphoreHandle_t mutex = nullptr; // task-side only; never used by the SDL callback
|
||||
SDL_AudioDeviceID id = 0;
|
||||
AudioCodecDirection direction;
|
||||
std::atomic<float> volume { 100.0f };
|
||||
std::atomic<bool> muted { false };
|
||||
std::atomic<uint32_t> callbacks { 0 };
|
||||
};
|
||||
|
||||
AudioData* get_data(Device* device) {
|
||||
return static_cast<AudioData*>(device_get_driver_data(device));
|
||||
}
|
||||
|
||||
class Lock {
|
||||
SemaphoreHandle_t mutex;
|
||||
public:
|
||||
explicit Lock(AudioData* data) : mutex(data->mutex) { xSemaphoreTake(mutex, portMAX_DELAY); }
|
||||
~Lock() { xSemaphoreGive(mutex); }
|
||||
};
|
||||
|
||||
const char* device_name(const AudioData* data) {
|
||||
const char* name = std::getenv(data->direction == AUDIO_CODEC_DIR_INPUT ? "SIM_AUDIO_INPUT" : "SIM_AUDIO_OUTPUT");
|
||||
return name != nullptr && name[0] != '\0' ? name : nullptr;
|
||||
}
|
||||
|
||||
bool available(const AudioData* data) {
|
||||
const char* name = device_name(data);
|
||||
if (name != nullptr && std::strcmp(name, "none") == 0) return false;
|
||||
const int capture = data->direction == AUDIO_CODEC_DIR_INPUT;
|
||||
const int count = SDL_GetNumAudioDevices(capture);
|
||||
if (name == nullptr) return count > 0;
|
||||
for (int i = 0; i < count; ++i) {
|
||||
const char* candidate = SDL_GetAudioDeviceName(i, capture);
|
||||
if (candidate != nullptr && std::strcmp(candidate, name) == 0) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void apply_volume(AudioData* data, void* bytes, size_t size) {
|
||||
const float gain = data->muted.load() ? 0.0f : data->volume.load() / 100.0f;
|
||||
auto* output = static_cast<uint8_t*>(bytes);
|
||||
for (size_t i = 0; i < size; i += sizeof(int16_t)) {
|
||||
int16_t sample;
|
||||
std::memcpy(&sample, output + i, sizeof(sample));
|
||||
sample = static_cast<int16_t>(sample * gain);
|
||||
std::memcpy(output + i, &sample, sizeof(sample));
|
||||
}
|
||||
}
|
||||
|
||||
void audio_callback(void* context, Uint8* stream, int length) {
|
||||
auto* data = static_cast<AudioData*>(context);
|
||||
const size_t count = static_cast<size_t>(length) / sizeof(int16_t);
|
||||
if (data->direction == AUDIO_CODEC_DIR_INPUT) {
|
||||
// Drop incoming frames when the bounded capture buffer is full. Muted capture
|
||||
// must not leave real microphone samples queued for a later unmute.
|
||||
if (data->muted.load()) std::memset(stream, 0, length);
|
||||
data->buffer.write(stream, count);
|
||||
} else {
|
||||
const size_t copied = data->buffer.read(stream, count) * sizeof(int16_t);
|
||||
std::memset(stream + copied, 0, length - copied); // silence on underrun
|
||||
apply_volume(data, stream, copied);
|
||||
}
|
||||
data->callbacks.fetch_add(1, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
error_t start(Device* device) {
|
||||
const auto* config = static_cast<const SdlAudioConfig*>(device->config);
|
||||
if (config == nullptr || (config->direction != AUDIO_CODEC_DIR_INPUT && config->direction != AUDIO_CODEC_DIR_OUTPUT)) {
|
||||
return ERROR_INVALID_ARGUMENT;
|
||||
}
|
||||
if (SDL_InitSubSystem(SDL_INIT_AUDIO) != 0) {
|
||||
LOG_E(TAG, "Cannot initialize audio: %s", SDL_GetError());
|
||||
return ERROR_RESOURCE;
|
||||
}
|
||||
auto* data = new (std::nothrow) AudioData;
|
||||
if (data == nullptr) {
|
||||
SDL_QuitSubSystem(SDL_INIT_AUDIO);
|
||||
return ERROR_OUT_OF_MEMORY;
|
||||
}
|
||||
data->direction = config->direction;
|
||||
data->mutex = xSemaphoreCreateMutex();
|
||||
if (data->mutex == nullptr) {
|
||||
delete data;
|
||||
SDL_QuitSubSystem(SDL_INIT_AUDIO);
|
||||
return ERROR_OUT_OF_MEMORY;
|
||||
}
|
||||
device_set_driver_data(device, data);
|
||||
const int capture = data->direction == AUDIO_CODEC_DIR_INPUT;
|
||||
for (int i = 0; i < SDL_GetNumAudioDevices(capture); ++i) {
|
||||
LOG_I(TAG, "%s device: %s", capture ? "Input" : "Output", SDL_GetAudioDeviceName(i, capture));
|
||||
}
|
||||
LOG_I(TAG, "%s: %s (%s)", device->name, device_name(data) != nullptr ? device_name(data) : "system default",
|
||||
available(data) ? "available" : "unavailable");
|
||||
return ERROR_NONE;
|
||||
}
|
||||
|
||||
error_t open(Device* device, const AudioCodecStreamConfig* config) {
|
||||
auto* data = get_data(device);
|
||||
if (config == nullptr) return ERROR_INVALID_ARGUMENT;
|
||||
if (config->direction != data->direction) return ERROR_NOT_SUPPORTED;
|
||||
// The shared stream module performs rate/channel conversion on S16 PCM.
|
||||
if (config->bits_per_sample != 16) return ERROR_NOT_SUPPORTED;
|
||||
const uint8_t channels = data->direction == AUDIO_CODEC_DIR_INPUT ? 1 : 2;
|
||||
if (config->sample_rate != SAMPLE_RATE || config->channels != channels) return ERROR_INVALID_ARGUMENT;
|
||||
Lock lock(data);
|
||||
if (data->id != 0) return ERROR_INVALID_STATE;
|
||||
if (!available(data)) {
|
||||
LOG_W(TAG, "No selected %s device available", data->direction == AUDIO_CODEC_DIR_INPUT ? "input" : "output");
|
||||
return ERROR_NOT_SUPPORTED;
|
||||
}
|
||||
#ifdef __APPLE__
|
||||
// Only ask when recording is requested, and only with real macOS audio (dummy
|
||||
// and disk backends are also useful for automated tests).
|
||||
if (data->direction == AUDIO_CODEC_DIR_INPUT && std::strcmp(SDL_GetCurrentAudioDriver(), "coreaudio") == 0) {
|
||||
error_t permission;
|
||||
while ((permission = sdl_audio_microphone_permission()) == ERROR_RESOURCE_BUSY) vTaskDelay(1);
|
||||
if (permission != ERROR_NONE) {
|
||||
LOG_W(TAG, "Microphone permission denied; enable access in macOS Privacy & Security > Microphone");
|
||||
return permission;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
SDL_AudioSpec wanted {};
|
||||
wanted.freq = SAMPLE_RATE;
|
||||
wanted.format = AUDIO_S16SYS;
|
||||
wanted.channels = channels;
|
||||
wanted.samples = 512;
|
||||
wanted.callback = audio_callback;
|
||||
wanted.userdata = data;
|
||||
data->buffer.reset();
|
||||
data->callbacks.store(0);
|
||||
// No allowed changes: SDL converts between our fixed PCM format and the host
|
||||
// device's format when necessary. No hardware-specific format leaks to apps.
|
||||
data->id = SDL_OpenAudioDevice(device_name(data), data->direction == AUDIO_CODEC_DIR_INPUT, &wanted, nullptr, 0);
|
||||
if (data->id == 0) {
|
||||
LOG_E(TAG, "Cannot open %s: %s", device->name, SDL_GetError());
|
||||
return ERROR_RESOURCE;
|
||||
}
|
||||
SDL_PauseAudioDevice(data->id, 0);
|
||||
return ERROR_NONE;
|
||||
}
|
||||
|
||||
error_t close(Device* device) {
|
||||
auto* data = get_data(device);
|
||||
Lock lock(data);
|
||||
if (data->id != 0) {
|
||||
// Preserve the end of short sounds. Drain is bounded even if the device has
|
||||
// disappeared; microphone close never waits for the capture buffer to empty.
|
||||
const TickType_t start = xTaskGetTickCount();
|
||||
while (data->direction == AUDIO_CODEC_DIR_OUTPUT && !data->buffer.empty()
|
||||
&& xTaskGetTickCount() - start < pdMS_TO_TICKS(250)
|
||||
&& SDL_GetAudioDeviceStatus(data->id) == SDL_AUDIO_PLAYING) {
|
||||
vTaskDelay(1);
|
||||
}
|
||||
SDL_CloseAudioDevice(data->id);
|
||||
data->id = 0;
|
||||
data->buffer.reset();
|
||||
}
|
||||
return ERROR_NONE;
|
||||
}
|
||||
|
||||
error_t stop(Device* device) {
|
||||
auto* data = get_data(device);
|
||||
close(device);
|
||||
vSemaphoreDelete(data->mutex);
|
||||
delete data;
|
||||
device_set_driver_data(device, nullptr);
|
||||
SDL_QuitSubSystem(SDL_INIT_AUDIO);
|
||||
return ERROR_NONE;
|
||||
}
|
||||
|
||||
error_t transfer(Device* device, void* destination, const void* source, size_t size, size_t* transferred, TickType_t timeout, bool capture) {
|
||||
if (transferred != nullptr) *transferred = 0;
|
||||
auto* data = get_data(device);
|
||||
if ((data->direction == AUDIO_CODEC_DIR_INPUT) != capture) return ERROR_NOT_SUPPORTED;
|
||||
const size_t frame_size = sizeof(int16_t) * (capture ? 1 : 2);
|
||||
if (size % frame_size != 0 || (size != 0 && (capture ? destination == nullptr : source == nullptr))) return ERROR_INVALID_ARGUMENT;
|
||||
Lock lock(data);
|
||||
if (data->id == 0) return ERROR_INVALID_STATE;
|
||||
const TickType_t start = xTaskGetTickCount();
|
||||
TickType_t last_callback = start;
|
||||
uint32_t callbacks = data->callbacks.load();
|
||||
size_t done = 0;
|
||||
error_t result = ERROR_NONE;
|
||||
while (done < size) {
|
||||
if (SDL_GetAudioDeviceStatus(data->id) != SDL_AUDIO_PLAYING) {
|
||||
result = ERROR_RESOURCE;
|
||||
break;
|
||||
}
|
||||
const size_t count = (size - done) / sizeof(int16_t);
|
||||
const size_t copied = capture
|
||||
? data->buffer.read(static_cast<uint8_t*>(destination) + done, count)
|
||||
: data->buffer.write(static_cast<const uint8_t*>(source) + done, count);
|
||||
done += copied * sizeof(int16_t);
|
||||
if (done == size) break;
|
||||
const TickType_t now = xTaskGetTickCount();
|
||||
if (timeout != portMAX_DELAY && now - start >= timeout) {
|
||||
result = ERROR_TIMEOUT;
|
||||
break;
|
||||
}
|
||||
const uint32_t current_callbacks = data->callbacks.load();
|
||||
if (current_callbacks != callbacks) {
|
||||
callbacks = current_callbacks;
|
||||
last_callback = now;
|
||||
} else if (now - last_callback >= pdMS_TO_TICKS(2000)) {
|
||||
// A stopped backend must not strand an infinite-timeout caller or a
|
||||
// concurrent Settings disable waiting for that caller to finish.
|
||||
result = ERROR_RESOURCE;
|
||||
break;
|
||||
}
|
||||
vTaskDelay(1);
|
||||
}
|
||||
if (capture) apply_volume(data, destination, done);
|
||||
if (transferred != nullptr) *transferred = done;
|
||||
return result;
|
||||
}
|
||||
|
||||
error_t read(Device* device, void* destination, size_t size, size_t* count, TickType_t timeout) {
|
||||
return transfer(device, destination, nullptr, size, count, timeout, true);
|
||||
}
|
||||
|
||||
error_t write(Device* device, const void* source, size_t size, size_t* count, TickType_t timeout) {
|
||||
return transfer(device, nullptr, source, size, count, timeout, false);
|
||||
}
|
||||
|
||||
error_t set_volume(Device* device, AudioCodecDirection direction, float volume) {
|
||||
auto* data = get_data(device);
|
||||
if (direction != data->direction) return ERROR_NOT_SUPPORTED;
|
||||
if (!std::isfinite(volume) || volume < 0.0f || volume > 100.0f) return ERROR_INVALID_ARGUMENT;
|
||||
data->volume.store(volume);
|
||||
return ERROR_NONE;
|
||||
}
|
||||
|
||||
error_t get_volume(Device* device, AudioCodecDirection direction, float* volume) {
|
||||
auto* data = get_data(device);
|
||||
if (direction != data->direction) return ERROR_NOT_SUPPORTED;
|
||||
*volume = data->volume.load();
|
||||
return ERROR_NONE;
|
||||
}
|
||||
|
||||
error_t set_mute(Device* device, AudioCodecDirection direction, bool muted) {
|
||||
auto* data = get_data(device);
|
||||
if (direction != data->direction) return ERROR_NOT_SUPPORTED;
|
||||
data->muted.store(muted);
|
||||
return ERROR_NONE;
|
||||
}
|
||||
|
||||
error_t get_mute(Device* device, AudioCodecDirection direction, bool* muted) {
|
||||
auto* data = get_data(device);
|
||||
if (direction != data->direction) return ERROR_NOT_SUPPORTED;
|
||||
*muted = data->muted.load();
|
||||
return ERROR_NONE;
|
||||
}
|
||||
|
||||
error_t get_rate(Device* device, AudioCodecDirection direction, uint32_t* rate) {
|
||||
if (direction != get_data(device)->direction) return ERROR_NOT_SUPPORTED;
|
||||
*rate = SAMPLE_RATE;
|
||||
return ERROR_NONE;
|
||||
}
|
||||
|
||||
error_t get_channels(Device* device, AudioCodecDirection direction, uint8_t* channels) {
|
||||
if (direction != get_data(device)->direction) return ERROR_NOT_SUPPORTED;
|
||||
*channels = direction == AUDIO_CODEC_DIR_INPUT ? 1 : 2;
|
||||
return ERROR_NONE;
|
||||
}
|
||||
|
||||
error_t get_capabilities(Device* device, AudioCodecDirection* direction) {
|
||||
auto* data = get_data(device);
|
||||
if (!available(data)) return ERROR_NOT_SUPPORTED;
|
||||
*direction = data->direction;
|
||||
return ERROR_NONE;
|
||||
}
|
||||
|
||||
const AudioCodecApi api = {
|
||||
.open = open,
|
||||
.close = close,
|
||||
.read = read,
|
||||
.write = write,
|
||||
.set_volume = set_volume,
|
||||
.get_volume = get_volume,
|
||||
.set_mute = set_mute,
|
||||
.get_mute = get_mute,
|
||||
.get_native_sample_rate = get_rate,
|
||||
.get_native_channels = get_channels,
|
||||
.get_capabilities = get_capabilities,
|
||||
.get_input_gain_multiplier = nullptr,
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" Module simulator_module;
|
||||
|
||||
Driver sdl_audio_driver = {
|
||||
.name = "sdl-audio",
|
||||
.compatible = (const char*[]) { "tactility,sdl-audio", nullptr },
|
||||
.start_device = start,
|
||||
.stop_device = stop,
|
||||
.api = &api,
|
||||
.device_type = &AUDIO_CODEC_TYPE,
|
||||
.owner = &simulator_module,
|
||||
.internal = nullptr,
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
#pragma once
|
||||
|
||||
#include <tactility/drivers/audio_codec.h>
|
||||
|
||||
struct SdlAudioConfig {
|
||||
AudioCodecDirection direction;
|
||||
};
|
||||
|
||||
#ifdef __APPLE__
|
||||
// Nonblocking: ERROR_RESOURCE_BUSY means that the user has not answered the prompt yet.
|
||||
error_t sdl_audio_microphone_permission();
|
||||
#endif
|
||||
@@ -0,0 +1,52 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
// Single producer / single consumer. The SDL callback is a native thread: it must never
|
||||
// allocate, block, log, or call FreeRTOS. Unsigned counters also work across wraparound.
|
||||
class SdlAudioBuffer {
|
||||
static constexpr uint32_t CAPACITY = 16384; // samples; ~171 ms of 48 kHz stereo
|
||||
std::array<int16_t, CAPACITY> samples {};
|
||||
std::atomic<uint32_t> read_position { 0 };
|
||||
std::atomic<uint32_t> write_position { 0 };
|
||||
|
||||
public:
|
||||
size_t write(const void* source, size_t count) {
|
||||
const uint32_t write = write_position.load(std::memory_order_relaxed);
|
||||
const uint32_t read = read_position.load(std::memory_order_acquire);
|
||||
count = std::min(count, static_cast<size_t>(CAPACITY - (write - read)));
|
||||
const size_t first = std::min(count, static_cast<size_t>(CAPACITY - write % CAPACITY));
|
||||
const auto* bytes = static_cast<const uint8_t*>(source);
|
||||
std::memcpy(samples.data() + write % CAPACITY, bytes, first * sizeof(int16_t));
|
||||
std::memcpy(samples.data(), bytes + first * sizeof(int16_t), (count - first) * sizeof(int16_t));
|
||||
write_position.store(write + count, std::memory_order_release);
|
||||
return count;
|
||||
}
|
||||
|
||||
size_t read(void* destination, size_t count) {
|
||||
const uint32_t read = read_position.load(std::memory_order_relaxed);
|
||||
const uint32_t write = write_position.load(std::memory_order_acquire);
|
||||
count = std::min(count, static_cast<size_t>(write - read));
|
||||
const size_t first = std::min(count, static_cast<size_t>(CAPACITY - read % CAPACITY));
|
||||
auto* bytes = static_cast<uint8_t*>(destination);
|
||||
std::memcpy(bytes, samples.data() + read % CAPACITY, first * sizeof(int16_t));
|
||||
std::memcpy(bytes + first * sizeof(int16_t), samples.data(), (count - first) * sizeof(int16_t));
|
||||
read_position.store(read + count, std::memory_order_release);
|
||||
return count;
|
||||
}
|
||||
|
||||
bool empty() const {
|
||||
return read_position.load(std::memory_order_acquire) == write_position.load(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
// Only while the SDL device is closed and no caller is doing I/O.
|
||||
void reset() {
|
||||
read_position.store(0);
|
||||
write_position.store(0);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
#include "sdl_audio.h"
|
||||
|
||||
#import <AVFoundation/AVFoundation.h>
|
||||
#include <atomic>
|
||||
|
||||
error_t sdl_audio_microphone_permission() {
|
||||
@autoreleasepool {
|
||||
switch ([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio]) {
|
||||
case AVAuthorizationStatusAuthorized:
|
||||
return ERROR_NONE;
|
||||
case AVAuthorizationStatusDenied:
|
||||
case AVAuthorizationStatusRestricted:
|
||||
return ERROR_NOT_ALLOWED;
|
||||
case AVAuthorizationStatusNotDetermined: {
|
||||
static std::atomic<bool> requested { false };
|
||||
if (!requested.exchange(true)) {
|
||||
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
|
||||
requested.store(false);
|
||||
}];
|
||||
}
|
||||
return ERROR_RESOURCE_BUSY;
|
||||
}
|
||||
}
|
||||
return ERROR_NOT_ALLOWED;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
#include "sdl_bridge.h"
|
||||
#include "sdl_input.h"
|
||||
|
||||
#include <tactility/error.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <mutex>
|
||||
|
||||
namespace {
|
||||
|
||||
struct PresentJob {
|
||||
Device* device;
|
||||
void* internal;
|
||||
int32_t x_start;
|
||||
int32_t y_start;
|
||||
int32_t x_end;
|
||||
int32_t y_end;
|
||||
const void* color_data;
|
||||
error_t result;
|
||||
};
|
||||
|
||||
std::mutex job_mutex;
|
||||
std::condition_variable job_ready_cv;
|
||||
std::condition_variable job_done_cv;
|
||||
bool job_pending = false;
|
||||
bool job_done = false;
|
||||
PresentJob pending_job;
|
||||
|
||||
}
|
||||
|
||||
error_t sdl_bridge_present(Device* device, void* internal, int32_t x_start, int32_t y_start, int32_t x_end, int32_t y_end, const void* color_data) {
|
||||
std::unique_lock<std::mutex> lock(job_mutex);
|
||||
|
||||
pending_job = { device, internal, x_start, y_start, x_end, y_end, color_data, ERROR_NONE };
|
||||
job_pending = true;
|
||||
job_done = false;
|
||||
job_ready_cv.notify_one();
|
||||
|
||||
job_done_cv.wait(lock, [] { return job_done; });
|
||||
return pending_job.result;
|
||||
}
|
||||
|
||||
void sdl_bridge_run_main_loop() {
|
||||
while (true) {
|
||||
sdl_input_pump();
|
||||
|
||||
std::unique_lock<std::mutex> lock(job_mutex);
|
||||
if (job_ready_cv.wait_for(lock, std::chrono::milliseconds(1), [] { return job_pending; })) {
|
||||
PresentJob job = pending_job;
|
||||
lock.unlock();
|
||||
|
||||
job.result = sdl_display_execute_draw_bitmap(job.device, job.internal, job.x_start, job.y_start, job.x_end, job.y_end, job.color_data);
|
||||
|
||||
lock.lock();
|
||||
pending_job.result = job.result;
|
||||
job_pending = false;
|
||||
job_done = true;
|
||||
lock.unlock();
|
||||
job_done_cv.notify_one();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
#pragma once
|
||||
|
||||
#include <tactility/error.h>
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
struct Device;
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief Runs forever, pumping SDL input and executing display present jobs submitted via
|
||||
* sdl_bridge_present(). Must be called exactly once, from the real OS main thread: macOS requires
|
||||
* SDL/Cocoa window creation, event pumping and rendering to happen there, but FreeRTOS tasks
|
||||
* (including the lvgl task that owns display flush and indev polling) run on separate pthreads
|
||||
* spawned by the FreeRTOS POSIX port, not on that thread.
|
||||
*/
|
||||
void sdl_bridge_run_main_loop(void);
|
||||
|
||||
/**
|
||||
* @brief Hands a display flush off to the main thread and blocks until it has finished copying
|
||||
* the pixel data out (see sdl_display_execute_draw_bitmap() in sdl_display.cpp). Called from the
|
||||
* lvgl task. Must block: the caller's pixel buffer is single-buffered and gets reused as soon as
|
||||
* this returns.
|
||||
*/
|
||||
error_t sdl_bridge_present(struct Device* device, void* internal, int32_t x_start, int32_t y_start, int32_t x_end, int32_t y_end, const void* color_data);
|
||||
|
||||
/**
|
||||
* @brief Implemented in sdl_display.cpp: the actual SDL work behind a display flush (lazy window
|
||||
* init on first call, SDL_UpdateTexture, present). Only ever called from sdl_bridge_run_main_loop()
|
||||
* on the main thread.
|
||||
*/
|
||||
error_t sdl_display_execute_draw_bitmap(struct Device* device, void* internal, int32_t x_start, int32_t y_start, int32_t x_end, int32_t y_end, const void* color_data);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -1,5 +1,6 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
#include "sdl_display.h"
|
||||
#include "sdl_bridge.h"
|
||||
|
||||
#include <tactility/device.h>
|
||||
#include <tactility/driver.h>
|
||||
@@ -15,50 +16,46 @@ constexpr auto* TAG = "SdlDisplay";
|
||||
#define GET_CONFIG(device) (static_cast<const SdlDisplayConfig*>((device)->config))
|
||||
|
||||
struct SdlDisplayInternal {
|
||||
bool initialized;
|
||||
bool init_failed;
|
||||
SDL_Window* window;
|
||||
SDL_Renderer* renderer;
|
||||
SDL_Texture* texture;
|
||||
};
|
||||
|
||||
// Only one sdl-display device exists in the simulator; sdl_input.cpp uses this to map window
|
||||
// coordinates back to the fixed logical resolution SDL_RenderSetLogicalSize() scales to the window.
|
||||
static SdlDisplayInternal* g_display_internal = nullptr;
|
||||
|
||||
SDL_Renderer* sdl_display_get_renderer(void) {
|
||||
return g_display_internal != nullptr ? g_display_internal->renderer : nullptr;
|
||||
}
|
||||
|
||||
// Re-blits the already-drawn texture at the renderer's current (possibly just-resized) scale.
|
||||
// No new pixel data needed: the window resizing doesn't change what LVGL last rendered, only how
|
||||
// large it should appear, and SDL only applies that until the next SDL_RenderPresent() call.
|
||||
void sdl_display_present_now(void) {
|
||||
if (g_display_internal == nullptr) {
|
||||
return;
|
||||
}
|
||||
SDL_RenderClear(g_display_internal->renderer);
|
||||
SDL_RenderCopy(g_display_internal->renderer, g_display_internal->texture, nullptr, nullptr);
|
||||
SDL_RenderPresent(g_display_internal->renderer);
|
||||
}
|
||||
|
||||
// region Driver lifecycle
|
||||
|
||||
static error_t start(Device* device) {
|
||||
const auto* config = GET_CONFIG(device);
|
||||
|
||||
auto* internal = static_cast<SdlDisplayInternal*>(malloc(sizeof(SdlDisplayInternal)));
|
||||
if (internal == nullptr) {
|
||||
return ERROR_OUT_OF_MEMORY;
|
||||
}
|
||||
|
||||
if (SDL_InitSubSystem(SDL_INIT_VIDEO) != 0) {
|
||||
LOG_E(TAG, "SDL_InitSubSystem failed: %s", SDL_GetError());
|
||||
free(internal);
|
||||
return ERROR_RESOURCE;
|
||||
}
|
||||
|
||||
internal->window = SDL_CreateWindow(
|
||||
"Tactility",
|
||||
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
|
||||
config->horizontal_resolution, config->vertical_resolution,
|
||||
SDL_WINDOW_SHOWN
|
||||
);
|
||||
internal->renderer = internal->window != nullptr
|
||||
? SDL_CreateRenderer(internal->window, -1, SDL_RENDERER_ACCELERATED)
|
||||
: nullptr;
|
||||
internal->texture = internal->renderer != nullptr
|
||||
? SDL_CreateTexture(internal->renderer, SDL_PIXELFORMAT_RGB565, SDL_TEXTUREACCESS_STREAMING,
|
||||
config->horizontal_resolution, config->vertical_resolution)
|
||||
: nullptr;
|
||||
|
||||
if (internal->window == nullptr || internal->renderer == nullptr || internal->texture == nullptr) {
|
||||
LOG_E(TAG, "Failed to create SDL window: %s", SDL_GetError());
|
||||
if (internal->texture != nullptr) SDL_DestroyTexture(internal->texture);
|
||||
if (internal->renderer != nullptr) SDL_DestroyRenderer(internal->renderer);
|
||||
if (internal->window != nullptr) SDL_DestroyWindow(internal->window);
|
||||
SDL_QuitSubSystem(SDL_INIT_VIDEO);
|
||||
free(internal);
|
||||
return ERROR_RESOURCE;
|
||||
}
|
||||
internal->initialized = false;
|
||||
internal->init_failed = false;
|
||||
internal->window = nullptr;
|
||||
internal->renderer = nullptr;
|
||||
internal->texture = nullptr;
|
||||
|
||||
device_set_driver_data(device, internal);
|
||||
return ERROR_NONE;
|
||||
@@ -67,10 +64,16 @@ static error_t start(Device* device) {
|
||||
static error_t stop(Device* device) {
|
||||
auto* internal = static_cast<SdlDisplayInternal*>(device_get_driver_data(device));
|
||||
|
||||
SDL_DestroyTexture(internal->texture);
|
||||
SDL_DestroyRenderer(internal->renderer);
|
||||
SDL_DestroyWindow(internal->window);
|
||||
SDL_QuitSubSystem(SDL_INIT_VIDEO);
|
||||
if (internal->initialized) {
|
||||
SDL_DestroyTexture(internal->texture);
|
||||
SDL_DestroyRenderer(internal->renderer);
|
||||
SDL_DestroyWindow(internal->window);
|
||||
SDL_QuitSubSystem(SDL_INIT_VIDEO);
|
||||
}
|
||||
|
||||
if (g_display_internal == internal) {
|
||||
g_display_internal = nullptr;
|
||||
}
|
||||
|
||||
free(internal);
|
||||
device_set_driver_data(device, nullptr);
|
||||
@@ -84,8 +87,77 @@ static error_t stop(Device* device) {
|
||||
static error_t sdl_display_reset(Device*) { return ERROR_NONE; }
|
||||
static error_t sdl_display_init(Device*) { return ERROR_NONE; }
|
||||
|
||||
static error_t sdl_display_draw_bitmap(Device* device, int32_t x_start, int32_t y_start, int32_t x_end, int32_t y_end, const void* color_data) {
|
||||
auto* internal = static_cast<SdlDisplayInternal*>(device_get_driver_data(device));
|
||||
static float sdl_display_get_dpi_scale() {
|
||||
float hdpi = 96.0f;
|
||||
if (SDL_GetDisplayDPI(0, nullptr, &hdpi, nullptr) != 0 || hdpi <= 0.0f) {
|
||||
return 1.0f;
|
||||
}
|
||||
return hdpi / 96.0f;
|
||||
}
|
||||
|
||||
static bool sdl_display_lazy_init(Device* device, SdlDisplayInternal* internal) {
|
||||
const auto* config = GET_CONFIG(device);
|
||||
|
||||
if (SDL_InitSubSystem(SDL_INIT_VIDEO) != 0) {
|
||||
LOG_E(TAG, "SDL_InitSubSystem failed: %s", SDL_GetError());
|
||||
return false;
|
||||
}
|
||||
|
||||
// Only the window's initial on-screen footprint scales here - the render/logical resolution
|
||||
// (config->horizontal_resolution/vertical_resolution, used below for the texture and
|
||||
// SDL_RenderSetLogicalSize()) is unaffected, same as any other resize the user does by hand.
|
||||
const float dpi_scale = sdl_display_get_dpi_scale();
|
||||
const int initial_width = static_cast<int>(config->horizontal_resolution * dpi_scale);
|
||||
const int initial_height = static_cast<int>(config->vertical_resolution * dpi_scale);
|
||||
|
||||
internal->window = SDL_CreateWindow(
|
||||
"Tactility",
|
||||
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
|
||||
initial_width, initial_height,
|
||||
SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI
|
||||
);
|
||||
internal->renderer = internal->window != nullptr
|
||||
? SDL_CreateRenderer(internal->window, -1, SDL_RENDERER_ACCELERATED)
|
||||
: nullptr;
|
||||
// Lets the window be resized freely while the renderer scales/letterboxes the fixed-resolution
|
||||
// texture below to fit - LVGL keeps rendering at horizontal_resolution x vertical_resolution.
|
||||
if (internal->renderer != nullptr) {
|
||||
SDL_RenderSetLogicalSize(internal->renderer, config->horizontal_resolution, config->vertical_resolution);
|
||||
}
|
||||
internal->texture = internal->renderer != nullptr
|
||||
? SDL_CreateTexture(internal->renderer, SDL_PIXELFORMAT_RGB565, SDL_TEXTUREACCESS_STREAMING,
|
||||
config->horizontal_resolution, config->vertical_resolution)
|
||||
: nullptr;
|
||||
|
||||
if (internal->window == nullptr || internal->renderer == nullptr || internal->texture == nullptr) {
|
||||
LOG_E(TAG, "Failed to create SDL window: %s", SDL_GetError());
|
||||
if (internal->texture != nullptr) SDL_DestroyTexture(internal->texture);
|
||||
if (internal->renderer != nullptr) SDL_DestroyRenderer(internal->renderer);
|
||||
if (internal->window != nullptr) SDL_DestroyWindow(internal->window);
|
||||
SDL_QuitSubSystem(SDL_INIT_VIDEO);
|
||||
return false;
|
||||
}
|
||||
|
||||
g_display_internal = internal;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Only ever called from sdl_bridge_run_main_loop() on the real main thread - required for
|
||||
// SDL/Cocoa window creation and rendering on macOS.
|
||||
error_t sdl_display_execute_draw_bitmap(Device* device, void* internal_ptr, int32_t x_start, int32_t y_start, int32_t x_end, int32_t y_end, const void* color_data) {
|
||||
auto* internal = static_cast<SdlDisplayInternal*>(internal_ptr);
|
||||
|
||||
if (internal->init_failed) {
|
||||
return ERROR_RESOURCE;
|
||||
}
|
||||
|
||||
if (!internal->initialized) {
|
||||
if (!sdl_display_lazy_init(device, internal)) {
|
||||
internal->init_failed = true;
|
||||
return ERROR_RESOURCE;
|
||||
}
|
||||
internal->initialized = true;
|
||||
}
|
||||
|
||||
SDL_Rect rect = { x_start, y_start, x_end - x_start, y_end - y_start };
|
||||
// RGB565 = 2 bytes/pixel.
|
||||
@@ -93,12 +165,20 @@ static error_t sdl_display_draw_bitmap(Device* device, int32_t x_start, int32_t
|
||||
return ERROR_RESOURCE;
|
||||
}
|
||||
|
||||
SDL_RenderClear(internal->renderer);
|
||||
SDL_RenderCopy(internal->renderer, internal->texture, nullptr, nullptr);
|
||||
SDL_RenderPresent(internal->renderer);
|
||||
sdl_display_present_now();
|
||||
return ERROR_NONE;
|
||||
}
|
||||
|
||||
static error_t sdl_display_draw_bitmap(Device* device, int32_t x_start, int32_t y_start, int32_t x_end, int32_t y_end, const void* color_data) {
|
||||
auto* internal = static_cast<SdlDisplayInternal*>(device_get_driver_data(device));
|
||||
|
||||
if (internal->init_failed) {
|
||||
return ERROR_RESOURCE;
|
||||
}
|
||||
|
||||
return sdl_bridge_present(device, internal, x_start, y_start, x_end, y_end, color_data);
|
||||
}
|
||||
|
||||
static enum DisplayColorFormat sdl_display_get_color_format(Device*) {
|
||||
return DISPLAY_COLOR_FORMAT_RGB565;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
#pragma once
|
||||
|
||||
#include <SDL2/SDL.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
@@ -12,6 +14,22 @@ struct SdlDisplayConfig {
|
||||
uint16_t vertical_resolution;
|
||||
};
|
||||
|
||||
/**
|
||||
* @return the display's renderer, or NULL if the display hasn't drawn its first frame yet
|
||||
* (see sdl_display_lazy_init() in sdl_display.cpp). Used by sdl_input.cpp to map window
|
||||
* coordinates back to the fixed logical resolution the renderer scales to fit the window.
|
||||
*/
|
||||
SDL_Renderer* sdl_display_get_renderer(void);
|
||||
|
||||
/**
|
||||
* @brief Re-presents the already-drawn frame at the renderer's current scale. Call this when the
|
||||
* window is resized: the window size change alone doesn't make SDL re-blit the last frame at
|
||||
* the new scale until something calls SDL_RenderPresent() again, and LVGL won't do that on
|
||||
* its own since nothing it's tracking actually changed. No-op if the display hasn't drawn its
|
||||
* first frame yet.
|
||||
*/
|
||||
void sdl_display_present_now(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -1,18 +1,54 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
#include "sdl_input.h"
|
||||
#include "sdl_display.h"
|
||||
|
||||
#include <tactility/drivers/keyboard.h>
|
||||
|
||||
#include <SDL2/SDL.h>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <mutex>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr size_t KEY_QUEUE_CAPACITY = 32;
|
||||
|
||||
// Written by sdl_input_pump() on the real main thread, read by sdl_input_get_pointer_state()/
|
||||
// sdl_input_pop_key()/sdl_input_has_queued_key() on the lvgl task.
|
||||
std::mutex state_mutex;
|
||||
|
||||
SdlPointerState pointer_state = { 0, 0, false };
|
||||
|
||||
} // namespace
|
||||
|
||||
// Web touch-injection override (headless sim viewer). Guarded by tick count so
|
||||
// a press auto-releases even if the viewer never sends the release event.
|
||||
// File-scope (not anonymous namespace): the extern "C" setters below must be
|
||||
// visible to the linker for WebServerService's touch endpoint.
|
||||
bool touch_override_active = false;
|
||||
SdlPointerState touch_override = { 0, 0, false };
|
||||
uint32_t touch_override_until_tick = 0;
|
||||
#define SIM_TOUCH_HOLD_MS 1500
|
||||
|
||||
extern "C" void sdl_input_set_touch_override(int32_t x, int32_t y, bool pressed) {
|
||||
std::lock_guard<std::mutex> lock(state_mutex);
|
||||
touch_override.x = x;
|
||||
touch_override.y = y;
|
||||
touch_override.pressed = pressed;
|
||||
touch_override_active = pressed;
|
||||
if (pressed) {
|
||||
touch_override_until_tick = SDL_GetTicks() + SIM_TOUCH_HOLD_MS;
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" void sdl_input_clear_touch_override(void) {
|
||||
std::lock_guard<std::mutex> lock(state_mutex);
|
||||
touch_override_active = false;
|
||||
touch_override.pressed = false;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
uint32_t key_queue[KEY_QUEUE_CAPACITY];
|
||||
size_t key_queue_head = 0;
|
||||
size_t key_queue_count = 0;
|
||||
@@ -34,6 +70,23 @@ void push_key(uint32_t key) {
|
||||
// all of these back to LVGL's own sentinels (CODEPOINT_ESCAPE/BACKSPACE/DELETE already equal their
|
||||
// LV_KEY_* counterpart numerically, so no translation is needed for those). Printable characters
|
||||
// arrive separately via SDL_TEXTINPUT.
|
||||
// The window can be freely resized (see sdl_display.cpp's SDL_WINDOW_RESIZABLE/
|
||||
// SDL_RenderSetLogicalSize()), so raw SDL mouse coordinates are in window-pixel space, not the
|
||||
// fixed logical resolution LVGL renders at. SDL_RenderWindowToLogical() is the renderer's own
|
||||
// inverse of that scaling, accounting for both the scale factor and any letterbox offset.
|
||||
void set_pointer_position(int32_t window_x, int32_t window_y) {
|
||||
SDL_Renderer* renderer = sdl_display_get_renderer();
|
||||
if (renderer == nullptr) {
|
||||
pointer_state.x = window_x;
|
||||
pointer_state.y = window_y;
|
||||
return;
|
||||
}
|
||||
float logical_x, logical_y;
|
||||
SDL_RenderWindowToLogical(renderer, window_x, window_y, &logical_x, &logical_y);
|
||||
pointer_state.x = static_cast<int32_t>(logical_x);
|
||||
pointer_state.y = static_cast<int32_t>(logical_y);
|
||||
}
|
||||
|
||||
uint32_t keycode_to_key(SDL_Keycode sdl_key, bool shift) {
|
||||
switch (sdl_key) {
|
||||
case SDLK_RIGHT: return CODEPOINT_ARROW_RIGHT;
|
||||
@@ -52,53 +105,92 @@ uint32_t keycode_to_key(SDL_Keycode sdl_key, bool shift) {
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void sdl_input_pump() {
|
||||
if (!text_input_started) {
|
||||
SDL_StartTextInput();
|
||||
text_input_started = true;
|
||||
// exit() must run with state_mutex unlocked: it never returns, so a lock_guard held across it
|
||||
// would never release the mutex, hanging any other thread that later calls into this file's
|
||||
// other functions (all of which lock state_mutex) while exit() tears the process down.
|
||||
bool quit_requested = false;
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(state_mutex);
|
||||
|
||||
if (!text_input_started) {
|
||||
SDL_StartTextInput();
|
||||
text_input_started = true;
|
||||
}
|
||||
|
||||
SDL_Event event;
|
||||
while (SDL_PollEvent(&event)) {
|
||||
switch (event.type) {
|
||||
case SDL_MOUSEMOTION:
|
||||
set_pointer_position(event.motion.x, event.motion.y);
|
||||
break;
|
||||
case SDL_MOUSEBUTTONDOWN:
|
||||
if (event.button.button == SDL_BUTTON_LEFT) {
|
||||
// event.button.x/y can be stale immediately after a window resize (an
|
||||
// SDL/X11 event-queue quirk - confirmed by comparing against a live
|
||||
// SDL_GetWindowSize() at the same instant). SDL_GetMouseState() queries the
|
||||
// OS for the current pointer position directly, sidestepping that entirely.
|
||||
int live_x, live_y;
|
||||
SDL_GetMouseState(&live_x, &live_y);
|
||||
set_pointer_position(live_x, live_y);
|
||||
pointer_state.pressed = true;
|
||||
}
|
||||
break;
|
||||
case SDL_MOUSEBUTTONUP:
|
||||
if (event.button.button == SDL_BUTTON_LEFT) {
|
||||
pointer_state.pressed = false;
|
||||
}
|
||||
break;
|
||||
case SDL_KEYDOWN:
|
||||
push_key(keycode_to_key(event.key.keysym.sym, (event.key.keysym.mod & KMOD_SHIFT) != 0));
|
||||
break;
|
||||
case SDL_TEXTINPUT:
|
||||
// ASCII only (first byte of event.text.text) - sufficient for a simulator keyboard.
|
||||
push_key(static_cast<uint8_t>(event.text.text[0]));
|
||||
break;
|
||||
case SDL_WINDOWEVENT:
|
||||
// Resizing doesn't change what LVGL last rendered, only how large it should
|
||||
// appear - re-present the existing frame at the new scale immediately, rather
|
||||
// than leaving stale-looking content on screen until the next LVGL-driven flush.
|
||||
if (event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) {
|
||||
sdl_display_present_now();
|
||||
}
|
||||
break;
|
||||
case SDL_QUIT:
|
||||
quit_requested = true;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SDL_Event event;
|
||||
while (SDL_PollEvent(&event)) {
|
||||
switch (event.type) {
|
||||
case SDL_MOUSEMOTION:
|
||||
pointer_state.x = event.motion.x;
|
||||
pointer_state.y = event.motion.y;
|
||||
break;
|
||||
case SDL_MOUSEBUTTONDOWN:
|
||||
if (event.button.button == SDL_BUTTON_LEFT) {
|
||||
pointer_state.x = event.button.x;
|
||||
pointer_state.y = event.button.y;
|
||||
pointer_state.pressed = true;
|
||||
}
|
||||
break;
|
||||
case SDL_MOUSEBUTTONUP:
|
||||
if (event.button.button == SDL_BUTTON_LEFT) {
|
||||
pointer_state.pressed = false;
|
||||
}
|
||||
break;
|
||||
case SDL_KEYDOWN:
|
||||
push_key(keycode_to_key(event.key.keysym.sym, (event.key.keysym.mod & KMOD_SHIFT) != 0));
|
||||
break;
|
||||
case SDL_TEXTINPUT:
|
||||
// ASCII only (first byte of event.text.text) - sufficient for a simulator keyboard.
|
||||
push_key(static_cast<uint8_t>(event.text.text[0]));
|
||||
break;
|
||||
case SDL_QUIT:
|
||||
exit(0);
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (quit_requested) {
|
||||
exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
void sdl_input_get_pointer_state(SdlPointerState* out_state) {
|
||||
std::lock_guard<std::mutex> lock(state_mutex);
|
||||
if (touch_override_active) {
|
||||
// Auto-release: viewer sends press only; LVGL needs press then release
|
||||
// to register a click. Hold long enough for several indev polls.
|
||||
if ((int32_t)(SDL_GetTicks() - touch_override_until_tick) >= 0) {
|
||||
touch_override_active = false;
|
||||
touch_override.pressed = false;
|
||||
} else {
|
||||
*out_state = touch_override;
|
||||
return;
|
||||
}
|
||||
}
|
||||
*out_state = pointer_state;
|
||||
}
|
||||
|
||||
bool sdl_input_pop_key(uint32_t* out_key) {
|
||||
std::lock_guard<std::mutex> lock(state_mutex);
|
||||
if (key_queue_count == 0) {
|
||||
return false;
|
||||
}
|
||||
@@ -109,5 +201,6 @@ bool sdl_input_pop_key(uint32_t* out_key) {
|
||||
}
|
||||
|
||||
bool sdl_input_has_queued_key() {
|
||||
std::lock_guard<std::mutex> lock(state_mutex);
|
||||
return key_queue_count > 0;
|
||||
}
|
||||
|
||||
@@ -19,9 +19,9 @@ struct SdlPointerState {
|
||||
|
||||
/**
|
||||
* @brief Drains all pending SDL events exactly once, updating the pointer state and key queue
|
||||
* below. Safe to call from both the sdl-pointer and sdl-keyboard drivers' polling functions:
|
||||
* SDL_PollEvent() drains a single global queue, so whichever driver is polled first on a given
|
||||
* LVGL indev tick pumps events for both.
|
||||
* below. Must be called only from the real OS main thread (sdl_bridge_run_main_loop()): SDL
|
||||
* requires event pumping to happen there on macOS. The getters below are safe to call from a
|
||||
* different thread (the lvgl task, via sdl-pointer/sdl-keyboard's polling functions).
|
||||
*/
|
||||
void sdl_input_pump(void);
|
||||
|
||||
@@ -42,6 +42,16 @@ bool sdl_input_pop_key(uint32_t* out_key);
|
||||
*/
|
||||
bool sdl_input_has_queued_key(void);
|
||||
|
||||
/**
|
||||
* @brief Web-injected touch override (for headless sim viewer without SDL window).
|
||||
* When active, sdl_pointer_get_touched_points() reports this state instead of
|
||||
* the SDL mouse state. Coordinates are in LVGL logical pixels (e.g. 640x480).
|
||||
* Pass pressed=false to release. Auto-releases after SIM_TOUCH_HOLD_MS unless
|
||||
* refreshed (tap = press, wait, release handled by the web viewer).
|
||||
*/
|
||||
void sdl_input_set_touch_override(int32_t x, int32_t y, bool pressed);
|
||||
void sdl_input_clear_touch_override(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -16,8 +16,6 @@ static error_t stop(Device*) { return ERROR_NONE; }
|
||||
// region KeyboardApi
|
||||
|
||||
static error_t sdl_keyboard_read_key(Device*, KeyboardKeyData* data) {
|
||||
sdl_input_pump();
|
||||
|
||||
uint32_t key = 0;
|
||||
if (sdl_input_pop_key(&key)) {
|
||||
data->key = key;
|
||||
|
||||
@@ -16,7 +16,6 @@ static error_t stop(Device*) { return ERROR_NONE; }
|
||||
// region PointerApi
|
||||
|
||||
static error_t sdl_pointer_read_data(Device*, TickType_t) {
|
||||
sdl_input_pump();
|
||||
return ERROR_NONE;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "drivers/sdl_display.h"
|
||||
#include "drivers/sdl_audio.h"
|
||||
|
||||
#include <tactility/device.h>
|
||||
#include <tactility/device_listener.h>
|
||||
@@ -16,11 +17,13 @@ extern "C" {
|
||||
extern Driver sdl_display_driver;
|
||||
extern Driver sdl_pointer_driver;
|
||||
extern Driver sdl_keyboard_driver;
|
||||
extern Driver sdl_audio_driver;
|
||||
|
||||
static Driver* const simulator_drivers[] = {
|
||||
&sdl_display_driver,
|
||||
&sdl_pointer_driver,
|
||||
&sdl_keyboard_driver,
|
||||
&sdl_audio_driver,
|
||||
nullptr
|
||||
};
|
||||
|
||||
@@ -29,10 +32,35 @@ static Driver* const simulator_drivers[] = {
|
||||
// These devices have no real bus to attach to (SDL has no notion of one), but every non-root
|
||||
// device is still expected to have a parent (see Device::parent) - they're parented to root once
|
||||
// it's available below.
|
||||
static const SdlDisplayConfig sdl_display_config = { 320, 240 };
|
||||
// Display resolution is overridable at runtime via SIM_DISPLAY_W/H env vars
|
||||
// so the sim can match real hardware (e.g. ES3C35P 3.5" = 320x480 portrait,
|
||||
// ES3C28P 2.8" = 320x240 landscape). Defaults to 640x480.
|
||||
static uint16_t sim_display_width(void) {
|
||||
const char* w = getenv("SIM_DISPLAY_W");
|
||||
if (w != nullptr) {
|
||||
long v = atol(w);
|
||||
if (v >= 120 && v <= 2048) return (uint16_t)v;
|
||||
}
|
||||
return 480;
|
||||
}
|
||||
|
||||
static uint16_t sim_display_height(void) {
|
||||
const char* h = getenv("SIM_DISPLAY_H");
|
||||
if (h != nullptr) {
|
||||
long v = atol(h);
|
||||
if (v >= 120 && v <= 2048) return (uint16_t)v;
|
||||
}
|
||||
return 320;
|
||||
}
|
||||
|
||||
static SdlDisplayConfig sdl_display_config = { 480, 320 };
|
||||
static Device sdl_display_device {};
|
||||
static Device sdl_pointer_device {};
|
||||
static Device sdl_keyboard_device {};
|
||||
static Device sdl_speaker_device {};
|
||||
static Device sdl_microphone_device {};
|
||||
static const SdlAudioConfig sdl_speaker_config { AUDIO_CODEC_DIR_OUTPUT };
|
||||
static const SdlAudioConfig sdl_microphone_config { AUDIO_CODEC_DIR_INPUT };
|
||||
|
||||
static bool construct_add_start(Device* device, Device* parent, const char* name, const void* config, const char* compatible) {
|
||||
device->address = 0;
|
||||
@@ -81,9 +109,15 @@ static void on_root_started(Device* device, DeviceEvent event, void* context) {
|
||||
return;
|
||||
}
|
||||
|
||||
sdl_display_config.horizontal_resolution = sim_display_width();
|
||||
sdl_display_config.vertical_resolution = sim_display_height();
|
||||
LOG_I(TAG, "Sim display %dx%d (SIM_DISPLAY_W/H override, default 480x320 landscape)",
|
||||
sdl_display_config.horizontal_resolution, sdl_display_config.vertical_resolution);
|
||||
construct_add_start(&sdl_display_device, device, "display0", &sdl_display_config, "tactility,sdl-display");
|
||||
construct_add_start(&sdl_pointer_device, device, "pointer0", nullptr, "tactility,sdl-pointer");
|
||||
construct_add_start(&sdl_keyboard_device, device, "keyboard0", nullptr, "tactility,sdl-keyboard");
|
||||
construct_add_start(&sdl_speaker_device, device, "speaker0", &sdl_speaker_config, "tactility,sdl-audio");
|
||||
construct_add_start(&sdl_microphone_device, device, "microphone0", &sdl_microphone_config, "tactility,sdl-audio");
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
dependencies:
|
||||
- Platforms/platform-posix
|
||||
- Drivers/audio-stream-module
|
||||
dts: simulator.dts
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>org.tactilityproject.simulator</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>Tactility</string>
|
||||
<key>NSMicrophoneUsageDescription</key>
|
||||
<string>Tactility uses the microphone when a simulator app records audio.</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,14 @@
|
||||
add_executable(SimulatorAudioTests EXCLUDE_FROM_ALL
|
||||
audio.cpp
|
||||
../Source/drivers/sdl_audio.cpp
|
||||
)
|
||||
target_include_directories(SimulatorAudioTests PRIVATE ${DOCTESTINC} ../Source/drivers)
|
||||
target_link_libraries(SimulatorAudioTests PRIVATE TactilityKernel platform-posix audio-stream-module SDL2-static)
|
||||
if (APPLE)
|
||||
target_sources(SimulatorAudioTests PRIVATE ../Source/drivers/sdl_audio_permission.mm)
|
||||
target_link_libraries(SimulatorAudioTests PRIVATE "-framework AVFoundation" "-framework Foundation")
|
||||
endif ()
|
||||
add_test(NAME SimulatorAudioTests COMMAND SimulatorAudioTests)
|
||||
set_tests_properties(SimulatorAudioTests PROPERTIES TIMEOUT 30 ENVIRONMENT "SDL_AUDIODRIVER=dummy;SIM_AUDIO_INPUT=;SIM_AUDIO_OUTPUT=")
|
||||
add_test(NAME SimulatorAudioPcmTests COMMAND SimulatorAudioTests --no-skip "--test-case=disk PCM*")
|
||||
set_tests_properties(SimulatorAudioPcmTests PROPERTIES TIMEOUT 30 ENVIRONMENT "SDL_AUDIODRIVER=disk;SIM_AUDIO_INPUT=;SIM_AUDIO_OUTPUT=")
|
||||
@@ -0,0 +1,301 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
#define DOCTEST_CONFIG_IMPLEMENT
|
||||
#include "doctest.h"
|
||||
#include "sdl_audio.h"
|
||||
#include "sdl_audio_buffer.h"
|
||||
|
||||
#include <tactility/device.h>
|
||||
#include <tactility/driver.h>
|
||||
#include <tactility/drivers/audio_stream.h>
|
||||
#include <tactility/freertos/task.h>
|
||||
#include <tactility/kernel_init.h>
|
||||
|
||||
#include <SDL2/SDL.h>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <cstdio>
|
||||
#include <fstream>
|
||||
#include <unistd.h>
|
||||
#include <vector>
|
||||
|
||||
extern Driver sdl_audio_driver;
|
||||
extern "C" {
|
||||
extern Module platform_posix_module;
|
||||
extern Module audio_stream_module;
|
||||
extern Device audio_stream_device;
|
||||
static Driver* const drivers[] = { &sdl_audio_driver, nullptr };
|
||||
Module simulator_module = { .name = "simulator-audio-test", .drivers = drivers };
|
||||
}
|
||||
|
||||
static const SdlAudioConfig output_config { AUDIO_CODEC_DIR_OUTPUT };
|
||||
static const SdlAudioConfig input_config { AUDIO_CODEC_DIR_INPUT };
|
||||
static Device speaker { .name = "speaker-test", .config = &output_config };
|
||||
static Device microphone { .name = "microphone-test", .config = &input_config };
|
||||
|
||||
struct Stream {
|
||||
AudioStreamHandle handle = nullptr;
|
||||
~Stream() { if (handle != nullptr) audio_stream_close(handle); }
|
||||
};
|
||||
|
||||
TEST_CASE("bounded PCM buffer preserves data across wrap and overflow") {
|
||||
SdlAudioBuffer buffer;
|
||||
std::vector<int16_t> input(20000);
|
||||
for (size_t i = 0; i < input.size(); ++i) input[i] = static_cast<int16_t>(i);
|
||||
std::vector<int16_t> output(20000, -1);
|
||||
CHECK(buffer.read(output.data(), output.size()) == 0);
|
||||
REQUIRE(buffer.write(input.data(), input.size()) == 16384);
|
||||
CHECK(buffer.write(input.data(), 2) == 0);
|
||||
REQUIRE(buffer.read(output.data(), 10000) == 10000);
|
||||
CHECK(std::equal(output.begin(), output.begin() + 10000, input.begin()));
|
||||
REQUIRE(buffer.write(input.data(), 10000) == 10000);
|
||||
REQUIRE(buffer.read(output.data(), output.size()) == 16384);
|
||||
CHECK(std::equal(output.begin(), output.begin() + 6384, input.begin() + 10000));
|
||||
CHECK(std::equal(output.begin() + 6384, output.begin() + 16384, input.begin()));
|
||||
CHECK(buffer.empty());
|
||||
}
|
||||
|
||||
TEST_CASE("simulator streams support independent full duplex and common PCM rates") {
|
||||
for (uint32_t rate : { 16000u, 44100u, 48000u }) {
|
||||
CAPTURE(rate);
|
||||
const AudioStreamConfig config { rate, 16, 1 };
|
||||
Stream input;
|
||||
Stream output;
|
||||
REQUIRE(audio_stream_open_input(&audio_stream_device, &config, &input.handle) == ERROR_NONE);
|
||||
REQUIRE(audio_stream_open_output(&audio_stream_device, &config, &output.handle) == ERROR_NONE);
|
||||
AudioStreamHandle duplicate = nullptr;
|
||||
CHECK(audio_stream_open_output(&audio_stream_device, &config, &duplicate) == ERROR_INVALID_STATE);
|
||||
std::vector<int16_t> samples(rate / 20, 1234);
|
||||
size_t count = 0;
|
||||
REQUIRE(audio_stream_write(output.handle, samples.data(), samples.size() * 2, &count, pdMS_TO_TICKS(1000)) == ERROR_NONE);
|
||||
CHECK(count == samples.size() * 2);
|
||||
REQUIRE(audio_stream_read(input.handle, samples.data(), samples.size() * 2, &count, pdMS_TO_TICKS(1000)) == ERROR_NONE);
|
||||
CHECK(count == samples.size() * 2);
|
||||
CHECK(std::all_of(samples.begin(), samples.end(), [](int16_t sample) { return sample == 0; }));
|
||||
REQUIRE(audio_stream_close(output.handle) == ERROR_NONE);
|
||||
output.handle = nullptr;
|
||||
// Closing the speaker must not stop the microphone.
|
||||
REQUIRE(audio_stream_read(input.handle, samples.data(), samples.size() * 2, &count, pdMS_TO_TICKS(1000)) == ERROR_NONE);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("simulator audio controls persist across opens and disabling closes output") {
|
||||
auto* device = &audio_stream_device;
|
||||
REQUIRE(audio_stream_set_volume(device, AUDIO_CODEC_DIR_OUTPUT, 25.0f) == ERROR_NONE);
|
||||
REQUIRE(audio_stream_set_mute(device, AUDIO_CODEC_DIR_OUTPUT, true) == ERROR_NONE);
|
||||
const AudioStreamConfig config { 48000, 16, 2 };
|
||||
Stream output;
|
||||
REQUIRE(audio_stream_open_output(device, &config, &output.handle) == ERROR_NONE);
|
||||
float volume = 0;
|
||||
bool muted = false;
|
||||
REQUIRE(audio_codec_get_volume(&speaker, AUDIO_CODEC_DIR_OUTPUT, &volume) == ERROR_NONE);
|
||||
REQUIRE(audio_codec_get_mute(&speaker, AUDIO_CODEC_DIR_OUTPUT, &muted) == ERROR_NONE);
|
||||
CHECK(volume == 25.0f);
|
||||
CHECK(muted);
|
||||
REQUIRE(audio_stream_set_enabled(device, AUDIO_CODEC_DIR_OUTPUT, false) == ERROR_NONE);
|
||||
output.handle = nullptr; // set_enabled closes and owns destruction of the handle
|
||||
CHECK(audio_stream_open_output(device, &config, &output.handle) == ERROR_NOT_ALLOWED);
|
||||
REQUIRE(audio_stream_set_enabled(device, AUDIO_CODEC_DIR_OUTPUT, true) == ERROR_NONE);
|
||||
REQUIRE(audio_stream_set_mute(device, AUDIO_CODEC_DIR_OUTPUT, false) == ERROR_NONE);
|
||||
REQUIRE(audio_stream_open_output(device, &config, &output.handle) == ERROR_NONE);
|
||||
}
|
||||
|
||||
TEST_CASE("bounded playback reports partial progress on a nonblocking timeout") {
|
||||
const AudioStreamConfig config { 48000, 16, 2 };
|
||||
Stream output;
|
||||
REQUIRE(audio_stream_open_output(&audio_stream_device, &config, &output.handle) == ERROR_NONE);
|
||||
std::vector<int16_t> samples(48000 * 2, 0);
|
||||
size_t count = 999;
|
||||
CHECK(audio_stream_write(output.handle, samples.data(), samples.size() * 2, &count, 0) == ERROR_TIMEOUT);
|
||||
CHECK(count > 0);
|
||||
CHECK(count < samples.size() * 2);
|
||||
CHECK(count % 4 == 0);
|
||||
}
|
||||
|
||||
TEST_CASE("converted streams report partial progress on timeout") {
|
||||
const AudioStreamConfig config { 16000, 16, 1 };
|
||||
Stream output;
|
||||
Stream input;
|
||||
REQUIRE(audio_stream_open_output(&audio_stream_device, &config, &output.handle) == ERROR_NONE);
|
||||
REQUIRE(audio_stream_open_input(&audio_stream_device, &config, &input.handle) == ERROR_NONE);
|
||||
std::vector<int16_t> samples(16000, 0);
|
||||
size_t count = 999;
|
||||
CHECK(audio_stream_write(output.handle, samples.data(), samples.size() * 2, &count, 0) == ERROR_TIMEOUT);
|
||||
CHECK(count > 0);
|
||||
CHECK(count < samples.size() * 2);
|
||||
CHECK(count % 2 == 0);
|
||||
vTaskDelay(pdMS_TO_TICKS(30)); // allow dummy capture to produce some samples
|
||||
count = 999;
|
||||
CHECK(audio_stream_read(input.handle, samples.data(), samples.size() * 2, &count, 0) == ERROR_TIMEOUT);
|
||||
CHECK(count > 0);
|
||||
CHECK(count < samples.size() * 2);
|
||||
CHECK(count % 2 == 0);
|
||||
}
|
||||
|
||||
TEST_CASE("missing selected microphone does not prevent speaker playback") {
|
||||
REQUIRE(SDL_setenv("SIM_AUDIO_INPUT", "tactility-nonexistent-microphone", 1) == 0);
|
||||
AudioCodecDirection capability;
|
||||
CHECK(audio_codec_get_capabilities(µphone, &capability) == ERROR_NOT_SUPPORTED);
|
||||
const AudioCodecStreamConfig config { 48000, 16, 1, AUDIO_CODEC_DIR_INPUT };
|
||||
CHECK(audio_codec_open(µphone, &config) == ERROR_NOT_SUPPORTED);
|
||||
CHECK(audio_codec_get_capabilities(&speaker, &capability) == ERROR_NONE);
|
||||
CHECK(capability == AUDIO_CODEC_DIR_OUTPUT);
|
||||
REQUIRE(SDL_setenv("SIM_AUDIO_INPUT", "", 1) == 0);
|
||||
}
|
||||
|
||||
TEST_CASE("unsupported sample widths fail without breaking a later open") {
|
||||
AudioStreamConfig config { 16000, 24, 1 };
|
||||
Stream output;
|
||||
CHECK(audio_stream_open_output(&audio_stream_device, &config, &output.handle) != ERROR_NONE);
|
||||
CHECK(output.handle == nullptr);
|
||||
config.bits_per_sample = 16;
|
||||
REQUIRE(audio_stream_open_output(&audio_stream_device, &config, &output.handle) == ERROR_NONE);
|
||||
}
|
||||
|
||||
TEST_CASE("zero sample rate is rejected before conversion") {
|
||||
const AudioStreamConfig config { 0, 16, 1 };
|
||||
Stream output;
|
||||
CHECK(audio_stream_open_output(&audio_stream_device, &config, &output.handle) == ERROR_INVALID_ARGUMENT);
|
||||
}
|
||||
|
||||
TEST_CASE("disabling while a codec is opening cancels the pending stream") {
|
||||
const auto* original_api = static_cast<const AudioCodecApi*>(sdl_audio_driver.api);
|
||||
static const AudioCodecApi* wrapped_api;
|
||||
wrapped_api = original_api;
|
||||
AudioCodecApi delayed_api = *original_api;
|
||||
delayed_api.open = [](Device* device, const AudioCodecStreamConfig* config) {
|
||||
vTaskDelay(pdMS_TO_TICKS(50)); // models waiting for microphone permission
|
||||
return wrapped_api->open(device, config);
|
||||
};
|
||||
sdl_audio_driver.api = &delayed_api;
|
||||
struct RestoreApi {
|
||||
const AudioCodecApi* api;
|
||||
~RestoreApi() { sdl_audio_driver.api = api; }
|
||||
} restore { original_api };
|
||||
REQUIRE(xTaskCreate([](void*) {
|
||||
vTaskDelay(pdMS_TO_TICKS(5));
|
||||
audio_stream_set_enabled(&audio_stream_device, AUDIO_CODEC_DIR_OUTPUT, false);
|
||||
// Re-enabling does not resurrect the cancelled attempt.
|
||||
audio_stream_set_enabled(&audio_stream_device, AUDIO_CODEC_DIR_OUTPUT, true);
|
||||
vTaskDelete(nullptr);
|
||||
}, "disable-audio", 8192, nullptr, 1, nullptr) == pdPASS);
|
||||
const AudioStreamConfig config { 48000, 16, 2 };
|
||||
Stream output;
|
||||
CHECK(audio_stream_open_output(&audio_stream_device, &config, &output.handle) == ERROR_NOT_ALLOWED);
|
||||
CHECK(output.handle == nullptr);
|
||||
sdl_audio_driver.api = original_api;
|
||||
REQUIRE(audio_stream_open_output(&audio_stream_device, &config, &output.handle) == ERROR_NONE);
|
||||
}
|
||||
|
||||
TEST_CASE("hardware output smoke test" * doctest::skip()) {
|
||||
// Explicit opt-in only: SDL_AUDIODRIVER=coreaudio ... --no-skip --test-case='hardware output smoke test'
|
||||
const AudioStreamConfig config { 48000, 16, 2 };
|
||||
Stream output;
|
||||
REQUIRE(audio_stream_set_volume(&audio_stream_device, AUDIO_CODEC_DIR_OUTPUT, 20) == ERROR_NONE);
|
||||
REQUIRE(audio_stream_open_output(&audio_stream_device, &config, &output.handle) == ERROR_NONE);
|
||||
std::vector<int16_t> samples(48000); // half a second, stereo, quiet 440 Hz tone
|
||||
for (size_t frame = 0; frame < samples.size() / 2; ++frame) {
|
||||
samples[frame * 2] = samples[frame * 2 + 1] = static_cast<int16_t>(3000 * std::sin(frame * 440.0 * 6.283185307 / 48000));
|
||||
}
|
||||
size_t count = 0;
|
||||
REQUIRE(audio_stream_write(output.handle, samples.data(), samples.size() * 2, &count, pdMS_TO_TICKS(2000)) == ERROR_NONE);
|
||||
CHECK(count == samples.size() * 2);
|
||||
}
|
||||
|
||||
TEST_CASE("disk PCM capture and playback apply gain and mute" * doctest::skip()) {
|
||||
REQUIRE(std::strcmp(SDL_GetCurrentAudioDriver(), "disk") == 0);
|
||||
auto* device = &audio_stream_device;
|
||||
const AudioStreamConfig config { 48000, 16, 1 };
|
||||
Stream input;
|
||||
Stream output;
|
||||
REQUIRE(audio_stream_set_volume(device, AUDIO_CODEC_DIR_INPUT, 50) == ERROR_NONE);
|
||||
REQUIRE(audio_stream_set_volume(device, AUDIO_CODEC_DIR_OUTPUT, 25) == ERROR_NONE);
|
||||
REQUIRE(audio_stream_open_input(device, &config, &input.handle) == ERROR_NONE);
|
||||
REQUIRE(audio_stream_open_output(device, &config, &output.handle) == ERROR_NONE);
|
||||
std::vector<int16_t> samples(960, -1);
|
||||
size_t count = 0;
|
||||
REQUIRE(audio_stream_read(input.handle, samples.data(), samples.size() * 2, &count, pdMS_TO_TICKS(1000)) == ERROR_NONE);
|
||||
CHECK(count == samples.size() * 2);
|
||||
// Fixture contains 10000; microphone gain is 50%.
|
||||
CHECK(std::all_of(samples.begin(), samples.end(), [](int16_t sample) { return sample == 5000; }));
|
||||
REQUIRE(audio_stream_write(output.handle, samples.data(), samples.size() * 2, &count, pdMS_TO_TICKS(1000)) == ERROR_NONE);
|
||||
REQUIRE(audio_stream_close(output.handle) == ERROR_NONE);
|
||||
output.handle = nullptr;
|
||||
{
|
||||
std::ifstream file(std::getenv("SDL_DISKAUDIOFILE"), std::ios::binary);
|
||||
REQUIRE(file.good());
|
||||
size_t nonzero = 0;
|
||||
int16_t sample;
|
||||
while (file.read(reinterpret_cast<char*>(&sample), sizeof(sample))) {
|
||||
CHECK((sample == 0 || sample == 1250)); // 25% output volume
|
||||
if (sample != 0) nonzero++;
|
||||
}
|
||||
CHECK(nonzero == samples.size() * 2); // mono was duplicated to stereo
|
||||
}
|
||||
REQUIRE(audio_stream_set_mute(device, AUDIO_CODEC_DIR_INPUT, true) == ERROR_NONE);
|
||||
REQUIRE(audio_stream_read(input.handle, samples.data(), samples.size() * 2, &count, pdMS_TO_TICKS(1000)) == ERROR_NONE);
|
||||
CHECK(std::all_of(samples.begin(), samples.end(), [](int16_t sample) { return sample == 0; }));
|
||||
REQUIRE(audio_stream_set_mute(device, AUDIO_CODEC_DIR_OUTPUT, true) == ERROR_NONE);
|
||||
REQUIRE(audio_stream_open_output(device, &config, &output.handle) == ERROR_NONE);
|
||||
std::fill(samples.begin(), samples.end(), 5000);
|
||||
REQUIRE(audio_stream_write(output.handle, samples.data(), samples.size() * 2, &count, pdMS_TO_TICKS(1000)) == ERROR_NONE);
|
||||
REQUIRE(audio_stream_close(output.handle) == ERROR_NONE);
|
||||
output.handle = nullptr;
|
||||
std::ifstream file(std::getenv("SDL_DISKAUDIOFILE"), std::ios::binary);
|
||||
REQUIRE(file.good());
|
||||
size_t total = 0;
|
||||
int16_t sample;
|
||||
while (file.read(reinterpret_cast<char*>(&sample), sizeof(sample))) {
|
||||
CHECK(sample == 0);
|
||||
total++;
|
||||
}
|
||||
CHECK(total >= samples.size() * 2);
|
||||
}
|
||||
|
||||
struct TestContext { int argc; char** argv; int result = 1; };
|
||||
|
||||
static void run_tests(void* argument) {
|
||||
auto* data = static_cast<TestContext*>(argument);
|
||||
Module* modules[] = { &platform_posix_module, &simulator_module, &audio_stream_module, nullptr };
|
||||
DtsDevice devices[] = { DTS_DEVICE_TERMINATOR };
|
||||
if (kernel_init(modules, devices) == ERROR_NONE
|
||||
&& device_construct_add_start(&speaker, "tactility,sdl-audio") == ERROR_NONE
|
||||
&& device_construct_add_start(µphone, "tactility,sdl-audio") == ERROR_NONE) {
|
||||
doctest::Context context(data->argc, data->argv);
|
||||
context.setOption("no-breaks", true);
|
||||
data->result = context.run();
|
||||
device_stop(µphone);
|
||||
device_stop(&speaker);
|
||||
}
|
||||
vTaskEndScheduler();
|
||||
vTaskDelete(nullptr);
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (std::getenv("SDL_AUDIODRIVER") == nullptr) SDL_setenv("SDL_AUDIODRIVER", "dummy", 1);
|
||||
char input_path[] = "sim-audio-input-XXXXXX";
|
||||
char output_path[] = "sim-audio-output-XXXXXX";
|
||||
const bool disk = std::strcmp(std::getenv("SDL_AUDIODRIVER"), "disk") == 0;
|
||||
if (disk) {
|
||||
const int input_fd = mkstemp(input_path);
|
||||
const int output_fd = mkstemp(output_path);
|
||||
if (input_fd < 0 || output_fd < 0) return 1;
|
||||
FILE* file = fdopen(input_fd, "wb");
|
||||
if (file == nullptr) return 1;
|
||||
const std::vector<int16_t> fixture(48000, 10000);
|
||||
const size_t written = std::fwrite(fixture.data(), sizeof(int16_t), fixture.size(), file);
|
||||
std::fclose(file);
|
||||
::close(output_fd);
|
||||
if (written != fixture.size()) return 1;
|
||||
SDL_setenv("SDL_DISKAUDIOFILEIN", input_path, 1);
|
||||
SDL_setenv("SDL_DISKAUDIOFILE", output_path, 1);
|
||||
}
|
||||
TestContext data { argc, argv };
|
||||
if (xTaskCreate(run_tests, "audio-test", 32768, &data, 1, nullptr) != pdPASS) return 1;
|
||||
vTaskStartScheduler();
|
||||
if (disk) {
|
||||
std::remove(input_path);
|
||||
std::remove(output_path);
|
||||
}
|
||||
return data.result;
|
||||
}
|
||||
+3
-17
@@ -7,31 +7,22 @@
|
||||
|
||||
## Higher Priority
|
||||
|
||||
- Add tests for app stdin/stdout
|
||||
- CrashDiagnostics shouldn't show a QR when there's no callstack
|
||||
- Apps currently have a `Context` object with an `appInstanceId` in it, purely for being able to close the app.
|
||||
Change it so that the app has its own termination signal that it waits for in the loop, it should subscribe to the event group.
|
||||
- stopAppFromToolbar() in Tactility.cpp stops the top-most app. Change it so the toolbar knows for which app id it is created, so it can rely on that.
|
||||
- Warn if file operations are done from prohibited tasks (e.g. lvgl task)
|
||||
- Move USB host task stacks to SPIRAM when available: esp32_usbhost*.cpp
|
||||
- Get rid of WiFi service (Wifi.cpp/h) in Tactility.cpp
|
||||
- Make it more clear to end-users that an SD card is required to run Tactility
|
||||
- Make it possible to override stack size for an app via config file (loaded at boot), and make it possible to set preferred memory location (e.g. internal/external)
|
||||
- Add bold fonts for e-ink readability improvement
|
||||
- Httpd.cpp: warn if running on same CPU core (or task) as UI/LVGL/window manager.
|
||||
- Improve Setup: Show "Step done" screen
|
||||
- Improve Setup: Add keyboard/keypad navigation explanation
|
||||
- display.h API: get_backlight does not change ref counting, but it should
|
||||
- bluetooth: various getters for child devices do not change ref counting, but they should (e.g. bluetooth_hid_device_get_device())
|
||||
- Improve kernel_init.cpp (and other modules): create driver_ensure_added() and driver_ensure_destructed()
|
||||
- Drivers/audio-codec-module is not a module. Move it somewhere else. Or make it an actual module.
|
||||
- LilyGO T-Dongle S3: 1 button control, stop auto-launching web server
|
||||
- Core2: support power off via software
|
||||
- Create `#define` for empty module (for modules that fully rely on device.properties and don't define drivers or have start/stop logic)
|
||||
- Get rid of TactilityC in favour of TactilityKernel and kernel modules
|
||||
- Improve SPI kernel driver (implement read, write, transactions)
|
||||
- Add font design tokens such as "regular", "title" and "smaller". Perhaps via the LVGL kernel module.
|
||||
- Fix glitches when installing app via App Hub with 4.3" Waveshare
|
||||
- TCA9534 keyboards should use interrupts
|
||||
- External app loading: Check the version of Tactility and check ESP target hardware to check for compatibility
|
||||
Check during installation process, but also when starting (SD card might have old app install from before Tactility OS update)
|
||||
@@ -45,6 +36,7 @@
|
||||
|
||||
## Medium Priority
|
||||
|
||||
- lvgl-module's spinner relies on hard-coded spinner asset from Tactility main project.
|
||||
- esp_lvgl_port settings has a large stack size (~9kB) to fix stackoverflow when LVGL events (e.g. button click) do actions like file operations do actions like file operations. Can we reduce the callstack?
|
||||
- `struct Driver` has an `.owner`, but it's not always set. Either validate on Module construct that it matches, or otherwise set it during module start. The problem: NULL parent currently means that driver is not removable. This clashes with setting it dynamically. Consider some kind of flag to determine removability.
|
||||
- Consider moving certain drivers into separate modules: audio, bt, wifi, etc
|
||||
@@ -52,9 +44,9 @@
|
||||
- Consider implementing LVGL gridnav in apps https://lvgl.io/docs/open/9.3/details/auxiliary-modules/gridnav.html
|
||||
- Make USB host driver disabled by default, so it doesn't consume memory
|
||||
- TactilityTool: Make API compatibility table (and check for compatibility in the tool itself)
|
||||
- Improve EspLcdDisplay to contain all the standard configuration options, and implement a default init function. Add a configuration class.
|
||||
- Unify the way displays are dimmed. Some implementations turn off the display when it's fully dimmed. Make this a separate functionality.
|
||||
- Bug: Crash handling app cannot be exited with an EncoderDevice. (current work-around is to manually reset the device)
|
||||
- Refactor HttpServer into C code and move implementation to http-module
|
||||
- Use GPS time to set/update the current time
|
||||
|
||||
## Lower Priority
|
||||
|
||||
@@ -62,20 +54,14 @@
|
||||
- lvgl-module has a keyboard.cpp that creates a `keyboard_group`. This group is set as the default group, so it can also work with trackball(= LVGL "encoder").
|
||||
Make a separate group that is the default group. The keyboard can then use it (or use its own).
|
||||
The basic idea is to invert the ownership: now the keyboard group is made the default group, but it's probably more logical to have the default group used by the keyboard.
|
||||
- lvgl-module's spinner relies on hard-coded spinner asset from Tactility main project.
|
||||
- Localize all apps
|
||||
- Support hot-plugging SD card (note: this is not possible if they require the CS pin hack)
|
||||
- Explore LVGL9's FreeRTOS functionality
|
||||
- CrashHandler: use "corrupted" flag
|
||||
- CrashHandler: process other types of crashes (WDT?)
|
||||
- Use GPS time to set/update the current time
|
||||
- Consider using non_null (either via MS GSL, or custom)
|
||||
- Fix system time to not be 1980 (use build year as a minimum). Consider keeping track of the last known time.
|
||||
- Use std::span or string_view in StringUtils https://youtu.be/FRkJCvHWdwQ?t=2754
|
||||
- Mutex: Implement give/take from ISR support (works only for non-recursive ones)
|
||||
- Show a warning screen if firmware encryption or secure boot are off when saving WiFi credentials.
|
||||
- Remove flex_flow from app_container in Gui.cpp
|
||||
- Bug: CYD 2432S032C screen rotation fails due to touch driver issue
|
||||
- Calculator app should show regular text input field on non-touch devices that have a keyboard (Cardputer, T-Lora Pager)
|
||||
- Allow for WSAD keys to navigate LVGL (this is extra nice for cardputer, but just handy in general)
|
||||
- Create a "How to" app for a device. It could explain things like keyboard navigation on first start.
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
# Simulator audio
|
||||
|
||||
The desktop simulator exposes an SDL speaker and microphone through Tactility's
|
||||
standard `audio_stream_*` API. On macOS, SDL uses CoreAudio. Audio Settings controls
|
||||
the simulator's input/output volume, mute, and enabled state; these controls do not
|
||||
change macOS's system volume.
|
||||
|
||||
## Running on macOS
|
||||
|
||||
Build the simulator in the usual host build environment (with `python`, `lark`,
|
||||
and `pyyaml` available, and without `ESP_IDF_VERSION`):
|
||||
|
||||
```sh
|
||||
cmake -S . -B buildsim
|
||||
cmake --build buildsim --target Tactility -j 8
|
||||
```
|
||||
|
||||
Create a fresh application bundle (the script deliberately refuses to overwrite
|
||||
an existing bundle):
|
||||
|
||||
```sh
|
||||
sh Buildscripts/release-simulator-macos-app.sh buildsim release/Tactility-audio.app
|
||||
open release/Tactility-audio.app
|
||||
```
|
||||
|
||||
Alternatively, run `../buildsim/Tactility/Tactility` with `Data/` as the working
|
||||
directory. Both the executable and the application bundle include a microphone
|
||||
usage description. macOS asks for microphone access on the first actual recording
|
||||
request, not at simulator startup. If denied, enable access in **System Settings
|
||||
→ Privacy & Security → Microphone** and relaunch. For command-line launches, macOS
|
||||
may attribute the permission to the terminal or launching application.
|
||||
|
||||
A Mac mini needs an external input device, such as a USB mic or headset. Without
|
||||
an input device, speaker output still works and input is reported unavailable.
|
||||
Connect the input before launch for predictable discovery/UI behavior.
|
||||
|
||||
## Selecting devices
|
||||
|
||||
By default, each stream opens the system's default device. Startup logs list SDL's
|
||||
device names. Optional environment variables select an exact name:
|
||||
|
||||
```sh
|
||||
SIM_AUDIO_OUTPUT="Mac mini Speakers" SIM_AUDIO_INPUT="USB Microphone" \
|
||||
release/Tactility-audio.app/Contents/MacOS/Tactility
|
||||
```
|
||||
|
||||
- `SIM_AUDIO_OUTPUT`: exact output name, or `none` to disable output.
|
||||
- `SIM_AUDIO_INPUT`: exact input name, or `none` to disable input.
|
||||
- Unset or empty values use the system default.
|
||||
|
||||
Selection is applied when opening a stream. An already-open stream does not
|
||||
automatically switch when the system default changes; close/reopen it or relaunch.
|
||||
A missing selected device causes an open failure rather than silently selecting a
|
||||
different device. Permission/device errors are logged under `SdlAudio`.
|
||||
|
||||
## Formats and behavior
|
||||
|
||||
- Signed 16-bit PCM; the shared stream module converts app sample rates and channel
|
||||
counts to 48 kHz mono capture / stereo playback. SDL handles host format conversion.
|
||||
- One input and one output stream can be open simultaneously.
|
||||
- Read/write from a worker task, never the LVGL thread.
|
||||
- Audio callbacks use bounded lock-free buffers, with silence on playback underrun
|
||||
and dropped incoming frames on capture overflow.
|
||||
- Reads/writes report partial byte counts on timeout, including converted streams.
|
||||
- Closing output drains its bounded buffer for up to 250 ms. Closing input does not
|
||||
affect output, and vice versa.
|
||||
- No audio mixing or acoustic echo cancellation is added by this backend. Use
|
||||
headphones when testing simultaneous microphone capture and playback.
|
||||
|
||||
## Verification
|
||||
|
||||
```sh
|
||||
cmake --build buildsim --target SimulatorAudioTests -j 8
|
||||
ctest --test-dir buildsim/Tests -R SimulatorAudio --output-on-failure
|
||||
```
|
||||
|
||||
These tests use SDL's dummy and disk backends without requiring microphone access.
|
||||
They cover full duplex, 16/44.1/48 kHz app formats, bounded buffering, partial
|
||||
timeouts, enable/disable, unavailable inputs, and sample-level input/output gain
|
||||
and mute. They also cover disabling audio while a slow codec open is pending,
|
||||
as can happen during a microphone permission prompt. Disk fixtures and output
|
||||
files are temporary and removed after the run.
|
||||
|
||||
To explicitly play a quiet half-second 440 Hz tone through real Mac audio:
|
||||
|
||||
```sh
|
||||
SDL_AUDIODRIVER=coreaudio SIM_AUDIO_OUTPUT= \
|
||||
buildsim/Tests/simulator/SimulatorAudioTests \
|
||||
--no-skip --test-case="hardware output smoke test"
|
||||
```
|
||||
|
||||
Physical microphone capture, the first-use permission prompt, and live device
|
||||
unplugging require a separate manual check with an input device attached.
|
||||
@@ -113,6 +113,10 @@ struct AudioStreamHandleImpl : AudioStreamHandleData {
|
||||
SemaphoreHandle_t drain_semaphore = nullptr;
|
||||
};
|
||||
|
||||
// A slow codec open (notably the macOS microphone permission prompt) reserves a
|
||||
// direction before a real handle exists. It must never be passed to close_stream().
|
||||
AudioStreamHandleImpl* const OPENING_STREAM = reinterpret_cast<AudioStreamHandleImpl*>(1);
|
||||
|
||||
struct AudioStreamData {
|
||||
Device* input_codec = nullptr;
|
||||
Device* output_codec = nullptr;
|
||||
@@ -130,6 +134,8 @@ struct AudioStreamData {
|
||||
bool output_muted = false;
|
||||
AudioStreamHandleImpl* open_input = nullptr;
|
||||
AudioStreamHandleImpl* open_output = nullptr;
|
||||
bool input_open_cancelled = false;
|
||||
bool output_open_cancelled = false;
|
||||
// Guards open_input/open_output and the closing/busy_count fields of any handle reachable
|
||||
// through them, so close (possibly forced by set_enabled) can't race with read/write.
|
||||
SemaphoreHandle_t mutex = nullptr;
|
||||
@@ -261,7 +267,7 @@ error_t open_stream(Device* device, const struct AudioStreamConfig* config, Audi
|
||||
return ERROR_INVALID_ARGUMENT;
|
||||
}
|
||||
|
||||
if (config->channels == 0) {
|
||||
if (config->channels == 0 || config->sample_rate == 0) {
|
||||
return ERROR_INVALID_ARGUMENT;
|
||||
}
|
||||
|
||||
@@ -291,7 +297,9 @@ error_t open_stream(Device* device, const struct AudioStreamConfig* config, Audi
|
||||
|
||||
// Reserve the slot with a placeholder so concurrent opens can't race past the check
|
||||
// above while we do the (potentially slow) codec open below outside the lock.
|
||||
auto* reservation = reinterpret_cast<AudioStreamHandleImpl*>(1);
|
||||
auto* reservation = OPENING_STREAM;
|
||||
bool* open_cancelled = is_input ? &data->input_open_cancelled : &data->output_open_cancelled;
|
||||
*open_cancelled = false;
|
||||
*slot = reservation;
|
||||
xSemaphoreGive(data->mutex);
|
||||
|
||||
@@ -361,6 +369,18 @@ error_t open_stream(Device* device, const struct AudioStreamConfig* config, Audi
|
||||
}
|
||||
|
||||
xSemaphoreTake(data->mutex, portMAX_DELAY);
|
||||
if (*open_cancelled) {
|
||||
// Keep the reservation until the codec is closed, so re-enabling cannot
|
||||
// open a second stream while this cancelled open is still cleaning up.
|
||||
xSemaphoreGive(data->mutex);
|
||||
vSemaphoreDelete(handle->drain_semaphore);
|
||||
delete handle;
|
||||
audio_codec_close(codec);
|
||||
xSemaphoreTake(data->mutex, portMAX_DELAY);
|
||||
*slot = nullptr;
|
||||
xSemaphoreGive(data->mutex);
|
||||
return ERROR_NOT_ALLOWED;
|
||||
}
|
||||
*slot = handle;
|
||||
xSemaphoreGive(data->mutex);
|
||||
|
||||
@@ -377,6 +397,7 @@ error_t open_output(Device* device, const struct AudioStreamConfig* config, Audi
|
||||
}
|
||||
|
||||
error_t read_stream(AudioStreamHandle handle_base, void* out_data, size_t data_size, size_t* bytes_read, TickType_t timeout) {
|
||||
if (bytes_read != nullptr) *bytes_read = 0;
|
||||
auto* handle = static_cast<AudioStreamHandleImpl*>(handle_base);
|
||||
if (handle->direction != AUDIO_CODEC_DIR_INPUT || handle->bytes_per_frame == 0) {
|
||||
return ERROR_INVALID_STATE;
|
||||
@@ -419,7 +440,7 @@ error_t read_stream(AudioStreamHandle handle_base, void* out_data, size_t data_s
|
||||
|
||||
size_t codec_bytes_read = 0;
|
||||
result = audio_codec_read(data->input_codec, handle->codec_buffer.data(), codec_bytes_needed, &codec_bytes_read, timeout);
|
||||
if (result == ERROR_NONE) {
|
||||
if (codec_bytes_read > 0) {
|
||||
size_t codec_frames_read = codec_bytes_read / handle->codec_bytes_per_frame;
|
||||
const int16_t* rate_input = reinterpret_cast<const int16_t*>(handle->codec_buffer.data());
|
||||
uint8_t rate_input_channels = handle->codec_channels;
|
||||
@@ -448,7 +469,7 @@ error_t read_stream(AudioStreamHandle handle_base, void* out_data, size_t data_s
|
||||
}
|
||||
}
|
||||
|
||||
if (result == ERROR_NONE && handle->input_gain != 1.0f && bytes_read != nullptr && *bytes_read > 0) {
|
||||
if (handle->input_gain != 1.0f && bytes_read != nullptr && *bytes_read > 0) {
|
||||
auto* samples = reinterpret_cast<int16_t*>(out_data);
|
||||
size_t sample_count = *bytes_read / sizeof(int16_t);
|
||||
for (size_t i = 0; i < sample_count; i++) {
|
||||
@@ -462,6 +483,7 @@ error_t read_stream(AudioStreamHandle handle_base, void* out_data, size_t data_s
|
||||
}
|
||||
|
||||
error_t write_stream(AudioStreamHandle handle_base, const void* in_data, size_t data_size, size_t* bytes_written, TickType_t timeout) {
|
||||
if (bytes_written != nullptr) *bytes_written = 0;
|
||||
auto* handle = static_cast<AudioStreamHandleImpl*>(handle_base);
|
||||
if (handle->direction != AUDIO_CODEC_DIR_OUTPUT || handle->bytes_per_frame == 0) {
|
||||
return ERROR_INVALID_STATE;
|
||||
@@ -532,9 +554,13 @@ error_t write_stream(AudioStreamHandle handle_base, const void* in_data, size_t
|
||||
size_t codec_bytes_to_write = codec_frames * handle->codec_bytes_per_frame;
|
||||
size_t codec_bytes_written = 0;
|
||||
result = audio_codec_write(data->output_codec, handle->codec_buffer.data(), codec_bytes_to_write, &codec_bytes_written, timeout);
|
||||
if (result == ERROR_NONE && bytes_written != nullptr) {
|
||||
// The caller provided `data_size` worth of input; we consumed all of it (resampled/converted).
|
||||
*bytes_written = data_size;
|
||||
if (bytes_written != nullptr && codec_frames > 0) {
|
||||
// A bounded host/hardware queue can accept only part of a converted write,
|
||||
// including when returning ERROR_TIMEOUT. Report progress in app-side whole
|
||||
// frames rather than leaving the count untouched or claiming the entire write.
|
||||
size_t written_frames = codec_bytes_written / handle->codec_bytes_per_frame;
|
||||
if (written_frames > codec_frames) written_frames = codec_frames;
|
||||
*bytes_written = (in_frames * written_frames / codec_frames) * handle->bytes_per_frame;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -686,13 +712,17 @@ error_t set_enabled(Device* device, AudioCodecDirection direction, bool enabled)
|
||||
data->output_enabled = enabled;
|
||||
}
|
||||
|
||||
// Capture and clear the slot under the lock so we hand close_stream() a pointer that
|
||||
// can't simultaneously be torn down by a racing close from the owning app (close_stream
|
||||
// re-checks `*slot == handle` and no-ops if it's already been cleared/replaced).
|
||||
// A pending open has no handle to close yet. Let its owning task clean up when
|
||||
// the codec returns, even if the user re-enables the direction in the meantime.
|
||||
AudioStreamHandleImpl* to_close = nullptr;
|
||||
if (!enabled) {
|
||||
AudioStreamHandleImpl** slot = is_input ? &data->open_input : &data->open_output;
|
||||
to_close = *slot;
|
||||
if (*slot == OPENING_STREAM) {
|
||||
if (is_input) data->input_open_cancelled = true;
|
||||
else data->output_open_cancelled = true;
|
||||
} else {
|
||||
to_close = *slot;
|
||||
}
|
||||
}
|
||||
xSemaphoreGive(data->mutex);
|
||||
|
||||
|
||||
@@ -9,3 +9,7 @@ properties:
|
||||
type: phandle
|
||||
required: true
|
||||
description: "I2S controller device that carries audio data"
|
||||
input-gain-percent:
|
||||
type: int
|
||||
default: 100
|
||||
description: "Extra digital gain multiplier applied by audio_stream on top of the ES8311's own 42dB hardware ADC gain, as an integer percentage (100 = 1.0x / no extra boost). For quiet MEMS mic capsules that are still quiet even at max hardware gain."
|
||||
|
||||
@@ -25,6 +25,14 @@ struct Es8311Config {
|
||||
uint8_t address;
|
||||
/** I2S controller device that carries audio data */
|
||||
struct Device* i2s_device;
|
||||
/**
|
||||
* Extra fixed digital gain multiplier applied by audio_stream on top of the ES8311's
|
||||
* own hardware ADC gain (0..42dB), as an integer percentage (100 = 1.0x / no extra boost).
|
||||
* Small MEMS mic capsules can still sound quiet even near max hardware gain; this is for
|
||||
* boards where 42dB hardware gain alone isn't enough. devicetree has no float property type,
|
||||
* hence the x100 integer encoding.
|
||||
*/
|
||||
uint16_t input_gain_percent;
|
||||
};
|
||||
|
||||
#ifdef __cplusplus
|
||||
|
||||
@@ -31,6 +31,7 @@ struct Es8311Data {
|
||||
bool is_open = false;
|
||||
AudioCodecDirection open_direction = AUDIO_CODEC_DIR_BOTH;
|
||||
esp_codec_dev_sample_info_t open_sample_info = {};
|
||||
float input_gain = 1.0f;
|
||||
};
|
||||
|
||||
#define GET_CONFIG(device) (static_cast<const Es8311Config*>((device)->config))
|
||||
@@ -144,8 +145,8 @@ error_t set_volume(Device* device, AudioCodecDirection direction, float volume_p
|
||||
}
|
||||
|
||||
if (direction == AUDIO_CODEC_DIR_INPUT) {
|
||||
// ES8311 ADC gain range is roughly 0..24 dB; map 0..100% linearly onto it.
|
||||
float db = (volume_percent / 100.0f) * 24.0f;
|
||||
// ES8311 ADC gain supports 0..42dB (0,6,12,18,24,30,36,42) in 6dB steps
|
||||
float db = (volume_percent / 100.0f) * 42.0f;
|
||||
return (esp_codec_dev_set_in_gain(data->codec_device, db) == ESP_CODEC_DEV_OK) ? ERROR_NONE : ERROR_RESOURCE;
|
||||
}
|
||||
|
||||
@@ -172,7 +173,8 @@ error_t get_volume(Device* device, AudioCodecDirection direction, float* volume_
|
||||
if (esp_codec_dev_get_in_gain(data->codec_device, &db) != ESP_CODEC_DEV_OK) {
|
||||
return ERROR_RESOURCE;
|
||||
}
|
||||
*volume_percent = (db / 24.0f) * 100.0f;
|
||||
*volume_percent = (db / 42.0f) * 100.0f;
|
||||
if (*volume_percent > 100.0f) *volume_percent = 100.0f;
|
||||
return ERROR_NONE;
|
||||
}
|
||||
|
||||
@@ -235,6 +237,12 @@ error_t get_capabilities(Device* device, AudioCodecDirection* supported_directio
|
||||
return ERROR_NONE;
|
||||
}
|
||||
|
||||
error_t get_input_gain_multiplier(Device* device, float* gain) {
|
||||
auto* data = GET_DATA(device);
|
||||
*gain = data->input_gain;
|
||||
return ERROR_NONE;
|
||||
}
|
||||
|
||||
static const struct AudioCodecApi API = {
|
||||
.open = open,
|
||||
.close = close,
|
||||
@@ -247,7 +255,7 @@ static const struct AudioCodecApi API = {
|
||||
.get_native_sample_rate = get_native_sample_rate,
|
||||
.get_native_channels = get_native_channels,
|
||||
.get_capabilities = get_capabilities,
|
||||
.get_input_gain_multiplier = nullptr,
|
||||
.get_input_gain_multiplier = get_input_gain_multiplier,
|
||||
};
|
||||
|
||||
// endregion
|
||||
@@ -257,6 +265,11 @@ static const struct AudioCodecApi API = {
|
||||
error_t start_device(Device* device) {
|
||||
const auto* config = GET_CONFIG(device);
|
||||
|
||||
if (config->input_gain_percent > 2000) {
|
||||
LOG_E(TAG, "Invalid input_gain_percent %u (must be 0..2000)", config->input_gain_percent);
|
||||
return ERROR_RESOURCE;
|
||||
}
|
||||
|
||||
auto* i2c_controller = device_get_parent(device);
|
||||
if (i2c_controller == nullptr || device_get_type(i2c_controller) != &I2C_CONTROLLER_TYPE) {
|
||||
LOG_E(TAG, "Parent is not an I2C controller");
|
||||
@@ -270,6 +283,8 @@ error_t start_device(Device* device) {
|
||||
}
|
||||
|
||||
auto* data = new Es8311Data();
|
||||
data->input_gain = (float) config->input_gain_percent / 100.0f;
|
||||
if (config->input_gain_percent == 0) data->input_gain = 1.0f; // 0 means unset
|
||||
|
||||
data->ctrl_if = audio_codec_adapter_new_i2c_ctrl(i2c_controller, config->address);
|
||||
data->data_if = audio_codec_adapter_new_i2s_data(i2s_controller);
|
||||
|
||||
@@ -27,11 +27,7 @@ static error_t start(Device* device) {
|
||||
auto* parent = device_get_parent(device);
|
||||
check(device_get_type(parent) == &I2C_CONTROLLER_TYPE);
|
||||
|
||||
auto address = GET_CONFIG(device)->address;
|
||||
if (i2c_controller_has_device_at_address(parent, address, I2C_TIMEOUT) != ERROR_NONE) {
|
||||
LOG_E(TAG, "No device found on I2C bus at address 0x%02X", address);
|
||||
return ERROR_RESOURCE;
|
||||
}
|
||||
// We don't check whether the device is present, because it doesn't respond reliably at boot
|
||||
|
||||
auto* internal = static_cast<TdeckKeyboardInternal*>(malloc(sizeof(TdeckKeyboardInternal)));
|
||||
if (internal == nullptr) {
|
||||
|
||||
@@ -28,11 +28,7 @@ static error_t start(Device* device) {
|
||||
auto* parent = device_get_parent(device);
|
||||
check(device_get_type(parent) == &I2C_CONTROLLER_TYPE);
|
||||
|
||||
auto address = GET_CONFIG(device)->address;
|
||||
if (i2c_controller_has_device_at_address(parent, address, I2C_TIMEOUT) != ERROR_NONE) {
|
||||
LOG_E(TAG, "No device found on I2C bus at address 0x%02X", address);
|
||||
return ERROR_RESOURCE;
|
||||
}
|
||||
// We don't check whether the device is present, because it doesn't respond reliably at boot
|
||||
|
||||
auto* internal = static_cast<TdeckKeyboardBacklightInternal*>(malloc(sizeof(TdeckKeyboardBacklightInternal)));
|
||||
if (internal == nullptr) {
|
||||
@@ -43,6 +39,8 @@ static error_t start(Device* device) {
|
||||
|
||||
auto brightness_default = GET_CONFIG(device)->brightness_default;
|
||||
|
||||
auto address = GET_CONFIG(device)->address;
|
||||
|
||||
// Configures the keyboard controller's own persisted default, used by its onboard ALT+B toggle.
|
||||
if (i2c_controller_write_register(parent, address, CMD_DEFAULT_BRIGHTNESS, &brightness_default, 1, I2C_TIMEOUT) != ERROR_NONE) {
|
||||
LOG_E(TAG, "Failed to set default brightness");
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
|
||||
include("${CMAKE_CURRENT_LIST_DIR}/../../Buildscripts/module.cmake")
|
||||
|
||||
file(GLOB_RECURSE SOURCE_FILES "source/*.c*")
|
||||
|
||||
tactility_add_module(st77922-module
|
||||
SRCS ${SOURCE_FILES}
|
||||
INCLUDE_DIRS include/
|
||||
REQUIRES TactilityKernel platform-esp32 esp_lcd_st77922 driver
|
||||
)
|
||||
@@ -0,0 +1,37 @@
|
||||
description: Touch interface integrated in the Sitronix ST77922 TDDI
|
||||
|
||||
include: ["i2c-device.yaml"]
|
||||
|
||||
compatible: "sitronix,st77922-touch"
|
||||
|
||||
bus: i2c
|
||||
|
||||
properties:
|
||||
x-max:
|
||||
type: int
|
||||
required: true
|
||||
description: Maximum X coordinate
|
||||
y-max:
|
||||
type: int
|
||||
required: true
|
||||
description: Maximum Y coordinate
|
||||
swap-xy:
|
||||
type: boolean
|
||||
default: false
|
||||
description: Swap the X and Y axes
|
||||
mirror-x:
|
||||
type: boolean
|
||||
default: false
|
||||
description: Mirror the X axis
|
||||
mirror-y:
|
||||
type: boolean
|
||||
default: false
|
||||
description: Mirror the Y axis
|
||||
pin-reset:
|
||||
type: phandles
|
||||
default: GPIO_PIN_SPEC_NONE
|
||||
description: Reset GPIO pin
|
||||
pin-interrupt:
|
||||
type: phandles
|
||||
default: GPIO_PIN_SPEC_NONE
|
||||
description: Interrupt GPIO pin
|
||||
@@ -0,0 +1,47 @@
|
||||
description: Sitronix ST77922 QSPI display panel
|
||||
|
||||
compatible: "sitronix,st77922"
|
||||
|
||||
bus: spi
|
||||
|
||||
properties:
|
||||
horizontal-resolution:
|
||||
type: int
|
||||
required: true
|
||||
description: Horizontal resolution in pixels
|
||||
vertical-resolution:
|
||||
type: int
|
||||
required: true
|
||||
description: Vertical resolution in pixels
|
||||
mirror-x:
|
||||
type: boolean
|
||||
default: false
|
||||
description: Mirror the X axis
|
||||
mirror-y:
|
||||
type: boolean
|
||||
default: false
|
||||
description: Mirror the Y axis
|
||||
invert-color:
|
||||
type: boolean
|
||||
default: false
|
||||
description: Invert the panel's color output
|
||||
bgr-order:
|
||||
type: boolean
|
||||
default: false
|
||||
description: Use BGR element order instead of RGB
|
||||
bits-per-pixel:
|
||||
type: int
|
||||
default: 16
|
||||
description: Color depth in bits per pixel
|
||||
pixel-clock-hz:
|
||||
type: int
|
||||
default: 80000000
|
||||
description: QSPI pixel clock frequency in Hz
|
||||
transaction-queue-depth:
|
||||
type: int
|
||||
default: 10
|
||||
description: Size of the internal SPI transaction queue
|
||||
backlight:
|
||||
type: phandle
|
||||
default: "NULL"
|
||||
description: Optional reference to this display's backlight device
|
||||
@@ -0,0 +1,3 @@
|
||||
dependencies:
|
||||
- TactilityKernel
|
||||
bindings: bindings
|
||||
@@ -0,0 +1,7 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
#pragma once
|
||||
|
||||
#include <tactility/bindings/bindings.h>
|
||||
#include <drivers/st77922.h>
|
||||
|
||||
DEFINE_DEVICETREE(st77922, struct St77922Config)
|
||||
@@ -0,0 +1,7 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
#pragma once
|
||||
|
||||
#include <tactility/bindings/bindings.h>
|
||||
#include <drivers/st77922_touch.h>
|
||||
|
||||
DEFINE_DEVICETREE(st77922_touch, struct St77922TouchConfig)
|
||||
@@ -0,0 +1,20 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
#pragma once
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#include <tactility/device.h>
|
||||
|
||||
struct St77922Config {
|
||||
uint16_t horizontal_resolution;
|
||||
uint16_t vertical_resolution;
|
||||
bool mirror_x;
|
||||
bool mirror_y;
|
||||
bool invert_color;
|
||||
bool bgr_order;
|
||||
uint32_t bits_per_pixel;
|
||||
uint32_t pixel_clock_hz;
|
||||
uint8_t transaction_queue_depth;
|
||||
struct Device* backlight;
|
||||
};
|
||||
@@ -0,0 +1,18 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
#pragma once
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#include <tactility/drivers/gpio.h>
|
||||
|
||||
struct St77922TouchConfig {
|
||||
uint8_t address;
|
||||
uint16_t x_max;
|
||||
uint16_t y_max;
|
||||
bool swap_xy;
|
||||
bool mirror_x;
|
||||
bool mirror_y;
|
||||
struct GpioPinSpec pin_reset;
|
||||
struct GpioPinSpec pin_interrupt;
|
||||
};
|
||||
@@ -0,0 +1,6 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
#pragma once
|
||||
|
||||
#include <tactility/module.h>
|
||||
|
||||
extern Module st77922_module;
|
||||
@@ -0,0 +1,21 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
#include <tactility/driver.h>
|
||||
#include <tactility/module.h>
|
||||
|
||||
extern "C" {
|
||||
|
||||
extern Driver st77922_driver;
|
||||
extern Driver st77922_touch_driver;
|
||||
|
||||
static Driver* const st77922_drivers[] = {
|
||||
&st77922_driver,
|
||||
&st77922_touch_driver,
|
||||
nullptr
|
||||
};
|
||||
|
||||
Module st77922_module = {
|
||||
.name = "st77922",
|
||||
.drivers = st77922_drivers
|
||||
};
|
||||
|
||||
} // extern "C"
|
||||
@@ -0,0 +1,270 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
#include <drivers/st77922.h>
|
||||
#include <st77922_module.h>
|
||||
#include "st77922_init.h"
|
||||
|
||||
#include <tactility/check.h>
|
||||
#include <tactility/device.h>
|
||||
#include <tactility/driver.h>
|
||||
#include <tactility/drivers/display.h>
|
||||
#include <tactility/drivers/esp32_spi.h>
|
||||
#include <tactility/drivers/spi_controller.h>
|
||||
#include <tactility/log.h>
|
||||
|
||||
#include <esp_err.h>
|
||||
#include <esp_heap_caps.h>
|
||||
#include <esp_lcd_io_spi.h>
|
||||
#include <esp_lcd_panel_io.h>
|
||||
#include <esp_lcd_panel_ops.h>
|
||||
#include <esp_lcd_st77922.h>
|
||||
#include <freertos/semphr.h>
|
||||
#include <cstdlib>
|
||||
|
||||
#define TAG "ST77922"
|
||||
#define GET_CONFIG(device) (static_cast<const St77922Config*>((device)->config))
|
||||
|
||||
struct St77922Internal {
|
||||
esp_lcd_panel_io_handle_t io_handle;
|
||||
esp_lcd_panel_handle_t panel_handle;
|
||||
SemaphoreHandle_t draw_done;
|
||||
uint8_t* transfer_buffer;
|
||||
size_t transfer_buffer_size;
|
||||
};
|
||||
|
||||
static bool IRAM_ATTR transfer_done(esp_lcd_panel_io_handle_t, esp_lcd_panel_io_event_data_t*, void* context) {
|
||||
auto* internal = static_cast<St77922Internal*>(context);
|
||||
BaseType_t task_woken = pdFALSE;
|
||||
xSemaphoreGiveFromISR(internal->draw_done, &task_woken);
|
||||
return task_woken == pdTRUE;
|
||||
}
|
||||
|
||||
static error_t start(Device* device) {
|
||||
auto* parent = device_get_parent(device);
|
||||
check(device_get_type(parent) == &SPI_CONTROLLER_TYPE);
|
||||
const auto* spi = static_cast<const Esp32SpiConfig*>(parent->config);
|
||||
const auto* config = GET_CONFIG(device);
|
||||
|
||||
GpioPinSpec cs;
|
||||
if (esp32_spi_get_cs_pin(device, &cs) != ERROR_NONE) {
|
||||
return ERROR_RESOURCE;
|
||||
}
|
||||
|
||||
auto* internal = static_cast<St77922Internal*>(calloc(1, sizeof(St77922Internal)));
|
||||
if (internal == nullptr) {
|
||||
return ERROR_OUT_OF_MEMORY;
|
||||
}
|
||||
internal->draw_done = xSemaphoreCreateBinary();
|
||||
if (internal->draw_done == nullptr) {
|
||||
free(internal);
|
||||
return ERROR_OUT_OF_MEMORY;
|
||||
}
|
||||
// The vendor port renders a complete frame in PSRAM, then copies it through a
|
||||
// 1/10-frame DMA buffer. Besides making full-frame refresh possible, this keeps
|
||||
// the panel's GRAM synchronized when animated objects invalidate old and new
|
||||
// positions in separate LVGL regions.
|
||||
const size_t bytes_per_pixel = config->bits_per_pixel / 8;
|
||||
const size_t rows_per_transfer = config->vertical_resolution > 10
|
||||
? config->vertical_resolution / 10 : config->vertical_resolution;
|
||||
internal->transfer_buffer_size =
|
||||
static_cast<size_t>(config->horizontal_resolution) * rows_per_transfer * bytes_per_pixel;
|
||||
if (spi->max_transfer_size > 0
|
||||
&& internal->transfer_buffer_size > static_cast<size_t>(spi->max_transfer_size)) {
|
||||
internal->transfer_buffer_size = static_cast<size_t>(spi->max_transfer_size);
|
||||
}
|
||||
internal->transfer_buffer = static_cast<uint8_t*>(heap_caps_malloc(
|
||||
internal->transfer_buffer_size, MALLOC_CAP_DMA | MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
|
||||
if (internal->transfer_buffer == nullptr) {
|
||||
vSemaphoreDelete(internal->draw_done);
|
||||
free(internal);
|
||||
return ERROR_OUT_OF_MEMORY;
|
||||
}
|
||||
|
||||
esp_lcd_panel_io_spi_config_t io_config = {
|
||||
.cs_gpio_num = static_cast<int>(cs.pin),
|
||||
.dc_gpio_num = -1,
|
||||
.spi_mode = 0,
|
||||
.pclk_hz = config->pixel_clock_hz,
|
||||
.trans_queue_depth = config->transaction_queue_depth,
|
||||
.on_color_trans_done = transfer_done,
|
||||
.user_ctx = internal,
|
||||
.lcd_cmd_bits = 32,
|
||||
.lcd_param_bits = 8,
|
||||
.cs_ena_pretrans = 0,
|
||||
.cs_ena_posttrans = 0,
|
||||
.flags = {
|
||||
.dc_high_on_cmd = 0,
|
||||
.dc_low_on_data = 0,
|
||||
.dc_low_on_param = 0,
|
||||
.octal_mode = 0,
|
||||
.quad_mode = 1,
|
||||
.sio_mode = 0,
|
||||
.lsb_first = 0,
|
||||
.cs_high_active = 0,
|
||||
},
|
||||
};
|
||||
|
||||
esp_err_t result = esp_lcd_new_panel_io_spi(
|
||||
static_cast<esp_lcd_spi_bus_handle_t>(spi->host), &io_config, &internal->io_handle);
|
||||
if (result != ESP_OK) {
|
||||
LOG_E(TAG, "Failed to create panel IO: %s", esp_err_to_name(result));
|
||||
heap_caps_free(internal->transfer_buffer);
|
||||
vSemaphoreDelete(internal->draw_done);
|
||||
free(internal);
|
||||
return ERROR_RESOURCE;
|
||||
}
|
||||
|
||||
size_t init_count = 0;
|
||||
st77922_vendor_config_t vendor = {
|
||||
.init_cmds = st77922_board_init_commands(&init_count),
|
||||
.init_cmds_size = static_cast<uint16_t>(init_count),
|
||||
.flags = { .use_qspi_interface = 1 },
|
||||
};
|
||||
esp_lcd_panel_dev_config_t panel_config = {
|
||||
.reset_gpio_num = -1,
|
||||
.rgb_ele_order = config->bgr_order ? LCD_RGB_ELEMENT_ORDER_BGR : LCD_RGB_ELEMENT_ORDER_RGB,
|
||||
.data_endian = LCD_RGB_DATA_ENDIAN_LITTLE,
|
||||
.bits_per_pixel = config->bits_per_pixel,
|
||||
.flags = { .reset_active_high = false },
|
||||
.vendor_config = &vendor,
|
||||
};
|
||||
result = esp_lcd_new_panel_st77922(internal->io_handle, &panel_config, &internal->panel_handle);
|
||||
bool ok = result == ESP_OK;
|
||||
ok = ok && esp_lcd_panel_reset(internal->panel_handle) == ESP_OK;
|
||||
ok = ok && esp_lcd_panel_init(internal->panel_handle) == ESP_OK;
|
||||
ok = ok && ((!config->mirror_x && !config->mirror_y)
|
||||
|| esp_lcd_panel_mirror(internal->panel_handle, config->mirror_x, config->mirror_y) == ESP_OK);
|
||||
ok = ok && (!config->invert_color || esp_lcd_panel_invert_color(internal->panel_handle, true) == ESP_OK);
|
||||
ok = ok && esp_lcd_panel_disp_on_off(internal->panel_handle, true) == ESP_OK;
|
||||
if (!ok) {
|
||||
LOG_E(TAG, "Failed to bring up panel: %s", esp_err_to_name(result));
|
||||
if (internal->panel_handle != nullptr) esp_lcd_panel_del(internal->panel_handle);
|
||||
esp_lcd_panel_io_del(internal->io_handle);
|
||||
heap_caps_free(internal->transfer_buffer);
|
||||
vSemaphoreDelete(internal->draw_done);
|
||||
free(internal);
|
||||
return ERROR_RESOURCE;
|
||||
}
|
||||
device_set_driver_data(device, internal);
|
||||
return ERROR_NONE;
|
||||
}
|
||||
|
||||
static error_t stop(Device* device) {
|
||||
auto* internal = static_cast<St77922Internal*>(device_get_driver_data(device));
|
||||
if (esp_lcd_panel_del(internal->panel_handle) != ESP_OK
|
||||
|| esp_lcd_panel_io_del(internal->io_handle) != ESP_OK) {
|
||||
return ERROR_RESOURCE;
|
||||
}
|
||||
heap_caps_free(internal->transfer_buffer);
|
||||
vSemaphoreDelete(internal->draw_done);
|
||||
free(internal);
|
||||
device_set_driver_data(device, nullptr);
|
||||
return ERROR_NONE;
|
||||
}
|
||||
|
||||
static error_t reset(Device* device) {
|
||||
auto* data = static_cast<St77922Internal*>(device_get_driver_data(device));
|
||||
return esp_lcd_panel_reset(data->panel_handle) == ESP_OK ? ERROR_NONE : ERROR_RESOURCE;
|
||||
}
|
||||
static error_t init(Device* device) {
|
||||
auto* data = static_cast<St77922Internal*>(device_get_driver_data(device));
|
||||
return esp_lcd_panel_init(data->panel_handle) == ESP_OK ? ERROR_NONE : ERROR_RESOURCE;
|
||||
}
|
||||
static error_t draw_bitmap(Device* device, int32_t xs, int32_t ys, int32_t xe, int32_t ye, const void* pixels) {
|
||||
auto* data = static_cast<St77922Internal*>(device_get_driver_data(device));
|
||||
const auto* config = GET_CONFIG(device);
|
||||
const size_t row_bytes = static_cast<size_t>(xe - xs) * config->bits_per_pixel / 8;
|
||||
if (row_bytes == 0 || row_bytes > data->transfer_buffer_size) {
|
||||
return ERROR_OUT_OF_RANGE;
|
||||
}
|
||||
|
||||
const size_t rows_per_transfer = data->transfer_buffer_size / row_bytes;
|
||||
const auto* source = static_cast<const uint8_t*>(pixels);
|
||||
int32_t chunk_y = ys;
|
||||
while (chunk_y < ye) {
|
||||
const size_t remaining_rows = static_cast<size_t>(ye - chunk_y);
|
||||
const size_t chunk_rows = remaining_rows < rows_per_transfer ? remaining_rows : rows_per_transfer;
|
||||
const size_t chunk_bytes = chunk_rows * row_bytes;
|
||||
memcpy(data->transfer_buffer, source, chunk_bytes);
|
||||
|
||||
xSemaphoreTake(data->draw_done, 0);
|
||||
if (esp_lcd_panel_draw_bitmap(
|
||||
data->panel_handle, xs, chunk_y, xe, chunk_y + static_cast<int32_t>(chunk_rows),
|
||||
data->transfer_buffer) != ESP_OK) {
|
||||
LOG_E(TAG, "Failed to queue color transfer at y=%ld", static_cast<long>(chunk_y));
|
||||
return ERROR_RESOURCE;
|
||||
}
|
||||
if (xSemaphoreTake(data->draw_done, pdMS_TO_TICKS(1000)) != pdTRUE) {
|
||||
LOG_E(TAG, "Timed out waiting for color transfer at y=%ld", static_cast<long>(chunk_y));
|
||||
return ERROR_TIMEOUT;
|
||||
}
|
||||
|
||||
source += chunk_bytes;
|
||||
chunk_y += static_cast<int32_t>(chunk_rows);
|
||||
}
|
||||
return ERROR_NONE;
|
||||
}
|
||||
static error_t mirror(Device* device, bool x, bool y) {
|
||||
auto* data = static_cast<St77922Internal*>(device_get_driver_data(device));
|
||||
return esp_lcd_panel_mirror(data->panel_handle, x, y) == ESP_OK ? ERROR_NONE : ERROR_RESOURCE;
|
||||
}
|
||||
static bool get_mirror_x(Device* device) { return GET_CONFIG(device)->mirror_x; }
|
||||
static bool get_mirror_y(Device* device) { return GET_CONFIG(device)->mirror_y; }
|
||||
static error_t invert(Device* device, bool value) {
|
||||
auto* data = static_cast<St77922Internal*>(device_get_driver_data(device));
|
||||
return esp_lcd_panel_invert_color(data->panel_handle, value) == ESP_OK ? ERROR_NONE : ERROR_RESOURCE;
|
||||
}
|
||||
static error_t on_off(Device* device, bool value) {
|
||||
auto* data = static_cast<St77922Internal*>(device_get_driver_data(device));
|
||||
return esp_lcd_panel_disp_on_off(data->panel_handle, value) == ESP_OK ? ERROR_NONE : ERROR_RESOURCE;
|
||||
}
|
||||
static error_t sleep(Device* device, bool value) {
|
||||
auto* data = static_cast<St77922Internal*>(device_get_driver_data(device));
|
||||
return esp_lcd_panel_disp_sleep(data->panel_handle, value) == ESP_OK ? ERROR_NONE : ERROR_RESOURCE;
|
||||
}
|
||||
static DisplayColorFormat color_format(Device*) { return DISPLAY_COLOR_FORMAT_RGB565_SWAPPED; }
|
||||
static uint16_t resolution_x(Device* device) { return GET_CONFIG(device)->horizontal_resolution; }
|
||||
static uint16_t resolution_y(Device* device) { return GET_CONFIG(device)->vertical_resolution; }
|
||||
static void frame_buffer(Device*, uint8_t, void** output) { *output = nullptr; }
|
||||
static uint8_t frame_buffer_count(Device*) { return 0; }
|
||||
static error_t backlight(Device* device, Device** output) {
|
||||
*output = GET_CONFIG(device)->backlight;
|
||||
return *output == nullptr ? ERROR_NOT_SUPPORTED : ERROR_NONE;
|
||||
}
|
||||
|
||||
static const DisplayApi display_api = {
|
||||
.capabilities = DISPLAY_CAPABILITY_CAP_MIRROR | DISPLAY_CAPABILITY_INVERT_COLOR |
|
||||
DISPLAY_CAPABILITY_ON_OFF | DISPLAY_CAPABILITY_SLEEP | DISPLAY_CAPABILITY_BACKLIGHT |
|
||||
DISPLAY_CAPABILITY_REQUIRES_FULL_FRAME,
|
||||
.reset = reset,
|
||||
.init = init,
|
||||
.draw_bitmap = draw_bitmap,
|
||||
.mirror = mirror,
|
||||
.swap_xy = nullptr,
|
||||
.get_swap_xy = nullptr,
|
||||
.get_mirror_x = get_mirror_x,
|
||||
.get_mirror_y = get_mirror_y,
|
||||
.set_gap = nullptr,
|
||||
.get_gap_x = nullptr,
|
||||
.get_gap_y = nullptr,
|
||||
.invert_color = invert,
|
||||
.disp_on_off = on_off,
|
||||
.disp_sleep = sleep,
|
||||
.get_color_format = color_format,
|
||||
.get_resolution_x = resolution_x,
|
||||
.get_resolution_y = resolution_y,
|
||||
.get_frame_buffer = frame_buffer,
|
||||
.get_frame_buffer_count = frame_buffer_count,
|
||||
.get_backlight = backlight,
|
||||
.has_capability = nullptr,
|
||||
};
|
||||
|
||||
Driver st77922_driver = {
|
||||
.name = "st77922",
|
||||
.compatible = (const char*[]) { "sitronix,st77922", nullptr },
|
||||
.start_device = start,
|
||||
.stop_device = stop,
|
||||
.api = &display_api,
|
||||
.device_type = &DISPLAY_TYPE,
|
||||
.owner = &st77922_module,
|
||||
.internal = nullptr
|
||||
};
|
||||
@@ -0,0 +1,74 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
#include "st77922_init.h"
|
||||
|
||||
// Initialization sequence supplied with the LCDWIKI/Hosyond ES3C35P vendor ESP-IDF demo.
|
||||
static const st77922_lcd_init_cmd_t init_commands[] = {
|
||||
{0xF1, (uint8_t []){0x00}, 1, 0},
|
||||
{0x60, (uint8_t []){0x00, 0x00, 0x00}, 3, 0},
|
||||
{0x65, (uint8_t []){0x80}, 1, 0},
|
||||
{0x79, (uint8_t []){0x06}, 1, 0},
|
||||
{0x7B, (uint8_t []){0x00, 0x08, 0x08}, 3, 0},
|
||||
{0x80, (uint8_t []){0x55, 0x62, 0x2F, 0x17, 0xF0, 0x52, 0x70, 0xD2, 0x52, 0x62, 0xEA}, 11, 0},
|
||||
{0x81, (uint8_t []){0x26, 0x52, 0x72, 0x27}, 4, 0},
|
||||
{0x84, (uint8_t []){0x92, 0x25}, 2, 0},
|
||||
{0x87, (uint8_t []){0x10, 0x10, 0x58, 0x00, 0x02, 0x3A}, 6, 0},
|
||||
{0x88, (uint8_t []){0x00, 0x00, 0x2C, 0x10, 0x04, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x06}, 15, 0},
|
||||
{0x89, (uint8_t []){0x00, 0x00, 0x00}, 3, 0},
|
||||
{0x8A, (uint8_t []){0x13, 0x00, 0x2C, 0x00, 0x00, 0x2C, 0x10, 0x10, 0x00, 0x3E, 0x19}, 11, 0},
|
||||
{0x8B, (uint8_t []){0x15, 0xB1, 0xB1, 0x44, 0x96, 0x2C, 0x10, 0x97, 0x8E}, 9, 0},
|
||||
{0x8C, (uint8_t []){0x1D, 0xB1, 0xB1, 0x44, 0x96, 0x2C, 0x10, 0x50, 0x0F, 0x01, 0xC5, 0x12, 0x09}, 13, 0},
|
||||
{0x8D, (uint8_t []){0x0C}, 1, 0},
|
||||
{0x8E, (uint8_t []){0x33, 0x01, 0x0C, 0x13, 0x01, 0x01}, 6, 0},
|
||||
{0xB3, (uint8_t []){0x00, 0x30}, 2, 0},
|
||||
{0xF1, (uint8_t []){0x00}, 1, 0},
|
||||
{0x71, (uint8_t []){0xD0}, 1, 0},
|
||||
{0x66, (uint8_t []){0x02, 0x3F}, 2, 0},
|
||||
{0xBE, (uint8_t []){0x26, 0x00, 0x9D}, 3, 0},
|
||||
{0x70, (uint8_t []){0x01, 0xA0, 0x11, 0x40, 0xE0, 0x00, 0x11, 0x69, 0x11, 0x00, 0x00, 0x1A}, 12, 0},
|
||||
{0x90, (uint8_t []){0x04, 0x04, 0x55, 0x74, 0x00, 0x40, 0x43, 0x27, 0x27}, 9, 0},
|
||||
{0x91, (uint8_t []){0x04, 0x04, 0x55, 0x75, 0x00, 0x40, 0x42, 0x27, 0x27}, 9, 0},
|
||||
{0x92, (uint8_t []){0x04, 0x44, 0x55, 0xC0, 0x06, 0x00, 0x07, 0x05, 0x90, 0x27}, 10, 0},
|
||||
{0x93, (uint8_t []){0x04, 0x43, 0x11, 0x00, 0x00, 0x00, 0x00, 0x05, 0x90, 0x27}, 10, 0},
|
||||
{0x94, (uint8_t []){0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, 6, 0},
|
||||
{0x95, (uint8_t []){0x96, 0x16, 0x00, 0x00, 0xFF}, 5, 0},
|
||||
{0x96, (uint8_t []){0x44, 0x53, 0x03, 0x12, 0x23, 0x24, 0x06, 0x05, 0x94, 0x27, 0x00, 0x44}, 12, 0},
|
||||
{0x97, (uint8_t []){0x44, 0x53, 0x47, 0x56, 0x20, 0x20, 0x02, 0x01, 0x94, 0x27, 0x00, 0x44}, 12, 0},
|
||||
{0xBA, (uint8_t []){0x55, 0x94, 0x2D, 0x94, 0x27}, 5, 0},
|
||||
{0x9A, (uint8_t []){0x40, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00}, 7, 0},
|
||||
{0x9B, (uint8_t []){0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00}, 7, 0},
|
||||
{0x9C, (uint8_t []){0x5C, 0x12, 0x00, 0x00, 0x10, 0x12, 0x00, 0x00, 0x10, 0x02, 0x00, 0x00, 0x00}, 13, 0},
|
||||
{0x9D, (uint8_t []){0x8A, 0x51, 0x00, 0x00, 0x00, 0x80, 0x1E, 0x01}, 8, 0},
|
||||
{0x9E, (uint8_t []){0x51, 0x00, 0x00, 0x00, 0x80, 0x1E, 0x01}, 7, 0},
|
||||
{0xB4, (uint8_t []){0x1D, 0x1C, 0x1E, 0x0B, 0x14, 0x02, 0x13, 0x09, 0x1E, 0x00, 0x1E, 0x10}, 12, 0},
|
||||
{0xB5, (uint8_t []){0x1D, 0x1C, 0x1E, 0x0A, 0x15, 0x03, 0x11, 0x08, 0x1E, 0x01, 0x1E, 0x12}, 12, 0},
|
||||
{0xB6, (uint8_t []){0x77, 0x77, 0x00, 0x0A, 0xFF, 0x0A, 0xFF}, 7, 0},
|
||||
{0x86, (uint8_t []){0xCD, 0x04, 0xB1, 0x02, 0x58, 0x12, 0x58, 0x0C, 0x13, 0x01, 0xA5, 0x00, 0xA5, 0xA5}, 14, 0},
|
||||
{0xB7, (uint8_t []){0x07, 0x0A, 0x0E, 0x06, 0x05, 0x03, 0x2B, 0x03, 0x03, 0x42, 0x07, 0x10, 0x10, 0x2E, 0x3F, 0x0D}, 16, 0},
|
||||
{0xB8, (uint8_t []){0x07, 0x0A, 0x0D, 0x05, 0x05, 0x02, 0x2B, 0x02, 0x03, 0x42, 0x06, 0x10, 0x0F, 0x2E, 0x3F, 0x0D}, 16, 0},
|
||||
{0xB9, (uint8_t []){0x23, 0x23}, 2, 0},
|
||||
{0xBF, (uint8_t []){0x10, 0x14, 0x14, 0x0B, 0x0B, 0x0B}, 6, 0},
|
||||
{0xF2, (uint8_t []){0x00}, 1, 0},
|
||||
{0x73, (uint8_t []){0x04, 0xDA, 0x12, 0x54, 0x47}, 5, 0},
|
||||
{0x77, (uint8_t []){0x6B, 0x5B, 0xFD, 0xC3, 0xC5}, 5, 0},
|
||||
{0x7A, (uint8_t []){0x15, 0x27}, 2, 0},
|
||||
{0x7B, (uint8_t []){0x04, 0x57}, 2, 0},
|
||||
{0x7E, (uint8_t []){0x01, 0x0E}, 2, 0},
|
||||
{0xBF, (uint8_t []){0x36}, 1, 0},
|
||||
{0xE3, (uint8_t []){0x40, 0x40}, 2, 0},
|
||||
{0xF0, (uint8_t []){0x00}, 1, 0},
|
||||
{0xD0, (uint8_t []){0x00}, 1, 0},
|
||||
{0x2A, (uint8_t []){0x00, 0x00, 0x01, 0x3F}, 4, 0},
|
||||
{0x2B, (uint8_t []){0x00, 0x00, 0x01, 0xDF}, 4, 0},
|
||||
{0x21, NULL, 0, 0},
|
||||
{0x11, NULL, 0, 120},
|
||||
{0x29, NULL, 0, 0},
|
||||
{0x2C, NULL, 0, 0},
|
||||
{0x3A, (uint8_t []){0x01}, 1, 0},
|
||||
{0x36, (uint8_t []){0x00}, 1, 0},
|
||||
{0x35, (uint8_t []){0x01}, 1, 20},
|
||||
};
|
||||
|
||||
const st77922_lcd_init_cmd_t* st77922_board_init_commands(size_t* count) {
|
||||
*count = sizeof(init_commands) / sizeof(init_commands[0]);
|
||||
return init_commands;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include <esp_lcd_st77922.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
const st77922_lcd_init_cmd_t* st77922_board_init_commands(size_t* count);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,207 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
#include <drivers/st77922_touch.h>
|
||||
#include <st77922_module.h>
|
||||
|
||||
#include <tactility/check.h>
|
||||
#include <tactility/device.h>
|
||||
#include <tactility/driver.h>
|
||||
#include <tactility/drivers/gpio_controller.h>
|
||||
#include <tactility/drivers/i2c_controller.h>
|
||||
#include <tactility/drivers/pointer.h>
|
||||
#include <tactility/log.h>
|
||||
|
||||
#include <freertos/task.h>
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
|
||||
#define TAG "ST77922 touch"
|
||||
#define GET_CONFIG(device) (static_cast<const St77922TouchConfig*>((device)->config))
|
||||
|
||||
static constexpr uint16_t REG_MAX_TOUCHES = 0x0009;
|
||||
static constexpr uint16_t REG_TOUCH_INFO = 0x0010;
|
||||
static constexpr uint16_t REG_TOUCH_POINT0 = 0x0014;
|
||||
static constexpr uint8_t MAX_POINTS = 10;
|
||||
static constexpr TickType_t TIMEOUT = pdMS_TO_TICKS(1000);
|
||||
|
||||
struct TouchPoint {
|
||||
uint16_t x;
|
||||
uint16_t y;
|
||||
};
|
||||
|
||||
struct St77922TouchInternal {
|
||||
Device* i2c;
|
||||
GpioDescriptor* reset;
|
||||
uint8_t supported_points;
|
||||
uint8_t point_count;
|
||||
TouchPoint points[MAX_POINTS];
|
||||
bool swap_xy;
|
||||
bool mirror_x;
|
||||
bool mirror_y;
|
||||
};
|
||||
|
||||
static error_t read_register(Device* i2c, uint16_t reg, uint8_t* data, size_t size, TickType_t timeout) {
|
||||
const uint8_t address[] = {
|
||||
static_cast<uint8_t>(reg >> 8),
|
||||
static_cast<uint8_t>(reg & 0xFF),
|
||||
};
|
||||
return i2c_controller_write_read(i2c, 0x55, address, sizeof(address), data, size, timeout);
|
||||
}
|
||||
|
||||
static error_t start(Device* device) {
|
||||
auto* parent = device_get_parent(device);
|
||||
check(device_get_type(parent) == &I2C_CONTROLLER_TYPE);
|
||||
const auto* config = GET_CONFIG(device);
|
||||
|
||||
auto* internal = static_cast<St77922TouchInternal*>(calloc(1, sizeof(St77922TouchInternal)));
|
||||
if (internal == nullptr) {
|
||||
return ERROR_OUT_OF_MEMORY;
|
||||
}
|
||||
internal->i2c = parent;
|
||||
internal->supported_points = 1;
|
||||
internal->swap_xy = config->swap_xy;
|
||||
internal->mirror_x = config->mirror_x;
|
||||
internal->mirror_y = config->mirror_y;
|
||||
|
||||
if (config->pin_reset.gpio_controller != nullptr) {
|
||||
internal->reset = gpio_descriptor_acquire(config->pin_reset.gpio_controller,
|
||||
config->pin_reset.pin, GPIO_FLAG_DIRECTION_OUTPUT | GPIO_FLAG_ACTIVE_LOW, GPIO_OWNER_GPIO);
|
||||
if (internal->reset == nullptr) {
|
||||
free(internal);
|
||||
return ERROR_RESOURCE;
|
||||
}
|
||||
if (gpio_descriptor_set_level(internal->reset, true) != ERROR_NONE) {
|
||||
gpio_descriptor_release(internal->reset);
|
||||
free(internal);
|
||||
return ERROR_RESOURCE;
|
||||
}
|
||||
vTaskDelay(pdMS_TO_TICKS(10));
|
||||
gpio_descriptor_set_level(internal->reset, false);
|
||||
vTaskDelay(pdMS_TO_TICKS(100));
|
||||
}
|
||||
|
||||
uint8_t supported = 0;
|
||||
if (read_register(parent, REG_MAX_TOUCHES, &supported, 1, TIMEOUT) == ERROR_NONE
|
||||
&& supported > 0 && supported <= MAX_POINTS) {
|
||||
internal->supported_points = supported;
|
||||
}
|
||||
LOG_I(TAG, "Controller reports %u touch points", internal->supported_points);
|
||||
device_set_driver_data(device, internal);
|
||||
return ERROR_NONE;
|
||||
}
|
||||
|
||||
static error_t stop(Device* device) {
|
||||
auto* internal = static_cast<St77922TouchInternal*>(device_get_driver_data(device));
|
||||
if (internal->reset != nullptr) {
|
||||
gpio_descriptor_release(internal->reset);
|
||||
}
|
||||
free(internal);
|
||||
device_set_driver_data(device, nullptr);
|
||||
return ERROR_NONE;
|
||||
}
|
||||
|
||||
static error_t enter_sleep(Device*) { return ERROR_NOT_SUPPORTED; }
|
||||
static error_t exit_sleep(Device*) { return ERROR_NOT_SUPPORTED; }
|
||||
|
||||
static error_t read_data(Device* device, TickType_t timeout) {
|
||||
auto* internal = static_cast<St77922TouchInternal*>(device_get_driver_data(device));
|
||||
uint8_t touch_info = 0;
|
||||
if (read_register(internal->i2c, REG_TOUCH_INFO, &touch_info, 1, timeout) != ERROR_NONE) {
|
||||
internal->point_count = 0;
|
||||
return ERROR_RESOURCE;
|
||||
}
|
||||
if ((touch_info & 0x08) == 0) {
|
||||
internal->point_count = 0;
|
||||
return ERROR_NONE;
|
||||
}
|
||||
|
||||
uint8_t data[7 * MAX_POINTS] = {};
|
||||
const size_t read_size = 7 * internal->supported_points;
|
||||
if (read_register(internal->i2c, REG_TOUCH_POINT0, data, read_size, timeout) != ERROR_NONE) {
|
||||
internal->point_count = 0;
|
||||
return ERROR_RESOURCE;
|
||||
}
|
||||
|
||||
internal->point_count = 0;
|
||||
for (uint8_t index = 0; index < internal->supported_points; index++) {
|
||||
const uint8_t offset = index * 7;
|
||||
if ((data[offset] & 0x80) == 0) {
|
||||
continue;
|
||||
}
|
||||
internal->points[internal->point_count++] = {
|
||||
.x = static_cast<uint16_t>(((data[offset] & 0x3F) << 8) | data[offset + 1]),
|
||||
.y = static_cast<uint16_t>(((data[offset + 2] & 0x3F) << 8) | data[offset + 3]),
|
||||
};
|
||||
}
|
||||
return ERROR_NONE;
|
||||
}
|
||||
|
||||
static bool get_touched_points(Device* device, uint16_t* x, uint16_t* y, uint16_t* strength,
|
||||
uint8_t* count, uint8_t maximum) {
|
||||
auto* internal = static_cast<St77922TouchInternal*>(device_get_driver_data(device));
|
||||
const auto* config = GET_CONFIG(device);
|
||||
*count = std::min(internal->point_count, maximum);
|
||||
for (uint8_t index = 0; index < *count; index++) {
|
||||
uint16_t point_x = internal->points[index].x;
|
||||
uint16_t point_y = internal->points[index].y;
|
||||
if (internal->swap_xy) {
|
||||
std::swap(point_x, point_y);
|
||||
}
|
||||
const uint16_t max_x = internal->swap_xy ? config->y_max : config->x_max;
|
||||
const uint16_t max_y = internal->swap_xy ? config->x_max : config->y_max;
|
||||
x[index] = internal->mirror_x ? max_x - point_x : point_x;
|
||||
y[index] = internal->mirror_y ? max_y - point_y : point_y;
|
||||
if (strength != nullptr) {
|
||||
strength[index] = 0;
|
||||
}
|
||||
}
|
||||
return *count > 0;
|
||||
}
|
||||
|
||||
static error_t set_swap_xy(Device* device, bool value) {
|
||||
static_cast<St77922TouchInternal*>(device_get_driver_data(device))->swap_xy = value;
|
||||
return ERROR_NONE;
|
||||
}
|
||||
static error_t get_swap_xy(Device* device, bool* value) {
|
||||
*value = static_cast<St77922TouchInternal*>(device_get_driver_data(device))->swap_xy;
|
||||
return ERROR_NONE;
|
||||
}
|
||||
static error_t set_mirror_x(Device* device, bool value) {
|
||||
static_cast<St77922TouchInternal*>(device_get_driver_data(device))->mirror_x = value;
|
||||
return ERROR_NONE;
|
||||
}
|
||||
static error_t get_mirror_x(Device* device, bool* value) {
|
||||
*value = static_cast<St77922TouchInternal*>(device_get_driver_data(device))->mirror_x;
|
||||
return ERROR_NONE;
|
||||
}
|
||||
static error_t set_mirror_y(Device* device, bool value) {
|
||||
static_cast<St77922TouchInternal*>(device_get_driver_data(device))->mirror_y = value;
|
||||
return ERROR_NONE;
|
||||
}
|
||||
static error_t get_mirror_y(Device* device, bool* value) {
|
||||
*value = static_cast<St77922TouchInternal*>(device_get_driver_data(device))->mirror_y;
|
||||
return ERROR_NONE;
|
||||
}
|
||||
|
||||
static const PointerApi pointer_api = {
|
||||
.enter_sleep = enter_sleep,
|
||||
.exit_sleep = exit_sleep,
|
||||
.read_data = read_data,
|
||||
.get_touched_points = get_touched_points,
|
||||
.set_swap_xy = set_swap_xy,
|
||||
.get_swap_xy = get_swap_xy,
|
||||
.set_mirror_x = set_mirror_x,
|
||||
.get_mirror_x = get_mirror_x,
|
||||
.set_mirror_y = set_mirror_y,
|
||||
.get_mirror_y = get_mirror_y,
|
||||
};
|
||||
|
||||
Driver st77922_touch_driver = {
|
||||
.name = "st77922-touch",
|
||||
.compatible = (const char*[]) { "sitronix,st77922-touch", nullptr },
|
||||
.start_device = start,
|
||||
.stop_device = stop,
|
||||
.api = &pointer_api,
|
||||
.device_type = &POINTER_TYPE,
|
||||
.owner = &st77922_module,
|
||||
.internal = nullptr
|
||||
};
|
||||
@@ -1,147 +0,0 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
|
||||
file(GLOB_RECURSE SOURCE_FILES "Source/*.c*")
|
||||
|
||||
get_filename_component(PROJECT_ROOT "${CMAKE_CURRENT_LIST_DIR}/.." ABSOLUTE)
|
||||
|
||||
# Get the project and device id
|
||||
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_ID simulator)
|
||||
set(COMPONENT_LIB FirmwareSim)
|
||||
set(TACTILITY_DEVICE_PROJECT Simulator)
|
||||
endif ()
|
||||
|
||||
set(DEVICETREE_LOCATION "${PROJECT_ROOT}/Devices/${TACTILITY_DEVICE_ID}")
|
||||
|
||||
# Check if device has Bluetooth enabled
|
||||
# Fixes the sdkconfig bluetooth enable options from getting nuked on non-P4+C6 builds when idf build runs
|
||||
if (DEFINED ENV{ESP_IDF_VERSION})
|
||||
file(READ "${DEVICETREE_LOCATION}/device.properties" device_properties_content)
|
||||
if (device_properties_content MATCHES "hardware\\.bluetooth=true")
|
||||
list(APPEND REQUIRES_LIST bt)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
#
|
||||
# DTS compiler python dependencies
|
||||
#
|
||||
|
||||
execute_process(
|
||||
COMMAND python -m pip install lark==1.3.1 pyyaml==6.0.3
|
||||
WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
|
||||
)
|
||||
|
||||
#
|
||||
# Devicetree dependency collection
|
||||
#
|
||||
|
||||
# REQUIRES_LIST below is computed once, at configure time. Without this, editing
|
||||
# devicetree.yaml (e.g. adding a driver dependency) doesn't trigger a cmake reconfigure,
|
||||
# so the new component's include dirs never reach the compiler until a fullclean.
|
||||
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
|
||||
"${DEVICETREE_LOCATION}/devicetree.yaml"
|
||||
)
|
||||
|
||||
execute_process(
|
||||
COMMAND python "${PROJECT_ROOT}/Buildscripts/DevicetreeCompiler/dependencies.py" "${DEVICETREE_LOCATION}"
|
||||
WORKING_DIRECTORY "${PROJECT_ROOT}"
|
||||
OUTPUT_VARIABLE DEVICE_DEPENDENCIES
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE
|
||||
)
|
||||
# Tokenize to array of lines
|
||||
separate_arguments(DEVICE_DEPENDENCIES UNIX_COMMAND "${DEVICE_DEPENDENCIES}")
|
||||
|
||||
#
|
||||
# "Generated/" directory creation
|
||||
#
|
||||
|
||||
set(GENERATED_DIR "${CMAKE_CURRENT_BINARY_DIR}/Generated")
|
||||
# Ensure the directory is built in the correct CMake build phase
|
||||
# If the check is not done, then another directory is created in the root of the build folder.
|
||||
if (DEFINED CMAKE_CURRENT_BINARY_DIR)
|
||||
file(MAKE_DIRECTORY "${GENERATED_DIR}")
|
||||
endif ()
|
||||
|
||||
#
|
||||
# Component
|
||||
#
|
||||
|
||||
list(APPEND REQUIRES_LIST
|
||||
Tactility
|
||||
TactilityKernel
|
||||
)
|
||||
|
||||
# Add devicetree dependencies
|
||||
foreach(dts_dependency IN LISTS DEVICE_DEPENDENCIES)
|
||||
message("Adding DTS dependency ${dts_dependency}")
|
||||
list(APPEND REQUIRES_LIST ${dts_dependency})
|
||||
endforeach()
|
||||
|
||||
if (DEFINED ENV{ESP_IDF_VERSION})
|
||||
list(APPEND REQUIRES_LIST
|
||||
TactilityC
|
||||
)
|
||||
|
||||
idf_component_register(
|
||||
SRCS ${SOURCE_FILES} "${GENERATED_DIR}/devicetree.c"
|
||||
REQUIRES ${REQUIRES_LIST}
|
||||
)
|
||||
else ()
|
||||
list(APPEND REQUIRES_LIST
|
||||
Tactility
|
||||
TactilityFreeRtos
|
||||
lvgl-module
|
||||
lvgl-window-manager-module
|
||||
app-module
|
||||
crypt-module
|
||||
gps-module
|
||||
http-module
|
||||
gps-generic-module
|
||||
gps-meshtastic-module
|
||||
service-module
|
||||
SDL2::SDL2-static
|
||||
SDL2-static
|
||||
)
|
||||
add_executable(FirmwareSim ${SOURCE_FILES} "${GENERATED_DIR}/devicetree.c")
|
||||
target_link_libraries(FirmwareSim PRIVATE ${REQUIRES_LIST})
|
||||
endif ()
|
||||
|
||||
#
|
||||
# Devicetree code generation
|
||||
#
|
||||
|
||||
# A plain add_custom_command(OUTPUT ...) only reruns when its explicit DEPENDS (devicetree.yaml)
|
||||
# changes, since ninja computes dirtiness up front, before any command in this invocation runs.
|
||||
# The devicetree's real inputs span many files (dts, bindings yaml, driver headers) that a single
|
||||
# DEPENDS can't enumerate, so this used to be forced to always-rerun via a separate "AlwaysRun"
|
||||
# custom target that deleted devicetree.c first (DEPENDS on a *target* only creates an order-only
|
||||
# ninja edge). That delete was invisible to ninja's DAG: on an up-to-date build, ninja would still
|
||||
# run AlwaysRun (custom targets with no real output are always considered dirty) and delete the
|
||||
# file, but *not* rerun the generation edge (its own explicit input hadn't changed) or recompile
|
||||
# devicetree.c.obj (also considered clean) - silently leaving devicetree.c missing on disk until
|
||||
# some later, unrelated build finally noticed and regenerated it. In between, any build that did
|
||||
# need to (re)compile devicetree.c.obj hit "No such file or directory".
|
||||
#
|
||||
# add_custom_target(... COMMAND ...) has no such problem: unlike add_custom_command(OUTPUT ...),
|
||||
# a custom target with a COMMAND always reruns on every ninja invocation, so generation and the
|
||||
# stale artifact removal happen atomically in one edge. BYPRODUCTS tells ninja which files this
|
||||
# target produces, so it still wires a proper (non-order-only) dependency for the sources that
|
||||
# consume them.
|
||||
add_custom_target(Generated ALL
|
||||
COMMAND python "${CMAKE_SOURCE_DIR}/Buildscripts/DevicetreeCompiler/compile.py"
|
||||
"${DEVICETREE_LOCATION}" "${GENERATED_DIR}"
|
||||
BYPRODUCTS "${GENERATED_DIR}/devicetree.c" "${GENERATED_DIR}/devicetree.h"
|
||||
WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
|
||||
COMMENT "Generating devicetree source files..."
|
||||
)
|
||||
set_source_files_properties("${GENERATED_DIR}/devicetree.c" PROPERTIES GENERATED TRUE)
|
||||
set_source_files_properties("${GENERATED_DIR}/devicetree.h" PROPERTIES GENERATED TRUE)
|
||||
# Update target for generated code
|
||||
target_sources(${COMPONENT_LIB} PRIVATE "${GENERATED_DIR}/devicetree.c")
|
||||
target_include_directories(${COMPONENT_LIB} PRIVATE "${GENERATED_DIR}")
|
||||
add_dependencies(${COMPONENT_LIB} Generated)
|
||||
@@ -1,22 +0,0 @@
|
||||
# ChangeLog
|
||||
|
||||
## v1.1.1 - 2025-06-26
|
||||
|
||||
* Added support for ESP32-C61
|
||||
|
||||
## v1.1.0 - 2025-05-06
|
||||
|
||||
* Added fast build for ELF application
|
||||
* Added a script to generate the symbol table for the ELF APP:
|
||||
* Supports generating symbols table based on ELF file
|
||||
* Supports generating symbols table based on static libraries
|
||||
|
||||
## v1.0.0 - 2024-12-09
|
||||
|
||||
* Added support for the following RISC-V chips: ESP32-P4 and ESP32-C6
|
||||
* Added support for linking other components to ELF file
|
||||
* Fixed the issue of getting wrong symbol type
|
||||
|
||||
## v0.1.0 - 2023-08-14
|
||||
|
||||
* Add basic ELF loader component
|
||||
@@ -1,40 +0,0 @@
|
||||
|
||||
if(CONFIG_ELF_LOADER)
|
||||
set(srcs "src/esp_elf_symbol.c"
|
||||
"src/esp_elf.c"
|
||||
"src/esp_elf_adapter.c")
|
||||
|
||||
if(CONFIG_ELF_LOADER_CUSTOMER_SYMBOLS)
|
||||
list(APPEND srcs "src/esp_all_symbol.c")
|
||||
endif()
|
||||
|
||||
if(CONFIG_IDF_TARGET_ARCH_XTENSA)
|
||||
list(APPEND srcs "src/arch/esp_elf_xtensa.c")
|
||||
|
||||
# ESP32-S2 need to set MMU to run ELF
|
||||
if(CONFIG_IDF_TARGET_ESP32S2 AND (CONFIG_ELF_LOADER_LOAD_PSRAM))
|
||||
list(APPEND srcs "src/soc/esp_elf_esp32s2.c")
|
||||
endif()
|
||||
elseif(CONFIG_IDF_TARGET_ARCH_RISCV)
|
||||
list(APPEND srcs "src/arch/esp_elf_riscv.c")
|
||||
endif()
|
||||
|
||||
set(include_dirs "include")
|
||||
set(ldfragments "linker.lf")
|
||||
endif()
|
||||
|
||||
if(CONFIG_IDF_TARGET_ESP32P4)
|
||||
set(priv_req spi_flash esp_mm)
|
||||
else()
|
||||
set(priv_req spi_flash)
|
||||
endif()
|
||||
|
||||
idf_component_register(SRCS ${srcs}
|
||||
INCLUDE_DIRS ${include_dirs}
|
||||
PRIV_REQUIRES spi_flash ${priv_req}
|
||||
LDFRAGMENTS ${ldfragments})
|
||||
|
||||
include(package_manager)
|
||||
if(CONFIG_ELF_LOADER)
|
||||
cu_pkg_define_version(${CMAKE_CURRENT_LIST_DIR})
|
||||
endif()
|
||||
@@ -1,53 +0,0 @@
|
||||
menu "Espressif ELF Loader Configuration"
|
||||
visible if (IDF_TARGET_ESP32 || IDF_TARGET_ESP32S2 || IDF_TARGET_ESP32S3 || IDF_TARGET_ESP32C6 || IDF_TARGET_ESP32P4 || IDF_TARGET_ESP32C61)
|
||||
|
||||
config ELF_LOADER_BUS_ADDRESS_MIRROR
|
||||
bool
|
||||
default y if (IDF_TARGET_ESP32 || IDF_TARGET_ESP32S2 || IDF_TARGET_ESP32S3)
|
||||
default n if (IDF_TARGET_ESP32C6 || IDF_TARGET_ESP32P4 || IDF_TARGET_ESP32C61)
|
||||
|
||||
config ELF_LOADER
|
||||
bool "Enable Espressif ELF Loader"
|
||||
default y
|
||||
depends on (IDF_TARGET_ESP32 || IDF_TARGET_ESP32S2 || IDF_TARGET_ESP32S3 || IDF_TARGET_ESP32C6 || IDF_TARGET_ESP32P4 || IDF_TARGET_ESP32C61)
|
||||
help
|
||||
Select this option to enable ELF Loader and show the submenu with ELF Loader configuration choices.
|
||||
|
||||
if ELF_LOADER
|
||||
config ELF_LOADER_CACHE_OFFSET
|
||||
bool
|
||||
default n
|
||||
help
|
||||
Select this option if D-cache and I-cache has different offset to access the same physical address.
|
||||
|
||||
config ELF_LOADER_SET_MMU
|
||||
bool
|
||||
default n
|
||||
help
|
||||
Select this option if D-cache and I-cache is not symmetry。
|
||||
|
||||
config ELF_LOADER_LOAD_PSRAM
|
||||
bool "Load ELF to PSRAM"
|
||||
default y
|
||||
depends on (IDF_TARGET_ESP32S2 || IDF_TARGET_ESP32S3 || IDF_TARGET_ESP32P4 || IDF_TARGET_ESP32C61) && SPIRAM
|
||||
select ELF_LOADER_CACHE_OFFSET if (IDF_TARGET_ESP32S2 || IDF_TARGET_ESP32S3)
|
||||
select ELF_LOADER_SET_MMU if IDF_TARGET_ESP32S2
|
||||
help
|
||||
Load ELF file into PSRAM instead of internal SRAM.
|
||||
|
||||
menu "ELF Symbols Table"
|
||||
|
||||
config ELF_LOADER_LIBC_SYMBOLS
|
||||
bool "Libc Symbols Table"
|
||||
default y
|
||||
|
||||
config ELF_LOADER_ESPIDF_SYMBOLS
|
||||
bool "ESP-IDF Symbols Table"
|
||||
default y
|
||||
|
||||
config ELF_LOADER_CUSTOMER_SYMBOLS
|
||||
bool "Customer Symbols Table"
|
||||
default n
|
||||
endmenu
|
||||
endif
|
||||
endmenu
|
||||
@@ -1,109 +0,0 @@
|
||||
## Description
|
||||
|
||||
[](https://components.espressif.com/components/espressif/elf_loader)
|
||||
|
||||
Espressif ELF(Executable and Linkable Format) loader is a software development kit that is developed based on the ESP-IDF, mainly used to load ELF file compiled based on ESP32 series SoCs to the executable memory area, then link and execute it.
|
||||
|
||||
In this way, the application does not need compile into the whole firmware in advance. It is like running the compiled program through terminal input `./main.o` on the Ubuntu platform automatically, which realizes the separation of application and kernel.
|
||||
|
||||
This ELF loader supports following SoCs:
|
||||
|
||||
- ESP32
|
||||
- ESP32-S2, support running ELF in PSRAM
|
||||
- ESP32-S3, support running ELF in PSRAM
|
||||
- ESP32-P4, support running ELF in PSRAM
|
||||
- ESP32-C6
|
||||
- ESP32-C61, support running ELF in PSRAM
|
||||
|
||||
### Usage
|
||||
|
||||
#### Firmware
|
||||
|
||||
Add a dependency on this component in your component or project's idf_component.yml file.
|
||||
|
||||
```yml
|
||||
dependencies:
|
||||
espressif/elf_loader: "1.*"
|
||||
```
|
||||
|
||||
Enable ELF loader in the menuconfig:
|
||||
|
||||
```
|
||||
Component config --->
|
||||
ESP-ELFLoader Configuration --->
|
||||
[*] Enable Espressif ELF Loader
|
||||
```
|
||||
|
||||
Add API calls in your project as follows:
|
||||
|
||||
```c
|
||||
#include "esp_elf.h"
|
||||
|
||||
esp_elf_t elf;
|
||||
|
||||
// Your Code
|
||||
|
||||
esp_elf_init(&elf);
|
||||
esp_elf_relocate(&elf, elf_file_data_bytes);
|
||||
esp_elf_request(&elf, 0, argc, argv);
|
||||
esp_elf_deinit(&elf);
|
||||
```
|
||||
|
||||
#### ELF APP
|
||||
|
||||
To use this feature to compile ELF file, including the required CMake file in your project's CMakeLists.txt file after the line project(XXXX).
|
||||
|
||||
```cmake
|
||||
project(XXXX)
|
||||
|
||||
# Add
|
||||
include(elf_loader)
|
||||
project_elf(XXXX)
|
||||
```
|
||||
|
||||
Build the project as an ordinary ESP-IDF project, and then the ELF file named `XXXX.app.elf` is in the build directory.
|
||||
|
||||
### ELF APP Fast Build
|
||||
|
||||
Users can enable ELF fast build functionality by configuring CMAKE's generator as Unit Makefile. The reference command is as follows:
|
||||
|
||||
```bash
|
||||
idf.py -G 'Unix Makefiles' set-target <chip-name>
|
||||
```
|
||||
|
||||
Then input the ELF APP build command as follows:
|
||||
|
||||
```
|
||||
idf.py elf
|
||||
```
|
||||
|
||||
The build system will only build ELF target components and show the following logs:
|
||||
|
||||
```
|
||||
Building C object esp-idf/main/CMakeFiles/__idf_main.dir/main.c.obj
|
||||
Linking C static library libmain.a
|
||||
Build ELF: hello_world.app.elf
|
||||
Built target elf
|
||||
```
|
||||
|
||||
### Adding the Component to Your Project
|
||||
|
||||
Please use the component manager command add-dependency to add the elf_loader component as a dependency in your project. During the CMake step, the component will be downloaded automatically.
|
||||
|
||||
```
|
||||
idf.py add-dependency "espressif/elf_loader=*"
|
||||
```
|
||||
|
||||
### Examples
|
||||
|
||||
Please use the component manager command create-project-from-example to create a project from the example template.
|
||||
|
||||
```
|
||||
idf.py create-project-from-example "espressif/elf_loader=*:elf_loader_example"
|
||||
```
|
||||
|
||||
This command will download the example elf_loader_example into the current folder. You can navigate into it to build and flash the example.
|
||||
|
||||
Alternatively, you can download examples from the esp-iot-solution repository:
|
||||
1. [build_elf_file_example](https://github.com/espressif/esp-iot-solution/tree/master/examples/elf_loader/build_elf_file_example)
|
||||
2. [elf_loader_example](https://github.com/espressif/esp-iot-solution/tree/master/examples/elf_loader/elf_loader_example)
|
||||
@@ -1,79 +0,0 @@
|
||||
# The script is to generate ELF for application
|
||||
|
||||
# Trick to temporarily redefine project(). When functions are overridden in CMake, the originals can still be accessed
|
||||
# using an underscore prefixed function of the same name. The following lines make sure that project calls
|
||||
# the original project(). See https://cmake.org/pipermail/cmake/2015-October/061751.html.
|
||||
function(project_elf)
|
||||
endfunction()
|
||||
|
||||
function(_project_elf)
|
||||
endfunction()
|
||||
|
||||
macro(project_elf project_name)
|
||||
# Enable these options to remove unused symbols and reduce linked objects
|
||||
set(cflags -nostartfiles
|
||||
-nostdlib
|
||||
-fPIC
|
||||
-shared
|
||||
-e app_main
|
||||
-fdata-sections
|
||||
-ffunction-sections
|
||||
-Wl,--gc-sections
|
||||
-fvisibility=hidden)
|
||||
|
||||
# Enable this options to remove unnecessary sections in
|
||||
list(APPEND cflags -Wl,--strip-all
|
||||
-Wl,--strip-debug
|
||||
-Wl,--strip-discarded)
|
||||
|
||||
list(APPEND cflags -Dmain=app_main)
|
||||
|
||||
idf_build_set_property(COMPILE_OPTIONS "${cflags}" APPEND)
|
||||
|
||||
set(elf_app "${CMAKE_PROJECT_NAME}.app.elf")
|
||||
|
||||
# Remove more unused sections
|
||||
string(REPLACE "-elf-gcc" "-elf-strip" ${CMAKE_STRIP} ${CMAKE_C_COMPILER})
|
||||
set(strip_flags --strip-unneeded
|
||||
--remove-section=.comment
|
||||
--remove-section=.got.loc
|
||||
--remove-section=.dynamic)
|
||||
|
||||
if(CONFIG_IDF_TARGET_ARCH_XTENSA)
|
||||
list(APPEND strip_flags --remove-section=.xt.lit
|
||||
--remove-section=.xt.prop
|
||||
--remove-section=.xtensa.info)
|
||||
elseif(CONFIG_IDF_TARGET_ARCH_RISCV)
|
||||
list(APPEND strip_flags --remove-section=.riscv.attributes)
|
||||
endif()
|
||||
|
||||
# Link input list of libraries to ELF
|
||||
list(PREPEND ELF_COMPONENTS "main")
|
||||
if(ELF_COMPONENTS)
|
||||
foreach(c ${ELF_COMPONENTS})
|
||||
list(APPEND elf_libs "esp-idf/${c}/lib${c}.a")
|
||||
|
||||
if(${CMAKE_GENERATOR} STREQUAL "Unix Makefiles")
|
||||
add_custom_command(OUTPUT elf_${c}_app
|
||||
COMMAND +${CMAKE_MAKE_PROGRAM} "__idf_${c}/fast"
|
||||
COMMENT "Build Component: ${c}"
|
||||
)
|
||||
list(APPEND elf_dependeces "elf_${c}_app")
|
||||
else()
|
||||
list(APPEND elf_dependeces "idf::${c}")
|
||||
endif()
|
||||
endforeach()
|
||||
endif()
|
||||
if (ELF_LIBS)
|
||||
list(APPEND elf_libs "${ELF_LIBS}")
|
||||
endif()
|
||||
spaces2list(elf_libs)
|
||||
|
||||
add_custom_command(OUTPUT elf_app
|
||||
COMMAND ${CMAKE_C_COMPILER} ${cflags} ${elf_libs} -o ${elf_app}
|
||||
COMMAND ${CMAKE_STRIP} ${strip_flags} ${elf_app}
|
||||
DEPENDS ${elf_dependeces}
|
||||
COMMENT "Build ELF: ${elf_app}"
|
||||
)
|
||||
add_custom_target(elf ALL DEPENDS elf_app)
|
||||
endmacro()
|
||||
@@ -1,19 +0,0 @@
|
||||
version: "1.1.1"
|
||||
targets:
|
||||
- esp32
|
||||
- esp32s2
|
||||
- esp32s3
|
||||
- esp32c6
|
||||
- esp32c61
|
||||
- esp32p4
|
||||
description: Espressif ELF(Executable and Linkable Format) Loader
|
||||
url: https://github.com/espressif/esp-iot-solution/tree/master/components/elf_loader
|
||||
dependencies:
|
||||
idf: ">=4.4.3"
|
||||
espressif/cmake_utilities: "0.*"
|
||||
examples:
|
||||
- path: ../../examples/elf_loader/build_elf_file_example
|
||||
- path: ../../examples/elf_loader/elf_loader_example
|
||||
sbom:
|
||||
supplier: 'Organization: Espressif Systems (Shanghai) CO LTD'
|
||||
originator: 'Organization: Espressif Systems (Shanghai) CO LTD'
|
||||
@@ -1,103 +0,0 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2023-2024 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "private/elf_types.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief Map symbol's address of ELF to physic space.
|
||||
*
|
||||
* @param elf - ELF object pointer
|
||||
* @param sym - ELF symbol address
|
||||
*
|
||||
* @return Mapped physic address.
|
||||
*/
|
||||
uintptr_t esp_elf_map_sym(esp_elf_t *elf, uintptr_t sym);
|
||||
|
||||
/**
|
||||
* @brief Initialize ELF object.
|
||||
*
|
||||
* @param elf - ELF object pointer
|
||||
*
|
||||
* @return ESP_OK if success or other if failed.
|
||||
*/
|
||||
int esp_elf_init(esp_elf_t *elf);
|
||||
|
||||
/**
|
||||
* @brief Decode and relocate ELF data.
|
||||
*
|
||||
* @param elf - ELF object pointer
|
||||
* @param pbuf - ELF data buffer
|
||||
*
|
||||
* @return ESP_OK if success or other if failed.
|
||||
*/
|
||||
int esp_elf_relocate(esp_elf_t *elf, const uint8_t *pbuf);
|
||||
|
||||
/**
|
||||
* @brief Request running relocated ELF function.
|
||||
*
|
||||
* @param elf - ELF object pointer
|
||||
* @param opt - Request options
|
||||
* @param argc - Arguments number
|
||||
* @param argv - Arguments value array
|
||||
*
|
||||
* @return ESP_OK if success or other if failed.
|
||||
*/
|
||||
int esp_elf_request(esp_elf_t *elf, int opt, int argc, char *argv[]);
|
||||
|
||||
/**
|
||||
* @brief Deinitialize ELF object.
|
||||
*
|
||||
* @param elf - ELF object pointer
|
||||
*
|
||||
* @return None
|
||||
*/
|
||||
void esp_elf_deinit(esp_elf_t *elf);
|
||||
|
||||
/**
|
||||
* @brief Print header description information of ELF.
|
||||
*
|
||||
* @param pbuf - ELF data buffer
|
||||
*
|
||||
* @return None
|
||||
*/
|
||||
void esp_elf_print_ehdr(const uint8_t *pbuf);
|
||||
|
||||
/**
|
||||
* @brief Print program header description information of ELF.
|
||||
*
|
||||
* @param pbuf - ELF data buffer
|
||||
*
|
||||
* @return None
|
||||
*/
|
||||
void esp_elf_print_phdr(const uint8_t *pbuf);
|
||||
|
||||
/**
|
||||
* @brief Print section header description information of ELF.
|
||||
*
|
||||
* @param pbuf - ELF data buffer
|
||||
*
|
||||
* @return None
|
||||
*/
|
||||
void esp_elf_print_shdr(const uint8_t *pbuf);
|
||||
|
||||
/**
|
||||
* @brief Print section information of ELF.
|
||||
*
|
||||
* @param pbuf - ELF data buffer
|
||||
*
|
||||
* @return None
|
||||
*/
|
||||
void esp_elf_print_sec(esp_elf_t *elf);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -1,99 +0,0 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2023 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "private/elf_types.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* Notes: align_size needs to be a power of 2 */
|
||||
|
||||
#define ELF_ALIGN(_a, align_size) (((_a) + (align_size - 1)) & \
|
||||
~(align_size - 1))
|
||||
|
||||
/**
|
||||
* @brief Allocate block of memory.
|
||||
*
|
||||
* @param n - Memory size in byte
|
||||
* @param exec - True: memory can run executable code; False: memory can R/W data
|
||||
*
|
||||
* @return Memory pointer if success or NULL if failed.
|
||||
*/
|
||||
void *esp_elf_malloc(uint32_t n, bool exec);
|
||||
|
||||
/**
|
||||
* @brief Free block of memory.
|
||||
*
|
||||
* @param ptr - memory block pointer allocated by "esp_elf_malloc"
|
||||
*
|
||||
* @return None
|
||||
*/
|
||||
void esp_elf_free(void *ptr);
|
||||
|
||||
/**
|
||||
* @brief Relocates target architecture symbol of ELF
|
||||
*
|
||||
* @param elf - ELF object pointer
|
||||
* @param rela - Relocated symbol data
|
||||
* @param sym - ELF symbol table
|
||||
* @param addr - Jumping target address
|
||||
*
|
||||
* @return ESP_OK if success or other if failed.
|
||||
*/
|
||||
int esp_elf_arch_relocate(esp_elf_t *elf, const elf32_rela_t *rela,
|
||||
const elf32_sym_t *sym, uint32_t addr);
|
||||
|
||||
/**
|
||||
* @brief Remap symbol from ".data" to ".text" section.
|
||||
*
|
||||
* @param elf - ELF object pointer
|
||||
* @param sym - ELF symbol table
|
||||
*
|
||||
* @return Remapped symbol value
|
||||
*/
|
||||
#ifdef CONFIG_ELF_LOADER_CACHE_OFFSET
|
||||
uintptr_t elf_remap_text(esp_elf_t *elf, uintptr_t sym);
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief Flush data from cache to external RAM.
|
||||
*
|
||||
* @param None
|
||||
*
|
||||
* @return None
|
||||
*/
|
||||
#ifdef CONFIG_ELF_LOADER_LOAD_PSRAM
|
||||
void esp_elf_arch_flush(void);
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief Initialize MMU hardware remapping function.
|
||||
*
|
||||
* @param elf - ELF object pointer
|
||||
*
|
||||
* @return 0 if success or a negative value if failed.
|
||||
*/
|
||||
#ifdef CONFIG_ELF_LOADER_SET_MMU
|
||||
int esp_elf_arch_init_mmu(esp_elf_t *elf);
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief De-initialize MMU hardware remapping function.
|
||||
*
|
||||
* @param elf - ELF object pointer
|
||||
*
|
||||
* @return None
|
||||
*/
|
||||
#ifdef CONFIG_ELF_LOADER_SET_MMU
|
||||
void esp_elf_arch_deinit_mmu(esp_elf_t *elf);
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -1,54 +0,0 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2023 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define ESP_ELFSYM_EXPORT(_sym) { #_sym, (void*)&_sym }
|
||||
#define ESP_ELFSYM_END { NULL, NULL }
|
||||
|
||||
/** @brief Function symbol description */
|
||||
|
||||
struct esp_elfsym {
|
||||
const char *name; /*!< Function name */
|
||||
const void *sym; /*!< Function pointer */
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Find symbol address by name.
|
||||
*
|
||||
* @param sym_name - Symbol name
|
||||
*
|
||||
* @return Symbol address if success or 0 if failed.
|
||||
*/
|
||||
uintptr_t elf_find_sym(const char *sym_name);
|
||||
|
||||
|
||||
/**
|
||||
* @brief Resolves a symbol name (e.g. function name) to its address.
|
||||
*
|
||||
* @param sym_name - Symbol name
|
||||
* @return Symbol address if success or 0 if failed.
|
||||
*/
|
||||
typedef uintptr_t (*symbol_resolver)(const char *sym_name);
|
||||
|
||||
/**
|
||||
* @brief Override the internal symbol resolver.
|
||||
* The default resolver is based on static lists that are determined by KConfig.
|
||||
* This override allows for an arbitrary implementation.
|
||||
*
|
||||
* @param resolver the resolver function
|
||||
*/
|
||||
void elf_set_symbol_resolver(symbol_resolver resolver);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -1,247 +0,0 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2023 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <unistd.h>
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include <stdbool.h>
|
||||
#include "sdkconfig.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define EI_NIDENT 16 /*!< Magic number and other information length */
|
||||
|
||||
/** @brief Type of segment */
|
||||
|
||||
#define PT_NULL 0 /*!< Program header table entry unused */
|
||||
#define PT_LOAD 1 /*!< Loadable program segment */
|
||||
#define PT_DYNAMIC 2 /*!< Dynamic linking information */
|
||||
#define PT_INTERP 3 /*!< Program interpreter */
|
||||
#define PT_NOTE 4 /*!< Auxiliary information */
|
||||
#define PT_SHLIB 5 /*!< Reserved */
|
||||
#define PT_PHDR 6 /*!< Entry for header table itself */
|
||||
#define PT_TLS 7 /*!< Thread-local storage segment */
|
||||
#define PT_NUM 8 /*!< Number of defined types */
|
||||
#define PT_LOOS 0x60000000 /*!< Start of OS-specific */
|
||||
#define PT_GNU_EH_FRAME 0x6474e550 /*!< GCC .eh_frame_hdr segment */
|
||||
#define PT_GNU_STACK 0x6474e551 /*!< Indicates stack executability */
|
||||
#define PT_GNU_RELRO 0x6474e552 /*!< Read-only after relocation */
|
||||
#define PT_LOSUNW 0x6ffffffa
|
||||
#define PT_SUNWBSS 0x6ffffffa /*!< Sun Specific segment */
|
||||
#define PT_SUNWSTACK 0x6ffffffb /*!< Stack segment */
|
||||
#define PT_HISUNW 0x6fffffff
|
||||
#define PT_HIOS 0x6fffffff /*!< End of OS-specific */
|
||||
#define PT_LOPROC 0x70000000 /*!< Start of processor-specific */
|
||||
#define PT_HIPROC 0x7fffffff /*!< End of processor-specific */
|
||||
|
||||
/** @brief Section Type */
|
||||
|
||||
#define SHT_NULL 0 /*!< invalid section header */
|
||||
#define SHT_PROGBITS 1 /*!< some useful section like .text, .data .got, .plt .rodata .interp and so on */
|
||||
#define SHT_SYMTAB 2 /*!< symbol table */
|
||||
#define SHT_STRTAB 3 /*!< string table */
|
||||
#define SHT_RELA 4 /*!< relocation table */
|
||||
#define SHT_HASH 5 /*!< HASH table */
|
||||
#define SHT_SYNAMIC 6 /*!< dynamic symbol table */
|
||||
#define SHT_NOTE 7 /*!< note information */
|
||||
#define SHT_NOBITS 8 /*!< .bss */
|
||||
#define SHT_REL 9 /*!< relocation table */
|
||||
#define SHT_SHKIB 10 /*!< reserved but has unspecified semantics. */
|
||||
#define SHT_SYNSYM 11 /*!< dynamic symbol */
|
||||
#define SHT_LOPROC 0x70000000 /*!< reserved for processor-specific semantics */
|
||||
#define SHT_LOUSER 0x7fffffff /*!< lower bound of the range of indexes reserved for application programs */
|
||||
#define SHT_HIUSER 0xffffffff /*!< upper bound of the range of indexes reserved for application programs. */
|
||||
|
||||
/** @brief Section Attribute Flags */
|
||||
|
||||
#define SHF_WRITE 1 /*!< writable when task runs */
|
||||
#define SHF_ALLOC 2 /*!< allocated when task runs */
|
||||
#define SHF_EXECINSTR 4 /*!< machine code */
|
||||
#define SHF_MASKPROG 0xf0000000 /*!< reserved for processor-specific semantics */
|
||||
|
||||
/** @brief Symbol Types */
|
||||
|
||||
#define STT_NOTYPE 0 /*!< symbol type is unspecified */
|
||||
#define STT_OBJECT 1 /*!< data object */
|
||||
#define STT_FUNC 2 /*!< code object */
|
||||
#define STT_SECTION 3 /*!< symbol identifies an ELF section */
|
||||
#define STT_FILE 4 /*!< symbol's name is file name */
|
||||
#define STT_COMMON 5 /*!< common data object */
|
||||
#define STT_TLS 6 /*!< thread-local data object */
|
||||
#define STT_NUM 7 /*!< defined types in generic range */
|
||||
#define STT_LOOS 10 /*!< Low OS specific range */
|
||||
#define STT_HIOS 12 /*!< High OS specific range */
|
||||
#define STT_LOPROC 13 /*!< processor specific range */
|
||||
#define STT_HIPROC 15 /*!< processor specific link range */
|
||||
|
||||
/** @brief Section names */
|
||||
|
||||
#define ELF_BSS ".bss" /*!< uninitialized data */
|
||||
#define ELF_DATA ".data" /*!< initialized data */
|
||||
#define ELF_DEBUG ".debug" /*!< debug */
|
||||
#define ELF_DYNAMIC ".dynamic" /*!< dynamic linking information */
|
||||
#define ELF_DYNSTR ".dynstr" /*!< dynamic string table */
|
||||
#define ELF_DYNSYM ".dynsym" /*!< dynamic symbol table */
|
||||
#define ELF_FINI ".fini" /*!< termination code */
|
||||
#define ELF_GOT ".got" /*!< global offset table */
|
||||
#define ELF_HASH ".hash" /*!< symbol hash table */
|
||||
#define ELF_INIT ".init" /*!< initialization code */
|
||||
#define ELF_REL_DATA ".rel.data" /*!< relocation data */
|
||||
#define ELF_REL_FINI ".rel.fini" /*!< relocation termination code */
|
||||
#define ELF_REL_INIT ".rel.init" /*!< relocation initialization code */
|
||||
#define ELF_REL_DYN ".rel.dyn" /*!< relocaltion dynamic link info */
|
||||
#define ELF_REL_RODATA ".rel.rodata" /*!< relocation read-only data */
|
||||
#define ELF_REL_TEXT ".rel.text" /*!< relocation code */
|
||||
#define ELF_RODATA ".rodata" /*!< read-only data */
|
||||
#define ELF_SHSTRTAB ".shstrtab" /*!< section header string table */
|
||||
#define ELF_STRTAB ".strtab" /*!< string table */
|
||||
#define ELF_SYMTAB ".symtab" /*!< symbol table */
|
||||
#define ELF_TEXT ".text" /*!< code */
|
||||
#define ELF_DATA_REL_RO ".data.rel.ro" /*!< dynamic read-only data */
|
||||
#define ELF_PLT ".plt" /*!< procedure linkage table. */
|
||||
#define ELF_GOT_PLT ".got.plt" /*!< a table where resolved addresses from external functions are stored */
|
||||
|
||||
/** @brief ELF section and symbol operation */
|
||||
|
||||
#define ELF_SEC_TEXT 0
|
||||
#define ELF_SEC_BSS 1
|
||||
#define ELF_SEC_DATA 2
|
||||
#define ELF_SEC_RODATA 3
|
||||
#define ELF_SEC_DRLRO 4
|
||||
#define ELF_SECS 5
|
||||
|
||||
#define ELF_ST_BIND(_i) ((_i) >> 4)
|
||||
#define ELF_ST_TYPE(_i) ((_i) & 0xf)
|
||||
#define ELF_ST_INFO(_b, _t) (((_b)<<4) + ((_t) & 0xf))
|
||||
|
||||
#define ELF_R_SYM(_i) ((_i) >> 8)
|
||||
#define ELF_R_TYPE(_i) ((unsigned char)(_i))
|
||||
#define ELF_R_INFO(_s, _t) (((_s) << 8) + (unsigned char)(_t))
|
||||
|
||||
#define ELF_SEC_MAP(_elf, _sec, _addr) \
|
||||
((_elf)->sec[(_sec)].addr - \
|
||||
(_elf)->sec[(_sec)].v_addr + \
|
||||
(_addr))
|
||||
|
||||
typedef unsigned int Elf32_Addr;
|
||||
typedef unsigned int Elf32_Off;
|
||||
typedef unsigned int Elf32_Word;
|
||||
typedef unsigned short Elf32_Half;
|
||||
typedef int Elf32_Sword;
|
||||
|
||||
/** @brief ELF Header */
|
||||
|
||||
typedef struct elf32_hdr {
|
||||
unsigned char ident[EI_NIDENT]; /*!< ELF Identification */
|
||||
Elf32_Half type; /*!< object file type */
|
||||
Elf32_Half machine; /*!< machine */
|
||||
Elf32_Word version; /*!< object file version */
|
||||
Elf32_Addr entry; /*!< virtual entry point */
|
||||
Elf32_Off phoff; /*!< program header table offset */
|
||||
Elf32_Off shoff; /*!< section header table offset */
|
||||
Elf32_Word flags; /*!< processor-specific flags */
|
||||
Elf32_Half ehsize; /*!< ELF header size */
|
||||
Elf32_Half phentsize; /*!< program header entry size */
|
||||
Elf32_Half phnum; /*!< number of program header entries */
|
||||
Elf32_Half shentsize; /*!< section header entry size */
|
||||
Elf32_Half shnum; /*!< number of section header entries */
|
||||
Elf32_Half shstrndx; /*!< section header table's "section header string table" entry offset */
|
||||
} elf32_hdr_t;
|
||||
|
||||
/** @brief Program Header */
|
||||
|
||||
typedef struct elf32_phdr {
|
||||
Elf32_Word type; /* segment type */
|
||||
Elf32_Off offset; /* segment offset */
|
||||
Elf32_Addr vaddr; /* virtual address of segment */
|
||||
Elf32_Addr paddr; /* physical address - ignored? */
|
||||
Elf32_Word filesz; /* number of bytes in file for seg. */
|
||||
Elf32_Word memsz; /* number of bytes in mem. for seg. */
|
||||
Elf32_Word flags; /* flags */
|
||||
Elf32_Word align; /* memory alignment */
|
||||
} elf32_phdr_t;
|
||||
|
||||
/** @brief Section Header */
|
||||
|
||||
typedef struct elf32_shdr {
|
||||
Elf32_Word name; /*!< section index and it is offset in section .shstrtab */
|
||||
Elf32_Word type; /*!< type */
|
||||
Elf32_Word flags; /*!< flags */
|
||||
Elf32_Addr addr; /*!< start address when map to task space */
|
||||
Elf32_Off offset; /*!< offset address from file start address */
|
||||
Elf32_Word size; /*!< size */
|
||||
Elf32_Word link; /*!< link to another section */
|
||||
Elf32_Word info; /*!< additional section information */
|
||||
Elf32_Word addralign; /*!< address align */
|
||||
Elf32_Word entsize; /*!< index table size */
|
||||
} elf32_shdr_t;
|
||||
|
||||
/** @brief Symbol Table Entry */
|
||||
|
||||
typedef struct elf32_sym {
|
||||
Elf32_Word name; /*!< name - index into string table */
|
||||
Elf32_Addr value; /*!< symbol value */
|
||||
Elf32_Word size; /*!< symbol size */
|
||||
unsigned char info; /*!< type and binding */
|
||||
unsigned char other; /*!< 0 - no defined meaning */
|
||||
Elf32_Half shndx; /*!< section header index */
|
||||
} elf32_sym_t;
|
||||
|
||||
/** @brief Relocation entry with implicit addend */
|
||||
|
||||
typedef struct elf32_rel {
|
||||
Elf32_Addr offset; /*!< offset of relocation */
|
||||
Elf32_Word info; /*!< symbol table index and type */
|
||||
} elf32_rel_t;
|
||||
|
||||
/** @brief Relocation entry with explicit addend */
|
||||
|
||||
typedef struct elf32_rela {
|
||||
Elf32_Addr offset; /*!< offset of relocation */
|
||||
Elf32_Word info; /*!< symbol table index and type */
|
||||
Elf32_Sword addend; /*!< Added information */
|
||||
} elf32_rela_t;
|
||||
|
||||
/** @brief ELF section object */
|
||||
|
||||
typedef struct esp_elf_sec {
|
||||
uintptr_t v_addr; /*!< symbol virtual address */
|
||||
off_t offset; /*!< offset in ELF */
|
||||
|
||||
uintptr_t addr; /*!< section physic address in memory */
|
||||
size_t size; /*!< section size */
|
||||
} esp_elf_sec_t;
|
||||
|
||||
/** @brief ELF object */
|
||||
|
||||
typedef struct esp_elf {
|
||||
unsigned char *psegment; /*!< segment buffer pointer */
|
||||
|
||||
uint32_t svaddr; /*!< start virtual address of segment */
|
||||
|
||||
unsigned char *ptext; /*!< instruction buffer pointer */
|
||||
|
||||
unsigned char *pdata; /*!< data buffer pointer */
|
||||
|
||||
esp_elf_sec_t sec[ELF_SECS]; /*!< ".bss", "data", "rodata", ".text" */
|
||||
|
||||
int (*entry)(int argc, char *argv[]); /*!< Entry pointer of ELF */
|
||||
|
||||
#ifdef CONFIG_ELF_LOADER_SET_MMU
|
||||
uint32_t text_off; /* .text symbol offset */
|
||||
|
||||
uint32_t mmu_off; /* MMU unit offset */
|
||||
uint32_t mmu_num; /* MMU unit total number */
|
||||
#endif
|
||||
} esp_elf_t;
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -1,202 +0,0 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
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.
|
||||
@@ -1,14 +0,0 @@
|
||||
[sections:elf_loader_got_plt]
|
||||
entries:
|
||||
.got.plt
|
||||
.got
|
||||
|
||||
[scheme:elf_loader_default]
|
||||
entries:
|
||||
elf_loader_got_plt -> flash_rodata
|
||||
|
||||
[mapping:elf_loader]
|
||||
archive: *
|
||||
entries:
|
||||
* (elf_loader_default);
|
||||
elf_loader_got_plt -> flash_rodata KEEP() SURROUND(_esp_elf_loader_got_plt)
|
||||
@@ -1 +0,0 @@
|
||||
set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR} ${CMAKE_MODULE_PATH})
|
||||
@@ -1,112 +0,0 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2024 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
#include <assert.h>
|
||||
#include <sys/errno.h>
|
||||
#include "esp_elf.h"
|
||||
#include "esp_log.h"
|
||||
#include "private/elf_platform.h"
|
||||
|
||||
/** @brief RISC-V relocations defined by the ABIs */
|
||||
|
||||
#define R_RISCV_NONE 0
|
||||
#define R_RISCV_32 1
|
||||
#define R_RISCV_64 2
|
||||
#define R_RISCV_RELATIVE 3
|
||||
#define R_RISCV_COPY 4
|
||||
#define R_RISCV_JUMP_SLOT 5
|
||||
#define R_RISCV_TLS_DTPMOD32 6
|
||||
#define R_RISCV_TLS_DTPMOD64 7
|
||||
#define R_RISCV_TLS_DTPREL32 8
|
||||
#define R_RISCV_TLS_DTPREL64 9
|
||||
#define R_RISCV_TLS_TPREL32 10
|
||||
#define R_RISCV_TLS_TPREL64 11
|
||||
#define R_RISCV_TLS_DESC 12
|
||||
#define R_RISCV_BRANCH 16
|
||||
#define R_RISCV_JAL 17
|
||||
#define R_RISCV_CALL 18
|
||||
#define R_RISCV_CALL_PLT 19
|
||||
#define R_RISCV_GOT_HI20 20
|
||||
#define R_RISCV_TLS_GOT_HI20 21
|
||||
#define R_RISCV_TLS_GD_HI20 22
|
||||
#define R_RISCV_PCREL_HI20 23
|
||||
#define R_RISCV_PCREL_LO12_I 24
|
||||
#define R_RISCV_PCREL_LO12_S 25
|
||||
#define R_RISCV_HI20 26
|
||||
#define R_RISCV_LO12_I 27
|
||||
#define R_RISCV_LO12_S 28
|
||||
#define R_RISCV_TPREL_HI20 29
|
||||
#define R_RISCV_TPREL_LO12_I 30
|
||||
#define R_RISCV_TPREL_LO12_S 31
|
||||
#define R_RISCV_TPREL_ADD 32
|
||||
#define R_RISCV_ADD8 33
|
||||
#define R_RISCV_ADD16 34
|
||||
#define R_RISCV_ADD32 35
|
||||
#define R_RISCV_ADD64 36
|
||||
#define R_RISCV_SUB8 37
|
||||
#define R_RISCV_SUB16 38
|
||||
#define R_RISCV_SUB32 39
|
||||
#define R_RISCV_SUB64 40
|
||||
#define R_RISCV_GNU_VTINHERIT 41
|
||||
#define R_RISCV_GNU_VTENTRY 42
|
||||
#define R_RISCV_ALIGN 43
|
||||
#define R_RISCV_RVC_BRANCH 44
|
||||
#define R_RISCV_RVC_JUMP 45
|
||||
#define R_RISCV_RVC_LUI 46
|
||||
#define R_RISCV_RELAX 51
|
||||
#define R_RISCV_SUB6 52
|
||||
#define R_RISCV_SET6 53
|
||||
#define R_RISCV_SET8 54
|
||||
#define R_RISCV_SET16 55
|
||||
#define R_RISCV_SET32 56
|
||||
#define R_RISCV_32_PCREL 57
|
||||
#define R_RISCV_IRELATIVE 58
|
||||
#define R_RISCV_PLT32 59
|
||||
|
||||
static const char *TAG = "elf_arch";
|
||||
|
||||
/**
|
||||
* @brief Relocates target architecture symbol of ELF
|
||||
*
|
||||
* @param elf - ELF object pointer
|
||||
* @param rela - Relocated symbol data
|
||||
* @param sym - ELF symbol table
|
||||
* @param addr - Jumping target address
|
||||
*
|
||||
* @return ESP_OK if success or other if failed.
|
||||
*/
|
||||
int esp_elf_arch_relocate(esp_elf_t *elf, const elf32_rela_t *rela,
|
||||
const elf32_sym_t *sym, uint32_t addr)
|
||||
{
|
||||
uint32_t *where;
|
||||
|
||||
assert(elf && rela);
|
||||
|
||||
where = (uint32_t *)((uint8_t *)elf->psegment + rela->offset + elf->svaddr);
|
||||
ESP_LOGD(TAG, "type: %d, where=%p addr=0x%x offset=0x%x",
|
||||
ELF_R_TYPE(rela->info), where, (int)elf->psegment, (int)rela->offset);
|
||||
|
||||
/* Do relocation based on relocation type */
|
||||
|
||||
switch (ELF_R_TYPE(rela->info)) {
|
||||
case R_RISCV_NONE:
|
||||
break;
|
||||
case R_RISCV_32:
|
||||
*where = addr + rela->addend;
|
||||
break;
|
||||
case R_RISCV_RELATIVE:
|
||||
*where = (Elf32_Addr)((uint8_t *)elf->psegment - elf->svaddr + rela->addend);
|
||||
break;
|
||||
case R_RISCV_JUMP_SLOT:
|
||||
*where = addr;
|
||||
break;
|
||||
default:
|
||||
ESP_LOGE(TAG, "info=%d is not supported\n", ELF_R_TYPE(rela->info));
|
||||
return -EINVAL;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user