Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 982bba70b2 | |||
| 9630707b41 | |||
| fd82efe08f | |||
| 72089f74f3 | |||
| 89e8baf517 | |||
| 2060095028 | |||
| 620d56e19a | |||
| a0583e3a30 | |||
| 054d1286b2 | |||
| 85da419a98 | |||
| 87c82f5314 | |||
| 4b7f82c38f | |||
| 6d55f0b200 | |||
| 61fc67cf4c | |||
| c8ee763f3d | |||
| 9e3dc3dc15 | |||
| a321bfeb4c | |||
| f95cd7df4c |
@@ -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.
|
||||
@@ -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:
|
||||
@@ -48,11 +45,10 @@ runs:
|
||||
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
|
||||
|
||||
+3
-1
@@ -3,6 +3,8 @@
|
||||
|
||||
build*/
|
||||
!.github/actions/build*/
|
||||
!Buildscripts/
|
||||
!Buildscripts/release-simulator-macos-app.sh
|
||||
cmake*/
|
||||
CMakeCache.txt
|
||||
*.cbp
|
||||
@@ -27,4 +29,4 @@ sdkconfig.board.*.dev
|
||||
.caveman.json
|
||||
.ai/mcp
|
||||
|
||||
__pycache__
|
||||
__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,
|
||||
|
||||
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()
|
||||
@@ -0,0 +1,61 @@
|
||||
#!/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>
|
||||
</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"
|
||||
+7
-3
@@ -62,9 +62,13 @@ if (DEFINED ENV{ESP_IDF_VERSION})
|
||||
# to every target; PanicHandler.cpp branches internally per architecture.
|
||||
idf_build_set_property(LINK_OPTIONS "-Wl,--wrap=esp_panic_handler" APPEND)
|
||||
|
||||
idf_build_set_property(LINK_OPTIONS "-Wl,--wrap=read" APPEND)
|
||||
idf_build_set_property(LINK_OPTIONS "-Wl,--wrap=write" APPEND)
|
||||
idf_build_set_property(LINK_OPTIONS "-Wl,--wrap=close" 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)
|
||||
|
||||
@@ -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,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,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>
|
||||
@@ -141,8 +142,10 @@ static bool sdl_display_lazy_init(Device* device, SdlDisplayInternal* internal)
|
||||
return true;
|
||||
}
|
||||
|
||||
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));
|
||||
// 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;
|
||||
@@ -166,6 +169,16 @@ static error_t sdl_display_draw_bitmap(Device* device, int32_t x_start, int32_t
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -7,13 +7,48 @@
|
||||
#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;
|
||||
@@ -70,65 +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:
|
||||
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:
|
||||
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;
|
||||
}
|
||||
@@ -139,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;
|
||||
}
|
||||
|
||||
|
||||
@@ -29,7 +29,28 @@ 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 = { 640, 480 };
|
||||
// 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 {};
|
||||
@@ -81,6 +102,10 @@ 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");
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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
|
||||
};
|
||||
@@ -10,15 +10,29 @@ tactility_add_module(app-module
|
||||
INCLUDE_DIRS include/
|
||||
REQUIRES TactilityKernel service-module minitar
|
||||
PRIV_REQUIRES TactilityKernelCpp
|
||||
WHOLE_ARCHIVE
|
||||
)
|
||||
|
||||
# Tells source/io.cpp its real-syscall fallback must go through __real_read/write/close()
|
||||
# rather than calling ::read/::write/::close() directly, on every platform whose build wraps
|
||||
# those symbols (ESP-IDF always; POSIX except macOS, whose linker doesn't support --wrap) -
|
||||
# see Tactility/CMakeLists.txt and the top-level CMakeLists.txt for where that's applied.
|
||||
if (NOT APPLE)
|
||||
# Tells source/io.cpp its real-syscall fallback must go through __real_read/write/close() rather
|
||||
# than calling ::read/::write/::close() directly, on every platform where those are wrapped: via
|
||||
# -Wl,--wrap= on ESP-IDF (see the top-level CMakeLists.txt) and non-Apple POSIX (below), or via
|
||||
# source/stdio_wrap.cpp's dyld interpose on Apple (whose linker lacks --wrap).
|
||||
tactility_get_module_name(app-module MODULE_NAME)
|
||||
target_compile_definitions(${MODULE_NAME} PRIVATE TT_APP_IO_WRAPS_STDIO)
|
||||
|
||||
# Routes every read()/write()/close() and printf-family call to source/stdio_wrap.cpp's __wrap_*
|
||||
# functions; see that file for what they do and why. ESP-IDF wraps the same symbols itself (see
|
||||
# the top-level CMakeLists.txt); Apple gets the same routing via dyld interpose instead, self-
|
||||
# registered in that file. PUBLIC so every consumer of this module (Tactility, and any test target
|
||||
# that links app-module directly) gets the flags too.
|
||||
if (NOT ESP_PLATFORM AND NOT APPLE)
|
||||
tactility_get_module_name(app-module MODULE_NAME)
|
||||
target_compile_definitions(${MODULE_NAME} PRIVATE TT_APP_IO_WRAPS_STDIO)
|
||||
target_link_options(${MODULE_NAME} PUBLIC
|
||||
"-Wl,--wrap=read" "-Wl,--wrap=write" "-Wl,--wrap=close"
|
||||
"-Wl,--wrap=printf" "-Wl,--wrap=fprintf" "-Wl,--wrap=vprintf" "-Wl,--wrap=vfprintf"
|
||||
"-Wl,--wrap=puts" "-Wl,--wrap=fputs" "-Wl,--wrap=putchar" "-Wl,--wrap=fputc"
|
||||
"-Wl,--wrap=getchar" "-Wl,--wrap=fgetc" "-Wl,--wrap=fgets"
|
||||
)
|
||||
endif ()
|
||||
|
||||
# install.cpp resolves an installed binary's fixed bin/<platform>/<binary>.so path itself, so it
|
||||
|
||||
@@ -8,13 +8,42 @@
|
||||
#include <cerrno>
|
||||
|
||||
#if defined(TT_APP_IO_WRAPS_STDIO)
|
||||
#ifdef ESP_PLATFORM
|
||||
// Newlib's stdio (fflush()'s buffer-flush path, in particular) calls the reentrant _read_r/
|
||||
// _write_r/_close_r syscall stubs directly. The plain read()/write()/close() newlib provides are
|
||||
// just thin wrappers around them (esp-idf's components/newlib/src/syscalls.c: `write(fd, dst,
|
||||
// size) { return _write_r(__getreent(), fd, dst, size); }`). Wrapping the _r stubs catches both;
|
||||
// wrapping the plain names would only catch direct write()-style callers.
|
||||
#include <reent.h>
|
||||
extern "C" {
|
||||
ssize_t __real__read_r(struct _reent* r, int fd, void* buffer, size_t size);
|
||||
ssize_t __real__write_r(struct _reent* r, int fd, const void* buffer, size_t size);
|
||||
int __real__close_r(struct _reent* r, int fd);
|
||||
}
|
||||
namespace {
|
||||
ssize_t real_read(int fd, void* buffer, size_t size) { return __real__read_r(__getreent(), fd, buffer, size); }
|
||||
ssize_t real_write(int fd, const void* buffer, size_t size) { return __real__write_r(__getreent(), fd, buffer, size); }
|
||||
int real_close(int fd) { return __real__close_r(__getreent(), fd); }
|
||||
} // namespace
|
||||
#else
|
||||
extern "C" {
|
||||
ssize_t __real_read(int fd, void* buffer, size_t size);
|
||||
ssize_t __real_write(int fd, const void* buffer, size_t size);
|
||||
int __real_close(int fd);
|
||||
}
|
||||
namespace {
|
||||
ssize_t real_read(int fd, void* buffer, size_t size) { return __real_read(fd, buffer, size); }
|
||||
ssize_t real_write(int fd, const void* buffer, size_t size) { return __real_write(fd, buffer, size); }
|
||||
int real_close(int fd) { return __real_close(fd); }
|
||||
} // namespace
|
||||
#endif
|
||||
#else
|
||||
#include <unistd.h>
|
||||
namespace {
|
||||
ssize_t real_read(int fd, void* buffer, size_t size) { return ::read(fd, buffer, size); }
|
||||
ssize_t real_write(int fd, const void* buffer, size_t size) { return ::write(fd, buffer, size); }
|
||||
int real_close(int fd) { return ::close(fd); }
|
||||
} // namespace
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
@@ -56,11 +85,7 @@ ssize_t app_io_read(int fd, void* buffer, size_t size) {
|
||||
errno = EBADF;
|
||||
return -1;
|
||||
}
|
||||
#if defined(TT_APP_IO_WRAPS_STDIO)
|
||||
return __real_read(fd, buffer, size);
|
||||
#else
|
||||
return ::read(fd, buffer, size);
|
||||
#endif
|
||||
return real_read(fd, buffer, size);
|
||||
}
|
||||
|
||||
ssize_t app_io_write(int fd, const void* buffer, size_t size) {
|
||||
@@ -78,22 +103,14 @@ ssize_t app_io_write(int fd, const void* buffer, size_t size) {
|
||||
// output is currently being intercepted. Without this, a log line emitted while any app
|
||||
// instance has its stdout captured would vanish from the console entirely instead of
|
||||
// just also being visible to the capturing parent.
|
||||
#if defined(TT_APP_IO_WRAPS_STDIO)
|
||||
__real_write(fd, buffer, size);
|
||||
#else
|
||||
::write(fd, buffer, size);
|
||||
#endif
|
||||
real_write(fd, buffer, size);
|
||||
return result;
|
||||
}
|
||||
if (table != nullptr && app_fd_table_is_app_owned(table, fd)) {
|
||||
errno = EBADF;
|
||||
return -1;
|
||||
}
|
||||
#if defined(TT_APP_IO_WRAPS_STDIO)
|
||||
return __real_write(fd, buffer, size);
|
||||
#else
|
||||
return ::write(fd, buffer, size);
|
||||
#endif
|
||||
return real_write(fd, buffer, size);
|
||||
}
|
||||
|
||||
int app_io_close(int fd) {
|
||||
@@ -108,11 +125,7 @@ int app_io_close(int fd) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
#if defined(TT_APP_IO_WRAPS_STDIO)
|
||||
return __real_close(fd);
|
||||
#else
|
||||
return ::close(fd);
|
||||
#endif
|
||||
return real_close(fd);
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
@@ -32,8 +32,10 @@ constexpr size_t APP_INSTANCE_ID_THREAD_SLOT_INDEX = 1;
|
||||
// Matches TactilityKernel's Thread wrapper's THREAD_PRIORITY_NORMAL.
|
||||
constexpr UBaseType_t APP_TASK_PRIORITY = 4;
|
||||
|
||||
// Used when an app's manifest doesn't request a specific stack depth (0). 8192 bytes' worth.
|
||||
constexpr size_t APP_DEFAULT_STACK_DEPTH = 8192 / sizeof(StackType_t);
|
||||
// Used when an app's manifest doesn't request a specific stack depth (0). 12288 bytes' worth.
|
||||
// Existing window-manager app manifests request at least 2400 words (9600 bytes); use a
|
||||
// conservative default above that baseline so a zero-depth app task cannot exhaust its stack.
|
||||
constexpr size_t APP_DEFAULT_STACK_DEPTH = 12288 / sizeof(StackType_t);
|
||||
|
||||
// Task control blocks must stay in internal RAM; only the stack itself may live in external memory.
|
||||
constexpr MemoryPolicy APP_TASK_TCB_POLICY = { MEMORY_CAPABILITY_INTERNAL, 0, 0 };
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Paired with -Wl,--wrap= on POSIX (this module's own CMakeLists.txt) and ESP32 (top-level
|
||||
// CMakeLists.txt); self-registered via dyld interpose below on Apple, whose linker doesn't
|
||||
// support --wrap.
|
||||
#include <app/io.h>
|
||||
|
||||
#include <sys/types.h>
|
||||
|
||||
#ifdef ESP_PLATFORM
|
||||
|
||||
// Newlib's own stdio (fflush()'s buffer-flush path, in particular) calls the reentrant
|
||||
// _read_r/_write_r/_close_r syscall stubs directly, not the plain read()/write()/close() newlib
|
||||
// itself provides as thin wrappers around them (see e.g. esp-idf's components/newlib/src/
|
||||
// syscalls.c: `write(fd, dst, size) { return _write_r(__getreent(), fd, dst, size); }`)
|
||||
// Wrapping the plain names only catches direct write()-style callers, not newlib's own internal
|
||||
// stdio calls, so the _r stubs are wrapped here instead.
|
||||
#include <reent.h>
|
||||
|
||||
extern "C" {
|
||||
|
||||
ssize_t __wrap__read_r(struct _reent* r, int fd, void* buffer, size_t size) {
|
||||
(void)r;
|
||||
return app_io_read(fd, buffer, size);
|
||||
}
|
||||
|
||||
ssize_t __wrap__write_r(struct _reent* r, int fd, const void* buffer, size_t size) {
|
||||
(void)r;
|
||||
return app_io_write(fd, buffer, size);
|
||||
}
|
||||
|
||||
int __wrap__close_r(struct _reent* r, int fd) {
|
||||
(void)r;
|
||||
return app_io_close(fd);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
extern "C" {
|
||||
|
||||
ssize_t __wrap_read(int fd, void* buffer, size_t size) {
|
||||
return app_io_read(fd, buffer, size);
|
||||
}
|
||||
|
||||
ssize_t __wrap_write(int fd, const void* buffer, size_t size) {
|
||||
return app_io_write(fd, buffer, size);
|
||||
}
|
||||
|
||||
int __wrap_close(int fd) {
|
||||
return app_io_close(fd);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#endif // ESP_PLATFORM
|
||||
|
||||
#ifdef __APPLE__
|
||||
|
||||
// --wrap also synthesizes __real_read/write/close automatically; dyld interpose doesn't, so
|
||||
// io.cpp's TT_APP_IO_WRAPS_STDIO fallback needs them defined here. dlsym(RTLD_NEXT, ...) is the
|
||||
// standard way to reach the true libSystem implementation despite the interpose below: a direct
|
||||
// call to read/write/close from this file would just recurse into __wrap_read/write/close, since
|
||||
// interpose rewrites every reference to those symbols in the process, this file included.
|
||||
#include <dlfcn.h>
|
||||
#include <unistd.h>
|
||||
|
||||
extern "C" {
|
||||
|
||||
ssize_t __real_read(int fd, void* buffer, size_t size) {
|
||||
static auto real = reinterpret_cast<ssize_t (*)(int, void*, size_t)>(dlsym(RTLD_NEXT, "read"));
|
||||
return real(fd, buffer, size);
|
||||
}
|
||||
|
||||
ssize_t __real_write(int fd, const void* buffer, size_t size) {
|
||||
static auto real = reinterpret_cast<ssize_t (*)(int, const void*, size_t)>(dlsym(RTLD_NEXT, "write"));
|
||||
return real(fd, buffer, size);
|
||||
}
|
||||
|
||||
int __real_close(int fd) {
|
||||
static auto real = reinterpret_cast<int (*)(int)>(dlsym(RTLD_NEXT, "close"));
|
||||
return real(fd);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// <mach-o/dyld-interposing.h> isn't a public SDK header (it ships with dyld's own source, not
|
||||
// Xcode/Command Line Tools), so this reimplements its DYLD_INTERPOSE macro locally; reused below
|
||||
// for the printf-family interposes too.
|
||||
#define TT_DYLD_INTERPOSE(replacement, replacee) \
|
||||
__attribute__((used)) static struct { const void* replacement; const void* replacee; } \
|
||||
tt_interpose_##replacee __attribute__((section("__DATA,__interpose"))) = { \
|
||||
(const void*)(unsigned long)&(replacement), (const void*)(unsigned long)&(replacee) \
|
||||
};
|
||||
|
||||
TT_DYLD_INTERPOSE(__wrap_read, read)
|
||||
TT_DYLD_INTERPOSE(__wrap_write, write)
|
||||
TT_DYLD_INTERPOSE(__wrap_close, close)
|
||||
|
||||
#endif // __APPLE__
|
||||
|
||||
// region glibc stdio wraps
|
||||
//
|
||||
// libc's printf/fprintf/etc are compiled into the C library and call an internal, non-exported
|
||||
// write() alias, which --wrap=write/the read/write/close interpose above can't reach: only calls
|
||||
// WE make to the public symbol. These wraps instead redirect calls WE make to printf/fprintf/etc,
|
||||
// the same trick as read/write/close above. Newlib (ESP-IDF) doesn't have this gap: its stdio does
|
||||
// call the wrappable syscall stubs, so this block is POSIX-only.
|
||||
//
|
||||
// Scoped to the printf/getc families only: fread/fwrite take an arbitrary FILE* and are already
|
||||
// used sitewide for real file I/O (e.g. File.cpp's readBinaryInternal), so wrapping them would
|
||||
// route every such call through this file's stdin/stdout check, a correctness risk for unrelated
|
||||
// code that isn't worth taking here. putc/getc are excluded too since libc defines them as
|
||||
// macros, not real calls, so wrapping those symbols wouldn't reliably intercept them.
|
||||
|
||||
#if !defined(ESP_PLATFORM)
|
||||
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#include <unistd.h>
|
||||
|
||||
extern "C" {
|
||||
int __real_vfprintf(FILE* stream, const char* format, va_list args);
|
||||
int __real_fputs(const char* s, FILE* stream);
|
||||
int __real_fputc(int c, FILE* stream);
|
||||
int __real_fgetc(FILE* stream);
|
||||
char* __real_fgets(char* buffer, int size, FILE* stream);
|
||||
}
|
||||
|
||||
#ifdef __APPLE__
|
||||
|
||||
// --wrap synthesizes these automatically elsewhere; on Apple they're defined here via
|
||||
// dlsym(RTLD_NEXT, ...) instead. See the read/write/close __real_* block above for why.
|
||||
#include <dlfcn.h>
|
||||
|
||||
extern "C" {
|
||||
|
||||
int __real_vfprintf(FILE* stream, const char* format, va_list args) {
|
||||
static auto real = reinterpret_cast<int (*)(FILE*, const char*, va_list)>(dlsym(RTLD_NEXT, "vfprintf"));
|
||||
return real(stream, format, args);
|
||||
}
|
||||
|
||||
int __real_fputs(const char* s, FILE* stream) {
|
||||
static auto real = reinterpret_cast<int (*)(const char*, FILE*)>(dlsym(RTLD_NEXT, "fputs"));
|
||||
return real(s, stream);
|
||||
}
|
||||
|
||||
int __real_fputc(int c, FILE* stream) {
|
||||
static auto real = reinterpret_cast<int (*)(int, FILE*)>(dlsym(RTLD_NEXT, "fputc"));
|
||||
return real(c, stream);
|
||||
}
|
||||
|
||||
int __real_fgetc(FILE* stream) {
|
||||
static auto real = reinterpret_cast<int (*)(FILE*)>(dlsym(RTLD_NEXT, "fgetc"));
|
||||
return real(stream);
|
||||
}
|
||||
|
||||
char* __real_fgets(char* buffer, int size, FILE* stream) {
|
||||
static auto real = reinterpret_cast<char* (*)(char*, int, FILE*)>(dlsym(RTLD_NEXT, "fgets"));
|
||||
return real(buffer, size, stream);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#endif // __APPLE__
|
||||
|
||||
namespace {
|
||||
|
||||
void writeAllToStdout(const void* data, size_t size) {
|
||||
const auto* bytes = static_cast<const char*>(data);
|
||||
size_t remaining = size;
|
||||
while (remaining > 0) {
|
||||
ssize_t written = app_io_write(STDOUT_FILENO, bytes, remaining);
|
||||
if (written <= 0) {
|
||||
break;
|
||||
}
|
||||
bytes += written;
|
||||
remaining -= static_cast<size_t>(written);
|
||||
}
|
||||
}
|
||||
|
||||
// Formats into stdout via app_io_write() rather than through a FILE*'s own buffering, since that
|
||||
// buffering is exactly what glibc's internal write() call sidesteps --wrap for in the first place.
|
||||
int formatToStdout(const char* format, va_list args) {
|
||||
char stackBuffer[256];
|
||||
va_list argsForStack;
|
||||
va_copy(argsForStack, args);
|
||||
int needed = vsnprintf(stackBuffer, sizeof(stackBuffer), format, argsForStack);
|
||||
va_end(argsForStack);
|
||||
if (needed < 0) {
|
||||
return needed;
|
||||
}
|
||||
if (static_cast<size_t>(needed) < sizeof(stackBuffer)) {
|
||||
writeAllToStdout(stackBuffer, static_cast<size_t>(needed));
|
||||
return needed;
|
||||
}
|
||||
auto heapBuffer = std::make_unique<char[]>(static_cast<size_t>(needed) + 1);
|
||||
va_list argsForHeap;
|
||||
va_copy(argsForHeap, args);
|
||||
vsnprintf(heapBuffer.get(), static_cast<size_t>(needed) + 1, format, argsForHeap);
|
||||
va_end(argsForHeap);
|
||||
writeAllToStdout(heapBuffer.get(), static_cast<size_t>(needed));
|
||||
return needed;
|
||||
}
|
||||
|
||||
int readOneFromStdin(char& out) {
|
||||
return static_cast<int>(app_io_read(STDIN_FILENO, &out, 1));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
int __wrap_vprintf(const char* format, va_list args) {
|
||||
return formatToStdout(format, args);
|
||||
}
|
||||
|
||||
int __wrap_printf(const char* format, ...) {
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
int result = formatToStdout(format, args);
|
||||
va_end(args);
|
||||
return result;
|
||||
}
|
||||
|
||||
int __wrap_vfprintf(FILE* stream, const char* format, va_list args) {
|
||||
if (stream == stdout) {
|
||||
return formatToStdout(format, args);
|
||||
}
|
||||
return __real_vfprintf(stream, format, args);
|
||||
}
|
||||
|
||||
int __wrap_fprintf(FILE* stream, const char* format, ...) {
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
int result = (stream == stdout) ? formatToStdout(format, args) : __real_vfprintf(stream, format, args);
|
||||
va_end(args);
|
||||
return result;
|
||||
}
|
||||
|
||||
int __wrap_puts(const char* s) {
|
||||
writeAllToStdout(s, strlen(s));
|
||||
writeAllToStdout("\n", 1);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int __wrap_fputs(const char* s, FILE* stream) {
|
||||
if (stream == stdout) {
|
||||
writeAllToStdout(s, strlen(s));
|
||||
return 0;
|
||||
}
|
||||
return __real_fputs(s, stream);
|
||||
}
|
||||
|
||||
int __wrap_putchar(int c) {
|
||||
auto ch = static_cast<char>(c);
|
||||
writeAllToStdout(&ch, 1);
|
||||
return c;
|
||||
}
|
||||
|
||||
int __wrap_fputc(int c, FILE* stream) {
|
||||
if (stream == stdout) {
|
||||
return __wrap_putchar(c);
|
||||
}
|
||||
return __real_fputc(c, stream);
|
||||
}
|
||||
|
||||
int __wrap_getchar() {
|
||||
char c;
|
||||
return readOneFromStdin(c) == 1 ? static_cast<unsigned char>(c) : EOF;
|
||||
}
|
||||
|
||||
int __wrap_fgetc(FILE* stream) {
|
||||
if (stream == stdin) {
|
||||
return __wrap_getchar();
|
||||
}
|
||||
return __real_fgetc(stream);
|
||||
}
|
||||
|
||||
char* __wrap_fgets(char* buffer, int size, FILE* stream) {
|
||||
if (stream != stdin) {
|
||||
return __real_fgets(buffer, size, stream);
|
||||
}
|
||||
if (size <= 0) {
|
||||
return nullptr;
|
||||
}
|
||||
int i = 0;
|
||||
for (; i < size - 1; ++i) {
|
||||
char c;
|
||||
if (readOneFromStdin(c) != 1) {
|
||||
break;
|
||||
}
|
||||
buffer[i] = c;
|
||||
if (c == '\n') {
|
||||
++i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (i == 0) {
|
||||
return nullptr;
|
||||
}
|
||||
buffer[i] = '\0';
|
||||
return buffer;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#ifdef __APPLE__
|
||||
TT_DYLD_INTERPOSE(__wrap_vprintf, vprintf)
|
||||
TT_DYLD_INTERPOSE(__wrap_printf, printf)
|
||||
TT_DYLD_INTERPOSE(__wrap_vfprintf, vfprintf)
|
||||
TT_DYLD_INTERPOSE(__wrap_fprintf, fprintf)
|
||||
TT_DYLD_INTERPOSE(__wrap_puts, puts)
|
||||
TT_DYLD_INTERPOSE(__wrap_fputs, fputs)
|
||||
TT_DYLD_INTERPOSE(__wrap_putchar, putchar)
|
||||
TT_DYLD_INTERPOSE(__wrap_fputc, fputc)
|
||||
TT_DYLD_INTERPOSE(__wrap_getchar, getchar)
|
||||
TT_DYLD_INTERPOSE(__wrap_fgetc, fgetc)
|
||||
TT_DYLD_INTERPOSE(__wrap_fgets, fgets)
|
||||
#endif // __APPLE__
|
||||
|
||||
#endif // !ESP_PLATFORM
|
||||
|
||||
// endregion
|
||||
@@ -6,30 +6,12 @@ enable_language(C CXX ASM)
|
||||
file(GLOB_RECURSE TEST_SOURCES CONFIGURE_DEPENDS ${PROJECT_SOURCE_DIR}/source/*.cpp)
|
||||
add_executable(AppModuleTests EXCLUDE_FROM_ALL ${TEST_SOURCES})
|
||||
|
||||
if (NOT APPLE)
|
||||
# Provides __wrap_read/write/close for the -Wl,--wrap= below (see Tactility/CMakeLists.txt
|
||||
# for the canonical pairing of this file with those flags).
|
||||
target_sources(AppModuleTests PRIVATE ${CMAKE_CURRENT_LIST_DIR}/../../../Tactility/Source/AppStdioWrap.cpp)
|
||||
endif ()
|
||||
|
||||
target_include_directories(AppModuleTests PRIVATE ${DOCTESTINC} ${CMAKE_CURRENT_LIST_DIR}/../private)
|
||||
|
||||
add_test(NAME AppModuleTests COMMAND AppModuleTests)
|
||||
|
||||
# Matches app-module's own TT_APP_IO_WRAPS_STDIO (see Modules/app-module/CMakeLists.txt):
|
||||
# io.cpp calls __real_read/write/close() on non-Apple POSIX, so any final link of it needs
|
||||
# these wraps too, or those symbols go unresolved. The printf-family/getc-family flags are
|
||||
# needed for the same reason: AppStdioWrap.cpp compiles those __wrap_* functions unconditionally
|
||||
# on this platform (see its own #if guard), and they reference __real_vfprintf/fputs/fputc/
|
||||
# fgetc/fgets - those only exist once the matching --wrap flag is passed.
|
||||
if (NOT APPLE)
|
||||
target_link_options(AppModuleTests PRIVATE
|
||||
"-Wl,--wrap=read" "-Wl,--wrap=write" "-Wl,--wrap=close"
|
||||
"-Wl,--wrap=printf" "-Wl,--wrap=fprintf" "-Wl,--wrap=vprintf" "-Wl,--wrap=vfprintf"
|
||||
"-Wl,--wrap=puts" "-Wl,--wrap=fputs" "-Wl,--wrap=putchar" "-Wl,--wrap=fputc"
|
||||
"-Wl,--wrap=getchar" "-Wl,--wrap=fgetc" "-Wl,--wrap=fgets"
|
||||
)
|
||||
endif ()
|
||||
# No --wrap flags or stdio_wrap.cpp source needed here: linking app-module below already brings
|
||||
# both along (see its own CMakeLists.txt).
|
||||
|
||||
target_link_libraries(AppModuleTests PUBLIC
|
||||
TactilityKernel
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
#include <tactility/delay.h>
|
||||
#include <tactility/freertos/task.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
@@ -110,6 +111,11 @@ int32_t stream_writer_app_main(int, char*[]) {
|
||||
return 7;
|
||||
}
|
||||
|
||||
int32_t printf_stream_writer_app_main(int, char*[]) {
|
||||
printf("loc");
|
||||
return 7;
|
||||
}
|
||||
|
||||
// Writes argv[0] to its own stdout, for the app_execute_with_streams() argv-delivery test.
|
||||
int32_t argv_echo_app_main(int argc, char* argv[]) {
|
||||
if (argc < 1) {
|
||||
@@ -321,3 +327,53 @@ TEST_CASE("app_execute_for_result_with_streams delivers both the stream data and
|
||||
app_manager_stop(parent_id);
|
||||
app_manager_remove("test.app.execute.parent_streams");
|
||||
}
|
||||
|
||||
TEST_CASE("app_execute_for_result_with_streams pipes a child's plain printf() calls too") {
|
||||
ensure_memory_loader_registered();
|
||||
|
||||
AppManifest parent_manifest { "test.app.execute.printf_parent", "Parent", APP_CATEGORY_USER, { APP_LOCATION_MEMORY, reinterpret_cast<void*>(location_app_main) } };
|
||||
REQUIRE_EQ(app_manager_add(&parent_manifest), ERROR_NONE);
|
||||
|
||||
uint32_t parent_id = 0;
|
||||
REQUIRE_EQ(app_start("test.app.execute.printf_parent", 0, nullptr, &parent_id), ERROR_NONE);
|
||||
CHECK(wait_for_state(parent_id, APP_INSTANCE_STATE_ACTIVE, 1000));
|
||||
|
||||
TaskEventGroup parent_event_group {};
|
||||
task_event_group_construct(&parent_event_group);
|
||||
AppEventSubscription parent_sub {};
|
||||
REQUIRE_EQ(app_event_subscribe_with_app_id(&parent_sub, &parent_event_group, parent_id), ERROR_NONE);
|
||||
|
||||
uint8_t storage[64];
|
||||
AppStream child_stdout {};
|
||||
AppStreamBinding binding { STDOUT_FILENO, &child_stdout, storage, sizeof(storage), &parent_event_group };
|
||||
|
||||
AppLocation location { APP_LOCATION_MEMORY, reinterpret_cast<void*>(printf_stream_writer_app_main) };
|
||||
uint32_t child_id = 0;
|
||||
REQUIRE_EQ(app_execute_for_result_with_streams(location, AppStackConfig {}, 0, nullptr, &binding, 1, parent_id, &child_id), ERROR_NONE);
|
||||
|
||||
std::vector<uint8_t> received;
|
||||
while (app_stream_await(&child_stdout, APP_FILE_WAIT_READABLE, pdMS_TO_TICKS(1000)) == ERROR_NONE) {
|
||||
uint8_t chunk[16];
|
||||
size_t n = app_stream_read(&child_stdout, chunk, sizeof(chunk));
|
||||
if (n == 0) {
|
||||
break; // EOF
|
||||
}
|
||||
received.insert(received.end(), chunk, chunk + n);
|
||||
}
|
||||
REQUIRE_EQ(received.size(), 3u);
|
||||
CHECK_EQ(std::memcmp(received.data(), "loc", 3), 0);
|
||||
|
||||
REQUIRE_EQ(task_event_group_wait(&parent_event_group, parent_sub.bit, false, nullptr, pdMS_TO_TICKS(2000)), ERROR_NONE);
|
||||
AppEvent event {};
|
||||
REQUIRE_EQ(app_event_poll(&parent_sub, &event), ERROR_NONE);
|
||||
CHECK_EQ(event.type, APP_EVENT_RESULT);
|
||||
CHECK_EQ(event.result.launch_id, child_id);
|
||||
CHECK_EQ(event.result.result, 7);
|
||||
|
||||
app_stream_unsubscribe(&child_stdout);
|
||||
app_event_unsubscribe(&parent_sub);
|
||||
task_event_group_destruct(&parent_event_group);
|
||||
app_manager_stop(child_id);
|
||||
app_manager_stop(parent_id);
|
||||
app_manager_remove("test.app.execute.printf_parent");
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
#include <unistd.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
@@ -66,6 +67,11 @@ int32_t stdout_writer_app_main(int, char*[]) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
int32_t stdout_printf_app_main(int, char*[]) {
|
||||
printf("hello");
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::atomic<bool> g_blocked_writer_saw_error { false };
|
||||
std::atomic<bool> g_blocked_writer_done { false };
|
||||
|
||||
@@ -180,6 +186,41 @@ TEST_CASE("app_start_with_streams pipes a child's app_io_write() calls into a pa
|
||||
app_manager_remove("test.io.writer");
|
||||
}
|
||||
|
||||
TEST_CASE("app_start_with_streams pipes a child's plain printf() calls into a parent-owned AppStream") {
|
||||
ensure_memory_loader_registered();
|
||||
|
||||
AppManifest manifest { "test.io.printf_writer", "PrintfWriter", APP_CATEGORY_USER, { APP_LOCATION_MEMORY, reinterpret_cast<void*>(stdout_printf_app_main) } };
|
||||
REQUIRE_EQ(app_manager_add(&manifest), ERROR_NONE);
|
||||
|
||||
TaskEventGroup event_group {};
|
||||
task_event_group_construct(&event_group);
|
||||
|
||||
uint8_t storage[64];
|
||||
AppStream child_stdout {};
|
||||
|
||||
AppStreamBinding binding { STDOUT_FILENO, &child_stdout, storage, sizeof(storage), &event_group };
|
||||
AppInstanceId child_id = 0;
|
||||
REQUIRE_EQ(app_start_with_streams("test.io.printf_writer", &binding, 1, &child_id), ERROR_NONE);
|
||||
|
||||
std::vector<uint8_t> received;
|
||||
while (app_stream_await(&child_stdout, APP_FILE_WAIT_READABLE, pdMS_TO_TICKS(1000)) == ERROR_NONE) {
|
||||
uint8_t chunk[16];
|
||||
size_t n = app_stream_read(&child_stdout, chunk, sizeof(chunk));
|
||||
if (n == 0) {
|
||||
break; // EOF
|
||||
}
|
||||
received.insert(received.end(), chunk, chunk + n);
|
||||
}
|
||||
|
||||
REQUIRE_EQ(received.size(), 5u);
|
||||
CHECK_EQ(std::memcmp(received.data(), "hello", 5), 0);
|
||||
|
||||
REQUIRE(wait_for_state(child_id, APP_INSTANCE_STATE_STOPPED, 1000));
|
||||
app_stream_unsubscribe(&child_stdout);
|
||||
task_event_group_destruct(&event_group);
|
||||
app_manager_remove("test.io.printf_writer");
|
||||
}
|
||||
|
||||
TEST_CASE("a write blocked on a full stream wakes with an error once the consumer closes it") {
|
||||
ensure_memory_loader_registered();
|
||||
g_blocked_writer_saw_error.store(false, std::memory_order_relaxed);
|
||||
|
||||
@@ -14,6 +14,15 @@ enum LvglFontSize {
|
||||
FONT_SIZE_LARGE,
|
||||
};
|
||||
|
||||
enum LvglFontScale {
|
||||
FONT_SCALE_SMALL,
|
||||
FONT_SCALE_DEFAULT,
|
||||
FONT_SCALE_LARGE,
|
||||
};
|
||||
|
||||
void lvgl_set_text_font_scale(enum LvglFontScale font_scale);
|
||||
enum LvglFontScale lvgl_get_text_font_scale(void);
|
||||
|
||||
const lv_font_t* lvgl_get_shared_icon_font(void);
|
||||
uint32_t lvgl_get_shared_icon_font_height(void);
|
||||
|
||||
|
||||
@@ -13,8 +13,30 @@ extern const lv_font_t TT_LVGL_LAUNCHER_FONT_ICON_SYMBOL;
|
||||
extern const lv_font_t TT_LVGL_STATUSBAR_FONT_ICON_SYMBOL;
|
||||
extern const lv_font_t TT_LVGL_SHARED_FONT_ICON_SYMBOL;
|
||||
|
||||
static enum LvglFontScale text_font_scale = FONT_SCALE_DEFAULT;
|
||||
|
||||
void lvgl_set_text_font_scale(enum LvglFontScale font_scale) {
|
||||
check(font_scale >= FONT_SCALE_SMALL && font_scale <= FONT_SCALE_LARGE);
|
||||
text_font_scale = font_scale;
|
||||
}
|
||||
|
||||
enum LvglFontScale lvgl_get_text_font_scale(void) {
|
||||
return text_font_scale;
|
||||
}
|
||||
|
||||
static enum LvglFontSize resolve_text_font_size(enum LvglFontSize font_size) {
|
||||
int resolved = (int)font_size + (int)text_font_scale - (int)FONT_SCALE_DEFAULT;
|
||||
if (resolved < FONT_SIZE_SMALL) {
|
||||
return FONT_SIZE_SMALL;
|
||||
}
|
||||
if (resolved > FONT_SIZE_LARGE) {
|
||||
return FONT_SIZE_LARGE;
|
||||
}
|
||||
return (enum LvglFontSize)resolved;
|
||||
}
|
||||
|
||||
uint32_t lvgl_get_text_font_height(enum LvglFontSize font_size) {
|
||||
switch (font_size) {
|
||||
switch (resolve_text_font_size(font_size)) {
|
||||
case FONT_SIZE_SMALL: return TT_LVGL_TEXT_FONT_SMALL_SIZE;
|
||||
case FONT_SIZE_DEFAULT: return TT_LVGL_TEXT_FONT_DEFAULT_SIZE;
|
||||
case FONT_SIZE_LARGE: return TT_LVGL_TEXT_FONT_LARGE_SIZE;
|
||||
@@ -22,7 +44,7 @@ uint32_t lvgl_get_text_font_height(enum LvglFontSize font_size) {
|
||||
}
|
||||
}
|
||||
const lv_font_t* lvgl_get_text_font(enum LvglFontSize font_size) {
|
||||
switch (font_size) {
|
||||
switch (resolve_text_font_size(font_size)) {
|
||||
case FONT_SIZE_SMALL: return &TT_LVGL_TEXT_FONT_SMALL_SYMBOL;
|
||||
case FONT_SIZE_DEFAULT: return &TT_LVGL_TEXT_FONT_DEFAULT_SYMBOL;
|
||||
case FONT_SIZE_LARGE: return &TT_LVGL_TEXT_FONT_LARGE_SYMBOL;
|
||||
|
||||
@@ -26,6 +26,8 @@ const struct ModuleSymbol lvgl_module_symbols[] = {
|
||||
DEFINE_MODULE_SYMBOL(lvgl_module),
|
||||
DEFINE_MODULE_SYMBOL(lvgl_module_configure),
|
||||
// lvgl_fonts
|
||||
DEFINE_MODULE_SYMBOL(lvgl_set_text_font_scale),
|
||||
DEFINE_MODULE_SYMBOL(lvgl_get_text_font_scale),
|
||||
DEFINE_MODULE_SYMBOL(lvgl_get_shared_icon_font),
|
||||
DEFINE_MODULE_SYMBOL(lvgl_get_shared_icon_font_height),
|
||||
DEFINE_MODULE_SYMBOL(lvgl_get_text_font),
|
||||
@@ -494,6 +496,12 @@ const struct ModuleSymbol lvgl_module_symbols[] = {
|
||||
// lv_image
|
||||
DEFINE_MODULE_SYMBOL(lv_image_create),
|
||||
DEFINE_MODULE_SYMBOL(lv_image_set_src),
|
||||
DEFINE_MODULE_SYMBOL(lv_image_set_scale),
|
||||
DEFINE_MODULE_SYMBOL(lv_image_set_scale_x),
|
||||
DEFINE_MODULE_SYMBOL(lv_image_set_scale_y),
|
||||
DEFINE_MODULE_SYMBOL(lv_image_get_scale),
|
||||
DEFINE_MODULE_SYMBOL(lv_image_get_scale_x),
|
||||
DEFINE_MODULE_SYMBOL(lv_image_get_scale_y),
|
||||
// lv_anim
|
||||
DEFINE_MODULE_SYMBOL(lv_anim_init),
|
||||
DEFINE_MODULE_SYMBOL(lv_anim_set_duration),
|
||||
|
||||
@@ -6,3 +6,12 @@ add_library(platform-posix OBJECT)
|
||||
target_sources(platform-posix PRIVATE ${SOURCES})
|
||||
#target_include_directories(platform-posix PUBLIC include/)
|
||||
target_link_libraries(platform-posix PUBLIC TactilityKernel)
|
||||
|
||||
# Routes every pthread_attr_setstack() call to __wrap_pthread_attr_setstack() in source/pthread_stack_wrap.c,
|
||||
# which no-ops it. see that file for why.
|
||||
# --wrap is a GNU ld option; Apple's linker doesn't support it, so that file instead self-registers a dyld interpose
|
||||
# for this symbol on Apple, needing no link flag. PUBLIC so every consumer of this OBJECT library
|
||||
# (Tactility, and every test target that links platform-posix directly) gets it applied too.
|
||||
if (NOT APPLE)
|
||||
target_link_options(platform-posix PUBLIC "-Wl,--wrap=pthread_attr_setstack")
|
||||
endif ()
|
||||
|
||||
@@ -2,20 +2,15 @@
|
||||
#include <stddef.h>
|
||||
|
||||
/**
|
||||
* Linked in with -Wl,--wrap=pthread_attr_setstack (see Tactility/CMakeLists.txt).
|
||||
* FreeRTOS's POSIX port hands every task a stack carved from its own heap (pvPortMalloc) via this call.
|
||||
* pthread_attr_setstack requires page alignment that pvPortMalloc doesn't guarantee.
|
||||
* When it succeeds anyway, the task's real pthread stack ends up living inside that small FreeRTOS heap region,
|
||||
* where a thread doing heavier stack work (e.g. Mesa GL shader compilation) can silently corrupt adjacent heap_4 objects.
|
||||
* No-op'ing the call instead leaves every task's pthread_attr_t at its pthread_attr_init() default,
|
||||
* so pthread_create() gives it a real, properly sized stack.
|
||||
*
|
||||
* FreeRTOS's POSIX port (Libraries/FreeRTOS-Kernel/portable/ThirdParty/GCC/Posix/port.c)
|
||||
* hands every task a stack carved out of its own heap (pvPortMalloc) via this call.
|
||||
* pthread_attr_setstack requires page alignment, which pvPortMalloc doesn't guarantee;
|
||||
* when it happens to succeed anyway (allocator alignment can vary run to run), the
|
||||
* task's real pthread stack ends up living inside that small FreeRTOS heap region -
|
||||
* fine for typical embedded task code, but a desktop GL driver doing on-the-fly shader
|
||||
* compilation on that thread (e.g. Mesa on first frame present) can overflow it and
|
||||
* silently corrupt adjacent heap_4 objects.
|
||||
*
|
||||
* Wrapping the call out entirely (rather than patching the vendored port.c) leaves every
|
||||
* task's pthread_attr_t at its pthread_attr_init() default, so pthread_create() always
|
||||
* gives it a real, properly allocated default-size stack instead.
|
||||
* Linked via -Wl,--wrap=pthread_attr_setstack (this module's own CMakeLists.txt) on non-Apple
|
||||
* platforms; reused as a dyld interpose target below on Apple platforms, whose linker lacks --wrap.
|
||||
*/
|
||||
int __wrap_pthread_attr_setstack(pthread_attr_t* attr, void* stackaddr, size_t stacksize) {
|
||||
(void)attr;
|
||||
@@ -23,3 +18,17 @@ int __wrap_pthread_attr_setstack(pthread_attr_t* attr, void* stackaddr, size_t s
|
||||
(void)stacksize;
|
||||
return 0;
|
||||
}
|
||||
|
||||
#ifdef __APPLE__
|
||||
|
||||
// <mach-o/dyld-interposing.h> isn't a public SDK header (it ships with dyld's own source, not
|
||||
// Xcode/Command Line Tools), so this reimplements its DYLD_INTERPOSE macro locally.
|
||||
#define TT_DYLD_INTERPOSE(replacement, replacee) \
|
||||
__attribute__((used)) static struct { const void* replacement; const void* replacee; } \
|
||||
tt_interpose_##replacee __attribute__((section("__DATA,__interpose"))) = { \
|
||||
(const void*)(unsigned long)&(replacement), (const void*)(unsigned long)&(replacee) \
|
||||
};
|
||||
|
||||
TT_DYLD_INTERPOSE(__wrap_pthread_attr_setstack, pthread_attr_setstack)
|
||||
|
||||
#endif
|
||||
|
||||
@@ -185,31 +185,9 @@ else ()
|
||||
# Exports Tactility's own symbols (-rdynamic) so a dlopen()ed app-posix-module app can resolve
|
||||
# calls back into it - the OS-native equivalent of app-esp32-module's custom symbol resolver.
|
||||
set_target_properties(Tactility PROPERTIES ENABLE_EXPORTS ON)
|
||||
# Routes every pthread_attr_setstack() call (FreeRTOS's POSIX port hands each task a stack
|
||||
# carved out of its own heap through this) to __wrap_pthread_attr_setstack() in
|
||||
# Platforms/platform-posix/source/pthread_stack_wrap.c, which no-ops it - see that file for why.
|
||||
# --wrap is a GNU ld option; Apple's linker doesn't support it.
|
||||
if (NOT APPLE)
|
||||
target_link_options(Tactility PRIVATE "-Wl,--wrap=pthread_attr_setstack")
|
||||
# Routes every read()/write()/close() call to Tactility/Source/AppStdioWrap.cpp's
|
||||
# __wrap_read/write/close(), which forward into app_io_read/write/close() - the fd-table
|
||||
# dispatch that lets an app's own stdio (e.g. a fileselection dialog's printf'd result
|
||||
# path) reach an AppStream a parent bound via app_manager_start_with_streams(). Mirrors
|
||||
# what ESP-IDF's build already does for the ESP32 target (see top-level CMakeLists.txt).
|
||||
target_link_options(Tactility PRIVATE "-Wl,--wrap=read" "-Wl,--wrap=write" "-Wl,--wrap=close")
|
||||
# glibc's printf/fprintf/etc don't call the public write() symbol internally (they're
|
||||
# already compiled into libc.so, out of --wrap's reach), so the read/write/close wrap
|
||||
# above can't see them. Newlib (ESP-IDF) doesn't have this gap - its stdio does call the
|
||||
# wrappable syscall stubs - so this block is POSIX-only. Wrapping these symbols instead
|
||||
# redirects OUR OWN calls to them (the only ones --wrap can rewrite) through
|
||||
# AppStdioWrap.cpp's __wrap_* functions, which check the target stream (stdout/stdin) and
|
||||
# fall back to the real libc function for any other FILE*.
|
||||
target_link_options(Tactility PRIVATE
|
||||
"-Wl,--wrap=printf" "-Wl,--wrap=fprintf" "-Wl,--wrap=vprintf" "-Wl,--wrap=vfprintf"
|
||||
"-Wl,--wrap=puts" "-Wl,--wrap=fputs" "-Wl,--wrap=putchar" "-Wl,--wrap=fputc"
|
||||
"-Wl,--wrap=getchar" "-Wl,--wrap=fgetc" "-Wl,--wrap=fgets"
|
||||
)
|
||||
endif ()
|
||||
# pthread_attr_setstack and read/write/close/printf-family aren't wrapped here: linking
|
||||
# platform-posix and app-module already brings those wraps along (see their own
|
||||
# CMakeLists.txt files).
|
||||
endif ()
|
||||
|
||||
#
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
namespace tt::settings::display {
|
||||
enum class FontSize;
|
||||
}
|
||||
|
||||
namespace tt::lvgl {
|
||||
|
||||
#ifdef ESP_PLATFORM
|
||||
@@ -12,6 +16,9 @@ static constexpr auto* PATH_PREFIX = "A:/";
|
||||
|
||||
bool isStarted();
|
||||
|
||||
/** Applies the selected semantic text size to the LVGL theme and future widgets. */
|
||||
void applyFontSize(settings::display::FontSize fontSize);
|
||||
|
||||
void start();
|
||||
|
||||
void stop();
|
||||
|
||||
@@ -18,16 +18,34 @@ enum class ScreensaverType {
|
||||
Mystify,
|
||||
MatrixRain,
|
||||
StackChan,
|
||||
McpScreen,
|
||||
BibleVerse, // Launch the Bible Verse app (if installed)
|
||||
Count // Sentinel for bounds checking - must be last
|
||||
};
|
||||
|
||||
enum class FontSize {
|
||||
Small,
|
||||
Default,
|
||||
Large,
|
||||
Count
|
||||
};
|
||||
|
||||
struct DisplaySettings {
|
||||
Orientation orientation;
|
||||
FontSize fontSize = FontSize::Default;
|
||||
uint8_t gammaCurve;
|
||||
uint8_t backlightDuty;
|
||||
bool backlightTimeoutEnabled;
|
||||
uint32_t backlightTimeoutMs; // 0 = Never
|
||||
ScreensaverType screensaverType = ScreensaverType::BouncingBalls;
|
||||
// Night dim: when enabled and the local hour falls inside
|
||||
// [nightDimStartHour, nightDimEndHour), the screensaver runs at
|
||||
// nightDimDuty instead of backlightDuty. A start == end window
|
||||
// means the whole day.
|
||||
bool nightDimEnabled = false;
|
||||
uint8_t nightDimStartHour = 22;
|
||||
uint8_t nightDimEndHour = 7;
|
||||
uint8_t nightDimDuty = 20;
|
||||
};
|
||||
|
||||
/** Compares default settings with the function parameter to return the difference */
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
#pragma once
|
||||
|
||||
namespace tt::settings::mcp {
|
||||
|
||||
struct McpSettings {
|
||||
bool mcpEnabled = false; // Enable MCP server endpoints on system web server
|
||||
};
|
||||
|
||||
bool load(McpSettings& settings);
|
||||
McpSettings getDefault();
|
||||
McpSettings loadOrGetDefault();
|
||||
bool save(const McpSettings& settings);
|
||||
|
||||
} // namespace tt::settings::mcp
|
||||
@@ -6,7 +6,7 @@ namespace tt::settings {
|
||||
|
||||
struct SystemSettings {
|
||||
Language language = Language::en_US;
|
||||
bool timeFormat24h = true;
|
||||
bool timeFormat24h = false;
|
||||
std::string dateFormat = std::string("DD/MM/YYYY"); // MM/DD/YYYY, DD/MM/YYYY, YYYY-MM-DD, YYYY/MM/DD
|
||||
};
|
||||
|
||||
|
||||
@@ -7,5 +7,6 @@ namespace tt::app::files {
|
||||
bool isSupportedAppFile(const std::string& filename);
|
||||
bool isSupportedImageFile(const std::string& filename);
|
||||
bool isSupportedTextFile(const std::string& filename);
|
||||
bool isSupportedAudioFile(const std::string& filename);
|
||||
|
||||
} // namespace
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
#pragma once
|
||||
#ifdef ESP_PLATFORM
|
||||
|
||||
#include <lvgl.h>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <tactility/device.h>
|
||||
#include <tactility/drivers/audio_stream.h>
|
||||
|
||||
namespace tt::mcp {
|
||||
|
||||
struct McpSystemState {
|
||||
std::mutex mutex;
|
||||
bool overrideActive = false;
|
||||
|
||||
// UI elements when McpOverrideApp is active
|
||||
lv_obj_t* drawArea = nullptr;
|
||||
uint16_t* framebuffer = nullptr;
|
||||
size_t framebufferSize = 0;
|
||||
uint16_t displayWidth = 320;
|
||||
uint16_t displayHeight = 240;
|
||||
uint16_t drawWidth = 320;
|
||||
uint16_t drawHeight = 240;
|
||||
int drawColor = 1; // 0 = white, 1 = black
|
||||
|
||||
// Audio device status
|
||||
Device* i2sDevice = nullptr;
|
||||
Device* audioStreamDevice = nullptr;
|
||||
AudioStreamHandle audioHandle = nullptr;
|
||||
volatile bool audioBusy = false;
|
||||
volatile bool audioRunning = false; // Used to abort play/record loop
|
||||
|
||||
// Video streaming state
|
||||
volatile bool streamRunning = false;
|
||||
void* streamTaskHandle = nullptr; // use void* to avoid freertos header inclusion dependency
|
||||
uint32_t framesDrawn = 0;
|
||||
uint32_t tcpBytesReceived = 0;
|
||||
uint32_t lastDrawMs = 0;
|
||||
double lastFps = 0.0;
|
||||
};
|
||||
|
||||
McpSystemState& getState();
|
||||
|
||||
bool clearScreen(int color);
|
||||
bool drawText(const std::string& text, int x, int y, int size);
|
||||
bool drawRgb565(const uint8_t* data, size_t size, int x, int y, int w, int h);
|
||||
bool drawBmp(const uint8_t* data, size_t size, int x, int y);
|
||||
bool drawPbm(const uint8_t* data, size_t size, int x, int y);
|
||||
std::string getScreenshotPbmBase64();
|
||||
|
||||
bool playTone(int frequency, int durationMs, int volume, std::string& error);
|
||||
bool recordVoice(int durationSec, const std::string& filename, size_t& recordedBytes, std::string& error);
|
||||
bool playAudioFile(const std::string& filename, int volume, std::string& error);
|
||||
bool playWavMemory(const uint8_t* data, size_t size, int volume, std::string& error);
|
||||
bool playMp3File(const std::string& filename, int volume, std::string& error);
|
||||
bool playMp3Memory(const uint8_t* data, size_t size, int volume, std::string& error);
|
||||
|
||||
bool getBatteryStatus(double& voltage_v, int& percentage_pct, std::string& error);
|
||||
bool setLedColor(int r, int g, int b, const std::string& mode, std::string& error);
|
||||
bool getSensors(double& temp_c, double& hum_pct, std::string& imu_json, std::string& error);
|
||||
bool scanBleDevices(int duration_ms, std::string& devices_json, std::string& error);
|
||||
bool writeSdFile(const std::string& filename, const std::string& content, std::string& error);
|
||||
bool readSdFile(const std::string& filename, std::string& content, std::string& error);
|
||||
bool downloadSdFile(const std::string& url, const std::string& filename, std::string& error);
|
||||
|
||||
bool startVideoStreamServer();
|
||||
void stopVideoStreamServer();
|
||||
bool getVideoStreamStats(std::string& stats_json);
|
||||
|
||||
bool listApps(std::string& apps_json, std::string& error);
|
||||
bool runApp(const std::string& appId, std::string& error);
|
||||
bool listSdFiles(const std::string& directory, std::string& files_json, std::string& error);
|
||||
|
||||
} // namespace tt::mcp
|
||||
|
||||
#endif
|
||||
File diff suppressed because it is too large
Load Diff
@@ -5,6 +5,8 @@
|
||||
#include <Tactility/settings/DisplaySettings.h>
|
||||
#include <Tactility/Timer.h>
|
||||
|
||||
#include <app/instance.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
|
||||
@@ -29,9 +31,15 @@ class DisplayIdleService final : public Service {
|
||||
// Active screensaver instance
|
||||
std::unique_ptr<Screensaver> screensaver;
|
||||
|
||||
// Screensaver auto-off: turn off backlight after 5 minutes of screensaver
|
||||
// App launched as screensaver (Bible Verse): instance id, 0 when none.
|
||||
// A separate flag (not just the id) tracks intent, so a user-closed app
|
||||
// doesn't look like an active screensaver and vice versa.
|
||||
AppInstanceId screensaverAppInstanceId = 0;
|
||||
bool screensaverAppActive = false;
|
||||
|
||||
// Screensaver auto-off: turn off backlight after 30 minutes of screensaver
|
||||
static constexpr uint32_t TICK_INTERVAL_MS = 50;
|
||||
static constexpr uint32_t SCREENSAVER_AUTO_OFF_MS = 5 * 60 * 1000; // 5 minutes
|
||||
static constexpr uint32_t SCREENSAVER_AUTO_OFF_MS = 30 * 60 * 1000; // 30 minutes
|
||||
static constexpr int SCREENSAVER_AUTO_OFF_TICKS = SCREENSAVER_AUTO_OFF_MS / TICK_INTERVAL_MS;
|
||||
int screensaverActiveCounter = 0;
|
||||
bool backlightOff = false;
|
||||
@@ -63,6 +71,7 @@ public:
|
||||
* arbitrary threads while the timer is running.
|
||||
*/
|
||||
void stopScreensaver();
|
||||
void startMcpScreensaver();
|
||||
|
||||
/**
|
||||
* Check if the screensaver is currently active.
|
||||
|
||||
@@ -81,6 +81,12 @@ private:
|
||||
static error_t handleApiAppsInstall(struct HttpServerRequest* request, void* user_ctx);
|
||||
static error_t handleApiWifi(struct HttpServerRequest* request, void* user_ctx);
|
||||
static error_t handleApiScreenshot(struct HttpServerRequest* request, void* user_ctx);
|
||||
static error_t handleApiSimTouch(struct HttpServerRequest* request, void* user_ctx);
|
||||
static error_t handleSimViewer(struct HttpServerRequest* request, void* user_ctx);
|
||||
static error_t handleApiMcp(struct HttpServerRequest* request, void* user_ctx);
|
||||
#ifdef ESP_PLATFORM
|
||||
static error_t handleApiScreenRaw(struct HttpServerRequest* request, void* user_ctx);
|
||||
#endif
|
||||
|
||||
// Dynamic asset serving
|
||||
static error_t handleAssets(struct HttpServerRequest* request, void* user_ctx);
|
||||
|
||||
@@ -1,200 +0,0 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Paired with -Wl,--wrap=read/write/close - see Tactility/CMakeLists.txt (POSIX) and the
|
||||
// top-level CMakeLists.txt (ESP32) for where that's applied. On a platform where it isn't
|
||||
// (currently: macOS, whose linker doesn't support --wrap), these are simply never called - real
|
||||
// read()/write()/close() calls go straight through unredirected.
|
||||
#include <app/io.h>
|
||||
|
||||
#include <sys/types.h>
|
||||
|
||||
extern "C" {
|
||||
|
||||
ssize_t __wrap_read(int fd, void* buffer, size_t size) {
|
||||
return app_io_read(fd, buffer, size);
|
||||
}
|
||||
|
||||
ssize_t __wrap_write(int fd, const void* buffer, size_t size) {
|
||||
return app_io_write(fd, buffer, size);
|
||||
}
|
||||
|
||||
int __wrap_close(int fd) {
|
||||
return app_io_close(fd);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// region glibc stdio wraps
|
||||
//
|
||||
// glibc's printf/fprintf/etc are compiled into libc.so and call an internal, non-exported write()
|
||||
// alias - --wrap=write (above) can't reach that call, only calls WE make to the public symbol.
|
||||
// These wraps instead redirect calls WE make to printf/fprintf/etc, the same trick as read/write/
|
||||
// close above. Newlib (ESP-IDF) doesn't have this gap - its stdio does call the wrappable syscall
|
||||
// stubs - so Tactility/CMakeLists.txt only applies the matching -Wl,--wrap= flags on POSIX.
|
||||
//
|
||||
// Scoped to the printf/getc families only: fread/fwrite take an arbitrary FILE* and are already
|
||||
// used sitewide for real file I/O (e.g. File.cpp's readBinaryInternal), so wrapping them would
|
||||
// route every such call through this file's stdin/stdout check - a correctness risk for unrelated
|
||||
// code that isn't worth taking here. putc/getc are excluded too since glibc defines them as
|
||||
// macros, not real calls, so wrapping those symbols wouldn't reliably intercept them.
|
||||
|
||||
#if !defined(ESP_PLATFORM) && !defined(__APPLE__)
|
||||
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#include <unistd.h>
|
||||
|
||||
extern "C" {
|
||||
int __real_vfprintf(FILE* stream, const char* format, va_list args);
|
||||
int __real_fputs(const char* s, FILE* stream);
|
||||
int __real_fputc(int c, FILE* stream);
|
||||
int __real_fgetc(FILE* stream);
|
||||
char* __real_fgets(char* buffer, int size, FILE* stream);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
void writeAllToStdout(const void* data, size_t size) {
|
||||
const auto* bytes = static_cast<const char*>(data);
|
||||
size_t remaining = size;
|
||||
while (remaining > 0) {
|
||||
ssize_t written = app_io_write(STDOUT_FILENO, bytes, remaining);
|
||||
if (written <= 0) {
|
||||
break;
|
||||
}
|
||||
bytes += written;
|
||||
remaining -= static_cast<size_t>(written);
|
||||
}
|
||||
}
|
||||
|
||||
// Formats into stdout via app_io_write() rather than through a FILE*'s own buffering, since that
|
||||
// buffering is exactly what glibc's internal write() call sidesteps --wrap for in the first place.
|
||||
int formatToStdout(const char* format, va_list args) {
|
||||
char stackBuffer[256];
|
||||
va_list argsForStack;
|
||||
va_copy(argsForStack, args);
|
||||
int needed = vsnprintf(stackBuffer, sizeof(stackBuffer), format, argsForStack);
|
||||
va_end(argsForStack);
|
||||
if (needed < 0) {
|
||||
return needed;
|
||||
}
|
||||
if (static_cast<size_t>(needed) < sizeof(stackBuffer)) {
|
||||
writeAllToStdout(stackBuffer, static_cast<size_t>(needed));
|
||||
return needed;
|
||||
}
|
||||
auto heapBuffer = std::make_unique<char[]>(static_cast<size_t>(needed) + 1);
|
||||
va_list argsForHeap;
|
||||
va_copy(argsForHeap, args);
|
||||
vsnprintf(heapBuffer.get(), static_cast<size_t>(needed) + 1, format, argsForHeap);
|
||||
va_end(argsForHeap);
|
||||
writeAllToStdout(heapBuffer.get(), static_cast<size_t>(needed));
|
||||
return needed;
|
||||
}
|
||||
|
||||
int readOneFromStdin(char& out) {
|
||||
return static_cast<int>(app_io_read(STDIN_FILENO, &out, 1));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
int __wrap_vprintf(const char* format, va_list args) {
|
||||
return formatToStdout(format, args);
|
||||
}
|
||||
|
||||
int __wrap_printf(const char* format, ...) {
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
int result = formatToStdout(format, args);
|
||||
va_end(args);
|
||||
return result;
|
||||
}
|
||||
|
||||
int __wrap_vfprintf(FILE* stream, const char* format, va_list args) {
|
||||
if (stream == stdout) {
|
||||
return formatToStdout(format, args);
|
||||
}
|
||||
return __real_vfprintf(stream, format, args);
|
||||
}
|
||||
|
||||
int __wrap_fprintf(FILE* stream, const char* format, ...) {
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
int result = (stream == stdout) ? formatToStdout(format, args) : __real_vfprintf(stream, format, args);
|
||||
va_end(args);
|
||||
return result;
|
||||
}
|
||||
|
||||
int __wrap_puts(const char* s) {
|
||||
writeAllToStdout(s, strlen(s));
|
||||
writeAllToStdout("\n", 1);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int __wrap_fputs(const char* s, FILE* stream) {
|
||||
if (stream == stdout) {
|
||||
writeAllToStdout(s, strlen(s));
|
||||
return 0;
|
||||
}
|
||||
return __real_fputs(s, stream);
|
||||
}
|
||||
|
||||
int __wrap_putchar(int c) {
|
||||
auto ch = static_cast<char>(c);
|
||||
writeAllToStdout(&ch, 1);
|
||||
return c;
|
||||
}
|
||||
|
||||
int __wrap_fputc(int c, FILE* stream) {
|
||||
if (stream == stdout) {
|
||||
return __wrap_putchar(c);
|
||||
}
|
||||
return __real_fputc(c, stream);
|
||||
}
|
||||
|
||||
int __wrap_getchar() {
|
||||
char c;
|
||||
return readOneFromStdin(c) == 1 ? static_cast<unsigned char>(c) : EOF;
|
||||
}
|
||||
|
||||
int __wrap_fgetc(FILE* stream) {
|
||||
if (stream == stdin) {
|
||||
return __wrap_getchar();
|
||||
}
|
||||
return __real_fgetc(stream);
|
||||
}
|
||||
|
||||
char* __wrap_fgets(char* buffer, int size, FILE* stream) {
|
||||
if (stream != stdin) {
|
||||
return __real_fgets(buffer, size, stream);
|
||||
}
|
||||
if (size <= 0) {
|
||||
return nullptr;
|
||||
}
|
||||
int i = 0;
|
||||
for (; i < size - 1; ++i) {
|
||||
char c;
|
||||
if (readOneFromStdin(c) != 1) {
|
||||
break;
|
||||
}
|
||||
buffer[i] = c;
|
||||
if (c == '\n') {
|
||||
++i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (i == 0) {
|
||||
return nullptr;
|
||||
}
|
||||
buffer[i] = '\0';
|
||||
return buffer;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#endif // !ESP_PLATFORM && !__APPLE__
|
||||
|
||||
// endregion
|
||||
@@ -40,6 +40,7 @@
|
||||
#include <Tactility/file/File.h>
|
||||
#include <Tactility/hal/SdCard.h>
|
||||
#include <Tactility/lvgl/KeyboardDeviceListener.h>
|
||||
#include <Tactility/lvgl/Lvgl.h>
|
||||
#include <Tactility/lvgl/Statusbar.h>
|
||||
#include <Tactility/lvgl/TrackballInit.h>
|
||||
#include <Tactility/lvgl/UsbHidInput.h>
|
||||
@@ -189,9 +190,12 @@ namespace app {
|
||||
#ifdef ESP_PLATFORM
|
||||
namespace apwebserver { extern const ::AppManifest manifest; }
|
||||
namespace crashdiagnostics { extern const ::AppManifest manifest; }
|
||||
namespace mcpsettings { extern const ::AppManifest manifest; }
|
||||
#if CONFIG_TT_TDECK_WORKAROUND == 1
|
||||
namespace keyboardsettings { extern const ::AppManifest manifest; } // T-Deck only for now
|
||||
#endif
|
||||
#else
|
||||
namespace mcpsettings { extern const ::AppManifest manifest; }
|
||||
#endif
|
||||
|
||||
namespace trackballsettings { extern const ::AppManifest manifest; } // T-Deck only for now
|
||||
@@ -250,11 +254,14 @@ static void registerInternalApps() {
|
||||
app_manager_add(&app::development::manifest);
|
||||
app_manager_add(&app::webserversettings::manifest);
|
||||
#ifdef ESP_PLATFORM
|
||||
app_manager_add(&app::mcpsettings::manifest);
|
||||
app_manager_add(&app::apwebserver::manifest);
|
||||
app_manager_add(&app::crashdiagnostics::manifest);
|
||||
#if defined(CONFIG_TT_TDECK_WORKAROUND)
|
||||
app_manager_add(&app::keyboardsettings::manifest);
|
||||
#endif
|
||||
#else
|
||||
app_manager_add(&app::mcpsettings::manifest);
|
||||
#endif
|
||||
|
||||
if (device_exists_of_type(&TRACKBALL_TYPE)) {
|
||||
@@ -433,6 +440,7 @@ static void onLvglStarted() {
|
||||
if (auto* display = lv_display_get_default(); display != nullptr) {
|
||||
auto displaySettings = settings::display::loadOrGetDefault();
|
||||
lv_display_set_rotation(display, settings::display::toLvglDisplayRotation(displaySettings.orientation));
|
||||
lvgl::applyFontSize(displaySettings.fontSize);
|
||||
}
|
||||
lvgl_unlock();
|
||||
|
||||
|
||||
@@ -107,6 +107,9 @@ void showNoInternet(Context* ctx) {
|
||||
}
|
||||
|
||||
void showApps(Context* ctx) {
|
||||
if (ctx->contentWrapper == nullptr) {
|
||||
return;
|
||||
}
|
||||
// Refresh rebuilds the list from scratch (cached copy, then again once the network fetch
|
||||
// lands), which would otherwise reset the user's scroll position each time.
|
||||
int32_t scrollY;
|
||||
@@ -266,7 +269,9 @@ void createWidgets(lv_obj_t* parent, void* userData) {
|
||||
|
||||
void destroyWidgets(void* userData) {
|
||||
auto* ctx = static_cast<Context*>(userData);
|
||||
ctx->scrollY = lv_obj_get_scroll_y(ctx->contentWrapper);
|
||||
if (ctx->contentWrapper != nullptr) {
|
||||
ctx->scrollY = lv_obj_get_scroll_y(ctx->contentWrapper);
|
||||
}
|
||||
ctx->contentWrapper = nullptr;
|
||||
ctx->refreshButton = nullptr;
|
||||
}
|
||||
@@ -334,7 +339,8 @@ extern const ::AppManifest manifest = {
|
||||
.id = "tactility.apphub",
|
||||
.name = "App Hub",
|
||||
.category = APP_CATEGORY_SYSTEM,
|
||||
.location = {APP_LOCATION_MEMORY, reinterpret_cast<void*>(appMain)}
|
||||
.location = {APP_LOCATION_MEMORY, reinterpret_cast<void*>(appMain)},
|
||||
.flags = APP_MANIFEST_FLAG_HIDDEN
|
||||
};
|
||||
|
||||
} // namespace tt::app::apphub
|
||||
|
||||
@@ -121,7 +121,7 @@ extern const ::AppManifest manifest = {
|
||||
.category = APP_CATEGORY_SYSTEM,
|
||||
.location = { .type = APP_LOCATION_MEMORY, .location = reinterpret_cast<void*>(appMain) },
|
||||
.flags = APP_MANIFEST_FLAG_HIDDEN,
|
||||
.stack = { .depth = 2400, .desired_memory_capability = 0 },
|
||||
.stack = { .depth = 3072, .desired_memory_capability = 0 },
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
@@ -245,7 +245,8 @@ extern const ::AppManifest manifest = {
|
||||
.id = "tactility.btmanage",
|
||||
.name = "Bluetooth",
|
||||
.category = APP_CATEGORY_SETTINGS,
|
||||
.location = { APP_LOCATION_MEMORY, reinterpret_cast<void*>(appMain) }
|
||||
.location = { APP_LOCATION_MEMORY, reinterpret_cast<void*>(appMain) },
|
||||
.flags = APP_MANIFEST_FLAG_HIDDEN
|
||||
};
|
||||
|
||||
} // namespace tt::app::btmanage
|
||||
|
||||
@@ -228,7 +228,8 @@ extern const ::AppManifest manifest = {
|
||||
.id = "tactility.chat",
|
||||
.name = "Chat",
|
||||
.category = APP_CATEGORY_USER,
|
||||
.location = { APP_LOCATION_MEMORY, reinterpret_cast<void*>(appMain) }
|
||||
.location = { APP_LOCATION_MEMORY, reinterpret_cast<void*>(appMain) },
|
||||
.flags = APP_MANIFEST_FLAG_HIDDEN
|
||||
};
|
||||
|
||||
} // namespace tt::app::chat
|
||||
|
||||
@@ -230,7 +230,8 @@ extern const ::AppManifest manifest = {
|
||||
.id = "tactility.development",
|
||||
.name = "Development",
|
||||
.category = APP_CATEGORY_SETTINGS,
|
||||
.location = { APP_LOCATION_MEMORY, reinterpret_cast<void*>(appMain) }
|
||||
.location = { APP_LOCATION_MEMORY, reinterpret_cast<void*>(appMain) },
|
||||
.flags = APP_MANIFEST_FLAG_HIDDEN
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
#ifdef ESP_PLATFORM
|
||||
#include <Tactility/service/displayidle/DisplayIdleService.h>
|
||||
#endif
|
||||
#include <Tactility/lvgl/Lvgl.h>
|
||||
#include <Tactility/settings/DisplaySettings.h>
|
||||
|
||||
#include <app/event.h>
|
||||
@@ -41,6 +42,10 @@ struct Context {
|
||||
lv_obj_t* timeoutSwitch = nullptr;
|
||||
lv_obj_t* timeoutDropdown = nullptr;
|
||||
lv_obj_t* screensaverDropdown = nullptr;
|
||||
lv_obj_t* nightDimSwitch = nullptr;
|
||||
lv_obj_t* nightDimStartDropdown = nullptr;
|
||||
lv_obj_t* nightDimEndDropdown = nullptr;
|
||||
lv_obj_t* nightDimDutySlider = nullptr;
|
||||
};
|
||||
|
||||
|
||||
@@ -90,6 +95,21 @@ void onOrientationSet(lv_event_t* event) {
|
||||
}
|
||||
}
|
||||
|
||||
void onFontSizeChanged(lv_event_t* event) {
|
||||
auto* ctx = static_cast<Context*>(lv_event_get_user_data(event));
|
||||
auto* dropdown = static_cast<lv_obj_t*>(lv_event_get_target(event));
|
||||
uint32_t selected_index = lv_dropdown_get_selected(dropdown);
|
||||
if (selected_index >= static_cast<uint32_t>(settings::display::FontSize::Count)) {
|
||||
return;
|
||||
}
|
||||
auto selected_size = static_cast<settings::display::FontSize>(selected_index);
|
||||
if (selected_size != ctx->displaySettings.fontSize) {
|
||||
ctx->displaySettings.fontSize = selected_size;
|
||||
ctx->displaySettingsUpdated = true;
|
||||
lvgl::applyFontSize(selected_size);
|
||||
}
|
||||
}
|
||||
|
||||
void onTimeoutSwitch(lv_event_t* event) {
|
||||
auto* ctx = static_cast<Context*>(lv_event_get_user_data(event));
|
||||
auto* sw = static_cast<lv_obj_t*>(lv_event_get_target(event));
|
||||
@@ -115,8 +135,8 @@ void onTimeoutChanged(lv_event_t* event) {
|
||||
auto* ctx = static_cast<Context*>(lv_event_get_user_data(event));
|
||||
auto* dropdown = static_cast<lv_obj_t*>(lv_event_get_target(event));
|
||||
uint32_t idx = lv_dropdown_get_selected(dropdown);
|
||||
// Map dropdown index to ms: 0=15s,1=30s,2=1m,3=2m,4=5m,5=Never
|
||||
static const uint32_t values_ms[] = {15000, 30000, 60000, 120000, 300000, 0};
|
||||
// Map dropdown index to ms: 0=15s,1=30s,2=1m,3=2m,4=5m,5=15m,6=30m,7=Never
|
||||
static const uint32_t values_ms[] = {15000, 30000, 60000, 120000, 300000, 900000, 1800000, 0};
|
||||
if (idx < (sizeof(values_ms)/sizeof(values_ms[0]))) {
|
||||
ctx->displaySettings.backlightTimeoutMs = values_ms[idx];
|
||||
ctx->displaySettingsUpdated = true;
|
||||
@@ -138,6 +158,82 @@ void onScreensaverChanged(lv_event_t* event) {
|
||||
}
|
||||
}
|
||||
|
||||
static void setNightDimControlsEnabled(Context* ctx, bool enabled) {
|
||||
if (ctx->nightDimStartDropdown != nullptr) {
|
||||
if (enabled) {
|
||||
lv_obj_clear_state(ctx->nightDimStartDropdown, LV_STATE_DISABLED);
|
||||
} else {
|
||||
lv_obj_add_state(ctx->nightDimStartDropdown, LV_STATE_DISABLED);
|
||||
}
|
||||
}
|
||||
if (ctx->nightDimEndDropdown != nullptr) {
|
||||
if (enabled) {
|
||||
lv_obj_clear_state(ctx->nightDimEndDropdown, LV_STATE_DISABLED);
|
||||
} else {
|
||||
lv_obj_add_state(ctx->nightDimEndDropdown, LV_STATE_DISABLED);
|
||||
}
|
||||
}
|
||||
if (ctx->nightDimDutySlider != nullptr) {
|
||||
if (enabled) {
|
||||
lv_obj_clear_state(ctx->nightDimDutySlider, LV_STATE_DISABLED);
|
||||
} else {
|
||||
lv_obj_add_state(ctx->nightDimDutySlider, LV_STATE_DISABLED);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static const char* hourOptions() {
|
||||
// 00..23, one per line
|
||||
static const char* options =
|
||||
"00\n01\n02\n03\n04\n05\n06\n07\n08\n09\n10\n11\n"
|
||||
"12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23";
|
||||
return options;
|
||||
}
|
||||
|
||||
void onNightDimSwitch(lv_event_t* event) {
|
||||
auto* ctx = static_cast<Context*>(lv_event_get_user_data(event));
|
||||
auto* sw = static_cast<lv_obj_t*>(lv_event_get_target(event));
|
||||
bool enabled = lv_obj_has_state(sw, LV_STATE_CHECKED);
|
||||
ctx->displaySettings.nightDimEnabled = enabled;
|
||||
ctx->displaySettingsUpdated = true;
|
||||
setNightDimControlsEnabled(ctx, enabled);
|
||||
}
|
||||
|
||||
void onNightDimStartChanged(lv_event_t* event) {
|
||||
auto* ctx = static_cast<Context*>(lv_event_get_user_data(event));
|
||||
auto* dropdown = static_cast<lv_obj_t*>(lv_event_get_target(event));
|
||||
uint32_t idx = lv_dropdown_get_selected(dropdown);
|
||||
if (idx > 23) {
|
||||
return;
|
||||
}
|
||||
ctx->displaySettings.nightDimStartHour = static_cast<uint8_t>(idx);
|
||||
ctx->displaySettingsUpdated = true;
|
||||
}
|
||||
|
||||
void onNightDimEndChanged(lv_event_t* event) {
|
||||
auto* ctx = static_cast<Context*>(lv_event_get_user_data(event));
|
||||
auto* dropdown = static_cast<lv_obj_t*>(lv_event_get_target(event));
|
||||
uint32_t idx = lv_dropdown_get_selected(dropdown);
|
||||
if (idx > 23) {
|
||||
return;
|
||||
}
|
||||
ctx->displaySettings.nightDimEndHour = static_cast<uint8_t>(idx);
|
||||
ctx->displaySettingsUpdated = true;
|
||||
}
|
||||
|
||||
void onNightDimDutyChanged(lv_event_t* event) {
|
||||
auto* ctx = static_cast<Context*>(lv_event_get_user_data(event));
|
||||
auto* slider = static_cast<lv_obj_t*>(lv_event_get_target(event));
|
||||
int32_t value = lv_slider_get_value(slider);
|
||||
if (value < 0) {
|
||||
value = 0;
|
||||
} else if (value > 255) {
|
||||
value = 255;
|
||||
}
|
||||
ctx->displaySettings.nightDimDuty = static_cast<uint8_t>(value);
|
||||
ctx->displaySettingsUpdated = true;
|
||||
}
|
||||
|
||||
void createWidgets(lv_obj_t* parent, void* userData) {
|
||||
auto* ctx = static_cast<Context*>(userData);
|
||||
|
||||
@@ -208,6 +304,23 @@ void createWidgets(lv_obj_t* parent, void* userData) {
|
||||
// Set the dropdown to match current orientation enum
|
||||
lv_dropdown_set_selected(orientation_dropdown, static_cast<uint16_t>(ctx->displaySettings.orientation));
|
||||
|
||||
// Font size
|
||||
|
||||
auto* font_size_wrapper = lv_obj_create(main_wrapper);
|
||||
lv_obj_set_size(font_size_wrapper, LV_PCT(100), LV_SIZE_CONTENT);
|
||||
lv_obj_set_style_pad_all(font_size_wrapper, 0, LV_STATE_DEFAULT);
|
||||
lv_obj_set_style_border_width(font_size_wrapper, 0, LV_STATE_DEFAULT);
|
||||
|
||||
auto* font_size_label = lv_label_create(font_size_wrapper);
|
||||
lv_label_set_text(font_size_label, "Font size");
|
||||
lv_obj_align(font_size_label, LV_ALIGN_LEFT_MID, 0, 0);
|
||||
|
||||
auto* font_size_dropdown = lv_dropdown_create(font_size_wrapper);
|
||||
lv_dropdown_set_options(font_size_dropdown, "Small\nDefault\nLarge");
|
||||
lv_obj_align(font_size_dropdown, LV_ALIGN_RIGHT_MID, 0, 0);
|
||||
lv_obj_add_event_cb(font_size_dropdown, onFontSizeChanged, LV_EVENT_VALUE_CHANGED, ctx);
|
||||
lv_dropdown_set_selected(font_size_dropdown, static_cast<uint16_t>(ctx->displaySettings.fontSize));
|
||||
|
||||
// Screen timeout
|
||||
// Note: DisplayIdleService doesn't act on these settings for kernel-driver displays yet
|
||||
// (it only looks up the deprecated tt::hal::display::DisplayDevice), so these currently
|
||||
@@ -240,7 +353,7 @@ void createWidgets(lv_obj_t* parent, void* userData) {
|
||||
lv_obj_align(timeout_value_label, LV_ALIGN_LEFT_MID, 0, 0);
|
||||
|
||||
ctx->timeoutDropdown = lv_dropdown_create(timeout_select_wrapper);
|
||||
lv_dropdown_set_options(ctx->timeoutDropdown, "15 seconds\n30 seconds\n1 minute\n2 minutes\n5 minutes\nNever");
|
||||
lv_dropdown_set_options(ctx->timeoutDropdown, "15 seconds\n30 seconds\n1 minute\n2 minutes\n5 minutes\n15 minutes\n30 minutes\nNever");
|
||||
lv_obj_align(ctx->timeoutDropdown, LV_ALIGN_RIGHT_MID, 0, 0);
|
||||
lv_obj_add_event_cb(ctx->timeoutDropdown, onTimeoutChanged, LV_EVENT_VALUE_CHANGED, ctx);
|
||||
// Initialize dropdown selection from settings
|
||||
@@ -255,8 +368,12 @@ void createWidgets(lv_obj_t* parent, void* userData) {
|
||||
idx = 3;
|
||||
else if (ms == 300000)
|
||||
idx = 4;
|
||||
else if (ms == 0)
|
||||
else if (ms == 900000)
|
||||
idx = 5;
|
||||
else if (ms == 1800000)
|
||||
idx = 6;
|
||||
else if (ms == 0)
|
||||
idx = 7;
|
||||
lv_dropdown_set_selected(ctx->timeoutDropdown, idx);
|
||||
if (!ctx->displaySettings.backlightTimeoutEnabled) {
|
||||
lv_obj_add_state(ctx->timeoutDropdown, LV_STATE_DISABLED);
|
||||
@@ -274,13 +391,78 @@ void createWidgets(lv_obj_t* parent, void* userData) {
|
||||
|
||||
ctx->screensaverDropdown = lv_dropdown_create(screensaver_wrapper);
|
||||
// Note: order correlates with settings::display::ScreensaverType enum order
|
||||
lv_dropdown_set_options(ctx->screensaverDropdown, "None\nBouncing Balls\nMystify\nMatrix Rain\nStackChan");
|
||||
lv_dropdown_set_options(ctx->screensaverDropdown, "None\nBouncing Balls\nMystify\nMatrix Rain\nStackChan\nMCP Screen\nBible Verse");
|
||||
lv_obj_align(ctx->screensaverDropdown, LV_ALIGN_RIGHT_MID, 0, 0);
|
||||
lv_obj_add_event_cb(ctx->screensaverDropdown, onScreensaverChanged, LV_EVENT_VALUE_CHANGED, ctx);
|
||||
lv_dropdown_set_selected(ctx->screensaverDropdown, static_cast<uint16_t>(ctx->displaySettings.screensaverType));
|
||||
if (!ctx->displaySettings.backlightTimeoutEnabled) {
|
||||
lv_obj_add_state(ctx->screensaverDropdown, LV_STATE_DISABLED);
|
||||
}
|
||||
|
||||
// Night dim: dim the backlight while the screensaver is up, during a time window
|
||||
auto* night_dim_wrapper = lv_obj_create(main_wrapper);
|
||||
lv_obj_set_size(night_dim_wrapper, LV_PCT(100), LV_SIZE_CONTENT);
|
||||
lv_obj_set_style_pad_all(night_dim_wrapper, 0, LV_STATE_DEFAULT);
|
||||
lv_obj_set_style_border_width(night_dim_wrapper, 0, LV_STATE_DEFAULT);
|
||||
|
||||
auto* night_dim_label = lv_label_create(night_dim_wrapper);
|
||||
lv_label_set_text(night_dim_label, "Night dim");
|
||||
lv_obj_align(night_dim_label, LV_ALIGN_LEFT_MID, 0, 0);
|
||||
|
||||
ctx->nightDimSwitch = lv_switch_create(night_dim_wrapper);
|
||||
if (ctx->displaySettings.nightDimEnabled) {
|
||||
lv_obj_add_state(ctx->nightDimSwitch, LV_STATE_CHECKED);
|
||||
}
|
||||
lv_obj_align(ctx->nightDimSwitch, LV_ALIGN_RIGHT_MID, 0, 0);
|
||||
lv_obj_add_event_cb(ctx->nightDimSwitch, onNightDimSwitch, LV_EVENT_VALUE_CHANGED, ctx);
|
||||
|
||||
auto* night_dim_start_wrapper = lv_obj_create(main_wrapper);
|
||||
lv_obj_set_size(night_dim_start_wrapper, LV_PCT(100), LV_SIZE_CONTENT);
|
||||
lv_obj_set_style_pad_all(night_dim_start_wrapper, 0, LV_STATE_DEFAULT);
|
||||
lv_obj_set_style_border_width(night_dim_start_wrapper, 0, LV_STATE_DEFAULT);
|
||||
|
||||
auto* night_dim_start_label = lv_label_create(night_dim_start_wrapper);
|
||||
lv_label_set_text(night_dim_start_label, "Dim from");
|
||||
lv_obj_align(night_dim_start_label, LV_ALIGN_LEFT_MID, 0, 0);
|
||||
|
||||
ctx->nightDimStartDropdown = lv_dropdown_create(night_dim_start_wrapper);
|
||||
lv_dropdown_set_options(ctx->nightDimStartDropdown, hourOptions());
|
||||
lv_obj_align(ctx->nightDimStartDropdown, LV_ALIGN_RIGHT_MID, 0, 0);
|
||||
lv_obj_add_event_cb(ctx->nightDimStartDropdown, onNightDimStartChanged, LV_EVENT_VALUE_CHANGED, ctx);
|
||||
lv_dropdown_set_selected(ctx->nightDimStartDropdown, ctx->displaySettings.nightDimStartHour > 23 ? 0 : ctx->displaySettings.nightDimStartHour);
|
||||
|
||||
auto* night_dim_end_wrapper = lv_obj_create(main_wrapper);
|
||||
lv_obj_set_size(night_dim_end_wrapper, LV_PCT(100), LV_SIZE_CONTENT);
|
||||
lv_obj_set_style_pad_all(night_dim_end_wrapper, 0, LV_STATE_DEFAULT);
|
||||
lv_obj_set_style_border_width(night_dim_end_wrapper, 0, LV_STATE_DEFAULT);
|
||||
|
||||
auto* night_dim_end_label = lv_label_create(night_dim_end_wrapper);
|
||||
lv_label_set_text(night_dim_end_label, "Dim until");
|
||||
lv_obj_align(night_dim_end_label, LV_ALIGN_LEFT_MID, 0, 0);
|
||||
|
||||
ctx->nightDimEndDropdown = lv_dropdown_create(night_dim_end_wrapper);
|
||||
lv_dropdown_set_options(ctx->nightDimEndDropdown, hourOptions());
|
||||
lv_obj_align(ctx->nightDimEndDropdown, LV_ALIGN_RIGHT_MID, 0, 0);
|
||||
lv_obj_add_event_cb(ctx->nightDimEndDropdown, onNightDimEndChanged, LV_EVENT_VALUE_CHANGED, ctx);
|
||||
lv_dropdown_set_selected(ctx->nightDimEndDropdown, ctx->displaySettings.nightDimEndHour > 23 ? 0 : ctx->displaySettings.nightDimEndHour);
|
||||
|
||||
auto* night_dim_duty_wrapper = lv_obj_create(main_wrapper);
|
||||
lv_obj_set_size(night_dim_duty_wrapper, LV_PCT(100), LV_SIZE_CONTENT);
|
||||
lv_obj_set_style_pad_all(night_dim_duty_wrapper, 0, LV_STATE_DEFAULT);
|
||||
lv_obj_set_style_border_width(night_dim_duty_wrapper, 0, LV_STATE_DEFAULT);
|
||||
|
||||
auto* night_dim_duty_label = lv_label_create(night_dim_duty_wrapper);
|
||||
lv_label_set_text(night_dim_duty_label, "Dim brightness");
|
||||
lv_obj_align(night_dim_duty_label, LV_ALIGN_LEFT_MID, 0, 0);
|
||||
|
||||
ctx->nightDimDutySlider = lv_slider_create(night_dim_duty_wrapper);
|
||||
lv_obj_set_width(ctx->nightDimDutySlider, LV_PCT(50));
|
||||
lv_obj_align(ctx->nightDimDutySlider, LV_ALIGN_RIGHT_MID, 0, 0);
|
||||
lv_slider_set_range(ctx->nightDimDutySlider, 0, 255);
|
||||
lv_slider_set_value(ctx->nightDimDutySlider, ctx->displaySettings.nightDimDuty, LV_ANIM_OFF);
|
||||
lv_obj_add_event_cb(ctx->nightDimDutySlider, onNightDimDutyChanged, LV_EVENT_VALUE_CHANGED, ctx);
|
||||
|
||||
setNightDimControlsEnabled(ctx, ctx->displaySettings.nightDimEnabled);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -26,4 +26,12 @@ bool isSupportedTextFile(const std::string& filename) {
|
||||
filename_lower.ends_with(".properties");
|
||||
}
|
||||
|
||||
bool isSupportedAudioFile(const std::string& filename) {
|
||||
std::string filename_lower = string::lowercase(filename);
|
||||
return filename_lower.ends_with(".mp3") ||
|
||||
filename_lower.ends_with(".wav") ||
|
||||
filename_lower.ends_with(".ogg") ||
|
||||
filename_lower.ends_with(".flac");
|
||||
}
|
||||
|
||||
} // namespace tt::app::filebrowser
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#include <app/event.h>
|
||||
#include <app/execute.h>
|
||||
#include <app/install.h>
|
||||
#include <app/start.h>
|
||||
#include <app/stream.h>
|
||||
|
||||
#include <lvgl/lvgl.h>
|
||||
@@ -204,6 +205,15 @@ void View::viewFile(const std::string& path, const std::string& filename) {
|
||||
// Remove forward slash, because we need a relative path
|
||||
notes::start(file_path.substr(1));
|
||||
}
|
||||
} else if (isSupportedAudioFile(filename)) {
|
||||
// External MP3 player reads argv as key=value pairs (see
|
||||
// CurrentAppCompat tt_app_start_with_bundle): file=<path>
|
||||
std::string file_arg = "file=" + file_path;
|
||||
const char* argv[] = { file_arg.c_str() };
|
||||
uint32_t instance_id = 0;
|
||||
if (app_start("one.tactility.mp3player", 1, argv, &instance_id) != ERROR_NONE) {
|
||||
LOG_W(TAG, "Failed to start MP3 player for %s", file_path.c_str());
|
||||
}
|
||||
} else if (isExecutablePath(file_path)) {
|
||||
runFile(file_path);
|
||||
} else {
|
||||
|
||||
@@ -85,7 +85,7 @@ int32_t appMain(int argc, char* argv[]) {
|
||||
|
||||
if (ctx.resultCode == 0) {
|
||||
// The parent captures this via an AppStream bound to our stdout (see startWithMode()) -
|
||||
// see AppStdioWrap.cpp for how printf() itself gets routed there on POSIX.
|
||||
// see Modules/app-module/source/stdio_wrap.cpp for how printf() itself gets routed there on POSIX.
|
||||
LOG_I(TAG, "Result: %s", ctx.resultPath.c_str());
|
||||
printf("%s", ctx.resultPath.c_str());
|
||||
}
|
||||
|
||||
@@ -426,7 +426,8 @@ extern const ::AppManifest manifest = {
|
||||
.id = "tactility.i2cscanner",
|
||||
.name = "I2C Scanner",
|
||||
.category = APP_CATEGORY_SYSTEM,
|
||||
.location = { APP_LOCATION_MEMORY, reinterpret_cast<void*>(appMain) }
|
||||
.location = { APP_LOCATION_MEMORY, reinterpret_cast<void*>(appMain) },
|
||||
.flags = APP_MANIFEST_FLAG_HIDDEN
|
||||
};
|
||||
|
||||
uint32_t start() {
|
||||
|
||||
@@ -138,7 +138,7 @@ int32_t appMain(int argc, char* argv[]) {
|
||||
|
||||
if (ctx.resultCode == 0) {
|
||||
// The caller captures this via an AppStream bound to our stdout (see start()); see
|
||||
// AppStdioWrap.cpp for how printf() itself gets routed there on POSIX.
|
||||
// Modules/app-module/source/stdio_wrap.cpp for how printf() itself gets routed there on POSIX.
|
||||
printf("%s", ctx.resultText.c_str());
|
||||
}
|
||||
return ctx.resultCode;
|
||||
|
||||
@@ -4,11 +4,26 @@
|
||||
#include <app/scheduler.h>
|
||||
#include <app/start.h>
|
||||
|
||||
#include <Tactility/DeprecatedPaths.h>
|
||||
#include <Tactility/MountPoints.h>
|
||||
#include <Tactility/Tactility.h>
|
||||
#include <Tactility/app/setup/Setup.h>
|
||||
#include <Tactility/file/File.h>
|
||||
#include <Tactility/lvgl/Lvgl.h>
|
||||
#include <Tactility/service/wifi/Wifi.h>
|
||||
#include <Tactility/settings/BootSettings.h>
|
||||
#include <Tactility/settings/Time.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <ctime>
|
||||
#include <string>
|
||||
|
||||
#include <lvgl.h>
|
||||
#include <lvgl/icons/launcher.h>
|
||||
#include <lvgl/fonts.h>
|
||||
#include <lvgl/icons/launcher.h>
|
||||
#include <lvgl/icons/statusbar.h>
|
||||
#include <lvgl/lvgl.h>
|
||||
|
||||
#include <lvgl_window_manager/window_manager.h>
|
||||
@@ -20,64 +35,29 @@
|
||||
#include <tactility/log.h>
|
||||
#include <tactility/memory.h>
|
||||
|
||||
#include <Tactility/app/setup/Setup.h>
|
||||
#include <Tactility/settings/BootSettings.h>
|
||||
#include <Tactility/Tactility.h>
|
||||
|
||||
namespace tt::app::launcher {
|
||||
|
||||
constexpr auto* TAG = "Launcher";
|
||||
constexpr auto* BACKGROUND_ASSET = "color-field.png";
|
||||
constexpr auto* CUSTOM_BACKGROUND_PATH = "tactility/launcher/background.bin";
|
||||
constexpr lv_color_t TEXT_COLOR = LV_COLOR_MAKE(0xF8, 0xF5, 0xF2);
|
||||
constexpr lv_color_t MUTED_TEXT_COLOR = LV_COLOR_MAKE(0xDF, 0xD6, 0xD3);
|
||||
constexpr lv_color_t ACCENT_COLOR = LV_COLOR_MAKE(0xEC, 0x75, 0x69);
|
||||
|
||||
namespace {
|
||||
|
||||
uint32_t getButtonPadding(UiDensity density, uint32_t buttonSize) {
|
||||
if (density == LVGL_UI_DENSITY_COMPACT) {
|
||||
return 0;
|
||||
} else {
|
||||
return buttonSize / 8;
|
||||
}
|
||||
}
|
||||
struct LauncherWidgets {
|
||||
lv_obj_t* timeLabel = nullptr;
|
||||
lv_obj_t* dateLabel = nullptr;
|
||||
lv_obj_t* dataLabel = nullptr;
|
||||
lv_obj_t* statusLabel = nullptr;
|
||||
lv_timer_t* updateTimer = nullptr;
|
||||
};
|
||||
|
||||
int32_t computeButtonMargin(int32_t available_span, int32_t total_button_size) {
|
||||
const int32_t usable = std::max<int32_t>(0, available_span - (3 * total_button_size));
|
||||
return std::min<int32_t>(usable / 16, total_button_size / 2);
|
||||
}
|
||||
|
||||
void onAppPressed(lv_event_t* e) {
|
||||
auto* appId = static_cast<const char*>(lv_event_get_user_data(e));
|
||||
void onAppPressed(lv_event_t* event) {
|
||||
const auto* app_id = static_cast<const char*>(lv_event_get_user_data(event));
|
||||
uint32_t instance_id = 0;
|
||||
app_start(appId, 0, nullptr, &instance_id);
|
||||
}
|
||||
|
||||
lv_obj_t* createAppButton(lv_obj_t* parent, UiDensity uiDensity, const char* imageFile, const char* appId, int32_t itemMargin, bool isLandscape) {
|
||||
const auto button_size = lvgl_get_launcher_icon_font_height();
|
||||
const auto button_padding = getButtonPadding(uiDensity, button_size);
|
||||
auto* apps_button = lv_button_create(parent);
|
||||
|
||||
lv_obj_set_style_pad_all(apps_button, static_cast<int32_t>(button_padding), LV_STATE_DEFAULT);
|
||||
if (isLandscape) {
|
||||
lv_obj_set_style_margin_hor(apps_button, itemMargin, LV_STATE_DEFAULT);
|
||||
} else {
|
||||
lv_obj_set_style_margin_ver(apps_button, itemMargin, LV_STATE_DEFAULT);
|
||||
}
|
||||
|
||||
lv_obj_set_style_shadow_width(apps_button, 0, LV_STATE_DEFAULT);
|
||||
lv_obj_set_style_bg_opa(apps_button, 0, LV_STATE_DEFAULT);
|
||||
|
||||
// create the image first
|
||||
auto* button_image = lv_image_create(apps_button);
|
||||
lv_obj_set_style_text_font(button_image, lvgl_get_launcher_icon_font(), LV_STATE_DEFAULT);
|
||||
lv_image_set_src(button_image, imageFile);
|
||||
lv_obj_set_style_text_color(button_image, lv_theme_get_color_primary(button_image), LV_STATE_DEFAULT);
|
||||
lv_obj_set_style_image_recolor(button_image, lv_theme_get_color_primary(parent), LV_STATE_DEFAULT);
|
||||
lv_obj_set_style_image_recolor_opa(button_image, LV_OPA_COVER, LV_STATE_DEFAULT);
|
||||
|
||||
// Ensure it's square (Material Symbols are slightly wider than tall)
|
||||
lv_obj_set_size(button_image, button_size, button_size);
|
||||
|
||||
lv_obj_add_event_cb(apps_button, onAppPressed, LV_EVENT_SHORT_CLICKED, (void*)appId);
|
||||
|
||||
return apps_button;
|
||||
app_start(app_id, 0, nullptr, &instance_id);
|
||||
}
|
||||
|
||||
bool shouldShowPowerButton() {
|
||||
@@ -85,180 +65,288 @@ bool shouldShowPowerButton() {
|
||||
device_for_each_of_type(&POWER_SUPPLY_TYPE, &show_power_button, [](Device* device, void* context) {
|
||||
if (device_is_ready(device) && power_supply_supports_power_off(device)) {
|
||||
*static_cast<bool*>(context) = true;
|
||||
return false; // stop iterating
|
||||
} else {
|
||||
return true; // continue iterating
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return show_power_button;
|
||||
}
|
||||
|
||||
void onButtonsWrapperResized(lv_event_t* e);
|
||||
int getBatteryPercentage() {
|
||||
Device* power = nullptr;
|
||||
device_for_each_of_type(&POWER_SUPPLY_TYPE, &power, [](Device* device, void* context) {
|
||||
if (device_is_ready(device) && power_supply_supports_property(device, POWER_SUPPLY_PROP_CAPACITY)) {
|
||||
*static_cast<Device**>(context) = device;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
if (power == nullptr) return -1;
|
||||
|
||||
// The screen object outlives this window's own widgets (lvgl-window-manager deletes and
|
||||
// recreates only the topmost window's widget on every app switch, not the screen itself), so
|
||||
// the LV_EVENT_SIZE_CHANGED callback registered on it must be removed once buttons_wrapper is
|
||||
// destroyed, to avoid a dangling user-data pointer the next time the display rotates while a
|
||||
// different window is topmost.
|
||||
void onButtonsWrapperDeleted(lv_event_t* e) {
|
||||
auto* buttons_wrapper = lv_event_get_target_obj(e);
|
||||
auto* screen = lv_obj_get_screen(buttons_wrapper);
|
||||
lv_obj_remove_event_cb_with_user_data(screen, onButtonsWrapperResized, buttons_wrapper);
|
||||
PowerSupplyPropertyValue charge_level;
|
||||
if (power_supply_get_property(power, POWER_SUPPLY_PROP_CAPACITY, &charge_level) != ERROR_NONE) return -1;
|
||||
return std::clamp(charge_level.int_value, 0, 100);
|
||||
}
|
||||
|
||||
// Re-applies the flex direction and per-button margins when the display orientation changes
|
||||
// while the launcher is the visible window (these are decided once at createWidgets() based on
|
||||
// the resolution at that time, so a later rotation needs this to catch up).
|
||||
void onButtonsWrapperResized(lv_event_t* e) {
|
||||
auto* buttons_wrapper = static_cast<lv_obj_t*>(lv_event_get_user_data(e));
|
||||
const auto* display = lv_obj_get_display(buttons_wrapper);
|
||||
|
||||
const auto button_size = lvgl_get_launcher_icon_font_height();
|
||||
const auto button_padding = getButtonPadding(lvgl_get_ui_density(), button_size);
|
||||
const auto total_button_size = button_size + (button_padding * 2);
|
||||
|
||||
const auto horizontal_px = lv_display_get_horizontal_resolution(display);
|
||||
const auto vertical_px = lv_display_get_vertical_resolution(display);
|
||||
const bool is_landscape_display = horizontal_px >= vertical_px;
|
||||
const auto current_flow = lv_obj_get_style_flex_flow(buttons_wrapper, LV_PART_MAIN);
|
||||
const bool was_landscape = current_flow == LV_FLEX_FLOW_ROW;
|
||||
if (is_landscape_display == was_landscape) {
|
||||
return;
|
||||
}
|
||||
|
||||
lv_obj_set_flex_flow(buttons_wrapper, is_landscape_display ? LV_FLEX_FLOW_ROW : LV_FLEX_FLOW_COLUMN);
|
||||
|
||||
const int32_t margin = is_landscape_display
|
||||
? computeButtonMargin(horizontal_px, total_button_size)
|
||||
: computeButtonMargin(vertical_px, total_button_size);
|
||||
|
||||
const uint32_t child_count = lv_obj_get_child_count(buttons_wrapper);
|
||||
for (uint32_t i = 0; i < child_count; i++) {
|
||||
auto* button = lv_obj_get_child(buttons_wrapper, i);
|
||||
lv_obj_set_style_margin_hor(button, is_landscape_display ? margin : 0, LV_STATE_DEFAULT);
|
||||
lv_obj_set_style_margin_ver(button, is_landscape_display ? 0 : margin, LV_STATE_DEFAULT);
|
||||
const char* getWifiStatusIcon(service::wifi::RadioState state) {
|
||||
using enum service::wifi::RadioState;
|
||||
switch (state) {
|
||||
case ConnectionActive: return LVGL_ICON_STATUSBAR_SIGNAL_WIFI_4_BAR;
|
||||
case Off:
|
||||
case OffPending: return LVGL_ICON_STATUSBAR_SIGNAL_WIFI_OFF;
|
||||
default: return LVGL_ICON_STATUSBAR_SIGNAL_WIFI_0_BAR;
|
||||
}
|
||||
}
|
||||
|
||||
void createWidgets(lv_obj_t* parent, void*) {
|
||||
auto* buttons_wrapper = lv_obj_create(parent);
|
||||
const char* getBatteryStatusIcon(int percentage) {
|
||||
if (percentage < 0) return "";
|
||||
if (percentage >= 95) return LVGL_ICON_STATUSBAR_BATTERY_ANDROID_FRAME_FULL;
|
||||
if (percentage >= 64) return LVGL_ICON_STATUSBAR_BATTERY_ANDROID_FRAME_5;
|
||||
if (percentage >= 32) return LVGL_ICON_STATUSBAR_BATTERY_ANDROID_FRAME_3;
|
||||
return LVGL_ICON_STATUSBAR_BATTERY_ANDROID_FRAME_1;
|
||||
}
|
||||
|
||||
auto ui_density = lvgl_get_ui_density();
|
||||
const auto button_size = lvgl_get_launcher_icon_font_height();
|
||||
const auto button_padding = getButtonPadding(ui_density, button_size);
|
||||
const auto total_button_size = button_size + (button_padding * 2);
|
||||
lv_obj_t* createAppButton(lv_obj_t* parent, const char* icon, const char* app_id, bool emphasized) {
|
||||
auto* button = lv_button_create(parent);
|
||||
lv_obj_set_size(button, 52, 52);
|
||||
lv_obj_set_style_radius(button, 15, LV_PART_MAIN);
|
||||
lv_obj_set_style_shadow_width(button, 0, LV_PART_MAIN);
|
||||
lv_obj_set_style_border_width(button, emphasized ? 2 : 1, LV_PART_MAIN);
|
||||
lv_obj_set_style_border_color(button, emphasized ? ACCENT_COLOR : lv_color_hex(0x746568), LV_PART_MAIN);
|
||||
lv_obj_set_style_border_opa(button, emphasized ? LV_OPA_COVER : LV_OPA_60, LV_PART_MAIN);
|
||||
lv_obj_set_style_bg_color(button, lv_color_hex(0x211B20), LV_PART_MAIN);
|
||||
lv_obj_set_style_bg_opa(button, emphasized ? LV_OPA_80 : LV_OPA_70, LV_PART_MAIN);
|
||||
lv_obj_set_style_bg_color(button, lv_color_hex(0x392C32), LV_STATE_PRESSED);
|
||||
lv_obj_set_style_transform_scale(button, 238, LV_STATE_PRESSED);
|
||||
lv_obj_set_style_outline_color(button, ACCENT_COLOR, LV_STATE_FOCUSED);
|
||||
lv_obj_set_style_outline_width(button, 2, LV_STATE_FOCUSED);
|
||||
lv_obj_set_style_outline_pad(button, 2, LV_STATE_FOCUSED);
|
||||
|
||||
lv_obj_align(buttons_wrapper, LV_ALIGN_CENTER, 0, 0);
|
||||
lv_obj_set_size(buttons_wrapper, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
|
||||
lv_obj_set_style_border_width(buttons_wrapper, 0, LV_STATE_DEFAULT);
|
||||
lv_obj_set_flex_grow(buttons_wrapper, 1);
|
||||
auto* image = lv_image_create(button);
|
||||
lv_obj_set_size(image, 36, 36);
|
||||
lv_obj_center(image);
|
||||
lv_obj_set_style_text_font(image, lvgl_get_launcher_icon_font(), LV_STATE_DEFAULT);
|
||||
lv_image_set_src(image, icon);
|
||||
lv_obj_set_style_image_recolor(image, TEXT_COLOR, LV_STATE_DEFAULT);
|
||||
lv_obj_set_style_image_recolor_opa(image, LV_OPA_COVER, LV_STATE_DEFAULT);
|
||||
lv_obj_add_event_cb(button, onAppPressed, LV_EVENT_SHORT_CLICKED, const_cast<char*>(app_id));
|
||||
return button;
|
||||
}
|
||||
|
||||
// Fix for button selection
|
||||
lv_obj_set_style_pad_all(buttons_wrapper, 6, LV_STATE_DEFAULT);
|
||||
|
||||
const auto* display = lv_obj_get_display(parent);
|
||||
const auto horizontal_px = lv_display_get_horizontal_resolution(display);
|
||||
const auto vertical_px = lv_display_get_vertical_resolution(display);
|
||||
const bool is_landscape_display = horizontal_px >= vertical_px;
|
||||
if (is_landscape_display) {
|
||||
lv_obj_set_flex_flow(buttons_wrapper, LV_FLEX_FLOW_ROW);
|
||||
void updateInformation(LauncherWidgets& widgets) {
|
||||
const std::time_t now = std::time(nullptr);
|
||||
std::tm local_time {};
|
||||
localtime_r(&now, &local_time);
|
||||
char time_buffer[12];
|
||||
char date_buffer[40];
|
||||
if (local_time.tm_year >= 125) {
|
||||
if (settings::isTimeFormat24Hour()) {
|
||||
std::strftime(time_buffer, sizeof(time_buffer), "%H:%M", &local_time);
|
||||
} else {
|
||||
std::strftime(time_buffer, sizeof(time_buffer), "%I:%M", &local_time);
|
||||
if (time_buffer[0] == '0') std::memmove(time_buffer, time_buffer + 1, std::strlen(time_buffer));
|
||||
}
|
||||
std::strftime(date_buffer, sizeof(date_buffer), "%A, %B %e", &local_time);
|
||||
} else {
|
||||
lv_obj_set_flex_flow(buttons_wrapper, LV_FLEX_FLOW_COLUMN);
|
||||
std::strcpy(time_buffer, "--:--");
|
||||
std::strcpy(date_buffer, "Set date and time");
|
||||
}
|
||||
lv_label_set_text(widgets.timeLabel, time_buffer);
|
||||
lv_label_set_text(widgets.dateLabel, date_buffer);
|
||||
|
||||
const auto wifi_state = service::wifi::getRadioState();
|
||||
std::string sd_card_path;
|
||||
const bool sd_ready = findFirstMountedSdCardPath(sd_card_path);
|
||||
const int battery_percentage = getBatteryPercentage();
|
||||
char data_buffer[80];
|
||||
if (battery_percentage >= 0) {
|
||||
std::snprintf(data_buffer, sizeof(data_buffer), "%s • %s • %d%%",
|
||||
wifi_state == service::wifi::RadioState::ConnectionActive ? "Wi-Fi connected" : "Wi-Fi offline",
|
||||
sd_ready ? "SD ready" : "No SD", battery_percentage);
|
||||
} else {
|
||||
std::snprintf(data_buffer, sizeof(data_buffer), "%s • %s",
|
||||
wifi_state == service::wifi::RadioState::ConnectionActive ? "Wi-Fi connected" : "Wi-Fi offline",
|
||||
sd_ready ? "SD ready" : "No SD");
|
||||
}
|
||||
lv_label_set_text(widgets.dataLabel, data_buffer);
|
||||
|
||||
char status_buffer[24];
|
||||
std::snprintf(status_buffer, sizeof(status_buffer), "%s%s", getWifiStatusIcon(wifi_state), getBatteryStatusIcon(battery_percentage));
|
||||
lv_label_set_text(widgets.statusLabel, status_buffer);
|
||||
}
|
||||
|
||||
void onUpdateTimer(lv_timer_t* timer) {
|
||||
updateInformation(*static_cast<LauncherWidgets*>(lv_timer_get_user_data(timer)));
|
||||
}
|
||||
|
||||
std::string getDefaultBackgroundPath() {
|
||||
return std::string(file::MOUNT_POINT_SYSTEM) + "/app/Launcher/assets/" + BACKGROUND_ASSET;
|
||||
}
|
||||
|
||||
void createWidgets(lv_obj_t* parent, void* user_data) {
|
||||
auto& widgets = *static_cast<LauncherWidgets*>(user_data);
|
||||
lv_obj_set_style_bg_color(parent, lv_color_hex(0x211A20), LV_PART_MAIN);
|
||||
lv_obj_set_style_bg_opa(parent, LV_OPA_COVER, LV_PART_MAIN);
|
||||
lv_obj_set_style_pad_all(parent, 0, LV_PART_MAIN);
|
||||
lv_obj_clear_flag(parent, LV_OBJ_FLAG_SCROLLABLE);
|
||||
|
||||
auto* display = lv_obj_get_display(parent);
|
||||
const auto display_width = lv_display_get_horizontal_resolution(display);
|
||||
const auto display_height = lv_display_get_vertical_resolution(display);
|
||||
const bool is_portrait = display_height > display_width;
|
||||
|
||||
auto background_path = lvgl::PATH_PREFIX + getDefaultBackgroundPath();
|
||||
std::string sd_card_path;
|
||||
if (findFirstMountedSdCardPath(sd_card_path)) {
|
||||
const auto custom_background_path = file::getChildPath(sd_card_path, CUSTOM_BACKGROUND_PATH);
|
||||
if (file::isFile(custom_background_path)) {
|
||||
const auto lvgl_custom_background_path = lvgl::PATH_PREFIX + custom_background_path;
|
||||
lv_image_header_t header {};
|
||||
if (lv_image_decoder_get_info(lvgl_custom_background_path.c_str(), &header) == LV_RESULT_OK) {
|
||||
if (header.w >= display_width && header.h >= display_height) {
|
||||
background_path = lvgl_custom_background_path;
|
||||
LOG_I(TAG, "Using SD background %s (%ux%u, format 0x%02x)",
|
||||
custom_background_path.c_str(), header.w, header.h, header.cf);
|
||||
} else {
|
||||
LOG_W(TAG, "Ignoring undersized SD background %s (%ux%u for %dx%d display)",
|
||||
custom_background_path.c_str(), header.w, header.h, display_width, display_height);
|
||||
}
|
||||
} else {
|
||||
LOG_W(TAG, "Ignoring invalid SD background %s", custom_background_path.c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const int32_t margin = is_landscape_display
|
||||
? computeButtonMargin(lv_display_get_horizontal_resolution(display), total_button_size)
|
||||
: computeButtonMargin(lv_display_get_vertical_resolution(display), total_button_size);
|
||||
auto* background = lv_image_create(parent);
|
||||
lv_image_set_src(background, background_path.c_str());
|
||||
lv_obj_align(background, LV_ALIGN_CENTER, 0, 0);
|
||||
lv_obj_add_flag(background, LV_OBJ_FLAG_IGNORE_LAYOUT);
|
||||
|
||||
auto* app_list_button = createAppButton(buttons_wrapper, ui_density, LVGL_ICON_LAUNCHER_APPS, "tactility.applist", margin, is_landscape_display);
|
||||
createAppButton(buttons_wrapper, ui_density, LVGL_ICON_LAUNCHER_FOLDER, "tactility.files", margin, is_landscape_display);
|
||||
createAppButton(buttons_wrapper, ui_density, LVGL_ICON_LAUNCHER_SETTINGS, "tactility.settings", margin, is_landscape_display);
|
||||
widgets.timeLabel = lv_label_create(parent);
|
||||
lv_label_set_text(widgets.timeLabel, "--:--");
|
||||
lv_obj_set_style_text_color(widgets.timeLabel, TEXT_COLOR, LV_PART_MAIN);
|
||||
#if LV_FONT_MONTSERRAT_48
|
||||
lv_obj_set_style_text_font(widgets.timeLabel, &lv_font_montserrat_48, LV_PART_MAIN);
|
||||
#else
|
||||
lv_obj_set_style_text_font(widgets.timeLabel, lvgl_get_text_font(FONT_SIZE_LARGE), LV_PART_MAIN);
|
||||
#endif
|
||||
lv_obj_align(widgets.timeLabel, LV_ALIGN_TOP_LEFT, 18, 58);
|
||||
|
||||
// The launcher's container is several levels below the screen, and LVGL only sends
|
||||
// LV_EVENT_SIZE_CHANGED to the screen object itself on a resolution change - so the
|
||||
// handler is attached there, with buttons_wrapper passed through as user data.
|
||||
lv_obj_add_event_cb(lv_obj_get_screen(parent), onButtonsWrapperResized, LV_EVENT_SIZE_CHANGED, buttons_wrapper);
|
||||
lv_obj_add_event_cb(buttons_wrapper, onButtonsWrapperDeleted, LV_EVENT_DELETE, nullptr);
|
||||
widgets.dateLabel = lv_label_create(parent);
|
||||
lv_obj_set_style_text_font(widgets.dateLabel, lvgl_get_text_font(FONT_SIZE_LARGE), LV_PART_MAIN);
|
||||
lv_obj_set_style_text_color(widgets.dateLabel, TEXT_COLOR, LV_PART_MAIN);
|
||||
lv_obj_align(widgets.dateLabel, LV_ALIGN_TOP_LEFT, 20, 118);
|
||||
|
||||
widgets.dataLabel = lv_label_create(parent);
|
||||
lv_obj_set_width(widgets.dataLabel, is_portrait ? display_width - 40 : 225);
|
||||
lv_label_set_long_mode(widgets.dataLabel, LV_LABEL_LONG_MODE_WRAP);
|
||||
lv_obj_set_style_text_font(widgets.dataLabel, lvgl_get_text_font(FONT_SIZE_SMALL), LV_PART_MAIN);
|
||||
lv_obj_set_style_text_color(widgets.dataLabel, MUTED_TEXT_COLOR, LV_PART_MAIN);
|
||||
lv_obj_align(widgets.dataLabel, LV_ALIGN_TOP_LEFT, 20, 148);
|
||||
|
||||
widgets.statusLabel = lv_label_create(parent);
|
||||
lv_obj_set_style_text_font(widgets.statusLabel, lvgl_get_statusbar_icon_font(), LV_PART_MAIN);
|
||||
lv_obj_set_style_text_color(widgets.statusLabel, TEXT_COLOR, LV_PART_MAIN);
|
||||
lv_obj_align(widgets.statusLabel, LV_ALIGN_TOP_RIGHT, -15, 8);
|
||||
|
||||
auto* button_rail = lv_obj_create(parent);
|
||||
if (is_portrait) {
|
||||
lv_obj_set_size(button_rail, 184, 60);
|
||||
lv_obj_align(button_rail, LV_ALIGN_BOTTOM_MID, 0, -7);
|
||||
lv_obj_set_flex_flow(button_rail, LV_FLEX_FLOW_ROW);
|
||||
} else {
|
||||
lv_obj_set_size(button_rail, 60, 184);
|
||||
lv_obj_align(button_rail, LV_ALIGN_RIGHT_MID, -7, 8);
|
||||
lv_obj_set_flex_flow(button_rail, LV_FLEX_FLOW_COLUMN);
|
||||
}
|
||||
lv_obj_set_flex_align(button_rail, LV_FLEX_ALIGN_SPACE_EVENLY, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
|
||||
lv_obj_set_style_pad_all(button_rail, 0, LV_PART_MAIN);
|
||||
lv_obj_set_style_border_width(button_rail, 0, LV_PART_MAIN);
|
||||
lv_obj_set_style_bg_opa(button_rail, LV_OPA_TRANSP, LV_PART_MAIN);
|
||||
lv_obj_clear_flag(button_rail, LV_OBJ_FLAG_SCROLLABLE);
|
||||
|
||||
auto* app_list_button = createAppButton(button_rail, LVGL_ICON_LAUNCHER_APPS, "tactility.applist", true);
|
||||
createAppButton(button_rail, LVGL_ICON_LAUNCHER_FOLDER, "tactility.files", false);
|
||||
createAppButton(button_rail, LVGL_ICON_LAUNCHER_SETTINGS, "tactility.settings", false);
|
||||
|
||||
// Some devices (e.g. T-Lora Pager) have no other way to power off, so the
|
||||
// button stays in the launcher; the confirmation flow lives in the PowerOff app.
|
||||
if (shouldShowPowerButton()) {
|
||||
auto* power_button = lv_button_create(parent);
|
||||
lv_obj_set_style_pad_all(power_button, 8, 0);
|
||||
lv_obj_align(power_button, LV_ALIGN_BOTTOM_MID, 0, -10);
|
||||
lv_obj_add_event_cb(power_button, onAppPressed, LV_EVENT_SHORT_CLICKED, (void*)"tactility.poweroff");
|
||||
lv_obj_set_style_shadow_width(power_button, 0, LV_STATE_DEFAULT);
|
||||
lv_obj_set_style_bg_opa(power_button, 0, LV_PART_MAIN);
|
||||
|
||||
lv_obj_set_size(power_button, 36, 36);
|
||||
lv_obj_align(power_button, LV_ALIGN_BOTTOM_LEFT, 16, -12);
|
||||
lv_obj_set_style_radius(power_button, LV_RADIUS_CIRCLE, LV_PART_MAIN);
|
||||
lv_obj_set_style_shadow_width(power_button, 0, LV_PART_MAIN);
|
||||
lv_obj_set_style_bg_color(power_button, lv_color_hex(0x211B20), LV_PART_MAIN);
|
||||
lv_obj_set_style_bg_opa(power_button, LV_OPA_70, LV_PART_MAIN);
|
||||
lv_obj_add_event_cb(power_button, onAppPressed, LV_EVENT_SHORT_CLICKED, const_cast<char*>("tactility.poweroff"));
|
||||
auto* power_label = lv_label_create(power_button);
|
||||
lv_label_set_text(power_label, LV_SYMBOL_POWER);
|
||||
lv_obj_set_style_text_color(power_label, lv_theme_get_color_primary(parent), LV_STATE_DEFAULT);
|
||||
lv_obj_set_style_text_color(power_label, TEXT_COLOR, LV_PART_MAIN);
|
||||
lv_obj_center(power_label);
|
||||
}
|
||||
|
||||
// If we don't have a touch device, we assume there's some other kind of input like a keyboard, an encoder or button control
|
||||
// In that scenario we want to automatically have the app list button selected so the user doesn't have to press the widget selection
|
||||
// an extra time.
|
||||
if (!device_has_active_by_type(&POINTER_TYPE)) {
|
||||
// lv_obj_update_layout(parent); // Resolve flex layout first, so focus/state invalidate against final coords
|
||||
lv_group_focus_obj(app_list_button);
|
||||
lv_obj_add_state(app_list_button, LV_STATE_FOCUS_KEY);
|
||||
}
|
||||
|
||||
updateInformation(widgets);
|
||||
widgets.updateTimer = lv_timer_create(onUpdateTimer, 1000, &widgets);
|
||||
}
|
||||
|
||||
void destroyWidgets(void* user_data) {
|
||||
auto& widgets = *static_cast<LauncherWidgets*>(user_data);
|
||||
if (widgets.updateTimer != nullptr) {
|
||||
lv_timer_delete(widgets.updateTimer);
|
||||
widgets.updateTimer = nullptr;
|
||||
}
|
||||
widgets.timeLabel = nullptr;
|
||||
widgets.dateLabel = nullptr;
|
||||
widgets.dataLabel = nullptr;
|
||||
widgets.statusLabel = nullptr;
|
||||
}
|
||||
|
||||
void runAutoStart() {
|
||||
settings::BootSettings boot_properties;
|
||||
AppManifest manifest;
|
||||
if (
|
||||
// Auto-start due to built-in requirement
|
||||
strcmp(CONFIG_TT_AUTO_START_APP_ID, "") != 0 &&
|
||||
app_manager_find_manifest(CONFIG_TT_AUTO_START_APP_ID, &manifest) == ERROR_NONE
|
||||
) {
|
||||
if (strcmp(CONFIG_TT_AUTO_START_APP_ID, "") != 0 &&
|
||||
app_manager_find_manifest(CONFIG_TT_AUTO_START_APP_ID, &manifest) == ERROR_NONE) {
|
||||
LOG_I(TAG, "Starting %s", CONFIG_TT_AUTO_START_APP_ID);
|
||||
uint32_t app_launch_id;
|
||||
app_start(CONFIG_TT_AUTO_START_APP_ID, 0, nullptr, &app_launch_id);
|
||||
} else if (
|
||||
// Auto-start due to user configuration
|
||||
settings::loadBootSettings(boot_properties) &&
|
||||
!boot_properties.autoStartAppId.empty() &&
|
||||
app_manager_find_manifest(boot_properties.autoStartAppId.c_str(), &manifest) == ERROR_NONE
|
||||
) {
|
||||
} else if (settings::loadBootSettings(boot_properties) &&
|
||||
!boot_properties.autoStartAppId.empty() &&
|
||||
app_manager_find_manifest(boot_properties.autoStartAppId.c_str(), &manifest) == ERROR_NONE) {
|
||||
LOG_I(TAG, "Starting %s", boot_properties.autoStartAppId.c_str());
|
||||
uint32_t app_launch_id;
|
||||
app_start(boot_properties.autoStartAppId.c_str(), 0, nullptr, &app_launch_id);
|
||||
} else {
|
||||
// No auto-start, consider running system setup
|
||||
if (!setup::isCompleted()) {
|
||||
setup::start();
|
||||
}
|
||||
} else if (!setup::isCompleted()) {
|
||||
setup::start();
|
||||
}
|
||||
}
|
||||
|
||||
int32_t appMain(int argc, char* argv[]) {
|
||||
uint32_t appInstanceId = app_scheduler_current_app_id();
|
||||
uint32_t app_instance_id = app_scheduler_current_app_id();
|
||||
runAutoStart();
|
||||
|
||||
LauncherWidgets widgets;
|
||||
WindowId window = window_manager_create_ext(app_instance_id, createWidgets, destroyWidgets, &widgets);
|
||||
|
||||
TaskEventGroup event_group {};
|
||||
task_event_group_construct(&event_group);
|
||||
|
||||
AppEventSubscription sub {};
|
||||
check(app_event_subscribe(&sub, &event_group) == ERROR_NONE);
|
||||
|
||||
WindowId window = window_manager_create(appInstanceId, createWidgets, nullptr);
|
||||
|
||||
// The launcher is meant to stay resident (it's the home screen) - it only gives up its
|
||||
// thread when app-module's scheduler asks it to (e.g. another new-model app is started).
|
||||
while (true) {
|
||||
task_event_group_wait_any(&event_group, nullptr, portMAX_DELAY);
|
||||
|
||||
bool shouldClose = false;
|
||||
bool should_close = false;
|
||||
AppEvent event {};
|
||||
while (app_event_poll(&sub, &event) == ERROR_NONE) {
|
||||
if (event.type == APP_EVENT_CLOSE) {
|
||||
shouldClose = true;
|
||||
should_close = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (shouldClose) break;
|
||||
if (should_close) break;
|
||||
}
|
||||
|
||||
window_manager_remove(window);
|
||||
@@ -275,16 +363,13 @@ extern const ::AppManifest manifest = {
|
||||
.category = APP_CATEGORY_SYSTEM,
|
||||
.location = { .type = APP_LOCATION_MEMORY, .location = reinterpret_cast<void*>(appMain) },
|
||||
.flags = APP_MANIFEST_FLAG_HIDDEN,
|
||||
// No file IO, so callstack can be in external RAM
|
||||
.stack = { .depth = 3072 , .desired_memory_capability = MEMORY_CAPABILITY_EXTERNAL }
|
||||
.stack = { .depth = 3072, .desired_memory_capability = MEMORY_CAPABILITY_EXTERNAL }
|
||||
};
|
||||
|
||||
// Kept for Tactility/Private/Tactility/app/launcher/Launcher.h's existing declaration (still
|
||||
// used by the old, unconverted CrashDiagnostics app to return to the launcher after a crash).
|
||||
uint32_t start() {
|
||||
uint32_t instance_id = 0;
|
||||
app_start(manifest.id, 0, nullptr, &instance_id);
|
||||
return instance_id;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
} // namespace tt::app::launcher
|
||||
|
||||
@@ -182,7 +182,8 @@ extern const ::AppManifest manifest = {
|
||||
.id = "tactility.localesettings",
|
||||
.name = "Region & Language",
|
||||
.category = APP_CATEGORY_SETTINGS,
|
||||
.location = { APP_LOCATION_MEMORY, reinterpret_cast<void*>(appMain) }
|
||||
.location = { APP_LOCATION_MEMORY, reinterpret_cast<void*>(appMain) },
|
||||
.flags = APP_MANIFEST_FLAG_HIDDEN
|
||||
};
|
||||
|
||||
} // namespace tt::app::localesettings
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
#ifdef ESP_PLATFORM
|
||||
#include <Tactility/Tactility.h>
|
||||
#include <Tactility/lvgl/Lvgl.h>
|
||||
#include <Tactility/settings/McpSettings.h>
|
||||
#include <Tactility/settings/WebServerSettings.h>
|
||||
#include <Tactility/service/webserver/WebServerService.h>
|
||||
#include <app/event.h>
|
||||
#include <app/manifest.h>
|
||||
#include <app/scheduler.h>
|
||||
#include <lvgl_window_manager/window_manager.h>
|
||||
#include <lvgl/widgets/toolbar.h>
|
||||
#include <lvgl/lvgl.h>
|
||||
#include <tactility/check.h>
|
||||
#include <tactility/log.h>
|
||||
#include <esp_netif.h>
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace tt::app::mcpsettings {
|
||||
constexpr auto* TAG = "McpSettingsApp";
|
||||
extern const ::AppManifest manifest;
|
||||
namespace {
|
||||
struct Context {
|
||||
uint32_t appInstanceId;
|
||||
settings::mcp::McpSettings mcpSettings;
|
||||
settings::webserver::WebServerSettings wsSettings;
|
||||
lv_obj_t* switchMcpEnabled = nullptr;
|
||||
lv_obj_t* labelUrlValue = nullptr;
|
||||
};
|
||||
|
||||
void updateUrlDisplay(Context* ctx) {
|
||||
if (ctx->labelUrlValue == nullptr) return;
|
||||
if (!ctx->mcpSettings.mcpEnabled) { lv_label_set_text(ctx->labelUrlValue, "Disabled"); return; }
|
||||
std::string url = "http://";
|
||||
bool ipAdded = false;
|
||||
for (const char* key : {"WIFI_STA_DEF", "WIFI_AP_DEF"}) {
|
||||
auto* netif = esp_netif_get_handle_from_ifkey(key);
|
||||
if (netif != nullptr) {
|
||||
esp_netif_ip_info_t info;
|
||||
if (esp_netif_get_ip_info(netif, &info) == ESP_OK && info.ip.addr != 0) {
|
||||
char ip[16]; snprintf(ip, sizeof(ip), IPSTR, IP2STR(&info.ip));
|
||||
url += ip; ipAdded = true; break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!ipAdded) url += ctx->wsSettings.wifiMode == settings::webserver::WiFiMode::AccessPoint ? "192.168.4.1" : "Connecting...";
|
||||
if (url.starts_with("http://") && ctx->wsSettings.webServerPort != 80) url += ":" + std::to_string(ctx->wsSettings.webServerPort);
|
||||
url += "/api/mcp";
|
||||
lv_label_set_text(ctx->labelUrlValue, url.c_str());
|
||||
}
|
||||
|
||||
void onBackPressed(lv_event_t* event) {
|
||||
auto* ctx = static_cast<Context*>(lv_event_get_user_data(event));
|
||||
app_event_emit_close(ctx->appInstanceId);
|
||||
}
|
||||
|
||||
void onMcpEnabledSwitch(lv_event_t* event) {
|
||||
auto* ctx = static_cast<Context*>(lv_event_get_user_data(event));
|
||||
const bool enabled = lv_obj_has_state(ctx->switchMcpEnabled, LV_STATE_CHECKED);
|
||||
getMainDispatcher().dispatch([ctx, enabled] {
|
||||
ctx->mcpSettings.mcpEnabled = enabled;
|
||||
lvgl_lock(); updateUrlDisplay(ctx); lvgl_unlock();
|
||||
if (!settings::mcp::save(ctx->mcpSettings)) LOG_W(TAG, "Failed to persist MCP settings");
|
||||
service::webserver::getPubsub()->publish(service::webserver::WebServerEvent::WebServerSettingsChanged);
|
||||
service::webserver::setWebServerEnabled(enabled);
|
||||
});
|
||||
}
|
||||
|
||||
void createWidgets(lv_obj_t* parent, void* userData) {
|
||||
auto* ctx = static_cast<Context*>(userData);
|
||||
ctx->wsSettings = settings::webserver::loadOrGetDefault();
|
||||
lv_obj_set_flex_flow(parent, LV_FLEX_FLOW_COLUMN);
|
||||
lv_obj_set_style_pad_row(parent, 0, LV_STATE_DEFAULT);
|
||||
auto* toolbar = lvgl_toolbar_create(parent, "MCP Settings");
|
||||
lvgl_toolbar_set_nav_action(toolbar, LV_SYMBOL_CLOSE, onBackPressed, ctx);
|
||||
ctx->switchMcpEnabled = lvgl_toolbar_add_switch_action(toolbar);
|
||||
if (ctx->mcpSettings.mcpEnabled) lv_obj_add_state(ctx->switchMcpEnabled, LV_STATE_CHECKED);
|
||||
lv_obj_add_event_cb(ctx->switchMcpEnabled, onMcpEnabledSwitch, LV_EVENT_VALUE_CHANGED, ctx);
|
||||
auto* main = lv_obj_create(parent); lv_obj_set_flex_flow(main, LV_FLEX_FLOW_COLUMN); lv_obj_set_width(main, LV_PCT(100)); lv_obj_set_flex_grow(main, 1);
|
||||
auto* wrapper = lv_obj_create(main); lv_obj_set_size(wrapper, LV_PCT(100), LV_SIZE_CONTENT); lv_obj_set_style_pad_all(wrapper, 10, LV_STATE_DEFAULT); lv_obj_set_style_border_width(wrapper, 1, LV_STATE_DEFAULT); lv_obj_set_flex_flow(wrapper, LV_FLEX_FLOW_COLUMN); lv_obj_set_style_flex_cross_place(wrapper, LV_FLEX_ALIGN_START, 0);
|
||||
auto* title = lv_label_create(wrapper); lv_label_set_text(title, "MCP Endpoint URL:");
|
||||
ctx->labelUrlValue = lv_label_create(wrapper); updateUrlDisplay(ctx);
|
||||
auto* info = lv_label_create(main); lv_label_set_long_mode(info, LV_LABEL_LONG_WRAP); lv_obj_set_width(info, LV_PCT(95));
|
||||
lv_label_set_text(info, "MCP (Model Context Protocol) Screen service allows LLMs to interact with the device screen, audio, and tools directly.\n\nEndpoints:\n- POST /api/mcp (JSON-RPC tools)\n- POST /api/screen/raw (big-endian RGB565 writes)\n\nTo show the LLM canvas, select 'MCP Screen' in Settings -> Display -> Screensaver. The canvas also pops up automatically when an LLM sends a draw command.");
|
||||
}
|
||||
|
||||
int32_t appMain(int, char**) {
|
||||
Context ctx{}; ctx.appInstanceId = app_scheduler_current_app_id(); ctx.mcpSettings = settings::mcp::loadOrGetDefault();
|
||||
TaskEventGroup group{}; task_event_group_construct(&group); AppEventSubscription sub{}; check(app_event_subscribe(&sub, &group) == ERROR_NONE);
|
||||
auto window = window_manager_create(ctx.appInstanceId, createWidgets, &ctx); bool close = false;
|
||||
while (!close) { task_event_group_wait_any(&group, nullptr, portMAX_DELAY); AppEvent event{}; while (app_event_poll(&sub, &event) == ERROR_NONE) if (event.type == APP_EVENT_CLOSE) { close = true; break; } }
|
||||
window_manager_remove(window); check(app_event_unsubscribe(&sub) == ERROR_NONE); task_event_group_destruct(&group); return 0;
|
||||
}
|
||||
}
|
||||
extern const ::AppManifest manifest = { .id = "McpSettings", .name = "MCP Screen", .category = APP_CATEGORY_SETTINGS, .location = { APP_LOCATION_MEMORY, reinterpret_cast<void*>(appMain) }, .flags = APP_MANIFEST_FLAG_HIDDEN, .stack = { .depth = 8192, .desired_memory_capability = 0 } };
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,66 @@
|
||||
#ifndef ESP_PLATFORM
|
||||
|
||||
#include <app/event.h>
|
||||
#include <app/manifest.h>
|
||||
#include <app/scheduler.h>
|
||||
#include <lvgl/lvgl.h>
|
||||
#include <lvgl_window_manager/window_manager.h>
|
||||
|
||||
namespace tt::app::mcpsettings {
|
||||
struct Context { AppInstanceId instanceId; };
|
||||
|
||||
void createMcpInfo(lv_obj_t* parent, void* userData) {
|
||||
auto* context = static_cast<Context*>(userData);
|
||||
lv_obj_t* title = lv_label_create(parent);
|
||||
lv_label_set_text(title, "MCP Settings");
|
||||
lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 18);
|
||||
|
||||
lv_obj_t* info = lv_label_create(parent);
|
||||
lv_label_set_text(info,
|
||||
"MCP is available while the simulator web server is running.\n\n"
|
||||
"Endpoint: POST /api/mcp\n"
|
||||
"JSON-RPC methods: tools/list, tools/call\n\n"
|
||||
"Simulator tools: get_capabilities, clear_screen, draw_text, list_apps, run_app\n\n"
|
||||
"Open the simulator dashboard/API at http://127.0.0.1/api/sysinfo.");
|
||||
lv_label_set_long_mode(info, LV_LABEL_LONG_WRAP);
|
||||
lv_obj_set_width(info, LV_PCT(90));
|
||||
lv_obj_align(info, LV_ALIGN_CENTER, 0, 8);
|
||||
|
||||
(void)context;
|
||||
}
|
||||
|
||||
int32_t appMain(int, char**) {
|
||||
Context context{app_scheduler_current_app_id()};
|
||||
TaskEventGroup group{};
|
||||
task_event_group_construct(&group);
|
||||
AppEventSubscription subscription{};
|
||||
if (app_event_subscribe(&subscription, &group) != ERROR_NONE) {
|
||||
task_event_group_destruct(&group);
|
||||
return -1;
|
||||
}
|
||||
auto window = window_manager_create(context.instanceId, createMcpInfo, &context);
|
||||
bool close = false;
|
||||
while (!close) {
|
||||
task_event_group_wait_any(&group, nullptr, portMAX_DELAY);
|
||||
AppEvent event{};
|
||||
while (app_event_poll(&subscription, &event) == ERROR_NONE) {
|
||||
if (event.type == APP_EVENT_CLOSE) { close = true; break; }
|
||||
}
|
||||
}
|
||||
window_manager_remove(window);
|
||||
app_event_unsubscribe(&subscription);
|
||||
task_event_group_destruct(&group);
|
||||
return 0;
|
||||
}
|
||||
|
||||
extern const AppManifest manifest = {
|
||||
.id = "McpSettings",
|
||||
.name = "MCP Settings",
|
||||
.category = APP_CATEGORY_SETTINGS,
|
||||
.location = {APP_LOCATION_MEMORY, reinterpret_cast<void*>(appMain)},
|
||||
.flags = 0,
|
||||
.stack = {.depth = 8192, .desired_memory_capability = 0}
|
||||
};
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -276,7 +276,8 @@ extern const ::AppManifest manifest = {
|
||||
.id = "tactility.notes",
|
||||
.name = "Notes",
|
||||
.category = APP_CATEGORY_USER,
|
||||
.location = { APP_LOCATION_MEMORY, reinterpret_cast<void*>(appMain) }
|
||||
.location = { APP_LOCATION_MEMORY, reinterpret_cast<void*>(appMain) },
|
||||
.flags = APP_MANIFEST_FLAG_HIDDEN
|
||||
};
|
||||
|
||||
} // namespace tt::app::notes
|
||||
|
||||
@@ -278,7 +278,8 @@ extern const ::AppManifest manifest = {
|
||||
.id = "tactility.power",
|
||||
.name = "Power",
|
||||
.category = APP_CATEGORY_SETTINGS,
|
||||
.location = { APP_LOCATION_MEMORY, reinterpret_cast<void*>(appMain) }
|
||||
.location = { APP_LOCATION_MEMORY, reinterpret_cast<void*>(appMain) },
|
||||
.flags = APP_MANIFEST_FLAG_HIDDEN
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
@@ -290,7 +290,8 @@ extern const ::AppManifest manifest = {
|
||||
.id = "tactility.screenshot",
|
||||
.name = "Screenshot",
|
||||
.category = APP_CATEGORY_SYSTEM,
|
||||
.location = { APP_LOCATION_MEMORY, reinterpret_cast<void*>(appMain) }
|
||||
.location = { APP_LOCATION_MEMORY, reinterpret_cast<void*>(appMain) },
|
||||
.flags = APP_MANIFEST_FLAG_HIDDEN
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
@@ -118,7 +118,7 @@ extern const ::AppManifest manifest = {
|
||||
.category = APP_CATEGORY_SYSTEM,
|
||||
.location = { .type = APP_LOCATION_MEMORY, .location = reinterpret_cast<void*>(appMain) },
|
||||
.flags = APP_MANIFEST_FLAG_HIDDEN,
|
||||
.stack = { .depth = 2400, .desired_memory_capability = 0 },
|
||||
.stack = { .depth = 3072, .desired_memory_capability = 0 },
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
@@ -457,7 +457,8 @@ extern const ::AppManifest manifest = {
|
||||
.id = "tactility.systeminfo",
|
||||
.name = "System Info",
|
||||
.category = APP_CATEGORY_SYSTEM,
|
||||
.location = { APP_LOCATION_MEMORY, reinterpret_cast<void*>(appMain) }
|
||||
.location = { APP_LOCATION_MEMORY, reinterpret_cast<void*>(appMain) },
|
||||
.flags = APP_MANIFEST_FLAG_HIDDEN
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
@@ -215,7 +215,8 @@ extern const ::AppManifest manifest = {
|
||||
.id = "tactility.timedatesettings",
|
||||
.name = "Time & Date",
|
||||
.category = APP_CATEGORY_SETTINGS,
|
||||
.location = { APP_LOCATION_MEMORY, reinterpret_cast<void*>(appMain) }
|
||||
.location = { APP_LOCATION_MEMORY, reinterpret_cast<void*>(appMain) },
|
||||
.flags = APP_MANIFEST_FLAG_HIDDEN
|
||||
};
|
||||
|
||||
} // namespace tt::app::timedatesettings
|
||||
|
||||
@@ -424,7 +424,8 @@ extern const ::AppManifest manifest = {
|
||||
.id = "tactility.webserversettings",
|
||||
.name = "Web Server",
|
||||
.category = APP_CATEGORY_SYSTEM,
|
||||
.location = { APP_LOCATION_MEMORY, reinterpret_cast<void*>(appMain) }
|
||||
.location = { APP_LOCATION_MEMORY, reinterpret_cast<void*>(appMain) },
|
||||
.flags = APP_MANIFEST_FLAG_HIDDEN
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
#include <Tactility/lvgl/Lvgl.h>
|
||||
#include <Tactility/settings/DisplaySettings.h>
|
||||
|
||||
#include <lvgl/fonts.h>
|
||||
#include <lvgl/lvgl.h>
|
||||
|
||||
namespace tt::lvgl {
|
||||
|
||||
void applyFontSize(settings::display::FontSize fontSize) {
|
||||
LvglFontScale scale;
|
||||
switch (fontSize) {
|
||||
using enum settings::display::FontSize;
|
||||
case Small:
|
||||
scale = FONT_SCALE_SMALL;
|
||||
break;
|
||||
case Large:
|
||||
scale = FONT_SCALE_LARGE;
|
||||
break;
|
||||
case Default:
|
||||
default:
|
||||
scale = FONT_SCALE_DEFAULT;
|
||||
break;
|
||||
}
|
||||
|
||||
lvgl_set_text_font_scale(scale);
|
||||
const lv_font_t* font = lvgl_get_text_font(FONT_SIZE_DEFAULT);
|
||||
|
||||
for (lv_display_t* display = lv_display_get_next(nullptr);
|
||||
display != nullptr;
|
||||
display = lv_display_get_next(display)) {
|
||||
#if LV_USE_THEME_DEFAULT
|
||||
if (lv_display_get_theme(display) == lv_theme_default_get()) {
|
||||
lv_obj_t* screen = lv_display_get_screen_active(display);
|
||||
lv_theme_default_init(
|
||||
display,
|
||||
lv_theme_get_color_primary(screen),
|
||||
lv_theme_get_color_secondary(screen),
|
||||
LV_THEME_DEFAULT_DARK,
|
||||
font
|
||||
);
|
||||
}
|
||||
#endif
|
||||
// The display layers are independent inheritance roots. Updating all of them makes
|
||||
// the new size visible immediately in regular screens, overlays, and the status bar.
|
||||
lv_obj_set_style_text_font(lv_display_get_screen_active(display), font, LV_PART_MAIN);
|
||||
lv_obj_set_style_text_font(lv_display_get_layer_top(display), font, LV_PART_MAIN);
|
||||
lv_obj_set_style_text_font(lv_display_get_layer_sys(display), font, LV_PART_MAIN);
|
||||
lv_obj_set_style_text_font(lv_display_get_layer_bottom(display), font, LV_PART_MAIN);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace tt::lvgl
|
||||
File diff suppressed because it is too large
Load Diff
@@ -3,10 +3,15 @@
|
||||
#include <Tactility/service/displayidle/DisplayIdleService.h>
|
||||
#include <Tactility/service/ServiceManifest.h>
|
||||
#include <Tactility/service/ServiceRegistration.h>
|
||||
#include <Tactility/mcp/McpSystem.h>
|
||||
|
||||
#include <app/manager.h>
|
||||
#include <app/start.h>
|
||||
|
||||
#include "BouncingBallsScreensaver.h"
|
||||
#include "MatrixRainScreensaver.h"
|
||||
#include "MystifyScreensaver.h"
|
||||
#include "McpScreensaver.h"
|
||||
#include "Screensaver.h"
|
||||
#include "StackChanScreensaver.h"
|
||||
|
||||
@@ -59,6 +64,34 @@ static bool hasDisplayWithBacklight() {
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Effective backlight duty for the screensaver: the dimmed night level when
|
||||
* night dim is enabled and the local hour is inside the configured window,
|
||||
* otherwise the regular duty. A start == end window covers the whole day.
|
||||
*/
|
||||
static uint8_t screensaverBacklightDuty(const settings::display::DisplaySettings& displaySettings) {
|
||||
if (!displaySettings.nightDimEnabled) {
|
||||
return displaySettings.backlightDuty;
|
||||
}
|
||||
const std::time_t now = std::time(nullptr);
|
||||
std::tm local_time {};
|
||||
if (localtime_r(&now, &local_time) == nullptr || local_time.tm_year < 125) {
|
||||
return displaySettings.backlightDuty;
|
||||
}
|
||||
const uint8_t hour = static_cast<uint8_t>(local_time.tm_hour);
|
||||
const uint8_t start = displaySettings.nightDimStartHour;
|
||||
const uint8_t end = displaySettings.nightDimEndHour;
|
||||
bool in_window;
|
||||
if (start == end) {
|
||||
in_window = true;
|
||||
} else if (start < end) {
|
||||
in_window = hour >= start && hour < end;
|
||||
} else {
|
||||
in_window = hour >= start || hour < end;
|
||||
}
|
||||
return in_window ? displaySettings.nightDimDuty : displaySettings.backlightDuty;
|
||||
}
|
||||
|
||||
void DisplayIdleService::stopScreensaver() {
|
||||
if (!lvgl_try_lock(100)) {
|
||||
// Lock failed - keep flag set to retry on next tick
|
||||
@@ -77,6 +110,17 @@ void DisplayIdleService::stopScreensaver() {
|
||||
screensaverOverlay = nullptr;
|
||||
}
|
||||
lvgl_unlock();
|
||||
|
||||
// Stop an app launched as screensaver (e.g. Bible Verse): on wake the
|
||||
// device returns to the launcher. Stopping is safe when the user already
|
||||
// closed it (unknown ids report STOPPED / stop is a no-op for them).
|
||||
if (screensaverAppActive) {
|
||||
screensaverAppActive = false;
|
||||
if (screensaverAppInstanceId != 0) {
|
||||
app_manager_stop(screensaverAppInstanceId);
|
||||
screensaverAppInstanceId = 0;
|
||||
}
|
||||
}
|
||||
stopScreensaverRequested.store(false, std::memory_order_relaxed);
|
||||
|
||||
// Reset auto-off state
|
||||
@@ -92,14 +136,31 @@ void DisplayIdleService::stopScreensaver() {
|
||||
}
|
||||
|
||||
void DisplayIdleService::activateScreensaver() {
|
||||
lv_obj_t* top = lv_layer_top();
|
||||
|
||||
if (screensaverOverlay != nullptr) return;
|
||||
|
||||
// Reset auto-off counter when starting screensaver
|
||||
screensaverActiveCounter = 0;
|
||||
backlightOff = false;
|
||||
|
||||
// Bible Verse screensaver: launch the app instead of drawing an overlay.
|
||||
// Falls back to a plain black overlay when the app is not installed.
|
||||
if (cachedDisplaySettings.screensaverType == settings::display::ScreensaverType::BibleVerse) {
|
||||
constexpr auto* BIBLE_VERSE_APP_ID = "one.tactility.bibleverse";
|
||||
AppManifest manifest {};
|
||||
AppInstanceId instance_id = 0;
|
||||
if (app_manager_find_manifest(BIBLE_VERSE_APP_ID, &manifest) == ERROR_NONE
|
||||
&& app_start(BIBLE_VERSE_APP_ID, 0, nullptr, &instance_id) == ERROR_NONE) {
|
||||
LOG_I(TAG, "Bible Verse screensaver: launched instance %u", (unsigned)instance_id);
|
||||
screensaverAppInstanceId = instance_id;
|
||||
screensaverAppActive = true;
|
||||
setBacklightBrightness(screensaverBacklightDuty(cachedDisplaySettings));
|
||||
return;
|
||||
}
|
||||
LOG_W(TAG, "Bible Verse app not installed, falling back to black screen");
|
||||
}
|
||||
|
||||
lv_obj_t* top = lv_layer_top();
|
||||
|
||||
if (screensaverOverlay != nullptr) return;
|
||||
|
||||
lv_coord_t screenW = lv_display_get_horizontal_resolution(nullptr);
|
||||
lv_coord_t screenH = lv_display_get_vertical_resolution(nullptr);
|
||||
|
||||
@@ -127,6 +188,9 @@ void DisplayIdleService::activateScreensaver() {
|
||||
case settings::display::ScreensaverType::StackChan:
|
||||
screensaver = std::make_unique<StackChanScreensaver>();
|
||||
break;
|
||||
case settings::display::ScreensaverType::McpScreen:
|
||||
screensaver = std::make_unique<McpScreensaver>();
|
||||
break;
|
||||
case settings::display::ScreensaverType::None:
|
||||
default:
|
||||
// Just black screen, no animated screensaver
|
||||
@@ -137,6 +201,8 @@ void DisplayIdleService::activateScreensaver() {
|
||||
if (screensaver) {
|
||||
screensaver->start(screensaverOverlay, screenW, screenH);
|
||||
}
|
||||
|
||||
setBacklightBrightness(screensaverBacklightDuty(cachedDisplaySettings));
|
||||
}
|
||||
|
||||
void DisplayIdleService::updateScreensaver() {
|
||||
@@ -166,8 +232,8 @@ void DisplayIdleService::tick() {
|
||||
inactive_ms = lv_display_get_inactive_time(nullptr);
|
||||
|
||||
// Only update if not stopping (prevents lag on touch)
|
||||
if (displayDimmed && screensaverOverlay && !stopScreensaverRequested.load(std::memory_order_acquire)) {
|
||||
// Check if screensaver should auto-off after 5 minutes
|
||||
if (displayDimmed && (screensaverOverlay || screensaverAppActive) && !stopScreensaverRequested.load(std::memory_order_acquire)) {
|
||||
// Check if screensaver should auto-off after 30 minutes
|
||||
if (!backlightOff) {
|
||||
screensaverActiveCounter++;
|
||||
if (screensaverActiveCounter >= SCREENSAVER_AUTO_OFF_TICKS) {
|
||||
@@ -176,6 +242,13 @@ void DisplayIdleService::tick() {
|
||||
screensaver->stop();
|
||||
screensaver.reset();
|
||||
}
|
||||
if (screensaverAppActive) {
|
||||
screensaverAppActive = false;
|
||||
if (screensaverAppInstanceId != 0) {
|
||||
app_manager_stop(screensaverAppInstanceId);
|
||||
screensaverAppInstanceId = 0;
|
||||
}
|
||||
}
|
||||
setBacklightBrightness(0);
|
||||
backlightOff = true;
|
||||
} else {
|
||||
@@ -211,6 +284,10 @@ void DisplayIdleService::tick() {
|
||||
}
|
||||
displayDimmed = true;
|
||||
} else if (displayDimmed && (inactive_ms < kWakeActivityThresholdMs)) {
|
||||
// The Bible Verse app keeps LVGL timers running (minute-advance),
|
||||
// so plain inactivity never drops while it is up. Taps still
|
||||
// register as activity: stop the verse app to return to launcher.
|
||||
// If the user already closed it, stopScreensaver() is a safe no-op.
|
||||
stopScreensaver();
|
||||
}
|
||||
}
|
||||
@@ -247,6 +324,13 @@ void DisplayIdleService::onStop(ServiceContext& service) {
|
||||
LOG_W(TAG, "Failed to stop screensaver during shutdown - potential resource leak");
|
||||
}
|
||||
}
|
||||
if (screensaverAppActive) {
|
||||
screensaverAppActive = false;
|
||||
if (screensaverAppInstanceId != 0) {
|
||||
app_manager_stop(screensaverAppInstanceId);
|
||||
screensaverAppInstanceId = 0;
|
||||
}
|
||||
}
|
||||
screensaver.reset();
|
||||
}
|
||||
|
||||
@@ -259,8 +343,19 @@ void DisplayIdleService::startScreensaver() {
|
||||
// Note: This is safe because we hold the LVGL lock which serializes with tick()
|
||||
cachedDisplaySettings = settings::display::loadOrGetDefault();
|
||||
|
||||
// The Bible Verse path launches an app task (not an overlay), which must
|
||||
// not run under the LVGL lock: drop it before activating.
|
||||
const bool launches_app =
|
||||
cachedDisplaySettings.screensaverType == settings::display::ScreensaverType::BibleVerse;
|
||||
if (launches_app) {
|
||||
lvgl_unlock();
|
||||
}
|
||||
|
||||
activateScreensaver();
|
||||
lvgl_unlock();
|
||||
|
||||
if (!launches_app) {
|
||||
lvgl_unlock();
|
||||
}
|
||||
|
||||
// Turn off backlight for "None" screensaver
|
||||
if (hasDisplayWithBacklight() && cachedDisplaySettings.screensaverType == settings::display::ScreensaverType::None) {
|
||||
@@ -270,7 +365,50 @@ void DisplayIdleService::startScreensaver() {
|
||||
}
|
||||
|
||||
bool DisplayIdleService::isScreensaverActive() const {
|
||||
return screensaverOverlay != nullptr;
|
||||
return screensaverOverlay != nullptr || screensaverAppActive;
|
||||
}
|
||||
|
||||
void DisplayIdleService::startMcpScreensaver() {
|
||||
if (!lvgl_try_lock(200)) {
|
||||
LOG_W(TAG, "startMcpScreensaver: failed to acquire LVGL lock");
|
||||
return;
|
||||
}
|
||||
|
||||
if (screensaverOverlay != nullptr) {
|
||||
const auto& mcpState = mcp::getState();
|
||||
if (mcpState.drawArea != nullptr) {
|
||||
lvgl_unlock();
|
||||
return;
|
||||
}
|
||||
if (screensaver) {
|
||||
screensaver->stop();
|
||||
screensaver.reset();
|
||||
}
|
||||
lv_obj_delete(screensaverOverlay);
|
||||
screensaverOverlay = nullptr;
|
||||
}
|
||||
|
||||
screensaverActiveCounter = 0;
|
||||
backlightOff = false;
|
||||
setBacklightBrightness(cachedDisplaySettings.backlightDuty == 0
|
||||
? 255 : screensaverBacklightDuty(cachedDisplaySettings));
|
||||
|
||||
lv_coord_t screenW = lv_display_get_horizontal_resolution(nullptr);
|
||||
lv_coord_t screenH = lv_display_get_vertical_resolution(nullptr);
|
||||
screensaverOverlay = lv_obj_create(lv_layer_top());
|
||||
lv_obj_remove_style_all(screensaverOverlay);
|
||||
lv_obj_set_size(screensaverOverlay, LV_PCT(100), LV_PCT(100));
|
||||
lv_obj_set_pos(screensaverOverlay, 0, 0);
|
||||
lv_obj_set_style_bg_color(screensaverOverlay, lv_color_black(), 0);
|
||||
lv_obj_set_style_bg_opa(screensaverOverlay, LV_OPA_COVER, 0);
|
||||
lv_obj_add_flag(screensaverOverlay, LV_OBJ_FLAG_CLICKABLE);
|
||||
lv_obj_add_event_cb(screensaverOverlay, stopScreensaverCb, LV_EVENT_CLICKED, this);
|
||||
|
||||
screensaver = std::make_unique<McpScreensaver>();
|
||||
screensaver->start(screensaverOverlay, screenW, screenH);
|
||||
lvgl_unlock();
|
||||
displayDimmed = true;
|
||||
LOG_I(TAG, "MCP screensaver activated");
|
||||
}
|
||||
|
||||
void DisplayIdleService::reloadSettings() {
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
#ifdef ESP_PLATFORM
|
||||
|
||||
#include "McpScreensaver.h"
|
||||
#include <Tactility/mcp/McpSystem.h>
|
||||
#include <tactility/log.h>
|
||||
|
||||
constexpr auto* TAG = "McpScreensaver";
|
||||
#include <esp_heap_caps.h>
|
||||
|
||||
namespace tt::service::displayidle {
|
||||
|
||||
|
||||
void McpScreensaver::start(lv_obj_t* overlay, lv_coord_t screenW, lv_coord_t screenH) {
|
||||
auto& state = mcp::getState();
|
||||
|
||||
// Full-screen canvas on the overlay
|
||||
lv_obj_t* canvas = lv_canvas_create(overlay);
|
||||
lv_obj_set_size(canvas, screenW, screenH);
|
||||
lv_obj_set_pos(canvas, 0, 0);
|
||||
lv_obj_set_style_radius(canvas, 0, LV_PART_MAIN);
|
||||
lv_obj_set_style_border_width(canvas, 0, LV_PART_MAIN);
|
||||
lv_obj_set_style_pad_all(canvas, 0, LV_PART_MAIN);
|
||||
lv_obj_remove_flag(canvas, LV_OBJ_FLAG_SCROLLABLE);
|
||||
|
||||
// Allocate framebuffer (prefer SPIRAM)
|
||||
size_t requiredSize = (size_t)screenW * screenH * sizeof(uint16_t);
|
||||
framebuffer = (uint16_t*)heap_caps_malloc(requiredSize, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
|
||||
if (framebuffer == nullptr) {
|
||||
framebuffer = (uint16_t*)heap_caps_malloc(requiredSize, MALLOC_CAP_8BIT);
|
||||
}
|
||||
framebufferSize = (framebuffer != nullptr) ? requiredSize : 0;
|
||||
|
||||
if (framebuffer == nullptr) {
|
||||
LOG_E(TAG, "Failed to allocate %uB framebuffer", (unsigned)requiredSize);
|
||||
lv_obj_t* err = lv_label_create(canvas);
|
||||
lv_label_set_text(err, "Framebuffer alloc failed");
|
||||
lv_obj_center(err);
|
||||
return;
|
||||
}
|
||||
|
||||
// Fill with a dark slate background (inverted for display path)
|
||||
size_t pixelCount = (size_t)screenW * screenH;
|
||||
for (size_t i = 0; i < pixelCount; ++i) {
|
||||
framebuffer[i] = ~0x18E3; // dark blue-grey
|
||||
}
|
||||
|
||||
lv_canvas_set_buffer(canvas, framebuffer, screenW, screenH, LV_COLOR_FORMAT_RGB565);
|
||||
|
||||
// Waiting label (removed on first MCP draw via lv_obj_clean)
|
||||
lv_obj_t* waitLabel = lv_label_create(canvas);
|
||||
lv_label_set_text(waitLabel, "Waiting for LLM...");
|
||||
lv_obj_set_style_text_color(waitLabel, lv_color_black(), LV_PART_MAIN); // white on screen (inverted)
|
||||
lv_obj_align(waitLabel, LV_ALIGN_CENTER, 0, -20);
|
||||
|
||||
lv_obj_t* resLabel = lv_label_create(canvas);
|
||||
lv_label_set_text_fmt(resLabel, "Display: %dx%d", (int)screenW, (int)screenH);
|
||||
lv_color_t resColor = lv_palette_lighten(LV_PALETTE_BLUE, 3);
|
||||
lv_obj_set_style_text_color(resLabel, lv_color_make(~resColor.red, ~resColor.green, ~resColor.blue), LV_PART_MAIN);
|
||||
lv_obj_align(resLabel, LV_ALIGN_CENTER, 0, 10);
|
||||
|
||||
// Register with McpSystemState
|
||||
std::lock_guard<std::mutex> lock(state.mutex);
|
||||
state.drawArea = canvas;
|
||||
state.framebuffer = framebuffer;
|
||||
state.framebufferSize = framebufferSize;
|
||||
state.displayWidth = (uint16_t)screenW;
|
||||
state.displayHeight = (uint16_t)screenH;
|
||||
state.drawWidth = (uint16_t)screenW;
|
||||
state.drawHeight = (uint16_t)screenH;
|
||||
// Don't reset overrideActive — if the LLM already drew, we keep the content
|
||||
|
||||
LOG_I(TAG, "McpScreensaver started (%dx%d)", (int)screenW, (int)screenH);
|
||||
}
|
||||
|
||||
void McpScreensaver::stop() {
|
||||
auto& state = mcp::getState();
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(state.mutex);
|
||||
state.drawArea = nullptr;
|
||||
state.framebuffer = nullptr;
|
||||
state.framebufferSize = 0;
|
||||
state.overrideActive = false;
|
||||
}
|
||||
|
||||
if (framebuffer != nullptr) {
|
||||
heap_caps_free(framebuffer);
|
||||
framebuffer = nullptr;
|
||||
framebufferSize = 0;
|
||||
}
|
||||
|
||||
LOG_I(TAG, "McpScreensaver stopped");
|
||||
}
|
||||
|
||||
void McpScreensaver::update(lv_coord_t /*screenW*/, lv_coord_t /*screenH*/) {
|
||||
// MCP draws on demand via HTTP — no per-frame animation needed
|
||||
}
|
||||
|
||||
} // namespace tt::service::displayidle
|
||||
|
||||
#endif // ESP_PLATFORM
|
||||
@@ -0,0 +1,30 @@
|
||||
#pragma once
|
||||
#ifdef ESP_PLATFORM
|
||||
|
||||
#include "Screensaver.h"
|
||||
#include <cstdint>
|
||||
|
||||
namespace tt::service::displayidle {
|
||||
|
||||
/**
|
||||
* MCP Screen screensaver.
|
||||
* Creates a full-screen LVGL canvas on the overlay and registers it in
|
||||
* McpSystemState so that MCP HTTP draw commands can paint to it.
|
||||
* Dismissed by a touch event (handled by the parent DisplayIdle overlay).
|
||||
*/
|
||||
class McpScreensaver final : public Screensaver {
|
||||
uint16_t* framebuffer = nullptr;
|
||||
size_t framebufferSize = 0;
|
||||
|
||||
public:
|
||||
McpScreensaver() = default;
|
||||
~McpScreensaver() override = default;
|
||||
|
||||
void start(lv_obj_t* overlay, lv_coord_t screenW, lv_coord_t screenH) override;
|
||||
void stop() override;
|
||||
void update(lv_coord_t screenW, lv_coord_t screenH) override;
|
||||
};
|
||||
|
||||
} // namespace tt::service::displayidle
|
||||
|
||||
#endif // ESP_PLATFORM
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,258 @@
|
||||
#ifndef ESP_PLATFORM
|
||||
|
||||
#include <Tactility/service/webserver/WebServerService.h>
|
||||
#include <Tactility/lvgl/Lvgl.h>
|
||||
#include <lvgl/lvgl.h>
|
||||
#include <app/manager.h>
|
||||
#include <app/start.h>
|
||||
#include <cJSON.h>
|
||||
#include <http/server.h>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace tt::service::webserver {
|
||||
namespace {
|
||||
constexpr size_t JSON_BODY_LIMIT = 64 * 1024;
|
||||
lv_obj_t* gCanvas = nullptr;
|
||||
bool gCanvasBlack = false;
|
||||
|
||||
lv_obj_t* getCanvas() {
|
||||
if (gCanvas != nullptr) return gCanvas;
|
||||
lv_display_t* display = lv_display_get_default();
|
||||
if (display == nullptr) return nullptr;
|
||||
lv_obj_t* layer = lv_display_get_layer_top(display);
|
||||
gCanvas = lv_obj_create(layer);
|
||||
lv_obj_set_pos(gCanvas, 0, 0);
|
||||
lv_obj_set_size(gCanvas, lv_display_get_horizontal_resolution(display), lv_display_get_vertical_resolution(display));
|
||||
lv_obj_set_style_pad_all(gCanvas, 0, LV_PART_MAIN);
|
||||
lv_obj_set_style_border_width(gCanvas, 0, LV_PART_MAIN);
|
||||
lv_obj_set_style_bg_opa(gCanvas, LV_OPA_TRANSP, LV_PART_MAIN);
|
||||
lv_obj_clear_flag(gCanvas, LV_OBJ_FLAG_SCROLLABLE);
|
||||
lv_obj_clear_flag(gCanvas, LV_OBJ_FLAG_CLICKABLE);
|
||||
return gCanvas;
|
||||
}
|
||||
|
||||
bool clearCanvas(int color) {
|
||||
lv_obj_t* canvas = getCanvas();
|
||||
if (canvas == nullptr) return false;
|
||||
lv_obj_clean(canvas);
|
||||
gCanvasBlack = color == 1;
|
||||
lv_obj_set_style_bg_color(canvas, gCanvasBlack ? lv_color_black() : lv_color_white(), LV_PART_MAIN);
|
||||
lv_obj_set_style_bg_opa(canvas, LV_OPA_COVER, LV_PART_MAIN);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool drawCanvasText(const char* text, int x, int y) {
|
||||
lv_obj_t* canvas = getCanvas();
|
||||
if (canvas == nullptr) return false;
|
||||
lv_obj_t* label = lv_label_create(canvas);
|
||||
lv_label_set_text(label, text);
|
||||
lv_obj_set_pos(label, x, y);
|
||||
lv_obj_set_style_text_color(label, gCanvasBlack ? lv_color_white() : lv_color_black(), LV_PART_MAIN);
|
||||
return true;
|
||||
}
|
||||
|
||||
cJSON* makeError(const cJSON* id, int code, const char* message) {
|
||||
cJSON* response = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(response, "jsonrpc", "2.0");
|
||||
cJSON* error = cJSON_AddObjectToObject(response, "error");
|
||||
cJSON_AddNumberToObject(error, "code", code);
|
||||
cJSON_AddStringToObject(error, "message", message);
|
||||
if (id != nullptr) cJSON_AddItemToObject(response, "id", cJSON_Duplicate(id, true));
|
||||
else cJSON_AddNullToObject(response, "id");
|
||||
return response;
|
||||
}
|
||||
|
||||
cJSON* makeTextResult(const cJSON* id, const char* text, bool isError = false) {
|
||||
cJSON* response = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(response, "jsonrpc", "2.0");
|
||||
cJSON* result = cJSON_AddObjectToObject(response, "result");
|
||||
cJSON* content = cJSON_AddArrayToObject(result, "content");
|
||||
cJSON* item = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(item, "type", "text");
|
||||
cJSON_AddStringToObject(item, "text", text);
|
||||
cJSON_AddItemToArray(content, item);
|
||||
if (isError) cJSON_AddBoolToObject(result, "isError", true);
|
||||
if (id != nullptr) cJSON_AddItemToObject(response, "id", cJSON_Duplicate(id, true));
|
||||
else cJSON_AddNullToObject(response, "id");
|
||||
return response;
|
||||
}
|
||||
|
||||
cJSON* makeToolList(const cJSON* id) {
|
||||
cJSON* response = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(response, "jsonrpc", "2.0");
|
||||
cJSON* result = cJSON_AddObjectToObject(response, "result");
|
||||
cJSON* tools = cJSON_AddArrayToObject(result, "tools");
|
||||
|
||||
cJSON* capabilities = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(capabilities, "name", "get_capabilities");
|
||||
cJSON_AddStringToObject(capabilities, "description", "Get the simulator platform and display capability information.");
|
||||
cJSON_AddItemToObject(capabilities, "inputSchema", cJSON_Parse("{\"type\":\"object\",\"properties\":{}}"));
|
||||
cJSON_AddItemToArray(tools, capabilities);
|
||||
|
||||
cJSON* listApps = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(listApps, "name", "list_apps");
|
||||
cJSON_AddStringToObject(listApps, "description", "List apps available in the simulator.");
|
||||
cJSON_AddItemToObject(listApps, "inputSchema", cJSON_Parse("{\"type\":\"object\",\"properties\":{}}"));
|
||||
cJSON_AddItemToArray(tools, listApps);
|
||||
|
||||
cJSON* runApp = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(runApp, "name", "run_app");
|
||||
cJSON_AddStringToObject(runApp, "description", "Launch an installed simulator app by its app ID.");
|
||||
cJSON_AddItemToObject(runApp, "inputSchema", cJSON_Parse("{\"type\":\"object\",\"properties\":{\"app_id\":{\"type\":\"string\"}},\"required\":[\"app_id\"]}"));
|
||||
cJSON_AddItemToArray(tools, runApp);
|
||||
|
||||
cJSON* clearScreen = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(clearScreen, "name", "clear_screen");
|
||||
cJSON_AddStringToObject(clearScreen, "description", "Clear the MCP drawing canvas to white (0) or black (1).");
|
||||
cJSON_AddItemToObject(clearScreen, "inputSchema", cJSON_Parse("{\"type\":\"object\",\"properties\":{\"color\":{\"type\":\"integer\",\"enum\":[0,1]}},\"required\":[\"color\"]}"));
|
||||
cJSON_AddItemToArray(tools, clearScreen);
|
||||
|
||||
cJSON* drawText = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(drawText, "name", "draw_text");
|
||||
cJSON_AddStringToObject(drawText, "description", "Draw text on the simulator MCP canvas at x,y coordinates.");
|
||||
cJSON_AddItemToObject(drawText, "inputSchema", cJSON_Parse("{\"type\":\"object\",\"properties\":{\"text\":{\"type\":\"string\"},\"x\":{\"type\":\"integer\"},\"y\":{\"type\":\"integer\"}},\"required\":[\"text\",\"x\",\"y\"]}"));
|
||||
cJSON_AddItemToArray(tools, drawText);
|
||||
|
||||
if (id != nullptr) cJSON_AddItemToObject(response, "id", cJSON_Duplicate(id, true));
|
||||
else cJSON_AddNullToObject(response, "id");
|
||||
return response;
|
||||
}
|
||||
|
||||
std::string listAppsJson() {
|
||||
std::vector<const AppManifest*> manifests;
|
||||
app_manager_for_each_manifest([](const AppManifest* manifest, void* context) {
|
||||
static_cast<std::vector<const AppManifest*>*>(context)->push_back(manifest);
|
||||
}, &manifests);
|
||||
|
||||
cJSON* apps = cJSON_CreateArray();
|
||||
for (const AppManifest* manifest : manifests) {
|
||||
cJSON* app = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(app, "id", manifest->id);
|
||||
cJSON_AddStringToObject(app, "name", manifest->name);
|
||||
cJSON_AddItemToArray(apps, app);
|
||||
}
|
||||
char* text = cJSON_PrintUnformatted(apps);
|
||||
std::string output = text == nullptr ? "[]" : text;
|
||||
cJSON_free(text);
|
||||
cJSON_Delete(apps);
|
||||
return output;
|
||||
}
|
||||
|
||||
cJSON* handleCall(const cJSON* id, const cJSON* params) {
|
||||
const cJSON* name = cJSON_GetObjectItemCaseSensitive(params, "name");
|
||||
const cJSON* args = cJSON_GetObjectItemCaseSensitive(params, "arguments");
|
||||
if (!cJSON_IsString(name) || (args != nullptr && !cJSON_IsObject(args))) {
|
||||
return makeError(id, -32602, "Invalid params");
|
||||
}
|
||||
|
||||
if (strcmp(name->valuestring, "clear_screen") == 0) {
|
||||
const cJSON* color = cJSON_GetObjectItemCaseSensitive(args, "color");
|
||||
if (!cJSON_IsNumber(color) || (color->valueint != 0 && color->valueint != 1)) {
|
||||
return makeError(id, -32602, "color must be 0 (white) or 1 (black)");
|
||||
}
|
||||
lvgl_lock();
|
||||
const bool cleared = clearCanvas(color->valueint);
|
||||
lvgl_unlock();
|
||||
return cleared ? makeTextResult(id, "ok") : makeTextResult(id, "no active display", true);
|
||||
}
|
||||
if (strcmp(name->valuestring, "draw_text") == 0) {
|
||||
const cJSON* text = cJSON_GetObjectItemCaseSensitive(args, "text");
|
||||
const cJSON* x = cJSON_GetObjectItemCaseSensitive(args, "x");
|
||||
const cJSON* y = cJSON_GetObjectItemCaseSensitive(args, "y");
|
||||
if (!cJSON_IsString(text) || text->valuestring == nullptr || strlen(text->valuestring) > 4096 ||
|
||||
!cJSON_IsNumber(x) || !cJSON_IsNumber(y) || x->valueint < 0 || y->valueint < 0) {
|
||||
return makeError(id, -32602, "text, non-negative x and y are required (text max 4096 chars)");
|
||||
}
|
||||
lvgl_lock();
|
||||
lv_display_t* display = lv_display_get_default();
|
||||
const bool inBounds = display != nullptr && x->valueint < lv_display_get_horizontal_resolution(display) &&
|
||||
y->valueint < lv_display_get_vertical_resolution(display);
|
||||
const bool drawn = inBounds && drawCanvasText(text->valuestring, x->valueint, y->valueint);
|
||||
lvgl_unlock();
|
||||
if (!inBounds) return makeError(id, -32602, "coordinates are outside the simulator display");
|
||||
return drawn ? makeTextResult(id, "ok") : makeTextResult(id, "could not draw on display", true);
|
||||
}
|
||||
if (strcmp(name->valuestring, "get_capabilities") == 0) {
|
||||
return makeTextResult(id, "{\"platform\":\"tactility-simulator\",\"mcp\":true,\"drawing\":true}");
|
||||
}
|
||||
if (strcmp(name->valuestring, "list_apps") == 0) {
|
||||
const std::string apps = listAppsJson();
|
||||
return makeTextResult(id, apps.c_str());
|
||||
}
|
||||
if (strcmp(name->valuestring, "run_app") == 0) {
|
||||
const cJSON* appId = cJSON_GetObjectItemCaseSensitive(args, "app_id");
|
||||
if (!cJSON_IsString(appId) || appId->valuestring == nullptr || appId->valuestring[0] == '\0') {
|
||||
return makeError(id, -32602, "app_id is required");
|
||||
}
|
||||
AppManifest manifest{};
|
||||
if (app_manager_find_manifest(appId->valuestring, &manifest) != ERROR_NONE) {
|
||||
return makeTextResult(id, "app not found", true);
|
||||
}
|
||||
AppInstanceId instanceId = 0;
|
||||
const error_t result = app_start(appId->valuestring, 0, nullptr, &instanceId);
|
||||
if (result != ERROR_NONE) return makeTextResult(id, "app launch failed", true);
|
||||
return makeTextResult(id, "ok");
|
||||
}
|
||||
return makeError(id, -32602, "Unknown simulator MCP tool");
|
||||
}
|
||||
|
||||
cJSON* handleRpc(const char* body) {
|
||||
cJSON* request = cJSON_Parse(body);
|
||||
if (request == nullptr) return makeError(nullptr, -32700, "Parse error");
|
||||
const cJSON* id = cJSON_GetObjectItemCaseSensitive(request, "id");
|
||||
const cJSON* version = cJSON_GetObjectItemCaseSensitive(request, "jsonrpc");
|
||||
const cJSON* method = cJSON_GetObjectItemCaseSensitive(request, "method");
|
||||
const cJSON* params = cJSON_GetObjectItemCaseSensitive(request, "params");
|
||||
|
||||
cJSON* response = nullptr;
|
||||
if (!cJSON_IsObject(request) || !cJSON_IsString(version) || strcmp(version->valuestring, "2.0") != 0 || !cJSON_IsString(method)) {
|
||||
response = makeError(id, -32600, "Invalid Request");
|
||||
} else if (strcmp(method->valuestring, "tools/list") == 0) {
|
||||
response = makeToolList(id);
|
||||
} else if (strcmp(method->valuestring, "tools/call") == 0) {
|
||||
response = handleCall(id, params);
|
||||
} else {
|
||||
response = makeError(id, -32601, "Method not found");
|
||||
}
|
||||
cJSON_Delete(request);
|
||||
return response;
|
||||
}
|
||||
}
|
||||
|
||||
error_t WebServerService::handleApiMcp(HttpServerRequest* request, void*) {
|
||||
const uint64_t length = http_server_request_get_content_length(request);
|
||||
if (length == 0 || length > JSON_BODY_LIMIT) {
|
||||
http_server_request_send_error(request, 400, "Invalid Content-Length");
|
||||
return ERROR_INVALID_ARGUMENT;
|
||||
}
|
||||
std::string body(static_cast<size_t>(length), '\0');
|
||||
size_t received = 0;
|
||||
while (received < body.size()) {
|
||||
const int count = http_server_request_receive(request, body.data() + received, body.size() - received);
|
||||
if (count <= 0) {
|
||||
http_server_request_send_error(request, 400, "Incomplete request body");
|
||||
return ERROR_UNDEFINED;
|
||||
}
|
||||
received += static_cast<size_t>(count);
|
||||
}
|
||||
|
||||
cJSON* response = handleRpc(body.c_str());
|
||||
char* text = cJSON_PrintUnformatted(response);
|
||||
cJSON_Delete(response);
|
||||
if (text == nullptr) {
|
||||
http_server_request_send_error(request, 500, "Serialization failed");
|
||||
return ERROR_RESOURCE;
|
||||
}
|
||||
http_server_request_set_content_type(request, "application/json");
|
||||
http_server_request_send_string(request, text);
|
||||
cJSON_free(text);
|
||||
return ERROR_NONE;
|
||||
}
|
||||
}
|
||||
|
||||
#endif // ESP_PLATFORM
|
||||
@@ -26,12 +26,26 @@
|
||||
|
||||
#if TT_FEATURE_SCREENSHOT_ENABLED
|
||||
#include <lv_screenshot.h>
|
||||
// lodepng.h enables its C++ overloads (std::vector/std::string) when compiled
|
||||
// as C++; save_png.c compiles it as C. WebServerService.cpp is C++, so opt out
|
||||
// of the C++ wrapper to get the same C API save_png.c uses.
|
||||
#define LODEPNG_NO_COMPILE_CPP
|
||||
#include "src/libs/lodepng/lodepng.h"
|
||||
#endif
|
||||
|
||||
#include "app/install.h"
|
||||
#include "app/manager.h"
|
||||
|
||||
#ifndef ESP_PLATFORM
|
||||
// Simulator touch injection backend (Devices/simulator sdl-pointer driver).
|
||||
// Declared extern "C" here instead of including the device header: Tactility
|
||||
// must not depend upward on a device implementation.
|
||||
extern "C" void sdl_input_set_touch_override(int32_t x, int32_t y, bool pressed);
|
||||
#endif
|
||||
|
||||
#ifdef ESP_PLATFORM
|
||||
#include <Tactility/mcp/McpSystem.h>
|
||||
#include <Tactility/settings/McpSettings.h>
|
||||
#include <esp_chip_info.h>
|
||||
#include <esp_flash.h>
|
||||
#include <esp_heap_caps.h>
|
||||
@@ -213,7 +227,11 @@ bool WebServerService::onStart(ServiceContext& service) {
|
||||
lock.lock();
|
||||
g_cachedSettings = settings::webserver::loadOrGetDefault();
|
||||
g_settingsCached = true;
|
||||
#ifdef ESP_PLATFORM
|
||||
serverEnabled = g_cachedSettings.webServerEnabled || settings::mcp::loadOrGetDefault().mcpEnabled;
|
||||
#else
|
||||
serverEnabled = g_cachedSettings.webServerEnabled;
|
||||
#endif
|
||||
}
|
||||
// Subscribe to settings change events to refresh cache
|
||||
settingsEventSubscription = pubsub->subscribe([](WebServerEvent event) {
|
||||
@@ -222,6 +240,14 @@ bool WebServerService::onStart(ServiceContext& service) {
|
||||
lock.lock();
|
||||
g_cachedSettings = settings::webserver::loadOrGetDefault();
|
||||
g_settingsCached = true;
|
||||
#ifdef ESP_PLATFORM
|
||||
const bool enabled = g_cachedSettings.webServerEnabled || settings::mcp::loadOrGetDefault().mcpEnabled;
|
||||
#else
|
||||
const bool enabled = g_cachedSettings.webServerEnabled;
|
||||
#endif
|
||||
if (g_webServerInstance.load() != nullptr) {
|
||||
g_webServerInstance.load()->setEnabled(enabled);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -481,6 +507,21 @@ bool WebServerService::startServer() {
|
||||
.callback = handleAdminPost,
|
||||
.user_ctx = ctx
|
||||
},
|
||||
// MCP is available on physical devices and the POSIX simulator.
|
||||
{
|
||||
.uri = "/api/mcp",
|
||||
.method = HTTP_METHOD_POST,
|
||||
.callback = handleApiMcp,
|
||||
.user_ctx = ctx
|
||||
},
|
||||
#ifdef ESP_PLATFORM
|
||||
{
|
||||
.uri = "/api/screen/raw",
|
||||
.method = HTTP_METHOD_POST,
|
||||
.callback = handleApiScreenRaw,
|
||||
.user_ctx = ctx
|
||||
},
|
||||
#endif
|
||||
// API endpoints for system info, apps, wifi, etc
|
||||
{
|
||||
.uri = "/api/*",
|
||||
@@ -500,6 +541,23 @@ bool WebServerService::startServer() {
|
||||
.callback = handleApiPut,
|
||||
.user_ctx = ctx
|
||||
},
|
||||
#ifndef ESP_PLATFORM
|
||||
// Simulator viewer aliases: the /sim page resolves api/ against its
|
||||
// own directory (/sim/api/...), so mirror the viewer-needed handlers
|
||||
// here. Same callbacks, auth enforced inside each handler.
|
||||
{
|
||||
.uri = "/sim/api/*",
|
||||
.method = HTTP_METHOD_GET,
|
||||
.callback = handleApiGet,
|
||||
.user_ctx = ctx
|
||||
},
|
||||
{
|
||||
.uri = "/sim/api/*",
|
||||
.method = HTTP_METHOD_POST,
|
||||
.callback = handleApiPost,
|
||||
.user_ctx = ctx
|
||||
},
|
||||
#endif
|
||||
{
|
||||
.uri = "/*", // Catch-all for dynamic assets
|
||||
.method = HTTP_METHOD_GET,
|
||||
@@ -528,6 +586,12 @@ bool WebServerService::startServer() {
|
||||
LOG_I(TAG, "HTTP server started successfully on port %u", (unsigned)settings.webServerPort);
|
||||
publish_event(this, WebServerEvent::WebServerStarted);
|
||||
|
||||
#ifdef ESP_PLATFORM
|
||||
if (settings::mcp::loadOrGetDefault().mcpEnabled) {
|
||||
mcp::startVideoStreamServer();
|
||||
}
|
||||
#endif
|
||||
|
||||
// Show statusbar icon
|
||||
if (statusbarIconId >= 0) {
|
||||
lvgl::statusbar_icon_set_image(statusbarIconId, LVGL_ICON_STATUSBAR_CLOUD);
|
||||
@@ -544,6 +608,9 @@ void WebServerService::stopServer() {
|
||||
return;
|
||||
}
|
||||
|
||||
#ifdef ESP_PLATFORM
|
||||
mcp::stopVideoStreamServer();
|
||||
#endif
|
||||
http_server_free(httpServer);
|
||||
httpServer = nullptr;
|
||||
|
||||
@@ -1008,9 +1075,17 @@ error_t WebServerService::handleAdminPost(HttpServerRequest* request, void* user
|
||||
|
||||
// API GET dispatcher - returns JSON system information
|
||||
// Note: /api/sysinfo is intentionally public for monitoring use cases
|
||||
// The /sim/api/* alias routes (sim viewer page) strip the /sim prefix here
|
||||
// so both /api/... and /sim/api/... share one dispatch table.
|
||||
static const char* api_path_suffix(HttpServerRequest* request, char* uri, size_t uri_size) {
|
||||
http_server_request_get_uri(request, uri, uri_size);
|
||||
if (strncmp(uri, "/sim/api/", 9) == 0) return uri + 4; // -> /api/...
|
||||
return uri;
|
||||
}
|
||||
|
||||
error_t WebServerService::handleApiGet(HttpServerRequest* request, void* user_ctx) {
|
||||
char uri[256];
|
||||
http_server_request_get_uri(request, uri, sizeof(uri));
|
||||
char uri_buf[256];
|
||||
const char* uri = api_path_suffix(request, uri_buf, sizeof(uri_buf));
|
||||
|
||||
// Public endpoint: sysinfo (basic device info for monitoring)
|
||||
if (strncmp(uri, "/api/sysinfo", 12) == 0) {
|
||||
@@ -1028,6 +1103,9 @@ error_t WebServerService::handleApiGet(HttpServerRequest* request, void* user_ct
|
||||
if (strncmp(uri, "/api/apps", 9) == 0) {
|
||||
return handleApiApps(request, user_ctx);
|
||||
}
|
||||
if (strncmp(uri, "/api/sim/touch", 14) == 0) {
|
||||
return handleApiSimTouch(request, user_ctx);
|
||||
}
|
||||
if (strncmp(uri, "/api/wifi", 9) == 0) {
|
||||
return handleApiWifi(request, user_ctx);
|
||||
}
|
||||
@@ -1048,11 +1126,14 @@ error_t WebServerService::handleApiPost(HttpServerRequest* request, void* user_c
|
||||
return authResult;
|
||||
}
|
||||
|
||||
char uri[256];
|
||||
http_server_request_get_uri(request, uri, sizeof(uri));
|
||||
char uri_buf[256];
|
||||
const char* uri = api_path_suffix(request, uri_buf, sizeof(uri_buf));
|
||||
if (strncmp(uri, "/api/apps/run", 13) == 0) {
|
||||
return handleApiAppsRun(request, user_ctx);
|
||||
}
|
||||
if (strncmp(uri, "/api/sim/touch", 14) == 0) {
|
||||
return handleApiSimTouch(request, user_ctx);
|
||||
}
|
||||
if (strncmp(uri, "/api/apps/uninstall", 19) == 0) {
|
||||
return handleApiAppsUninstall(request, user_ctx);
|
||||
}
|
||||
@@ -1488,11 +1569,76 @@ error_t WebServerService::handleApiWifi(HttpServerRequest* request, void*) {
|
||||
}
|
||||
|
||||
// GET /api/screenshot - Capture and return screenshot as PNG
|
||||
// Screenshots are saved to SD card root (if available) or /data with incrementing numbers
|
||||
// Fast path (no query or ?fast=1): snapshot LVGL to a memory buffer, PNG-encode
|
||||
// to memory with lodepng, stream directly. No filesystem touch, no slot scan.
|
||||
// Legacy path (?fast=0): previous save-to-webscreenshotN.png behavior.
|
||||
error_t WebServerService::handleApiScreenshot(HttpServerRequest* request, void*) {
|
||||
LOG_I(TAG, "GET /api/screenshot");
|
||||
|
||||
#if TT_FEATURE_SCREENSHOT_ENABLED
|
||||
std::string sfast;
|
||||
bool fast = true;
|
||||
if (getQueryParam(request, "fast", sfast)) fast = (sfast != "0");
|
||||
|
||||
if (fast) {
|
||||
// Hold the LVGL lock across snapshot + encode: both must see a stable
|
||||
// framebuffer. lv_snapshot_take renders synchronously under the lock.
|
||||
if (!lvgl_try_lock(pdMS_TO_TICKS(500))) {
|
||||
LOG_E(TAG, "Could not acquire LVGL lock within 500ms");
|
||||
http_server_request_send_error(request, 500, "could not acquire LVGL lock");
|
||||
return ERROR_UNDEFINED;
|
||||
}
|
||||
lv_draw_buf_t* snapshot = lv_snapshot_take(lv_scr_act(), LV_COLOR_FORMAT_RGB888);
|
||||
if (snapshot == nullptr) {
|
||||
lvgl_unlock();
|
||||
LOG_E(TAG, "lv_snapshot_take failed");
|
||||
http_server_request_send_error(request, 500, "snapshot failed");
|
||||
return ERROR_UNDEFINED;
|
||||
}
|
||||
// lodepng wants RGB triplets; snapshot is RGB888 = 3 bytes/px already,
|
||||
// but in BGR order on little-endian — swap R and B in place.
|
||||
uint32_t px_count = snapshot->header.w * snapshot->header.h;
|
||||
uint8_t* px = snapshot->data;
|
||||
for (uint32_t i = 0; i < px_count; i++) {
|
||||
uint8_t tmp = px[0];
|
||||
px[0] = px[2];
|
||||
px[2] = tmp;
|
||||
px += 3;
|
||||
}
|
||||
unsigned char* png = nullptr;
|
||||
size_t png_size = 0;
|
||||
unsigned enc_err = lodepng_encode24(&png, &png_size, snapshot->data,
|
||||
snapshot->header.w, snapshot->header.h);
|
||||
uint32_t w = snapshot->header.w, h = snapshot->header.h;
|
||||
lv_draw_buf_destroy(snapshot);
|
||||
lvgl_unlock();
|
||||
if (enc_err != 0 || png == nullptr) {
|
||||
LOG_E(TAG, "lodepng_encode24 failed: %u", enc_err);
|
||||
http_server_request_send_error(request, 500, "png encode failed");
|
||||
return ERROR_UNDEFINED;
|
||||
}
|
||||
LOG_I(TAG, "Screenshot %lux%lu %d bytes (memory path)", (unsigned long)w, (unsigned long)h, (int)png_size);
|
||||
http_server_request_set_content_type(request, "image/png");
|
||||
error_t result = ERROR_NONE;
|
||||
if (http_server_request_send_chunk_start(request) != ERROR_NONE) {
|
||||
result = ERROR_UNDEFINED;
|
||||
} else {
|
||||
size_t sent = 0;
|
||||
while (sent < png_size) {
|
||||
size_t n = png_size - sent > 8192 ? 8192 : png_size - sent;
|
||||
if (http_server_request_send_chunk(request, png + sent, n) != ERROR_NONE) {
|
||||
result = ERROR_UNDEFINED;
|
||||
break;
|
||||
}
|
||||
sent += n;
|
||||
}
|
||||
http_server_request_send_chunk_end(request);
|
||||
}
|
||||
free(png);
|
||||
LOG_I(TAG, "[200] /api/screenshot fast %d bytes", (int)png_size);
|
||||
return result;
|
||||
}
|
||||
|
||||
// Determine save location: prefer SD card root if mounted, otherwise /data
|
||||
std::string save_path = getDataPath();
|
||||
|
||||
@@ -1734,6 +1880,83 @@ error_t WebServerService::handleReboot(HttpServerRequest* request, void*) {
|
||||
return ERROR_NONE; // Unreachable on ESP_PLATFORM, but satisfies function signature
|
||||
}
|
||||
|
||||
// POST /api/sim/touch?x=123&y=456[&down=0|1] - inject touch into simulator.
|
||||
// Simulator-only: on ESP32 there is no sdl-pointer backend, so this 404s.
|
||||
// x/y are LVGL logical pixels (see viewer footer for current WxH).
|
||||
// down=1 (default) presses and auto-releases after ~1.5s (long enough for LVGL
|
||||
// indev polls to register a click); down=0 releases immediately.
|
||||
error_t WebServerService::handleApiSimTouch(HttpServerRequest* request, void*) {
|
||||
#ifdef ESP_PLATFORM
|
||||
http_server_request_send_error(request, 404, "simulator only");
|
||||
return ERROR_UNDEFINED;
|
||||
#else
|
||||
std::string sx, sy, sdown;
|
||||
int x = -1, y = -1;
|
||||
if (getQueryParam(request, "x", sx)) x = atoi(sx.c_str());
|
||||
if (getQueryParam(request, "y", sy)) y = atoi(sy.c_str());
|
||||
bool down = true;
|
||||
if (getQueryParam(request, "down", sdown)) down = (sdown != "0");
|
||||
if (x < 0 || y < 0 || x > 4096 || y > 4096) {
|
||||
http_server_request_send_error(request, 400, "x and y params required (0..4096)");
|
||||
return ERROR_UNDEFINED;
|
||||
}
|
||||
sdl_input_set_touch_override((int32_t)x, (int32_t)y, down);
|
||||
LOG_I(TAG, "[200] /api/sim/touch x=%d y=%d down=%d", x, y, (int)down);
|
||||
http_server_request_send_string(request, "ok");
|
||||
return ERROR_NONE;
|
||||
#endif
|
||||
}
|
||||
|
||||
// GET /sim - live simulator viewer: MJPEG-style screenshot refresh + click-to-touch.
|
||||
error_t WebServerService::handleSimViewer(HttpServerRequest* request, void*) {
|
||||
bool authPassed = false;
|
||||
error_t authResult = validateRequestAuth(request, authPassed);
|
||||
if (!authPassed) {
|
||||
return authResult;
|
||||
}
|
||||
http_server_request_set_content_type(request, "text/html");
|
||||
// NOTE: the page resolves api/ against its own directory (new URL(u,base)).
|
||||
// Locally that is /sim -> /sim/api/...; behind tailscale
|
||||
// (--set-path=/simagent -> /) it is /simagent/sim -> /simagent/api/...
|
||||
// Both need handler aliases, registered in startServer() below:
|
||||
// /sim/api/* mirrors /api/* (screenshot, sim/touch). The page itself must
|
||||
// therefore be served with a trailing-slash-insensitive /sim match so the
|
||||
// browser treats /sim as a directory (see handleAssets /sim route).
|
||||
static const char* page =
|
||||
"<!doctype html><html><head><meta charset=utf-8><meta name=viewport "
|
||||
"content='width=device-width,initial-scale=1'>"
|
||||
"<title>Tactility Sim</title><style>"
|
||||
"body{margin:0;background:#111;color:#eee;font-family:sans-serif;"
|
||||
"display:flex;flex-direction:column;align-items:center;gap:8px;padding:12px}"
|
||||
"img{width:min(96vw,720px);image-rendering:pixelated;border:1px solid #333;"
|
||||
"border-radius:8px;touch-action:none;cursor:crosshair;background:#000}"
|
||||
".bar{display:flex;gap:8px;align-items:center;font-size:13px;color:#aaa}"
|
||||
"button{background:#313244;color:#fff;border:0;border-radius:8px;padding:6px 12px}"
|
||||
"</style></head><body>"
|
||||
"<div class=bar><b>Tactility Sim</b><span id=st>live</span>"
|
||||
"<button onclick='snap()'>refresh</button></div>"
|
||||
"<img id=scr alt='sim screen'>"
|
||||
"<div class=bar>click/tap the screen to touch · <span id=res></span> logical</div>"
|
||||
"<script>"
|
||||
"const img=document.getElementById('scr'),st=document.getElementById('st'),"
|
||||
"res=document.getElementById('res');"
|
||||
"const base=new URL('.',location.href).href;"
|
||||
"const api=u=>new URL(u,base).href;"
|
||||
"function snap(){img.src=api('api/screenshot?fast=1')+'&ts='+Date.now();}"
|
||||
"setInterval(snap,500);snap();"
|
||||
"img.addEventListener('error',()=>{st.textContent='reconnecting…';});"
|
||||
"img.addEventListener('load',()=>{st.textContent='live';"
|
||||
"res.textContent=img.naturalWidth+'x'+img.naturalHeight;});"
|
||||
"img.addEventListener('pointerdown',e=>{"
|
||||
"const r=img.getBoundingClientRect();"
|
||||
"const x=Math.round((e.clientX-r.left)/r.width*img.naturalWidth);"
|
||||
"const y=Math.round((e.clientY-r.top)/r.height*img.naturalHeight);"
|
||||
"fetch(api('api/sim/touch')+'?x='+x+'&y='+y,{method:'POST'});});"
|
||||
"</script></body></html>";
|
||||
http_server_request_send_string(request, page);
|
||||
return ERROR_NONE;
|
||||
}
|
||||
|
||||
error_t WebServerService::handleAssets(HttpServerRequest* request, void*) {
|
||||
// Auth check for UI access control
|
||||
bool authPassed = false;
|
||||
@@ -1746,6 +1969,32 @@ error_t WebServerService::handleAssets(HttpServerRequest* request, void*) {
|
||||
http_server_request_get_uri(request, uri, sizeof(uri));
|
||||
LOG_I(TAG, "GET %s", uri);
|
||||
|
||||
// Simulator live viewer (no auth bypass: checked inside handler).
|
||||
// Served with redirect-to-slash so relative api/ URLs resolve under /sim/
|
||||
// (browsers treat /sim as a file, /sim/ as a directory for URL purposes).
|
||||
// NOTE: /sim/api/* does NOT need special-casing here: the /sim/api/*
|
||||
// handler aliases registered in startServer() route straight into
|
||||
// handleApiGet/handleApiPost, which strip the /sim prefix via
|
||||
// api_path_suffix(). This block only serves the viewer page itself.
|
||||
if (strncmp(uri, "/sim", 4) == 0 && (uri[4] == '\0' || uri[4] == '?' || uri[4] == '/')) {
|
||||
// Redirect bare /sim -> /sim/ so relative api/ resolves correctly.
|
||||
if (uri[4] == '\0' || uri[4] == '?') {
|
||||
std::string loc = "/sim/";
|
||||
const char* q = strchr(uri, '?');
|
||||
if (q != nullptr) { loc += q; }
|
||||
http_server_request_set_header(request, "Location", loc.c_str());
|
||||
http_server_request_send_error(request, 301, "see /sim/");
|
||||
return ERROR_NONE;
|
||||
}
|
||||
if (strncmp(uri, "/sim/api/", 9) == 0) {
|
||||
// Should have matched the /sim/api/* alias in startServer(); if we
|
||||
// get here the method has no alias (e.g. PUT) — 404 it.
|
||||
http_server_request_send_error(request, 404, "not found");
|
||||
return ERROR_UNDEFINED;
|
||||
}
|
||||
return handleSimViewer(request, nullptr);
|
||||
}
|
||||
|
||||
// Special case: serve favicon from system assets
|
||||
if (strcmp(uri, "/favicon.ico") == 0) {
|
||||
std::string faviconPathStr = std::string(file::MOUNT_POINT_SYSTEM) + "/spinner.png";
|
||||
|
||||
@@ -117,7 +117,7 @@ bool save(const AudioSettings& settings) {
|
||||
map[SETTINGS_KEY_OUTPUT_VOLUME] = toString(settings.outputVolume);
|
||||
|
||||
std::string settings_path;
|
||||
if (getSettingsFilePath(settings_path)) {
|
||||
if (!getSettingsFilePath(settings_path)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user