25 Commits

Author SHA1 Message Date
Adolfo Reyna 59612020bb chore: checkpoint app work before firmware sync 2026-09-07 23:01:26 -04:00
Adolfo Reyna e42036a044 feat: redesign BookPlayer picker controls 2026-09-02 10:30:35 -04:00
Adolfo Reyna 52bf3e1870 feat(live-captions): add ESP32 streaming captions app 2026-08-21 22:41:01 -04:00
Adolfo Reyna 03e65fb7f7 fix(bookplayer): remove fades from page playback 2026-08-20 19:45:17 -04:00
Adolfo Reyna e010828e5e docs(agents): use reyna-cli for Tactility board discovery & management
Main / Build (AudioTest) (push) Has been cancelled
Main / Build (BibleVerse) (push) Has been cancelled
Main / Build (BookPlayer) (push) Has been cancelled
Main / Build (Brainfuck) (push) Has been cancelled
Main / Build (Breakout) (push) Has been cancelled
Main / Build (Calculator) (push) Has been cancelled
Main / Build (Diceware) (push) Has been cancelled
Main / Build (EpubReader) (push) Has been cancelled
Main / Build (EspNowBridge) (push) Has been cancelled
Main / Build (GPIO) (push) Has been cancelled
Main / Build (GameBoy) (push) Has been cancelled
Main / Build (GraphicsDemo) (push) Has been cancelled
Main / Build (HelloWorld) (push) Has been cancelled
Main / Build (M5UnitTest) (push) Has been cancelled
Main / Build (Magic8Ball) (push) Has been cancelled
Main / Build (McpScreen) (push) Has been cancelled
Main / Build (MediaKeys) (push) Has been cancelled
Main / Build (Mp3Player) (push) Has been cancelled
Main / Build (MystifyDemo) (push) Has been cancelled
Main / Build (PocketDungeon) (push) Has been cancelled
Main / Build (ReynaBot) (push) Has been cancelled
Main / Build (RobotArm) (push) Has been cancelled
Main / Build (SerialConsole) (push) Has been cancelled
Main / Build (Snake) (push) Has been cancelled
Main / Build (TamaTac) (push) Has been cancelled
Main / Build (TodoList) (push) Has been cancelled
Main / Build (TwoEleven) (push) Has been cancelled
Main / Build (VoiceRecorder) (push) Has been cancelled
Main / Bundle (push) Has been cancelled
Main / PublishApps (push) Has been cancelled
Prefer reyna-cli (registry-addressed by device ID) over raw IPs/curl for the
Tactility LAN fleet. Document board ID->IP map (kidosos_* boards, esp32_screen,
little32), discover/devices/sysinfo/apps/install/run/report commands, and the
USB serial monitor for capturing ELF missing-symbol logs.
2026-08-19 21:28:02 -04:00
Adolfo Reyna 479a448900 docs(tactility-app-dev): note device_get_* not exported; use device_find_* legacy API
Main / Build (AudioTest) (push) Has been cancelled
Main / Build (BibleVerse) (push) Has been cancelled
Main / Build (BookPlayer) (push) Has been cancelled
Main / Build (Brainfuck) (push) Has been cancelled
Main / Build (Breakout) (push) Has been cancelled
Main / Build (Calculator) (push) Has been cancelled
Main / Build (Diceware) (push) Has been cancelled
Main / Build (EpubReader) (push) Has been cancelled
Main / Build (EspNowBridge) (push) Has been cancelled
Main / Build (GPIO) (push) Has been cancelled
Main / Build (GameBoy) (push) Has been cancelled
Main / Build (GraphicsDemo) (push) Has been cancelled
Main / Build (HelloWorld) (push) Has been cancelled
Main / Build (M5UnitTest) (push) Has been cancelled
Main / Build (Magic8Ball) (push) Has been cancelled
Main / Build (McpScreen) (push) Has been cancelled
Main / Build (MediaKeys) (push) Has been cancelled
Main / Build (Mp3Player) (push) Has been cancelled
Main / Build (MystifyDemo) (push) Has been cancelled
Main / Build (PocketDungeon) (push) Has been cancelled
Main / Build (ReynaBot) (push) Has been cancelled
Main / Build (RobotArm) (push) Has been cancelled
Main / Build (SerialConsole) (push) Has been cancelled
Main / Build (Snake) (push) Has been cancelled
Main / Build (TamaTac) (push) Has been cancelled
Main / Build (TodoList) (push) Has been cancelled
Main / Build (TwoEleven) (push) Has been cancelled
Main / Build (VoiceRecorder) (push) Has been cancelled
Main / Bundle (push) Has been cancelled
Main / PublishApps (push) Has been cancelled
Flashed 0.8.0-dev firmware exports device_find_* but not the newer device_get_*
out-param API. verify_symbols.py compares vs local firmware source and can pass
even when the flashed firmware differs — confirm on-device via serial
(/dev/cu.usbmodem*, 115200). Record the local extern-declare workaround.
2026-08-19 21:19:28 -04:00
Adolfo Reyna f785bd3fb2 fix(bookplayer): use exported device_find_* API for audio stream lookup
Main / Build (AudioTest) (push) Has been cancelled
Main / Build (BibleVerse) (push) Has been cancelled
Main / Build (BookPlayer) (push) Has been cancelled
Main / Build (Brainfuck) (push) Has been cancelled
Main / Build (Breakout) (push) Has been cancelled
Main / Build (Calculator) (push) Has been cancelled
Main / Build (Diceware) (push) Has been cancelled
Main / Build (EpubReader) (push) Has been cancelled
Main / Build (EspNowBridge) (push) Has been cancelled
Main / Build (GPIO) (push) Has been cancelled
Main / Build (GameBoy) (push) Has been cancelled
Main / Build (GraphicsDemo) (push) Has been cancelled
Main / Build (HelloWorld) (push) Has been cancelled
Main / Build (M5UnitTest) (push) Has been cancelled
Main / Build (Magic8Ball) (push) Has been cancelled
Main / Build (McpScreen) (push) Has been cancelled
Main / Build (MediaKeys) (push) Has been cancelled
Main / Build (Mp3Player) (push) Has been cancelled
Main / Build (MystifyDemo) (push) Has been cancelled
Main / Build (PocketDungeon) (push) Has been cancelled
Main / Build (ReynaBot) (push) Has been cancelled
Main / Build (RobotArm) (push) Has been cancelled
Main / Build (SerialConsole) (push) Has been cancelled
Main / Build (Snake) (push) Has been cancelled
Main / Build (TamaTac) (push) Has been cancelled
Main / Build (TodoList) (push) Has been cancelled
Main / Build (TwoEleven) (push) Has been cancelled
Main / Build (VoiceRecorder) (push) Has been cancelled
Main / Bundle (push) Has been cancelled
Main / PublishApps (push) Has been cancelled
The flashed 0.8.0-dev firmware exports the legacy device_find_by_name /
device_find_first_by_type lookup API, not the newer device_get_* out-param
API. Switching to device_get_* (to match newer SDK headers) caused
'ELF: Can't find symbol device_get_by_name' at load on .129/.114. Revert to
the exported legacy functions, declared locally since the newer SDK header
dropped them. Verified on .129 via serial: elf entry resolves, app shows.
2026-08-19 21:18:14 -04:00
Adolfo Reyna ef9d4e8de9 fix(bookplayer): keep audio stream open across page turns + fade-in/out
Main / Build (AudioTest) (push) Has been cancelled
Main / Build (BibleVerse) (push) Has been cancelled
Main / Build (BookPlayer) (push) Has been cancelled
Main / Build (Brainfuck) (push) Has been cancelled
Main / Build (Breakout) (push) Has been cancelled
Main / Build (Calculator) (push) Has been cancelled
Main / Build (Diceware) (push) Has been cancelled
Main / Build (EpubReader) (push) Has been cancelled
Main / Build (EspNowBridge) (push) Has been cancelled
Main / Build (GPIO) (push) Has been cancelled
Main / Build (GameBoy) (push) Has been cancelled
Main / Build (GraphicsDemo) (push) Has been cancelled
Main / Build (HelloWorld) (push) Has been cancelled
Main / Build (M5UnitTest) (push) Has been cancelled
Main / Build (Magic8Ball) (push) Has been cancelled
Main / Build (McpScreen) (push) Has been cancelled
Main / Build (MediaKeys) (push) Has been cancelled
Main / Build (Mp3Player) (push) Has been cancelled
Main / Build (MystifyDemo) (push) Has been cancelled
Main / Build (PocketDungeon) (push) Has been cancelled
Main / Build (ReynaBot) (push) Has been cancelled
Main / Build (RobotArm) (push) Has been cancelled
Main / Build (SerialConsole) (push) Has been cancelled
Main / Build (Snake) (push) Has been cancelled
Main / Build (TamaTac) (push) Has been cancelled
Main / Build (TodoList) (push) Has been cancelled
Main / Build (TwoEleven) (push) Has been cancelled
Main / Build (VoiceRecorder) (push) Has been cancelled
Main / Bundle (push) Has been cancelled
Main / PublishApps (push) Has been cancelled
Close and re-creating the codec on every page change caused an audible pop
between pages. Now open_output_stream reuses an already-open stream when the
format matches, the codec is left open on a natural page finish (only torn
down on user stop / back / app close), and a short fade-in/out is applied at
each page boundary. Also fixes pre-existing device API renames (device_find_*
-> device_get_* out-param style).

Docs: record where the Tactility SDK actually lives and that the fresh CDN
0.8.0-dev SDK is broken for this setup (app-module resolution), with the
cached working copy workaround.
2026-08-19 21:09:21 -04:00
Adolfo Reyna 6e83272c8e feat: PipecatVoice native Tactility app — voice gateway companion
Native ELF app (sibling to VoiceRecorder/ReynaBot). Mic/speaker via audio-stream +
I2S (16kHz PCM) + websocket transport (lwip, cJSON). Defaults to Hermes WS
ws://192.168.68.102:8642/api/esp32/voice/ws (voice profile) with Pipecat voice
gateway ws://<mac>:7861 second target. Adapted from ReynaBot PTT + events
(ready/listening/transcript/thinking/response_text/audio_start/audio_end/done).
Cloned ReynaBot websocket.c/h as base.
2026-08-06 08:44:08 -04:00
Adolfo 9def43b4ed Merge personal/main into main - preserve GameBoy fixes and RobotArm mDNS
Main / Build (AudioTest) (push) Has been cancelled
Main / Build (BibleVerse) (push) Has been cancelled
Main / Build (BookPlayer) (push) Has been cancelled
Main / Build (Brainfuck) (push) Has been cancelled
Main / Build (Breakout) (push) Has been cancelled
Main / Build (Calculator) (push) Has been cancelled
Main / Build (Diceware) (push) Has been cancelled
Main / Build (EpubReader) (push) Has been cancelled
Main / Build (EspNowBridge) (push) Has been cancelled
Main / Build (GPIO) (push) Has been cancelled
Main / Build (GameBoy) (push) Has been cancelled
Main / Build (GraphicsDemo) (push) Has been cancelled
Main / Build (HelloWorld) (push) Has been cancelled
Main / Build (M5UnitTest) (push) Has been cancelled
Main / Build (Magic8Ball) (push) Has been cancelled
Main / Build (McpScreen) (push) Has been cancelled
Main / Build (MediaKeys) (push) Has been cancelled
Main / Build (Mp3Player) (push) Has been cancelled
Main / Build (MystifyDemo) (push) Has been cancelled
Main / Build (PocketDungeon) (push) Has been cancelled
Main / Build (ReynaBot) (push) Has been cancelled
Main / Build (RobotArm) (push) Has been cancelled
Main / Build (SerialConsole) (push) Has been cancelled
Main / Build (Snake) (push) Has been cancelled
Main / Build (TamaTac) (push) Has been cancelled
Main / Build (TodoList) (push) Has been cancelled
Main / Build (TwoEleven) (push) Has been cancelled
Main / Build (VoiceRecorder) (push) Has been cancelled
Main / Bundle (push) Has been cancelled
Main / PublishApps (push) Has been cancelled
- Keep GameBoy emulator with canvas fixes from personal/main (4ff787f etc)
- Keep RobotArm mDNS auto-connect (6d9001f) over local cute version
- Keep BibleVerse stack overflow fix (4a15309)
- Keep manifest V2 conversions (c258aeb)
2026-07-21 17:43:00 -04:00
Adolfo c258aebca1 chore(manifest): convert all local apps to V2 format for SDK 0.8.0-dev
- AudioTest, BookPlayer, McpScreen, Mp3Player, PocketDungeon, ReynaBot, RobotArm, VoiceRecorder
- V1 [manifest] version=0.1 -> V2 manifest.version=0.2
- sdk 0.7.0-dev -> 0.8.0-dev
- flags handling: app.flags=HideStatusBar
- Fixes 'Invalid manifest format: manifest.version not found' error during build
2026-07-21 17:42:30 -04:00
Adolfo 4a153099f9 fix(bibleverse): fix gui stack overflow after firmware update
Gui task stack is 4096 with 2800 free min. After recent driver migrations,
app overflowed:

- verse_buf[2048] on stack in show_current_verse
- bin_path[320]+idx_path[320] in load_book
- temp[512] in parse_books_json

Caused 'stack overflow in task gui' + LoadProhibited in sdmmc/stat path.

Fix:
- MAX_PATH 320 -> 128 (paths <80 chars)
- temp 512 -> 256
- verse_buf stack -> heap malloc/free
- ref buffers reduced

Also bump manifest to V2 (0.2) required by SDK 0.8.0-dev and versionCode 2.

Tested on 192.168.68.132 (ES3C28P): loads 66 books, displays verse, no reboot.
2026-07-21 14:16:20 -04:00
Adolfo aebee50d25 Merge origin/main into main - integrate EspNowBridge + upstream SDK 0.8.0-dev updates
- Merged CI workflow to include all local apps + EspNowBridge
- HelloWorld manifest now V2 format from upstream (sdk 0.8.0-dev)
- Kept local SfxEngine enhancements (polyphonic gate, auto-normalization)
- Brings main up to date with origin/main 25b966a
2026-07-21 11:16:16 -04:00
Adolfo 6d9001fcd7 feat(RobotArm): mDNS auto-connect, connecting screen, scroller fix
Main / Build (BookPlayer) (push) Has been cancelled
Main / Build (Brainfuck) (push) Has been cancelled
Main / Build (Breakout) (push) Has been cancelled
Main / Build (Calculator) (push) Has been cancelled
Main / Build (Diceware) (push) Has been cancelled
Main / Build (EpubReader) (push) Has been cancelled
Main / Build (GPIO) (push) Has been cancelled
Main / Build (GraphicsDemo) (push) Has been cancelled
Main / Build (HelloWorld) (push) Has been cancelled
Main / Build (M5UnitTest) (push) Has been cancelled
Main / Build (Magic8Ball) (push) Has been cancelled
Main / Build (MediaKeys) (push) Has been cancelled
Main / Build (MystifyDemo) (push) Has been cancelled
Main / Build (SerialConsole) (push) Has been cancelled
Main / Build (Snake) (push) Has been cancelled
Main / Build (TamaTac) (push) Has been cancelled
Main / Build (TodoList) (push) Has been cancelled
Main / Build (TwoEleven) (push) Has been cancelled
Main / Bundle (push) Has been cancelled
- Pure mDNS discovery via tt_mdns_browse('_robotarm','_tcp') + resolve 'robotarm.local'
  Fallback to 192.168.68.148/.103 for old firmware, no LAN-wide scan
- Connecting screen first: shows 'Finding robotarm...' + spinner + retry button,
  establishes connection then shows main UI (auto-connect on IP change)
- Fix overall scroller lost: root not scrollable, inner content flex-column
  scrollable vertically, all nested cards/grid/hdr/brow/seqbar clear_flag
  SCROLLABLE + scrollbar OFF - no double scrollbars
- Keep 2x tall sliders 22x72 3 cols, cute pastel cards, Home/Read/Open/Close
  56x18, shoulder max 70, open=0 close=180
- Sequencer bottom not fixed but inside scrollable content, colored blocks
  22x22 no info, white 3px border highlight current, larger buttons 38x32
  Play 56x32, smooth move_all_joints
- Fix missing symbol on 0.8.0-dev old firmware: remove esp_log (ESP_LOGI),
  lwip_recvfrom/sendto, keep 50U (was 52U) matching ReynaBot working set
- MicroPython arm: mdns_server.py now advertises _robotarm._tcp.local PTR/SRV/TXT
  for tt_mdns_browse, A robotarm.local, re-announce 60s
2026-07-20 14:04:18 -04:00
Adolfo 653ad8902f fix(GameBoy): FPS but no game - cache invalidation bug
Root cause: LVGL9 canvas = lv_image backed by draw_buf with image cache.
Mutating raw uint16_t* buffer without lv_image_cache_drop + lv_draw_buf_invalidate_cache
leaves stale texture (gray/black). Only label (FPS) updated via lv_label_set_text_fmt,
so symptom = FPS counter works, game invisible.

Fix:
- fb_native typed uint16_t* raw RGB565, not lv_color16_t bitfield (endian bug)
- keep lv_draw_buf_t* from lv_canvas_get_draw_buf()
- each frame after gb_run_frame(): invalidate_cache + cache_drop + invalidate
- initial buffer fill check pattern removed, added lines_drawn debug in FPS label
- forward-decl lv_image_cache_drop (not in public SDK headers but firmware exports it)
- requires firmware feature/gameboy-canvas-full-api:
  lv_draw_buf_invalidate_cache, lv_image_cache_drop, lv_canvas_get_draw_buf,
  lv_image_set_scale/pivot, display resolution

SDK 0.8.0-dev built with IDF 5.5.2 - 0 undefined beyond firmware exports.
Builds to 50K GameBoy.app

Also preserves mDNS browse API from parent branch (Mdns.h/cpp, tt_mdns.h/cpp)
which sits on top of 60764979 'kidsOS-XXXX' mdns init.
2026-07-20 12:36:11 -04:00
Adolfo e4d1d35da4 feat(GameBoy): restore integer scaling using full canvas API
- use lv_display_get_*_resolution to compute available area
- apply lv_image_set_scale 2x/3x + pivot center when display large enough
- removes previous comment hack 'avoid non-exported LVGL transform symbols'
- now requires firmware feature/gameboy-canvas-full-api (symbols exported)

SDK: 0.8.0-dev built with IDF 5.5.2, 0 missing symbols
2026-07-20 00:21:01 -04:00
Adolfo 7c3c4ad2fe feat(pocketdungeon): fullscreen HideStatusBar + v0.1.2
Main / Build (BookPlayer) (push) Has been cancelled
Main / Build (Brainfuck) (push) Has been cancelled
Main / Build (Breakout) (push) Has been cancelled
Main / Build (Calculator) (push) Has been cancelled
Main / Build (Diceware) (push) Has been cancelled
Main / Build (EpubReader) (push) Has been cancelled
Main / Build (GPIO) (push) Has been cancelled
Main / Build (GraphicsDemo) (push) Has been cancelled
Main / Build (HelloWorld) (push) Has been cancelled
Main / Build (M5UnitTest) (push) Has been cancelled
Main / Build (Magic8Ball) (push) Has been cancelled
Main / Build (MediaKeys) (push) Has been cancelled
Main / Build (MystifyDemo) (push) Has been cancelled
Main / Build (SerialConsole) (push) Has been cancelled
Main / Build (Snake) (push) Has been cancelled
Main / Build (TamaTac) (push) Has been cancelled
Main / Build (TodoList) (push) Has been cancelled
Main / Build (TwoEleven) (push) Has been cancelled
Main / Bundle (push) Has been cancelled
- manifest: flags=HideStatusBar (V1 format supported since 0.8.0-dev)
  parsers AppManifestParsingV1/V2 already parse app.flags / flags
  reference: firmware Tests AppManifestParsingTest flags=HideStatusBar
- Verified: screenshot pd_fullscreen.png 6.0K no statusbar, title at top edge,
  true fullscreen immersive, exit via X / Q/ESC / long-press pause still works
- IDF 5.5 build 0 missing symbols, 51KB app

Board 192.168.68.134 fullscreen GOAL+CONTROLS left + icons right
2026-07-19 23:09:40 -04:00
Shadowtrance 25b966a340 Add EspNowBridge + updates for Audio System (#36) 2026-07-19 21:52:39 +02:00
Hermes Reyna Bot 6eb032cb53 Restore GameBoy canvas path and FPS marker 2026-07-17 18:11:05 -04:00
Hermes Reyna Bot 07749d86a1 Add GameBoy emulator prototype 2026-07-17 11:05:33 -04:00
Ken Van Hoeylandt 8721a653e7 Tool 4.1.0 2026-07-03 23:17:09 +02:00
Ken Van Hoeylandt 694b68de1a Fixes for app publishing (#35) 2026-07-03 22:30:14 +02:00
Ken Van Hoeylandt 71bf2631f4 Implement CDN uploading (#34) 2026-07-03 21:41:18 +02:00
Ken Van Hoeylandt 4ab2377970 Manifest format update (#33) 2026-07-03 00:04:29 +02:00
Ken Van Hoeylandt 8a0f9ef4e4 SDK 0.7.0 & bump app versions (#32) 2026-07-02 19:31:34 +02:00
83 changed files with 9710 additions and 717 deletions
@@ -39,6 +39,12 @@ print(f"undef {len(undef)} missing {missing}")
### New missing from v2/v3/v4/v5 UI passes ### New missing from v2/v3/v4/v5 UI passes
- `device_get_by_name`, `device_get_first_by_type` (out-param API) → **Not exported** on flashed 0.8.0-dev (verified via serial on .129: `E ELF: Can't find symbol device_get_by_name`). The firmware exports the **legacy** `device_find_by_name` / `device_find_first_by_type` instead. Gotcha: newer SDK/CDN headers declare only `device_get_*` (so `device_find_*` fails to compile), but the flashed firmware only exports `device_find_*` (so `device_get_*` fails at load). Fix: call the exported legacy `device_find_*` and declare them locally in the app source since the SDK header dropped them:
```c
extern struct Device* device_find_by_name(const char* name);
extern struct Device* device_find_first_by_type(const struct DeviceType* type);
```
Verify the ACTUAL load on-device via serial (`/dev/cu.usbmodem*`, 115200) — `verify_symbols.py` compares against local firmware source and can report 0 missing even when the flashed firmware's export table differs.
- `lv_obj_set_style_bg_grad_color/dir/stop` → **Not exported** 0.8.0-dev. Gradient fails `missing symbol`. Use solid `0x0E0E14`. - `lv_obj_set_style_bg_grad_color/dir/stop` → **Not exported** 0.8.0-dev. Gradient fails `missing symbol`. Use solid `0x0E0E14`.
- `LV_OPA_95` → **Not defined** (only 0/10/20/30/40/50/60/70/80/90/100/COVER/TRANSP). Use `COVER` or `90`. - `LV_OPA_95` → **Not defined** (only 0/10/20/30/40/50/60/70/80/90/100/COVER/TRANSP). Use `COVER` or `90`.
- `lv_arc_create`, `lv_arc_set_range/value/bg_angles`, `lv_arc_get_value` → **Not exported on 0.7.0-dev**, added `dff93cb6 Add lv_arc.h symbols (#496)` after 0.7 release. Symptom blue modal `Error / Application failed to start: missing symbol / OK`, heap healthy ~31KB not OOM. Fix horizontal slide using `lv_slider_create` + `lv_indev_get_point/active`. See `book-browser.md`. - `lv_arc_create`, `lv_arc_set_range/value/bg_angles`, `lv_arc_get_value` → **Not exported on 0.7.0-dev**, added `dff93cb6 Add lv_arc.h symbols (#496)` after 0.7 release. Symptom blue modal `Error / Application failed to start: missing symbol / OK`, heap healthy ~31KB not OOM. Fix horizontal slide using `lv_slider_create` + `lv_indev_get_point/active`. See `book-browser.md`.
+21
View File
@@ -0,0 +1,21 @@
name: Publish Apps
inputs:
sdk_version:
description: The SDK version that determines the path on the CDN
required: true
runs:
using: 'composite'
steps:
- name: 'Download cdn-files'
uses: actions/download-artifact@v4
with:
name: 'cdn-files'
path: cdn_files
- name: 'Install boto3'
shell: bash
run: pip install boto3
- name: 'Upload files'
shell: bash
run: python Buildscripts/CDN/upload-app-files.py cdn_files ${{ inputs.sdk_version }} ${{ env.CDN_ID }} ${{ env.CDN_TOKEN_NAME }} ${{ env.CDN_TOKEN_VALUE }}
+9 -1
View File
@@ -1,5 +1,10 @@
name: Release Apps name: Release Apps
outputs:
sdk_version:
description: 'Common SDK version shared by all bundled apps'
value: ${{ steps.release.outputs.sdk_version }}
runs: runs:
using: 'composite' using: 'composite'
steps: steps:
@@ -11,8 +16,11 @@ runs:
run: rsync -av downloaded_apps/*/*.app cdn_files/ run: rsync -av downloaded_apps/*/*.app cdn_files/
shell: bash shell: bash
- name: 'Create CDN release files' - name: 'Create CDN release files'
run: python release.py cdn_files/ id: release
shell: bash shell: bash
run: |
python release.py cdn_files/
echo "sdk_version=$(cat sdk_version.txt)" >> "$GITHUB_OUTPUT"
- name: 'Upload Artifact' - name: 'Upload Artifact'
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
with: with:
+22 -1
View File
@@ -12,10 +12,12 @@ jobs:
Build: Build:
strategy: strategy:
matrix: matrix:
app_name: [Brainfuck, Breakout, BookPlayer, Calculator, Diceware, EpubReader, GPIO, GraphicsDemo, HelloWorld, M5UnitTest, Magic8Ball, MediaKeys, MystifyDemo, SerialConsole, Snake, TamaTac, TodoList, TwoEleven] app_name: [AudioTest, BibleVerse, BookPlayer, Brainfuck, Breakout, Calculator, Diceware, EpubReader, EspNowBridge, GPIO, GameBoy, GraphicsDemo, HelloWorld, M5UnitTest, Magic8Ball, McpScreen, MediaKeys, Mp3Player, MystifyDemo, PocketDungeon, ReynaBot, RobotArm, SerialConsole, Snake, TamaTac, TodoList, TwoEleven, VoiceRecorder]
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with:
persist-credentials: false
- name: "Build" - name: "Build"
uses: ./.github/actions/build-app uses: ./.github/actions/build-app
with: with:
@@ -23,7 +25,26 @@ jobs:
Bundle: Bundle:
runs-on: ubuntu-latest runs-on: ubuntu-latest
needs: [Build] needs: [Build]
outputs:
sdk_version: ${{ steps.release.outputs.sdk_version }}
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: "Build" - name: "Build"
id: release
uses: ./.github/actions/release-apps uses: ./.github/actions/release-apps
PublishApps:
runs-on: ubuntu-latest
needs: [Bundle]
if: (github.event_name == 'push' && github.ref == 'refs/heads/main')
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- name: "Publish Apps"
env:
CDN_ID: ${{ secrets.CDN_ID }}
CDN_TOKEN_NAME: ${{ secrets.CDN_TOKEN_NAME }}
CDN_TOKEN_VALUE: ${{ secrets.CDN_TOKEN_VALUE }}
uses: ./.github/actions/publish-apps
with:
sdk_version: ${{ needs.Bundle.outputs.sdk_version }}
+65 -10
View File
@@ -9,23 +9,42 @@ Tactility external ELF apps — loaded at runtime via firmware symbol table. Eac
Upstream: `https://github.com/TactilityProject/TactilityApps` Upstream: `https://github.com/TactilityProject/TactilityApps`
Personal Gitea mirror: `https://git.reynafamily.com/adolforeyna/tactility_apps` (`personal` remote) Personal Gitea mirror: `https://git.reynafamily.com/adolforeyna/tactility_apps` (`personal` remote)
Dev board IP: `192.168.68.112` (S3, OS 0.8.0-dev, SDK 0.8.0-dev) — main deploy target. `.111` also online. OS image is 0.8.0-dev so manifest should use `sdk=0.8.0-dev` or loader warns. Dev board IP: `192.168.68.112` (S3, OS 0.8.0-dev, SDK 0.8.0-dev) — main deploy target. `.111` and `.114` also online. OS image is 0.8.0-dev so manifest should use `sdk=0.8.0-dev` or loader warns.
## Local Workstation ## Local Workstation
- Host: M2 Air (14,2) macOS 26.5.2 - Host: macOS 26.5.2
- Project: `/Users/adolforeyna/Projects/Tactility/apps` - Project: `/Users/adolforeyna/Projects/electronics/tactility/tactility_apps`
- ESP-IDF: `/Users/adolforeyna/esp/esp-idf`, Python env `idf5.3_py3.9_env` at `~/.espressif/python_env/idf5.3_py3.9_env` - ESP-IDF: `/Users/adolforeyna/esp/esp-idf` (v5.5.2), Python env `idf5.5_py3.9_env` at `~/.espressif/python_env/idf5.5_py3.9_env` (NOT `idf5.3_py3.9_env` — that env does not exist on this machine)
- Tactility SDK: `/Users/adolforeyna/Projects/Tactility/firmware/release/TactilitySDK` (built locally, `--local-sdk`)
### Tactility SDK location (IMPORTANT)
- When you run `tactility.py ... build` **without** `--local-sdk`, it auto-downloads the SDK to the per-app cache:
`Apps/<Name>/.tactility/<version>-<platform>/TactilitySDK` (e.g. `Apps/BookPlayer/.tactility/0.8.0-dev-esp32s3/TactilitySDK`).
- **The freshly CDN-downloaded 0.8.0-dev SDK for esp32s3 is broken for this setup** — it fails at CMake with
`Failed to resolve component 'app-module' required by component 'TactilitySDK': unknown name` and also renames the
device API (`device_find_*` → `device_get_by_name/device_get_first_by_type` out-param style). It is a *different,
newer* SDK than the working one.
- **The known-good SDK is the locally-cached copy** already present in the other apps'
`.tactility/0.8.0-dev-esp32s3/TactilitySDK` (the one that carries a `Drivers/` folder). It builds clean.
- Workaround when a fresh download fails: copy the working cached SDK over the broken one:
```bash
SRC=Apps/PipecatVoice/.tactility/0.8.0-dev-esp32s3 # known-good copy
DST=Apps/MyApp/.tactility/0.8.0-dev-esp32s3
rm -rf "$DST/TactilitySDK"; cp -R "$SRC/TactilitySDK" "$DST/"
```
Then rebuild. (Resolving the root cause on the newer SDK is still TODO — consider pinning/downloading the cached zip
so this isn't needed per-app.)
### Hardware ### Hardware
| Board | IP | Port | Notes | | Board | IP | Port | Notes |
|-------|-----|------|-------| |-------|-----|------|-------|
| ES3C28P 2.8" color 240x320 | `192.168.68.112` | `/dev/cu.usbmodem101` | Primary deploy target, 16MB flash, OCT PSRAM, SD for ELF assets | | ES3C28P 2.8" color 240x320 | `192.168.68.112` | `/dev/cu.usbmodem101` | Primary deploy target, 16MB flash, OCT PSRAM, SD for ELF assets |
| Waveshare RLCD 4.2" mono 400x300 ST7305 | `192.168.68.111`? .1101 USB | `/dev/cu.usbmodem1101` | Secondary, compact density, mono threshold 60, font 18 | | ES3C28P 2.8" color 240x320 | `192.168.68.114` | `/dev/cu.usbmodem101` | Secondary S3 (used for recent BookPlayer deploys) |
| Waveshare RLCD 4.2" mono 400x300 ST7305 | `192.168.68.111` | `/dev/cu.usbmodem1101` | Secondary, compact density, SD threshold 60, font 18 |
User shorthand: "ending in 112" → `192.168.68.112`. User shorthand: "ending in 112" → `192.168.68.112`. Install is dashboard-port API (80), not dev port 6666.
## Build, Deploy, Run — Correct Env Wrapper ## Build, Deploy, Run — Correct Env Wrapper
@@ -34,11 +53,10 @@ Hermes desktop Python 3.11 venv pollutes `PYTHONPATH` → `tactility.py` crashes
Always: Always:
```bash ```bash
cd /Users/adolforeyna/Projects/Tactility/apps cd /Users/adolforeyna/Projects/electronics/tactility/tactility_apps
unset PYTHONPATH; unset PYTHONHOME unset PYTHONPATH; unset PYTHONHOME
export IDF_PYTHON_ENV_PATH=/Users/adolforeyna/.espressif/python_env/idf5.3_py3.9_env export IDF_PYTHON_ENV_PATH=/Users/adolforeyna/.espressif/python_env/idf5.5_py3.9_env
source /Users/adolforeyna/esp/esp-idf/export.sh source /Users/adolforeyna/esp/esp-idf/export.sh
export TACTILITY_SDK_PATH=/Users/adolforeyna/Projects/Tactility/firmware/release/TactilitySDK
# Build # Build
$IDF_PYTHON_ENV_PATH/bin/python tactility.py Apps/MyApp clean $IDF_PYTHON_ENV_PATH/bin/python tactility.py Apps/MyApp clean
@@ -51,6 +69,7 @@ xtensa-esp32s3-elf-nm -D Apps/MyApp/build/cmake-build-esp32s3/MyApp.app.elf | gr
python .claude/skills/tactility-app-development/scripts/verify_symbols.py Apps/MyApp python .claude/skills/tactility-app-development/scripts/verify_symbols.py Apps/MyApp
# Install to device (dashboard API port 80, not dev port 6666) # Install to device (dashboard API port 80, not dev port 6666)
# Preferred: use reyna-cli (see "Device discovery & management via reyna-cli" below)
$IDF_PYTHON_ENV_PATH/bin/python tactility.py Apps/MyApp install 192.168.68.112 esp32s3 $IDF_PYTHON_ENV_PATH/bin/python tactility.py Apps/MyApp install 192.168.68.112 esp32s3
# or dashboard directly: # or dashboard directly:
curl -X PUT http://192.168.68.112/api/apps/install -F "file=@build/MyApp.app" curl -X PUT http://192.168.68.112/api/apps/install -F "file=@build/MyApp.app"
@@ -65,6 +84,41 @@ curl http://192.168.68.112/api/apps # list installed
# If 6666 refused → use dashboard PUT above # If 6666 refused → use dashboard PUT above
``` ```
### Device discovery & management via reyna-cli
`reyna-cli` (at `/Users/adolforeyna/.local/bin/reyna-cli`) wraps the Tactility LAN web API with a device registry
(`~/.hermes/local_devices.yaml`). Prefer it over raw IPs/curl for fleet discovery and management. Boards are
addressed by their stable registry **ID** (not IP — DHCP IPs change); `devices list` maps IDs→IPs.
Registered Tactility boards (from `reyna-cli devices list`):
| ID | IP | Board |
|----|----|-------|
| `kidosos_a790` | `.129` | Personal 3.5-inch Tactility Board (Dev) — USB `/dev/cu.usbmodem*` for serial |
| `kidosos_5c5c` | `.114` | Grace's 2.8-inch board |
| `kidosos_5690` | `.107` | Elias's 2.8-inch board |
| `kidosos_591c` | `.128` | Kitchen 2.8-inch board |
| `esp32_screen` | `.123` | ESP32 Screen |
| `little32` | `.122` | Little32 Kitchen ESP32 Screen |
Commands:
```bash
reyna-cli tactility discover # probe all boards; online/offline + sysinfo
reyna-cli devices list # registry (id, ip, display name, status)
reyna-cli tactility sysinfo kidsos_a790 # firmware/version/heap/psram/SD
reyna-cli tactility apps kidsos_a790 # installed apps
reyna-cli tactility install kidsos_5c5c build/MyApp.app # PUT install by device id
reyna-cli tactility run kidsos_5c5c one.tactility.myapp # launch app
reyna-cli tactility report kidsos_a790 # apps + SD + bible/podcast usage
# most commands accept --json for machine-readable output
```
Use a serial monitor on the USB board for loader/ELF diagnostics: `/dev/cu.usbmodem*` @ 115200
(e.g. `idf5.5_py3.9_env/bin/python -m serial.tools.miniterm /dev/cu.usbmodem31201 115200`). This is how you
capture `E ELF: Can't find symbol X` on `.129` — `verify_symbols.py` only compares against local firmware
SOURCE and can pass even when the flashed firmware's export table differs.
### manifest.properties ### manifest.properties
```properties ```properties
@@ -103,6 +157,7 @@ Keep app source as pure C (no `auto`, no lambdas in `.c`) or rename to `.cpp`.
Tactility firmware exports symbols via `ESP_ELFSYM_EXPORT` / `DEFINE_MODULE_SYMBOL` in `firmware/Modules/lvgl-module/source/symbols.c`. If ELF references an unexported symbol → device modal `Error / Application failed to start: missing symbol`, heap still healthy (~31KB free) → NOT OOM. Tactility firmware exports symbols via `ESP_ELFSYM_EXPORT` / `DEFINE_MODULE_SYMBOL` in `firmware/Modules/lvgl-module/source/symbols.c`. If ELF references an unexported symbol → device modal `Error / Application failed to start: missing symbol`, heap still healthy (~31KB free) → NOT OOM.
Known missing on 0.8.0-dev: Known missing on 0.8.0-dev:
- `device_get_by_name` / `device_get_first_by_type` (out-param API) → **Not exported** by flashed firmware; use legacy exported `device_find_by_name` / `device_find_first_by_type` (declare them locally — newer SDK headers dropped them). Gotcha: `verify_symbols.py` compares vs local firmware SOURCE and can pass even when the flashed firmware's export table differs — confirm on-device via serial (`/dev/cu.usbmodem*`, 115200): `E ELF: Can't find symbol X`.
- `lv_font_montserrat_14/18` → use `lvgl_get_text_font(SMALL/DEFAULT/LARGE)` via `tactility/lvgl_fonts.h` - `lv_font_montserrat_14/18` → use `lvgl_get_text_font(SMALL/DEFAULT/LARGE)` via `tactility/lvgl_fonts.h`
- `lv_obj_set_style_bg_grad_color/dir/stop`, `LV_OPA_95/5`, `LV_SYMBOL_STAR` → use solid colors, COVER/90 - `lv_obj_set_style_bg_grad_color/dir/stop`, `LV_OPA_95/5`, `LV_SYMBOL_STAR` → use solid colors, COVER/90
- `lv_obj_set_style_max_width` → use `LV_PCT(92)` fixed percents for gutters - `lv_obj_set_style_max_width` → use `LV_PCT(92)` fixed percents for gutters
+7 -10
View File
@@ -1,10 +1,7 @@
[manifest] manifest.version=0.2
version=0.1 target.sdk=0.8.0-dev
[target] target.platforms=esp32s3
sdk=0.7.0-dev app.id=one.tactility.audiotest
platforms=esp32s3 app.version.name=0.1.0
[app] app.version.code=1
id=one.tactility.audiotest app.name=Audio Test
versionName=0.1.0
versionCode=1
name=Audio Test
+15 -14
View File
@@ -33,7 +33,7 @@ LV_FONT_DECLARE(georgia_regular_24)
#define MAX_BIBLE_BOOKS 66 #define MAX_BIBLE_BOOKS 66
#define MAX_BOOK_NAME 40 #define MAX_BOOK_NAME 40
#define MAX_VERSE_TEXT 2048 #define MAX_VERSE_TEXT 2048
#define MAX_PATH 320 #define MAX_PATH 128
typedef struct { typedef struct {
uint32_t offset; uint32_t offset;
@@ -239,7 +239,7 @@ static bool parse_books_json(AppCtx* ctx, const char* json_str) {
const char* obj_end = strchr(obj_start, '}'); const char* obj_end = strchr(obj_start, '}');
if (!obj_end) break; if (!obj_end) break;
// parse fields within obj_start..obj_end // parse fields within obj_start..obj_end
char temp[512]; char temp[256];
size_t len = (size_t)(obj_end - obj_start + 1); size_t len = (size_t)(obj_end - obj_start + 1);
if (len >= sizeof(temp)) len = sizeof(temp)-1; if (len >= sizeof(temp)) len = sizeof(temp)-1;
memcpy(temp, obj_start, len); memcpy(temp, obj_start, len);
@@ -672,27 +672,27 @@ static void show_current_verse(AppCtx* ctx) {
const char* text_ptr = "(empty)"; const char* text_ptr = "(empty)";
if (off < ctx->book_bin_size) text_ptr = (const char*)(ctx->book_bin + off); if (off < ctx->book_bin_size) text_ptr = (const char*)(ctx->book_bin + off);
char verse_buf[MAX_VERSE_TEXT]; // Fix stack overflow: verse_buf was 2048 bytes on stack, causing gui task (4096) overflow
strncpy(verse_buf, text_ptr, sizeof(verse_buf)-1); // Use heap allocation
verse_buf[sizeof(verse_buf)-1]='\0'; char* verse_buf = (char*)malloc(MAX_VERSE_TEXT);
if (!verse_buf) {
ESP_LOGE(TAG, "Failed to malloc verse_buf");
return;
}
strncpy(verse_buf, text_ptr, MAX_VERSE_TEXT-1);
verse_buf[MAX_VERSE_TEXT-1]='\0';
char ref_buf[96]; char ref_buf[64];
snprintf(ref_buf, sizeof(ref_buf), "%s %d:%d", ctx->books[ctx->cur_book_idx].bname, vi->cnum, vi->vnum); snprintf(ref_buf, sizeof(ref_buf), "%s %d:%d", ctx->books[ctx->cur_book_idx].bname, vi->cnum, vi->vnum);
// Editorial reference style like your image: "PSALMS 23:1" with tracking char ref_pretty[80];
char ref_pretty[108]; char bname_upper[40];
// Use uppercase for book? Keep title for now but uppercase style for editorial match
// We'll format as "— PSALMS 23:1 —" feel? For dark mode keep minimal like ref image
// Reference image shows lines flanking citation - we do with letterspacing + dim
// For now: "PSALMS 23:1" style - uppercase via runtime? We'll uppercase book name
char bname_upper[48];
strncpy(bname_upper, ctx->books[ctx->cur_book_idx].bname, sizeof(bname_upper)-1); strncpy(bname_upper, ctx->books[ctx->cur_book_idx].bname, sizeof(bname_upper)-1);
bname_upper[sizeof(bname_upper)-1]='\0'; bname_upper[sizeof(bname_upper)-1]='\0';
for (char* p=bname_upper; *p; ++p) *p = toupper((unsigned char)*p); for (char* p=bname_upper; *p; ++p) *p = toupper((unsigned char)*p);
snprintf(ref_pretty, sizeof(ref_pretty), "%s %d:%d", bname_upper, vi->cnum, vi->vnum); snprintf(ref_pretty, sizeof(ref_pretty), "%s %d:%d", bname_upper, vi->cnum, vi->vnum);
if (ctx->lbl_verse) { if (ctx->lbl_verse) {
// start faded for transition
lv_obj_set_style_text_opa(ctx->lbl_verse, 60, 0); lv_obj_set_style_text_opa(ctx->lbl_verse, 60, 0);
lv_label_set_text(ctx->lbl_verse, verse_buf); lv_label_set_text(ctx->lbl_verse, verse_buf);
apply_verse_scaling(ctx, verse_buf); apply_verse_scaling(ctx, verse_buf);
@@ -741,6 +741,7 @@ static void show_current_verse(AppCtx* ctx) {
if (ctx->cur_global >= ctx->total_verses-1) lv_obj_add_state(ctx->btn_next, LV_STATE_DISABLED); if (ctx->cur_global >= ctx->total_verses-1) lv_obj_add_state(ctx->btn_next, LV_STATE_DISABLED);
else lv_obj_clear_state(ctx->btn_next, LV_STATE_DISABLED); else lv_obj_clear_state(ctx->btn_next, LV_STATE_DISABLED);
} }
free(verse_buf);
save_progress(ctx); save_progress(ctx);
verse_fade_in(ctx); verse_fade_in(ctx);
} }
+8 -11
View File
@@ -1,11 +1,8 @@
[manifest] manifest.version=0.2
version=0.1 target.sdk=0.8.0-dev
[target] target.platforms=esp32s3,esp32p4
sdk=0.8.0-dev app.id=one.tactility.bibleverse
platforms=esp32s3,esp32p4 app.version.name=0.1.0
[app] app.version.code=2
id=one.tactility.bibleverse app.name=Bible Verse
versionName=0.1.0 app.description=Single verse at a time, advances each minute. Tap to show controls.
versionCode=1
name=Bible Verse
description=Single verse at a time, advances each minute. Tap to show controls.
+8
View File
@@ -63,3 +63,11 @@ Each book subfolder must contain a `manifest.json` file. Here is a sample format
- **Images**: PNG or JPG format. Recommended size is `320×240` pixels (or scaled to match standard aspect ratios). - **Images**: PNG or JPG format. Recommended size is `320×240` pixels (or scaled to match standard aspect ratios).
- **Audio**: Mono `MP3` or uncompressed standard `WAV` files. For ESP32-S3 systems, lower sampling rates (e.g. 16 kHz mono) are recommended for memory efficiency. - **Audio**: Mono `MP3` or uncompressed standard `WAV` files. For ESP32-S3 systems, lower sampling rates (e.g. 16 kHz mono) are recommended for memory efficiency.
## Book Selection and Playback
The picker displays the selected book's first page image full-screen with its title.
Tap the left or right side of the cover, or swipe right or left, to choose the
previous or next book. Tap the Play button to begin page-one narration through the
same playback flow used by the in-book player. Once playing, the existing
previous, pause/play, next, progress, and auto-advance controls remain unchanged.
+346 -70
View File
@@ -5,6 +5,7 @@
#include <tactility/device.h> #include <tactility/device.h>
#include <tactility/drivers/audio_stream.h> #include <tactility/drivers/audio_stream.h>
#include <lvgl/fonts.h>
#include <string.h> #include <string.h>
#include <stdlib.h> #include <stdlib.h>
@@ -31,6 +32,8 @@
#define MAX_PATH 256 #define MAX_PATH 256
#define MAX_TITLE 128 #define MAX_TITLE 128
#define MAX_AUTHOR 128 #define MAX_AUTHOR 128
#define MAX_LVGL_IMAGE_PATH 1024
#define PICKER_COVER_LOAD_DELAY_MS 250
typedef enum { typedef enum {
STATE_IDLE, STATE_IDLE,
@@ -53,6 +56,10 @@ typedef struct {
// Book picker list data // Book picker list data
BookMetadata books[MAX_BOOKS]; BookMetadata books[MAX_BOOKS];
int book_count; int book_count;
int selected_book;
lv_coord_t picker_drag_start_x;
bool picker_dragging;
bool picker_dragged;
// Currently loaded book details // Currently loaded book details
char current_book_slug[MAX_PATH]; char current_book_slug[MAX_PATH];
@@ -64,8 +71,18 @@ typedef struct {
// UI elements // UI elements
AppHandle app; AppHandle app;
// Keep the decoded cover on a dedicated back sibling. The picker controls
// are a separate transparent sibling above it, mirroring the player image
// first / chrome second composition without invalidating the cover for UI
// updates.
lv_obj_t* picker_background;
lv_obj_t* picker_wrapper; lv_obj_t* picker_wrapper;
lv_obj_t* lst_books; lv_obj_t* picker_cover;
lv_obj_t* picker_touch_area;
lv_obj_t* lbl_picker_title;
lv_obj_t* lbl_picker_author;
lv_obj_t* btn_picker_play;
lv_obj_t* lbl_picker_status;
lv_obj_t* player_wrapper; lv_obj_t* player_wrapper;
lv_obj_t* header_bar; lv_obj_t* header_bar;
@@ -80,9 +97,22 @@ typedef struct {
// Audio State // Audio State
char current_audio_path[512]; char current_audio_path[512];
char picker_cover_path[MAX_LVGL_IMAGE_PATH];
char player_image_path[MAX_LVGL_IMAGE_PATH];
lv_timer_t* picker_cover_timer;
uint8_t* audio_buf; // Shared MP3 input and WAV buffer uint8_t* audio_buf; // Shared MP3 input and WAV buffer
mp3d_sample_t* pcm_buf; // MP3 decoded pcm buffer mp3d_sample_t* pcm_buf; // MP3 decoded pcm buffer
// Currently-open output stream format (so we can reuse it across page
// changes instead of tearing the codec down/recreating it every page).
uint32_t stream_rate;
uint8_t stream_channels;
uint8_t stream_bits;
// Page navigation stops the decoder task but keeps a compatible output
// stream open for the next page.
bool keep_stream_on_stop;
TaskHandle_t playback_task_handle; TaskHandle_t playback_task_handle;
} AppCtx; } AppCtx;
@@ -106,17 +136,29 @@ static AppCtx g_ctx;
/* ─── Forward Declarations ─── */ /* ─── Forward Declarations ─── */
static void update_ui(AppCtx* ctx); static void update_ui(AppCtx* ctx);
static void wait_for_playback_task_to_exit(AppCtx* ctx); static void wait_for_playback_task_to_exit(AppCtx* ctx, bool keep_stream_open);
static void load_page(AppCtx* ctx, int page_index, bool start_audio); static void load_page(AppCtx* ctx, int page_index, bool start_audio);
static void return_to_picker(AppCtx* ctx); static void return_to_picker(AppCtx* ctx);
static void audio_playback_task(void* arg); static void audio_playback_task(void* arg);
static void play_mp3(AppCtx* ctx); static void play_mp3(AppCtx* ctx);
static void play_wav(AppCtx* ctx); static void play_wav(AppCtx* ctx);
static void scan_books(AppCtx* ctx); static void scan_books(AppCtx* ctx);
static bool select_picker_book(AppCtx* ctx, int index);
static void open_selected_book(AppCtx* ctx, bool start_audio);
static void clear_picker_cover(AppCtx* ctx);
static void schedule_picker_cover_load(AppCtx* ctx);
static void cancel_picker_cover_load(AppCtx* ctx);
/* ─── Audio-stream helpers ─── */ /* ─── Audio-stream helpers ─── */
// The flashed firmware exports the legacy device_find_* lookup API; the newer
// device_get_* (out-param) API is not yet exported on 0.8.0-dev, so calling it
// fails at load with "missing symbol". The newer SDK headers dropped the legacy
// declarations, so declare them here (symbols are resolved at runtime by the ELF
// loader against the flashed firmware).
extern struct Device* device_find_by_name(const char* name);
extern struct Device* device_find_first_by_type(const struct DeviceType* type);
static bool find_audio_stream_device(AppCtx* ctx) { static bool find_audio_stream_device(AppCtx* ctx) {
// Prefer device_find_first_by_type but keep compatibility with name lookup
struct Device* dev = device_find_by_name("audio-stream"); struct Device* dev = device_find_by_name("audio-stream");
if (dev) { if (dev) {
ctx->stream_dev = dev; ctx->stream_dev = dev;
@@ -134,10 +176,20 @@ static void close_stream_if_open(AppCtx* ctx) {
if (ctx->stream_handle) { if (ctx->stream_handle) {
audio_stream_close(ctx->stream_handle); audio_stream_close(ctx->stream_handle);
ctx->stream_handle = NULL; ctx->stream_handle = NULL;
ctx->stream_rate = 0;
ctx->stream_channels = 0;
ctx->stream_bits = 0;
} }
} }
static bool open_output_stream(AppCtx* ctx, uint32_t sample_rate, uint8_t channels, uint8_t bits) { static bool open_output_stream(AppCtx* ctx, uint32_t sample_rate, uint8_t channels, uint8_t bits) {
// Reuse the already-open stream when the format hasn't changed. This keeps the
// codec alive across page changes, avoiding the audible pop caused by closing and
// re-initialising the audio hardware on every page turn.
if (ctx->stream_handle && ctx->stream_rate == sample_rate
&& ctx->stream_channels == channels && ctx->stream_bits == bits) {
return true;
}
close_stream_if_open(ctx); close_stream_if_open(ctx);
if (!ctx->stream_dev) return false; if (!ctx->stream_dev) return false;
struct AudioStreamConfig cfg = { struct AudioStreamConfig cfg = {
@@ -151,6 +203,9 @@ static bool open_output_stream(AppCtx* ctx, uint32_t sample_rate, uint8_t channe
ctx->stream_handle = NULL; ctx->stream_handle = NULL;
return false; return false;
} }
ctx->stream_rate = sample_rate;
ctx->stream_channels = channels;
ctx->stream_bits = bits;
ESP_LOGI(TAG, "audio_stream output opened: %u Hz %u ch %u-bit", (unsigned)sample_rate, channels, bits); ESP_LOGI(TAG, "audio_stream output opened: %u Hz %u ch %u-bit", (unsigned)sample_rate, channels, bits);
return true; return true;
} }
@@ -236,20 +291,52 @@ static void handle_audio_finished(AppCtx* ctx) {
} }
/* ─── Helper to wait for playback thread to terminate safely ─── */ /* ─── Helper to wait for playback thread to terminate safely ─── */
static void wait_for_playback_task_to_exit(AppCtx* ctx) { static void wait_for_playback_task_to_exit(AppCtx* ctx, bool keep_stream_open) {
if (ctx->playback_task_handle != NULL) { if (ctx->playback_task_handle != NULL) {
ctx->keep_stream_on_stop = keep_stream_open;
ctx->state = STATE_IDLE; ctx->state = STATE_IDLE;
while (ctx->playback_task_handle != NULL) { while (ctx->playback_task_handle != NULL) {
tt_lvgl_unlock(); tt_lvgl_unlock();
vTaskDelay(pdMS_TO_TICKS(10)); vTaskDelay(pdMS_TO_TICKS(10));
tt_lvgl_lock(portMAX_DELAY); tt_lvgl_lock(portMAX_DELAY);
} }
ctx->keep_stream_on_stop = false;
} }
} }
/* ─── Load Page Content (Image, Caption, Audio path) ─── */ /* ─── Load Page Content (Image, Caption, Audio path) ─── */
static void load_image_from_page(AppCtx* ctx, cJSON* page, lv_obj_t* image,
char* lv_img_path, size_t lv_img_path_size) {
cJSON* img_item = cJSON_GetObjectItem(page, "image");
if (lv_img_path && lv_img_path_size > 0) lv_img_path[0] = '\0';
if (img_item && img_item->valuestring) {
char img_path[512];
snprintf(img_path, sizeof(img_path), "/sdcard/books/%s/%s", ctx->current_book_slug, img_item->valuestring);
FILE* img_file = fopen(img_path, "rb");
if (img_file) {
fclose(img_file);
if (!lv_img_path || lv_img_path_size == 0) {
lv_image_set_src(image, LV_SYMBOL_IMAGE);
return;
}
#ifdef ESP_PLATFORM
snprintf(lv_img_path, lv_img_path_size, "A:%s", img_path);
#else
snprintf(lv_img_path, lv_img_path_size, "A:/%s", img_path);
#endif
lv_image_set_src(image, lv_img_path);
return;
}
ESP_LOGW(TAG, "Image file not found: %s", img_path);
}
lv_image_set_src(image, LV_SYMBOL_IMAGE);
}
static void load_page(AppCtx* ctx, int page_index, bool start_audio) { static void load_page(AppCtx* ctx, int page_index, bool start_audio) {
wait_for_playback_task_to_exit(ctx); wait_for_playback_task_to_exit(ctx, true);
if (page_index < 0 || page_index >= ctx->page_count) return; if (page_index < 0 || page_index >= ctx->page_count) return;
ctx->current_page = page_index; ctx->current_page = page_index;
@@ -258,31 +345,10 @@ static void load_page(AppCtx* ctx, int page_index, bool start_audio) {
cJSON* page = cJSON_GetArrayItem(ctx->pages_array, page_index); cJSON* page = cJSON_GetArrayItem(ctx->pages_array, page_index);
if (!page) return; if (!page) return;
cJSON* img_item = cJSON_GetObjectItem(page, "image");
cJSON* snd_item = cJSON_GetObjectItem(page, "audio"); cJSON* snd_item = cJSON_GetObjectItem(page, "audio");
// Load Image file load_image_from_page(ctx, page, ctx->img_page,
if (img_item && img_item->valuestring) { ctx->player_image_path, sizeof(ctx->player_image_path));
char img_path[512];
snprintf(img_path, sizeof(img_path), "/sdcard/books/%s/%s", ctx->current_book_slug, img_item->valuestring);
FILE* img_file = fopen(img_path, "rb");
if (img_file) {
fclose(img_file);
char lv_img_path[1024];
#ifdef ESP_PLATFORM
snprintf(lv_img_path, sizeof(lv_img_path), "A:%s", img_path);
#else
snprintf(lv_img_path, sizeof(lv_img_path), "A:/%s", img_path);
#endif
lv_image_set_src(ctx->img_page, lv_img_path);
} else {
ESP_LOGW(TAG, "Image file not found: %s", img_path);
lv_image_set_src(ctx->img_page, LV_SYMBOL_IMAGE);
}
} else {
lv_image_set_src(ctx->img_page, LV_SYMBOL_IMAGE);
}
// Update Page index indicator // Update Page index indicator
char ind_buf[32]; char ind_buf[32];
@@ -321,7 +387,8 @@ static void load_page(AppCtx* ctx, int page_index, bool start_audio) {
/* ─── Return to Book Picker Screen ─── */ /* ─── Return to Book Picker Screen ─── */
static void return_to_picker(AppCtx* ctx) { static void return_to_picker(AppCtx* ctx) {
wait_for_playback_task_to_exit(ctx); wait_for_playback_task_to_exit(ctx, false);
close_stream_if_open(ctx);
if (ctx->manifest_root) { if (ctx->manifest_root) {
cJSON_Delete(ctx->manifest_root); cJSON_Delete(ctx->manifest_root);
@@ -330,6 +397,7 @@ static void return_to_picker(AppCtx* ctx) {
} }
lv_obj_add_flag(ctx->player_wrapper, LV_OBJ_FLAG_HIDDEN); lv_obj_add_flag(ctx->player_wrapper, LV_OBJ_FLAG_HIDDEN);
lv_obj_remove_flag(ctx->picker_background, LV_OBJ_FLAG_HIDDEN);
lv_obj_remove_flag(ctx->picker_wrapper, LV_OBJ_FLAG_HIDDEN); lv_obj_remove_flag(ctx->picker_wrapper, LV_OBJ_FLAG_HIDDEN);
} }
@@ -442,7 +510,7 @@ static void play_mp3(AppCtx* ctx) {
channels = info.channels; channels = info.channels;
} }
// Adjust Volume // Adjust volume without altering the start or end of the narration.
int vol = ctx->volume; int vol = ctx->volume;
int16_t* samples_ptr = (int16_t*)ctx->pcm_buf; int16_t* samples_ptr = (int16_t*)ctx->pcm_buf;
size_t sample_count = (size_t)samples * info.channels; size_t sample_count = (size_t)samples * info.channels;
@@ -485,10 +553,14 @@ static void play_mp3(AppCtx* ctx) {
} }
fclose(file); fclose(file);
close_stream_if_open(ctx);
bool stopped_externally = (ctx->state == STATE_IDLE); bool stopped_externally = (ctx->state == STATE_IDLE);
if (stopped_externally && !ctx->keep_stream_on_stop) {
// App exit and returning to the picker release the output device.
close_stream_if_open(ctx);
}
if (!stopped_externally) { if (!stopped_externally) {
tt_lvgl_lock(portMAX_DELAY); tt_lvgl_lock(portMAX_DELAY);
handle_audio_finished(ctx); handle_audio_finished(ctx);
@@ -588,7 +660,7 @@ static void play_wav(AppCtx* ctx) {
size_t read_bytes = fread(ctx->audio_buf, 1, to_read, file); size_t read_bytes = fread(ctx->audio_buf, 1, to_read, file);
if (read_bytes == 0) break; if (read_bytes == 0) break;
// Scaling Volume // Adjust volume without altering the start or end of the narration.
int vol = ctx->volume; int vol = ctx->volume;
int16_t* samples_ptr = (int16_t*)ctx->audio_buf; int16_t* samples_ptr = (int16_t*)ctx->audio_buf;
size_t sample_count = read_bytes / sizeof(int16_t); size_t sample_count = read_bytes / sizeof(int16_t);
@@ -629,10 +701,14 @@ static void play_wav(AppCtx* ctx) {
} }
fclose(file); fclose(file);
close_stream_if_open(ctx);
bool stopped_externally = (ctx->state == STATE_IDLE); bool stopped_externally = (ctx->state == STATE_IDLE);
if (stopped_externally && !ctx->keep_stream_on_stop) {
// App exit and returning to the picker release the output device.
close_stream_if_open(ctx);
}
if (!stopped_externally) { if (!stopped_externally) {
tt_lvgl_lock(portMAX_DELAY); tt_lvgl_lock(portMAX_DELAY);
handle_audio_finished(ctx); handle_audio_finished(ctx);
@@ -643,13 +719,19 @@ static void play_wav(AppCtx* ctx) {
vTaskDelete(NULL); vTaskDelete(NULL);
} }
/* ─── Picker events ─── */ /* ─── Full-screen book picker ─── */
static void on_book_selected(lv_event_t* e) { static bool select_picker_book(AppCtx* ctx, int index) {
int index = (int)(intptr_t)lv_event_get_user_data(e); if (index < 0 || index >= ctx->book_count) return false;
AppCtx* ctx = &g_ctx;
if (ctx->manifest_root) {
cJSON_Delete(ctx->manifest_root);
ctx->manifest_root = NULL;
ctx->pages_array = NULL;
}
BookMetadata* book = &ctx->books[index]; BookMetadata* book = &ctx->books[index];
strncpy(ctx->current_book_slug, book->slug, sizeof(ctx->current_book_slug) - 1); strncpy(ctx->current_book_slug, book->slug, sizeof(ctx->current_book_slug) - 1);
ctx->current_book_slug[sizeof(ctx->current_book_slug) - 1] = '\0';
char manifest_path[512]; char manifest_path[512];
snprintf(manifest_path, sizeof(manifest_path), "/sdcard/books/%s/manifest.json", book->slug); snprintf(manifest_path, sizeof(manifest_path), "/sdcard/books/%s/manifest.json", book->slug);
@@ -658,7 +740,7 @@ static void on_book_selected(lv_event_t* e) {
if (!json_str) { if (!json_str) {
const char* buttons[] = {"OK"}; const char* buttons[] = {"OK"};
tt_app_alertdialog_start("Read Error", "Failed to open the book manifest.", buttons, 1); tt_app_alertdialog_start("Read Error", "Failed to open the book manifest.", buttons, 1);
return; return false;
} }
ctx->manifest_root = cJSON_Parse(json_str); ctx->manifest_root = cJSON_Parse(json_str);
@@ -667,7 +749,7 @@ static void on_book_selected(lv_event_t* e) {
if (!ctx->manifest_root) { if (!ctx->manifest_root) {
const char* buttons[] = {"OK"}; const char* buttons[] = {"OK"};
tt_app_alertdialog_start("JSON Error", "The book manifest is not formatted correctly.", buttons, 1); tt_app_alertdialog_start("JSON Error", "The book manifest is not formatted correctly.", buttons, 1);
return; return false;
} }
ctx->pages_array = cJSON_GetObjectItem(ctx->manifest_root, "pages"); ctx->pages_array = cJSON_GetObjectItem(ctx->manifest_root, "pages");
@@ -677,7 +759,7 @@ static void on_book_selected(lv_event_t* e) {
cJSON_Delete(ctx->manifest_root); cJSON_Delete(ctx->manifest_root);
ctx->manifest_root = NULL; ctx->manifest_root = NULL;
ctx->pages_array = NULL; ctx->pages_array = NULL;
return; return false;
} }
ctx->page_count = cJSON_GetArraySize(ctx->pages_array); ctx->page_count = cJSON_GetArraySize(ctx->pages_array);
@@ -687,30 +769,149 @@ static void on_book_selected(lv_event_t* e) {
cJSON_Delete(ctx->manifest_root); cJSON_Delete(ctx->manifest_root);
ctx->manifest_root = NULL; ctx->manifest_root = NULL;
ctx->pages_array = NULL; ctx->pages_array = NULL;
return; return false;
} }
ctx->selected_book = index;
lv_label_set_text(ctx->lbl_picker_title, book->title);
lv_label_set_text(ctx->lbl_picker_author, book->author[0] ? book->author : "");
char picker_status[64];
snprintf(picker_status, sizeof(picker_status), "%d / %d - Tap sides or swipe", index + 1, ctx->book_count);
lv_label_set_text(ctx->lbl_picker_status, picker_status);
schedule_picker_cover_load(ctx);
return true;
}
static void clear_picker_cover(AppCtx* ctx) {
if (!ctx->picker_cover) return;
// Release the previous file-backed source before its stable path buffer is
// reused. The symbol fallback has no file decoder or SD resource attached.
lv_image_set_src(ctx->picker_cover, LV_SYMBOL_IMAGE);
ctx->picker_cover_path[0] = '\0';
}
static void on_picker_cover_timer(lv_timer_t* timer) {
AppCtx* ctx = (AppCtx*)lv_timer_get_user_data(timer);
if (!ctx) return;
// The timer is one-shot and LVGL will dispose it after this callback.
// Clear the stored pointer first so a subsequent selection cannot delete a
// timer that is already being finalized.
ctx->picker_cover_timer = NULL;
if (!ctx->pages_array || !ctx->picker_cover) return;
cJSON* first_page = cJSON_GetArrayItem(ctx->pages_array, 0);
if (!first_page) return;
load_image_from_page(ctx, first_page, ctx->picker_cover,
ctx->picker_cover_path, sizeof(ctx->picker_cover_path));
}
static void schedule_picker_cover_load(AppCtx* ctx) {
cancel_picker_cover_load(ctx);
clear_picker_cover(ctx);
// Loading a full SD PNG from onShow has rebooted the S3 before LVGL's first
// event-loop pass. The player performs this same load from a user event;
// defer the picker equivalent until its UI is live and stable.
ctx->picker_cover_timer = lv_timer_create(on_picker_cover_timer, PICKER_COVER_LOAD_DELAY_MS, ctx);
if (ctx->picker_cover_timer) {
lv_timer_set_repeat_count(ctx->picker_cover_timer, 1);
} else {
ESP_LOGE(TAG, "Failed to schedule picker cover image load");
}
}
static void cancel_picker_cover_load(AppCtx* ctx) {
if (ctx->picker_cover_timer) {
lv_timer_delete(ctx->picker_cover_timer);
ctx->picker_cover_timer = NULL;
}
}
static void open_selected_book(AppCtx* ctx, bool start_audio) {
if (!ctx->manifest_root || ctx->page_count <= 0) return;
BookMetadata* book = &ctx->books[ctx->selected_book];
lv_label_set_text(ctx->lbl_book_title, book->title); lv_label_set_text(ctx->lbl_book_title, book->title);
// Switch views // Switch views
cancel_picker_cover_load(ctx);
lv_obj_add_flag(ctx->picker_background, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag(ctx->picker_wrapper, LV_OBJ_FLAG_HIDDEN); lv_obj_add_flag(ctx->picker_wrapper, LV_OBJ_FLAG_HIDDEN);
lv_obj_remove_flag(ctx->player_wrapper, LV_OBJ_FLAG_HIDDEN); lv_obj_remove_flag(ctx->player_wrapper, LV_OBJ_FLAG_HIDDEN);
lv_obj_remove_flag(ctx->header_bar, LV_OBJ_FLAG_HIDDEN); lv_obj_remove_flag(ctx->header_bar, LV_OBJ_FLAG_HIDDEN);
lv_obj_remove_flag(ctx->ctrl_bar, LV_OBJ_FLAG_HIDDEN); lv_obj_remove_flag(ctx->ctrl_bar, LV_OBJ_FLAG_HIDDEN);
lv_obj_remove_flag(ctx->bar_progress, LV_OBJ_FLAG_HIDDEN); lv_obj_remove_flag(ctx->bar_progress, LV_OBJ_FLAG_HIDDEN);
load_page(ctx, 0, false); load_page(ctx, 0, start_audio);
}
static void change_picker_book(AppCtx* ctx, int index) {
if (index < 0 || index >= ctx->book_count || index == ctx->selected_book) return;
select_picker_book(ctx, index);
}
static void on_picker_touch(lv_event_t* e) {
AppCtx* ctx = (AppCtx*)lv_event_get_user_data(e);
lv_event_code_t code = lv_event_get_code(e);
lv_indev_t* indev = lv_indev_active();
if (!ctx || !indev || ctx->book_count == 0) return;
lv_point_t point;
lv_indev_get_point(indev, &point);
if (code == LV_EVENT_PRESSED) {
ctx->picker_drag_start_x = point.x;
ctx->picker_dragging = true;
ctx->picker_dragged = false;
} else if (code == LV_EVENT_PRESSING && ctx->picker_dragging) {
int dx = point.x - ctx->picker_drag_start_x;
const int threshold = 28;
if (abs(dx) >= threshold) {
int steps = dx / threshold;
int next_index = ctx->selected_book - steps; // swipe left advances
if (next_index < 0) next_index = 0;
if (next_index >= ctx->book_count) next_index = ctx->book_count - 1;
if (next_index != ctx->selected_book) {
change_picker_book(ctx, next_index);
ctx->picker_dragged = true;
}
ctx->picker_drag_start_x = point.x;
}
} else if (code == LV_EVENT_RELEASED || code == LV_EVENT_PRESS_LOST) {
ctx->picker_dragging = false;
} else if (code == LV_EVENT_CLICKED) {
if (ctx->picker_dragged) {
ctx->picker_dragged = false;
return;
}
if (point.x < lv_obj_get_width(ctx->picker_touch_area) / 2) {
change_picker_book(ctx, ctx->selected_book - 1);
} else {
change_picker_book(ctx, ctx->selected_book + 1);
}
}
}
static void on_picker_play_click(lv_event_t* e) {
AppCtx* ctx = (AppCtx*)lv_event_get_user_data(e);
open_selected_book(ctx, true);
}
static void on_picker_close_click(lv_event_t* e) {
(void)e;
// Follow the normal external-app lifecycle so onHide releases the pending
// cover timer, file-backed image sources, manifest, and audio buffers.
tt_app_stop();
} }
/* ─── Scan Books ─── */ /* ─── Scan Books ─── */
static void scan_books(AppCtx* ctx) { static void scan_books(AppCtx* ctx) {
ctx->book_count = 0; ctx->book_count = 0;
lv_obj_clean(ctx->lst_books);
DIR* dir = opendir("/sdcard/books"); DIR* dir = opendir("/sdcard/books");
if (!dir) { if (!dir) {
ESP_LOGE(TAG, "Failed to scan books: /sdcard/books folder missing."); ESP_LOGE(TAG, "Failed to scan books: /sdcard/books folder missing.");
lv_list_add_text(ctx->lst_books, "No SD card or books directory found."); lv_label_set_text(ctx->lbl_picker_status, "No SD card or books directory found.");
return; return;
} }
@@ -753,7 +954,7 @@ static void scan_books(AppCtx* ctx) {
closedir(dir); closedir(dir);
if (ctx->book_count == 0) { if (ctx->book_count == 0) {
lv_list_add_text(ctx->lst_books, "No book manifest.json files found."); lv_label_set_text(ctx->lbl_picker_status, "No book manifest.json files found.");
return; return;
} }
@@ -768,17 +969,8 @@ static void scan_books(AppCtx* ctx) {
} }
} }
// Add items to screen list lv_obj_remove_flag(ctx->btn_picker_play, LV_OBJ_FLAG_HIDDEN);
for (int i = 0; i < ctx->book_count; ++i) { select_picker_book(ctx, 0);
char label_text[512];
if (ctx->books[i].author[0] != '\0') {
snprintf(label_text, sizeof(label_text), "%s\nby %s", ctx->books[i].title, ctx->books[i].author);
} else {
snprintf(label_text, sizeof(label_text), "%s", ctx->books[i].title);
}
lv_obj_t* btn = lv_list_add_button(ctx->lst_books, LV_SYMBOL_DIRECTORY, label_text);
lv_obj_add_event_cb(btn, on_book_selected, LV_EVENT_CLICKED, (void*)(intptr_t)i);
}
} }
/* ─── Player Control Events ─── */ /* ─── Player Control Events ─── */
@@ -856,26 +1048,103 @@ static void onShowApp(AppHandle app, void* data, lv_obj_t* parent) {
ESP_LOGE(TAG, "audio-stream device not found! Tried 'audio-stream' name and AUDIO_STREAM_TYPE"); ESP_LOGE(TAG, "audio-stream device not found! Tried 'audio-stream' name and AUDIO_STREAM_TYPE");
} }
// Create dual layouts // Create dual layouts.
// 1. Picker Screen wrapper // 1. The picker cover lives in its own back sibling. Keep all picker UI
// and touch objects in the transparent foreground sibling above so changing
// a title/status/button does not force the PNG-backed image through that
// overlay's redraw path.
g_ctx.picker_background = lv_obj_create(parent);
lv_obj_set_size(g_ctx.picker_background, LV_PCT(100), LV_PCT(100));
lv_obj_set_style_border_width(g_ctx.picker_background, 0, 0);
lv_obj_set_style_pad_all(g_ctx.picker_background, 0, 0);
lv_obj_set_style_pad_gap(g_ctx.picker_background, 0, 0);
lv_obj_set_style_bg_color(g_ctx.picker_background, lv_color_hex(0x1E1E2E), 0);
lv_obj_set_style_bg_opa(g_ctx.picker_background, LV_OPA_COVER, 0);
lv_obj_remove_flag(g_ctx.picker_background, LV_OBJ_FLAG_SCROLLABLE);
g_ctx.picker_cover = lv_image_create(g_ctx.picker_background);
lv_obj_align(g_ctx.picker_cover, LV_ALIGN_CENTER, 0, 0);
lv_obj_set_style_bg_opa(g_ctx.picker_cover, LV_OPA_TRANSP, 0);
lv_obj_set_style_pad_all(g_ctx.picker_cover, 0, 0);
lv_obj_set_style_border_width(g_ctx.picker_cover, 0, 0);
lv_obj_remove_flag(g_ctx.picker_cover, LV_OBJ_FLAG_SCROLLABLE);
g_ctx.picker_wrapper = lv_obj_create(parent); g_ctx.picker_wrapper = lv_obj_create(parent);
lv_obj_set_size(g_ctx.picker_wrapper, LV_PCT(100), LV_PCT(100)); lv_obj_set_size(g_ctx.picker_wrapper, LV_PCT(100), LV_PCT(100));
lv_obj_set_style_border_width(g_ctx.picker_wrapper, 0, 0); lv_obj_set_style_border_width(g_ctx.picker_wrapper, 0, 0);
lv_obj_set_style_pad_all(g_ctx.picker_wrapper, 0, 0); lv_obj_set_style_pad_all(g_ctx.picker_wrapper, 0, 0);
lv_obj_set_style_pad_gap(g_ctx.picker_wrapper, 0, 0); lv_obj_set_style_pad_gap(g_ctx.picker_wrapper, 0, 0);
lv_obj_set_style_bg_color(g_ctx.picker_wrapper, lv_color_hex(0x1E1E2E), 0); lv_obj_set_style_bg_opa(g_ctx.picker_wrapper, LV_OPA_TRANSP, 0);
lv_obj_remove_flag(g_ctx.picker_wrapper, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_t* toolbar = tt_lvgl_toolbar_create_for_app(g_ctx.picker_wrapper, app); g_ctx.picker_touch_area = lv_obj_create(g_ctx.picker_wrapper);
lv_obj_align(toolbar, LV_ALIGN_TOP_MID, 0, 0); lv_obj_set_size(g_ctx.picker_touch_area, LV_PCT(100), LV_PCT(100));
lv_obj_align(g_ctx.picker_touch_area, LV_ALIGN_CENTER, 0, 0);
lv_obj_set_style_bg_opa(g_ctx.picker_touch_area, LV_OPA_TRANSP, 0);
lv_obj_set_style_border_width(g_ctx.picker_touch_area, 0, 0);
lv_obj_set_style_pad_all(g_ctx.picker_touch_area, 0, 0);
lv_obj_remove_flag(g_ctx.picker_touch_area, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_add_flag(g_ctx.picker_touch_area, LV_OBJ_FLAG_CLICKABLE);
lv_obj_add_event_cb(g_ctx.picker_touch_area, on_picker_touch, LV_EVENT_PRESSED, &g_ctx);
lv_obj_add_event_cb(g_ctx.picker_touch_area, on_picker_touch, LV_EVENT_PRESSING, &g_ctx);
lv_obj_add_event_cb(g_ctx.picker_touch_area, on_picker_touch, LV_EVENT_RELEASED, &g_ctx);
lv_obj_add_event_cb(g_ctx.picker_touch_area, on_picker_touch, LV_EVENT_PRESS_LOST, &g_ctx);
lv_obj_add_event_cb(g_ctx.picker_touch_area, on_picker_touch, LV_EVENT_CLICKED, &g_ctx);
g_ctx.lst_books = lv_list_create(g_ctx.picker_wrapper); lv_obj_t* picker_title_panel = lv_obj_create(g_ctx.picker_wrapper);
lv_obj_set_width(g_ctx.lst_books, LV_PCT(100)); lv_obj_set_size(picker_title_panel, LV_PCT(100), 68);
lv_obj_align_to(g_ctx.lst_books, toolbar, LV_ALIGN_OUT_BOTTOM_MID, 0, 0); lv_obj_align(picker_title_panel, LV_ALIGN_TOP_MID, 0, 0);
int32_t toolbar_height = lv_obj_get_height(toolbar); lv_obj_set_style_bg_color(picker_title_panel, lv_color_hex(0x11111B), 0);
int32_t parent_height = lv_obj_get_content_height(parent); lv_obj_set_style_bg_opa(picker_title_panel, LV_OPA_60, 0);
lv_obj_set_height(g_ctx.lst_books, parent_height - toolbar_height); lv_obj_set_style_border_width(picker_title_panel, 0, 0);
lv_obj_set_style_bg_color(g_ctx.lst_books, lv_color_hex(0x1E1E2E), 0); lv_obj_set_style_pad_all(picker_title_panel, 0, 0);
lv_obj_set_style_border_color(g_ctx.lst_books, lv_color_hex(0x313244), 0); lv_obj_remove_flag(picker_title_panel, LV_OBJ_FLAG_SCROLLABLE);
g_ctx.lbl_picker_title = lv_label_create(picker_title_panel);
lv_obj_set_width(g_ctx.lbl_picker_title, LV_PCT(86));
lv_obj_align(g_ctx.lbl_picker_title, LV_ALIGN_TOP_MID, 0, 10);
lv_obj_set_style_text_align(g_ctx.lbl_picker_title, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_set_style_text_color(g_ctx.lbl_picker_title, lv_color_hex(0xFFFFFF), 0);
lv_obj_set_style_text_font(g_ctx.lbl_picker_title, lvgl_get_text_font(FONT_SIZE_LARGE), 0);
lv_label_set_long_mode(g_ctx.lbl_picker_title, LV_LABEL_LONG_WRAP);
g_ctx.lbl_picker_author = lv_label_create(picker_title_panel);
lv_obj_set_width(g_ctx.lbl_picker_author, LV_PCT(86));
lv_obj_align(g_ctx.lbl_picker_author, LV_ALIGN_TOP_MID, 0, 42);
lv_obj_set_style_text_align(g_ctx.lbl_picker_author, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_set_style_text_color(g_ctx.lbl_picker_author, lv_color_hex(0xE0E0E8), 0);
lv_label_set_long_mode(g_ctx.lbl_picker_author, LV_LABEL_LONG_DOT);
g_ctx.lbl_picker_status = lv_label_create(g_ctx.picker_wrapper);
lv_obj_set_width(g_ctx.lbl_picker_status, LV_PCT(86));
lv_obj_align(g_ctx.lbl_picker_status, LV_ALIGN_BOTTOM_MID, 0, -54);
lv_obj_set_style_text_align(g_ctx.lbl_picker_status, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_set_style_text_color(g_ctx.lbl_picker_status, lv_color_hex(0xF5F5FA), 0);
g_ctx.btn_picker_play = lv_button_create(g_ctx.picker_wrapper);
lv_obj_set_size(g_ctx.btn_picker_play, 58, 42);
lv_obj_align(g_ctx.btn_picker_play, LV_ALIGN_BOTTOM_MID, 0, -10);
lv_obj_set_style_radius(g_ctx.btn_picker_play, 21, 0);
lv_obj_set_style_bg_color(g_ctx.btn_picker_play, lv_color_hex(0x89B4FA), 0);
lv_obj_set_style_text_color(g_ctx.btn_picker_play, lv_color_hex(0x11111B), 0);
lv_obj_t* lbl_picker_play = lv_label_create(g_ctx.btn_picker_play);
lv_label_set_text(lbl_picker_play, LV_SYMBOL_PLAY);
lv_obj_center(lbl_picker_play);
lv_obj_add_event_cb(g_ctx.btn_picker_play, on_picker_play_click, LV_EVENT_CLICKED, &g_ctx);
lv_obj_add_flag(g_ctx.btn_picker_play, LV_OBJ_FLAG_HIDDEN);
// A dedicated side exit control leaves the center cover, top title panel,
// and bottom play target clear while reserving its own small touch area.
lv_obj_t* btn_picker_close = lv_button_create(g_ctx.picker_wrapper);
lv_obj_set_size(btn_picker_close, 42, 42);
lv_obj_align(btn_picker_close, LV_ALIGN_RIGHT_MID, -8, 0);
lv_obj_set_style_radius(btn_picker_close, 21, 0);
lv_obj_set_style_bg_color(btn_picker_close, lv_color_hex(0xD64545), 0);
lv_obj_set_style_text_color(btn_picker_close, lv_color_hex(0xFFFFFF), 0);
lv_obj_t* lbl_picker_close = lv_label_create(btn_picker_close);
lv_label_set_text(lbl_picker_close, LV_SYMBOL_CLOSE);
lv_obj_center(lbl_picker_close);
lv_obj_add_event_cb(btn_picker_close, on_picker_close_click, LV_EVENT_CLICKED, &g_ctx);
// 2. Player Screen wrapper (hidden on start) // 2. Player Screen wrapper (hidden on start)
g_ctx.player_wrapper = lv_obj_create(parent); g_ctx.player_wrapper = lv_obj_create(parent);
@@ -987,9 +1256,16 @@ static void onShowApp(AppHandle app, void* data, lv_obj_t* parent) {
} }
static void onHideApp(AppHandle app, void* data) { static void onHideApp(AppHandle app, void* data) {
wait_for_playback_task_to_exit(&g_ctx); wait_for_playback_task_to_exit(&g_ctx, false);
close_stream_if_open(&g_ctx); close_stream_if_open(&g_ctx);
cancel_picker_cover_load(&g_ctx);
clear_picker_cover(&g_ctx);
if (g_ctx.img_page) {
lv_image_set_src(g_ctx.img_page, LV_SYMBOL_IMAGE);
g_ctx.player_image_path[0] = '\0';
}
if (g_ctx.manifest_root) { if (g_ctx.manifest_root) {
cJSON_Delete(g_ctx.manifest_root); cJSON_Delete(g_ctx.manifest_root);
g_ctx.manifest_root = NULL; g_ctx.manifest_root = NULL;
+7 -10
View File
@@ -1,10 +1,7 @@
[manifest] manifest.version=0.2
version=0.1 target.sdk=0.8.0-dev
[target] target.platforms=esp32s3
sdk=0.8.0-dev app.id=one.tactility.bookplayer
platforms=esp32s3 app.version.name=1.0.0
[app] app.version.code=1
id=one.tactility.bookplayer app.name=Book Player
versionName=1.0.0
versionCode=1
name=Book Player
+8 -11
View File
@@ -1,11 +1,8 @@
[manifest] manifest.version=0.2
version=0.1 target.sdk=0.8.0-dev
[target] target.platforms=esp32,esp32s3,esp32c6,esp32p4
sdk=0.7.0-dev app.id=one.tactility.brainfuck
platforms=esp32,esp32s3,esp32c6,esp32p4 app.version.name=0.5.0
[app] app.version.code=5
id=one.tactility.brainfuck app.name=Brainfuck interpreter
versionName=0.2.0 app.description=Brainfuck esoteric language interpreter
versionCode=2
name=Brainfuck interpreter
description=Brainfuck esoteric language interpreter
+2 -3
View File
@@ -12,8 +12,8 @@
#include <esp_random.h> #include <esp_random.h>
#include <tt_lvgl_keyboard.h> #include <tt_lvgl_keyboard.h>
#include <tactility/lvgl_module.h> #include <lvgl/lvgl.h>
#include <tactility/lvgl_fonts.h> #include <lvgl/fonts.h>
constexpr auto* TAG = "Breakout"; constexpr auto* TAG = "Breakout";
@@ -124,7 +124,6 @@ void Breakout::onShow(AppHandle appHandle, lv_obj_t* parent) {
if (!sfxEngine) { if (!sfxEngine) {
sfxEngine = new SfxEngine(); sfxEngine = new SfxEngine();
sfxEngine->start(); sfxEngine->start();
sfxEngine->applyVolumePreset(SfxEngine::VolumePreset::Quiet);
sfxEngine->setEnabled(soundEnabled); sfxEngine->setEnabled(soundEnabled);
} }
+8 -11
View File
@@ -1,11 +1,8 @@
[manifest] manifest.version=0.2
version=0.1 target.sdk=0.8.0-dev
[target] target.platforms=esp32,esp32s3,esp32c6,esp32p4
sdk=0.7.0-dev app.id=one.tactility.breakout
platforms=esp32,esp32s3,esp32c6,esp32p4 app.version.name=0.5.0
[app] app.version.code=5
id=one.tactility.breakout app.name=Breakout
versionName=0.2.0 app.description=Classic brick-breaking arcade game
versionCode=2
name=Breakout
description=Classic brick-breaking arcade game
+7 -10
View File
@@ -1,10 +1,7 @@
[manifest] manifest.version=0.2
version=0.1 target.sdk=0.8.0-dev
[target] target.platforms=esp32,esp32s3,esp32c6,esp32p4
sdk=0.7.0-dev app.id=one.tactility.calculator
platforms=esp32,esp32s3,esp32c6,esp32p4 app.version.name=0.6.0
[app] app.version.code=6
id=one.tactility.calculator app.name=Calculator
versionName=0.3.0
versionCode=3
name=Calculator
+7 -10
View File
@@ -1,10 +1,7 @@
[manifest] manifest.version=0.2
version=0.1 target.sdk=0.8.0-dev
[target] target.platforms=esp32,esp32s3,esp32c6,esp32p4
sdk=0.7.0-dev app.id=one.tactility.diceware
platforms=esp32,esp32s3,esp32c6,esp32p4 app.version.name=0.6.0
[app] app.version.code=6
id=one.tactility.diceware app.name=Diceware
versionName=0.3.0
versionCode=3
name=Diceware
+8 -11
View File
@@ -1,11 +1,8 @@
[manifest] manifest.version=0.2
version=0.1 target.sdk=0.8.0-dev
[target] target.platforms=esp32s3,esp32p4
sdk=0.7.0-dev app.id=one.tactility.epubreader
platforms=esp32s3,esp32p4 app.version.name=0.4.0
[app] app.version.code=4
id=one.tactility.epubreader app.name=Epub Reader
versionName=0.1.0 app.description=Epub and text file reader. Requires PSRAM!
versionCode=1
name=Epub Reader
description=Epub and text file reader. Requires PSRAM!
+16
View File
@@ -0,0 +1,16 @@
cmake_minimum_required(VERSION 3.20)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
if (DEFINED ENV{TACTILITY_SDK_PATH})
set(TACTILITY_SDK_PATH $ENV{TACTILITY_SDK_PATH})
else()
set(TACTILITY_SDK_PATH "../../release/TactilitySDK")
message(WARNING "TACTILITY_SDK_PATH environment variable is not set, defaulting to ${TACTILITY_SDK_PATH}")
endif()
include("${TACTILITY_SDK_PATH}/TactilitySDK.cmake")
set(EXTRA_COMPONENT_DIRS ${TACTILITY_SDK_PATH})
project(EspNowBridge)
tactility_project(EspNowBridge)
Binary file not shown.
+11
View File
@@ -0,0 +1,11 @@
file(GLOB_RECURSE SOURCE_FILES
Source/*.c*
)
idf_component_register(
SRCS ${SOURCE_FILES}
# Library headers must be included directly,
# because all regular dependencies get stripped by elf_loader's cmake script
INCLUDE_DIRS ../../../Libraries/TactilityCpp/Include
REQUIRES TactilitySDK bootloader_support esp_app_format
)
@@ -0,0 +1,739 @@
#include "EspNowBridge.h"
#include <tactility/device.h>
#include <tactility/drivers/wifi.h>
#include <tactility/wifi_auto_scan.h>
#include <tactility/firmware/firmware.h>
#include <tt_app.h>
#include <tt_app_fileselection.h>
#include <tt_bundle.h>
#include <tt_lock.h>
#include <tt_lvgl.h>
#include <tt_lvgl_toolbar.h>
#include <esp_app_desc.h>
#include <esp_app_format.h>
#include <esp_system.h>
#include <tactility/log.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <algorithm>
#include <cinttypes>
#include <cstdio>
#include <cstring>
static constexpr auto* TAG = "EspNowBridge";
static constexpr size_t CHUNK_SIZE = 1500;
static constexpr uint32_t TRANSPORT_WAIT_TIMEOUT_MS = 5000;
static constexpr uint32_t UPDATE_TASK_STACK_SIZE = 8192;
AutoScanPauseGuard::AutoScanPauseGuard() { wifi_auto_scan_set_paused(true); }
AutoScanPauseGuard::~AutoScanPauseGuard() { wifi_auto_scan_set_paused(false); }
// Binary partition table format (gen_esp32part.py STRUCT_FORMAT '<2sBBLL16sL'): a flat array of
// 32-byte little-endian records starting at flash offset PARTITION_TABLE_OFFSET, terminated by
// an all-0xFF entry or an MD5-checksum record (magic 0xEBEB). Not exposed as a C header by
// ESP-IDF (only the Python generator knows the format) - this is a hand-ported minimal reader,
// just enough to locate the app partition inside a merged/factory bin.
static constexpr size_t PARTITION_TABLE_OFFSET = 0x8000;
static constexpr size_t PARTITION_TABLE_MAX_ENTRIES = 128; // covers the largest partition table IDF supports (0x1000 / 32)
static constexpr uint16_t PARTITION_ENTRY_MAGIC = 0x50AA; // little-endian bytes 0xAA, 0x50
static constexpr uint16_t PARTITION_MD5_MAGIC = 0xEBEB;
static constexpr uint8_t PARTITION_TYPE_APP = 0x00;
static constexpr uint8_t PARTITION_SUBTYPE_FACTORY = 0x00;
static constexpr uint8_t PARTITION_SUBTYPE_OTA_0 = 0x10;
struct __attribute__((packed)) PartitionEntry {
uint16_t magic;
uint8_t type;
uint8_t subtype;
uint32_t offset;
uint32_t size;
char name[16];
uint32_t flags;
};
static_assert(sizeof(PartitionEntry) == 32, "partition table entry must be 32 bytes");
/**
* Scans the partition table embedded in a merged/factory bin (at PARTITION_TABLE_OFFSET) for
* the app partition to flash: prefers "factory" if present, otherwise the first OTA slot
* (ota_0) - matches what a real M5Stack ESP-Hosted factory image contains.
* @return true if an app partition was found, with appOffset/appSize set to its location
* within the file (these are the same as the absolute flash offsets the merged bin preserves).
*/
static bool findAppPartitionInMergedBin(FILE* file, size_t& appOffset, size_t& appSize) {
if (fseek(file, static_cast<long>(PARTITION_TABLE_OFFSET), SEEK_SET) != 0) {
return false;
}
bool foundFactory = false;
bool foundOta0 = false;
size_t factoryOffset = 0, factorySize = 0;
size_t ota0Offset = 0, ota0Size = 0;
for (size_t i = 0; i < PARTITION_TABLE_MAX_ENTRIES; i++) {
PartitionEntry entry;
if (fread(&entry, 1, sizeof(entry), file) != sizeof(entry)) {
break;
}
if (entry.magic == PARTITION_MD5_MAGIC) {
break;
}
if (entry.magic != PARTITION_ENTRY_MAGIC) {
break;
}
if (entry.type == PARTITION_TYPE_APP) {
if (entry.subtype == PARTITION_SUBTYPE_FACTORY) {
foundFactory = true;
factoryOffset = entry.offset;
factorySize = entry.size;
} else if (entry.subtype == PARTITION_SUBTYPE_OTA_0 && !foundOta0) {
foundOta0 = true;
ota0Offset = entry.offset;
ota0Size = entry.size;
}
}
}
if (foundFactory) {
appOffset = factoryOffset;
appSize = factorySize;
return true;
}
if (foundOta0) {
appOffset = ota0Offset;
appSize = ota0Size;
return true;
}
return false;
}
/**
* Validates the app image at the given file offset and extracts its version string. The actual
* transfer size used for the OTA loop is just the real remaining file size from appOffset (see
* performUpdate) - hand-computing the image's "logical" size from segment headers + checksum/
* hash padding drifts a bit short of the real length, so we just use the file size instead.
*/
static bool parseImageHeader(FILE* file, size_t appOffset, char* versionOut, size_t versionOutLen, std::string* errorOut = nullptr) {
esp_image_header_t imageHeader;
if (fseek(file, static_cast<long>(appOffset), SEEK_SET) != 0 ||
fread(&imageHeader, 1, sizeof(imageHeader), file) != sizeof(imageHeader)) {
if (errorOut != nullptr) {
*errorOut = "Failed to read image header";
}
return false;
}
if (imageHeader.magic != ESP_IMAGE_HEADER_MAGIC) {
if (errorOut != nullptr) {
*errorOut = "Selected file is not a valid firmware image (bad magic)";
}
return false;
}
// Fail fast on a wrong-chip image (e.g. an ESP32 or S3 binary picked by mistake) before
// streaming the whole file over the paced, slow bridge link - esp_hosted_slave_ota_end()
// would eventually catch this too, but only after the entire transfer already completed.
if (imageHeader.chip_id != ESP_CHIP_ID_ESP32C6) {
if (errorOut != nullptr) {
char buf[96];
snprintf(buf, sizeof(buf), "Wrong chip: image targets chip id %u, expected ESP32-C6",
(unsigned)imageHeader.chip_id);
*errorOut = buf;
}
return false;
}
esp_image_segment_header_t segmentHeader;
size_t firstSegmentOffset = appOffset + sizeof(imageHeader);
if (fseek(file, static_cast<long>(firstSegmentOffset), SEEK_SET) != 0 ||
fread(&segmentHeader, 1, sizeof(segmentHeader), file) != sizeof(segmentHeader)) {
if (errorOut != nullptr) {
*errorOut = "Failed to read first segment header";
}
return false;
}
esp_app_desc_t appDesc;
size_t appDescOffset = appOffset + sizeof(imageHeader) + sizeof(segmentHeader);
if (fseek(file, static_cast<long>(appDescOffset), SEEK_SET) == 0 && fread(&appDesc, 1, sizeof(appDesc), file) == sizeof(appDesc)) {
strncpy(versionOut, appDesc.version, versionOutLen - 1);
versionOut[versionOutLen - 1] = '\0';
} else {
strncpy(versionOut, "unknown", versionOutLen - 1);
versionOut[versionOutLen - 1] = '\0';
}
return true;
}
static bool getCurrentVersionString(const FirmwareOps* ops, void* ctx, char* versionOut, size_t versionOutLen) {
FirmwareInfo info = {};
if (ops == nullptr || ops->get_info(ctx, &info) != ERROR_NONE) {
return false;
}
if (info.name[0] != '\0') {
snprintf(versionOut, versionOutLen, "%u.%u.%u (%s)",
(unsigned)info.fw_major, (unsigned)info.fw_minor, (unsigned)info.fw_patch, info.name);
} else {
snprintf(versionOut, versionOutLen, "%u.%u.%u",
(unsigned)info.fw_major, (unsigned)info.fw_minor, (unsigned)info.fw_patch);
}
return true;
}
/** Only slave firmware >= v2.6.0 implements esp_hosted_slave_ota_activate() - older slaves
* reject/lack the RPC entirely. Matches upstream's host_performs_slave_ota example. */
static bool activateSupported(uint32_t major, uint32_t minor) {
return (major > 2) || (major == 2 && minor > 5);
}
std::atomic<EspNowBridge*> EspNowBridge::liveInstance_{nullptr};
void EspNowBridge::onCreate(AppHandle app) {
appHandle_ = app;
taskDoneSemaphore_ = xSemaphoreCreateBinary();
liveInstance_ = this;
}
void EspNowBridge::onDestroy(AppHandle /*app*/) {
// Clear liveInstance_ first so any task still running bails out at its next liveInstance_
// check instead of continuing to touch this instance's members.
liveInstance_ = nullptr;
// Wait for any outstanding background task (OTA update, transport-wait) to actually finish -
// the app framework frees this instance shortly after onDestroy() returns, so a task that
// outlives it would dereference freed memory.
while (outstandingTasks_.load() > 0) {
if (taskDoneSemaphore_ != nullptr) {
xSemaphoreTake(taskDoneSemaphore_, pdMS_TO_TICKS(1000));
}
}
if (taskDoneSemaphore_ != nullptr) {
vSemaphoreDelete(taskDoneSemaphore_);
taskDoneSemaphore_ = nullptr;
}
}
void EspNowBridge::refreshCurrentVersion() {
char versionStr[32];
if (getCurrentVersionString(firmwareOps_, firmwareCtx_, versionStr, sizeof(versionStr))) {
lv_label_set_text_fmt(currentVersionLabel_, "Co-processor firmware: %s", versionStr);
} else {
lv_label_set_text(currentVersionLabel_, "Co-processor firmware: unknown (link not up)");
}
}
bool EspNowBridge::isWifiRadioOn() {
if (wifiDevice_ == nullptr) {
return false;
}
WifiRadioState radioState = WIFI_RADIO_STATE_OFF;
if (wifi_get_radio_state(wifiDevice_, &radioState) != ERROR_NONE) {
return false;
}
// ON with any station state (disconnected/pending/connected) is fine - the ESP-NOW bridge
// just needs the radio + esp_hosted transport up, not a completed AP connection.
return radioState == WIFI_RADIO_STATE_ON;
}
void EspNowBridge::refreshWifiPrompt() {
if (isWifiRadioOn()) {
lv_obj_add_flag(enableWifiButton_, LV_OBJ_FLAG_HIDDEN);
setUpdateButtonsDisabled(false);
} else {
lv_obj_clear_flag(enableWifiButton_, LV_OBJ_FLAG_HIDDEN);
setUpdateButtonsDisabled(true);
}
}
void EspNowBridge::setUpdateButtonsDisabled(bool disabled) {
if (disabled) {
lv_obj_add_state(updateButton_, LV_STATE_DISABLED);
lv_obj_add_state(updateBundledButton_, LV_STATE_DISABLED);
} else {
lv_obj_clear_state(updateButton_, LV_STATE_DISABLED);
lv_obj_clear_state(updateBundledButton_, LV_STATE_DISABLED);
}
}
void EspNowBridge::setStatus(const std::string& text) {
lv_label_set_text(statusLabel_, text.c_str());
}
void EspNowBridge::setProgress(int percent) {
lv_bar_set_value(progressBar_, percent, LV_ANIM_OFF);
}
namespace {
struct UiDispatchPayload {
EspNowBridge* instance;
void (*work)(EspNowBridge&, void*);
void* context;
void (*freeContext)(void*);
};
}
void EspNowBridge::dispatchToUi(void (*work)(EspNowBridge&, void*), void* context, void (*freeContext)(void*)) {
auto* payload = new UiDispatchPayload{this, work, context, freeContext};
// lv_async_call() itself is an LVGL operation and must be lock-guarded when called from a
// non-LVGL task (see tt_lvgl_lock()'s doc comment) - the OTA worker task calls dispatchToUi()
// repeatedly during the transfer, and without this lock most of those calls were silently
// racing LVGL's own task and getting lost (only the very last status update, right before
// esp_restart(), happened to land - everything else stayed stuck at "Waiting for
// co-processor link...").
bool locked = tt_lvgl_lock(TT_LVGL_DEFAULT_LOCK_TIME);
if (!locked) {
// Without the lock, lv_async_call() itself would be touching LVGL's internal timer list
// unguarded - and if it happened to still enqueue successfully, the callback below would
// later fire against `payload` after we've already freed it here. Drop the update instead.
if (freeContext != nullptr) {
freeContext(context);
}
delete payload;
return;
}
lv_result_t result = lv_async_call([](void* userData) {
auto* payload = static_cast<UiDispatchPayload*>(userData);
if (EspNowBridge::liveInstance_.load() == payload->instance && payload->instance->isShown_.load()) {
payload->work(*payload->instance, payload->context);
}
if (payload->freeContext != nullptr) {
payload->freeContext(payload->context);
}
delete payload;
}, payload);
tt_lvgl_unlock();
if (result != LV_RESULT_OK) {
if (freeContext != nullptr) {
freeContext(context);
}
delete payload;
}
}
namespace {
void workSetStatus(EspNowBridge& app, void* context) {
app.setStatus(*static_cast<std::string*>(context));
}
void freeString(void* context) { delete static_cast<std::string*>(context); }
void workSetProgress(EspNowBridge& app, void* context) {
app.setProgress(*static_cast<int*>(context));
}
void freeInt(void* context) { delete static_cast<int*>(context); }
} // namespace
void EspNowBridge::performUpdate(const std::string& filePath) {
dispatchToUi([](EspNowBridge& app, void*) {
app.setUpdateButtonsDisabled(true);
app.setProgress(0);
app.setStatus("Waiting for co-processor link...");
}, nullptr, nullptr);
if (firmwareOps_ == nullptr) {
dispatchToUi([](EspNowBridge& app, void*) {
app.setStatus("This WiFi device has no updatable co-processor");
app.setUpdateButtonsDisabled(false);
}, nullptr, nullptr);
return;
}
if (!firmwareOps_->wait_ready(firmwareCtx_, TRANSPORT_WAIT_TIMEOUT_MS)) {
dispatchToUi([](EspNowBridge& app, void*) {
app.setStatus("Co-processor link not available - update cancelled");
app.setUpdateButtonsDisabled(false);
}, nullptr, nullptr);
return;
}
FILE* file = fopen(filePath.c_str(), "rb");
if (file == nullptr) {
dispatchToUi([](EspNowBridge& app, void*) {
app.setStatus("Failed to open selected file");
app.setUpdateButtonsDisabled(false);
}, nullptr, nullptr);
return;
}
fseek(file, 0, SEEK_END);
long fileSizeSigned = ftell(file);
if (fileSizeSigned <= 0) {
fclose(file);
dispatchToUi([](EspNowBridge& app, void*) {
app.setStatus("Failed to determine file size");
app.setUpdateButtonsDisabled(false);
}, nullptr, nullptr);
return;
}
size_t fileSize = static_cast<size_t>(fileSizeSigned);
// Support both a plain app image (starting with the app image header at offset 0) and a
// merged/factory bin (e.g. M5Stack's official ESP-Hosted factory image) - detected by whether
// a valid partition table is found at PARTITION_TABLE_OFFSET.
size_t appOffset = 0;
size_t partitionSize = 0;
bool isMergedBin = findAppPartitionInMergedBin(file, appOffset, partitionSize);
if (isMergedBin && appOffset >= fileSize) {
fclose(file);
dispatchToUi([](EspNowBridge& app, void*) {
app.setStatus("Merged bin's app partition is outside the file - selected file looks truncated");
app.setUpdateButtonsDisabled(false);
}, nullptr, nullptr);
return;
}
char newVersion[32];
std::string parseError;
if (!parseImageHeader(file, appOffset, newVersion, sizeof(newVersion), &parseError)) {
fclose(file);
dispatchToUi(workSetStatus, new std::string(parseError), freeString);
dispatchToUi([](EspNowBridge& app, void*) {
app.setUpdateButtonsDisabled(false);
}, nullptr, nullptr);
return;
}
// Merged bins pad the app partition to its declared size; a plain app image is exactly as
// long as the app itself. Transfer whichever is smaller.
size_t remainingInFile = fileSize - appOffset;
size_t firmwareSize = isMergedBin ? std::min(partitionSize, remainingInFile) : remainingInFile;
std::string versionStr(newVersion);
{
char buf[64];
snprintf(buf, sizeof(buf), "Pushing firmware %s...", versionStr.c_str());
dispatchToUi(workSetStatus, new std::string(buf), freeString);
}
// Held on the app instance (not a local variable) so it outlives this function - see
// heldAutoScanPauseGuard_'s declaration for why. Released when the host actually restarts
// (moot, since esp_restart() doesn't return) or if the update fails early below.
heldAutoScanPauseGuard_.emplace();
FirmwareUpdateRequest updateRequest = {};
updateRequest.image_size = firmwareSize;
FirmwareUpdateHandle* handle = nullptr;
if (firmwareOps_->begin(firmwareCtx_, &updateRequest, &handle) != ERROR_NONE) {
fclose(file);
heldAutoScanPauseGuard_.reset();
dispatchToUi([](EspNowBridge& app, void*) {
app.setStatus("Failed to start OTA on co-processor");
app.setUpdateButtonsDisabled(false);
}, nullptr, nullptr);
return;
}
if (fseek(file, static_cast<long>(appOffset), SEEK_SET) != 0) {
fclose(file);
firmwareOps_->abort(handle);
heldAutoScanPauseGuard_.reset();
dispatchToUi([](EspNowBridge& app, void*) {
app.setStatus("Failed to seek to firmware start");
app.setUpdateButtonsDisabled(false);
}, nullptr, nullptr);
return;
}
uint8_t chunk[CHUNK_SIZE];
size_t sent = 0;
bool writeFailed = false;
int lastReportedPercent = -1;
while (sent < firmwareSize) {
size_t toRead = (firmwareSize - sent > CHUNK_SIZE) ? CHUNK_SIZE : (firmwareSize - sent);
size_t actuallyRead = fread(chunk, 1, toRead, file);
if (actuallyRead != toRead) {
LOG_E(TAG, "Failed to read file at offset %zu", sent);
writeFailed = true;
break;
}
if (firmwareOps_->write(handle, chunk, actuallyRead) != ERROR_NONE) {
LOG_E(TAG, "firmwareOps_->write() failed at offset %zu", sent);
writeFailed = true;
break;
}
// Pace the transfer - esp_hosted's SDIO driver only retries a write twice with no
// backoff before giving up and restarting the host. Back-to-back chunk writes with zero
// gap were observed to saturate the bus enough to trigger a genuine SDIO timeout
// mid-transfer, not just around the post-activate reboot.
vTaskDelay(pdMS_TO_TICKS(5));
sent += actuallyRead;
// Only touch LVGL every couple of percent, not every 1500-byte chunk - frequent
// display-bus activity during the transfer was implicated in SDIO transport crashes
// under sustained OTA write load.
int percent = (int)((sent * 100) / firmwareSize);
if (percent != lastReportedPercent) {
dispatchToUi(workSetProgress, new int(percent), freeInt);
lastReportedPercent = percent;
}
}
fclose(file);
if (writeFailed) {
firmwareOps_->abort(handle);
heldAutoScanPauseGuard_.reset();
dispatchToUi([](EspNowBridge& app, void*) {
app.setStatus("Update failed while transferring firmware");
app.setUpdateButtonsDisabled(false);
}, nullptr, nullptr);
return;
}
if (firmwareOps_->finish(handle) != ERROR_NONE) {
heldAutoScanPauseGuard_.reset();
dispatchToUi([](EspNowBridge& app, void*) {
app.setStatus("Failed to finalize OTA on co-processor");
app.setUpdateButtonsDisabled(false);
}, nullptr, nullptr);
return;
}
// Check the *currently running* (pre-update) slave version - the new image isn't running
// yet - and skip straight to the required host restart for older slaves.
FirmwareInfo runningInfo = {};
bool canActivate = firmwareOps_->get_info(firmwareCtx_, &runningInfo) == ERROR_NONE
&& activateSupported(runningInfo.fw_major, runningInfo.fw_minor);
if (canActivate) {
if (firmwareOps_->activate(firmwareCtx_) != ERROR_NONE) {
heldAutoScanPauseGuard_.reset();
dispatchToUi([](EspNowBridge& app, void*) {
app.setStatus("Failed to activate new firmware - co-processor still running old firmware");
app.setUpdateButtonsDisabled(false);
}, nullptr, nullptr);
return;
}
}
// heldAutoScanPauseGuard_ is deliberately left held (never explicitly released) - the host
// restarts itself immediately below, and there's no safe window to resume normal WiFi
// activity before that.
{
char buf[80];
if (canActivate) {
snprintf(buf, sizeof(buf), "Firmware %s activated - restarting...", versionStr.c_str());
} else {
snprintf(buf, sizeof(buf), "Firmware %s pushed - restarting to apply...", versionStr.c_str());
}
dispatchToUi(workSetStatus, new std::string(buf), freeString);
}
// Give the status message above a moment to actually be seen before the restart cuts the
// display, then restart.
vTaskDelay(pdMS_TO_TICKS(1500));
esp_restart();
}
void EspNowBridge::updateTaskEntry(void* arg) {
auto* self = static_cast<EspNowBridge*>(arg);
self->performUpdate(self->pendingUpdateFilePath_);
self->updateTask_ = nullptr;
if (self->outstandingTasks_.fetch_sub(1) == 1 && self->taskDoneSemaphore_ != nullptr) {
xSemaphoreGive(self->taskDoneSemaphore_);
}
vTaskDelete(nullptr);
}
void EspNowBridge::startUpdateTask(const std::string& filePath) {
if (updateTask_ != nullptr) {
return;
}
pendingUpdateFilePath_ = filePath;
outstandingTasks_.fetch_add(1);
if (xTaskCreate(updateTaskEntry, "espnow_bridge_ota", UPDATE_TASK_STACK_SIZE / sizeof(StackType_t), this, tskIDLE_PRIORITY + 1, &updateTask_) != pdPASS) {
outstandingTasks_.fetch_sub(1);
}
}
void EspNowBridge::onUpdateButtonClicked(lv_event_t* /*event*/) {
auto* self = liveInstance_.load();
if (self == nullptr || !self->isWifiRadioOn()) {
return;
}
self->pickFileLaunchId_ = tt_app_fileselection_start_for_existing_file();
}
// Name of the slave bridge firmware bundled in this app's assets/ folder
// lets users flash the known-good bridge firmware without needing to source/copy a
// .bin onto the SD card themselves. The SD-card picker (onUpdateButtonClicked above) stays
// available too, for factory-image downgrades or custom builds.
static constexpr auto* BUNDLED_FIRMWARE_ASSET_NAME = "espnow_bridge_slave_c6.bin";
void EspNowBridge::onUpdateBundledButtonClicked(lv_event_t* /*event*/) {
auto* self = liveInstance_.load();
if (self == nullptr || !self->isWifiRadioOn()) {
return;
}
char assetPath[256] = {};
size_t assetPathSize = sizeof(assetPath);
tt_app_get_assets_child_path(self->appHandle_, BUNDLED_FIRMWARE_ASSET_NAME, assetPath, &assetPathSize);
if (assetPath[0] == '\0') {
LOG_E(TAG, "Failed to resolve bundled firmware asset path");
return;
}
self->startUpdateTask(assetPath);
}
void EspNowBridge::onEnableWifiButtonClicked(lv_event_t* /*event*/) {
auto* self = liveInstance_.load();
if (self == nullptr || self->wifiDevice_ == nullptr) {
return;
}
device_start(self->wifiDevice_);
// start_device() allocates a fresh driver context (Platforms/platform-esp32's
// esp32_wifi.cpp), which wipes any event callback registered before the device was started -
// re-register now that it's actually running. Also refresh once directly rather than relying
// solely on the next WifiEvent, so the "WiFi on" prompt updates immediately even though the
// co-processor firmware version below isn't available yet.
wifi_add_event_callback(self->wifiDevice_, self, onWifiEvent);
self->refreshWifiPrompt();
self->refreshCurrentVersion();
// The co-processor RPC transport isn't up the instant device_start() returns - it comes up
// asynchronously (~1-2s later) - so firmwareOps_->get_info() above reliably fails right after
// enabling WiFi. Nothing else reliably re-triggers a version refresh once the transport
// actually comes up (WifiEvent only covers radio/station state, not transport readiness), so
// wait for it explicitly on a background task and refresh once it's ready.
if (self->firmwareOps_ != nullptr) {
self->outstandingTasks_.fetch_add(1);
if (xTaskCreate(waitForTransportTaskEntry, "espnow_bridge_wait", 4096 / sizeof(StackType_t), self, tskIDLE_PRIORITY + 1, nullptr) != pdPASS) {
self->outstandingTasks_.fetch_sub(1);
}
}
}
void EspNowBridge::waitForTransportTaskEntry(void* arg) {
auto* self = static_cast<EspNowBridge*>(arg);
constexpr uint32_t WAIT_TIMEOUT_MS = 10000;
// liveInstance_ must be checked before touching any member of self - if onDestroy() already
// ran, `self` may be freed, and dereferencing self->firmwareOps_ first would be a
// use-after-free even just to read the pointer.
if (liveInstance_.load() == self && self->firmwareOps_ != nullptr
&& self->firmwareOps_->wait_ready(self->firmwareCtx_, WAIT_TIMEOUT_MS)
&& liveInstance_.load() == self) {
self->dispatchToUi([](EspNowBridge& app, void*) {
app.refreshCurrentVersion();
}, nullptr, nullptr);
}
if (self->outstandingTasks_.fetch_sub(1) == 1 && self->taskDoneSemaphore_ != nullptr) {
xSemaphoreGive(self->taskDoneSemaphore_);
}
vTaskDelete(nullptr);
}
void EspNowBridge::onWifiEvent(Device* /*device*/, void* callbackContext, WifiEvent /*event*/) {
auto* self = static_cast<EspNowBridge*>(callbackContext);
if (liveInstance_.load() != self) {
return;
}
self->dispatchToUi([](EspNowBridge& app, void*) {
app.refreshWifiPrompt();
app.refreshCurrentVersion();
}, nullptr, nullptr);
}
void EspNowBridge::onShow(AppHandle app, lv_obj_t* parent) {
isShown_ = true;
lv_obj_remove_flag(parent, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_set_flex_flow(parent, LV_FLEX_FLOW_COLUMN);
lv_obj_t* toolbar = tt_lvgl_toolbar_create_for_app(parent, app);
lv_obj_align(toolbar, LV_ALIGN_TOP_MID, 0, 0);
auto* wrapper = lv_obj_create(parent);
lv_obj_set_style_border_width(wrapper, 0, LV_STATE_DEFAULT);
lv_obj_set_flex_flow(wrapper, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_pad_all(wrapper, 8, LV_STATE_DEFAULT);
lv_obj_set_width(wrapper, LV_PCT(100));
lv_obj_set_flex_grow(wrapper, 1);
currentVersionLabel_ = lv_label_create(wrapper);
lv_obj_set_style_pad_bottom(currentVersionLabel_, 12, LV_STATE_DEFAULT);
enableWifiButton_ = lv_button_create(wrapper);
lv_obj_add_event_cb(enableWifiButton_, onEnableWifiButtonClicked, LV_EVENT_CLICKED, nullptr);
auto* enableWifiButtonLabel = lv_label_create(enableWifiButton_);
lv_label_set_text(enableWifiButtonLabel, "Enable WiFi (required for co-processor link)");
lv_obj_set_style_pad_bottom(enableWifiButton_, 12, LV_STATE_DEFAULT);
updateBundledButton_ = lv_button_create(wrapper);
lv_obj_add_event_cb(updateBundledButton_, onUpdateBundledButtonClicked, LV_EVENT_CLICKED, nullptr);
auto* updateBundledButtonLabel = lv_label_create(updateBundledButton_);
lv_label_set_text(updateBundledButtonLabel, "Update to bundled firmware");
lv_obj_set_style_pad_bottom(updateBundledButton_, 12, LV_STATE_DEFAULT);
updateButton_ = lv_button_create(wrapper);
lv_obj_add_event_cb(updateButton_, onUpdateButtonClicked, LV_EVENT_CLICKED, nullptr);
auto* updateButtonLabel = lv_label_create(updateButton_);
lv_label_set_text(updateButtonLabel, "Update from SD card...");
lv_obj_set_style_pad_bottom(updateButton_, 12, LV_STATE_DEFAULT);
progressBar_ = lv_bar_create(wrapper);
lv_obj_set_size(progressBar_, LV_PCT(100), LV_PCT(6));
lv_bar_set_range(progressBar_, 0, 100);
lv_bar_set_value(progressBar_, 0, LV_ANIM_OFF);
statusLabel_ = lv_label_create(wrapper);
lv_label_set_text(statusLabel_, "Ready");
wifiDevice_ = wifi_find_first_registered_device();
if (wifiDevice_ != nullptr) {
wifi_add_event_callback(wifiDevice_, this, onWifiEvent);
if (wifi_get_firmware_ops(wifiDevice_, &firmwareOps_, &firmwareCtx_) != ERROR_NONE) {
firmwareOps_ = nullptr;
firmwareCtx_ = nullptr;
}
}
refreshCurrentVersion();
refreshWifiPrompt();
// If an SD-card file was picked before this onShow() ran (FileSelection tears down and
// rebuilds this app's whole widget tree), perform the update now that widgets are valid
// again. The bundled-firmware button doesn't go through this path - it calls
// startUpdateTask() directly since there's no separate app launch/result round trip involved.
if (!pendingUpdateFilePath_.empty()) {
std::string path = std::move(pendingUpdateFilePath_);
pendingUpdateFilePath_.clear();
startUpdateTask(path);
}
}
void EspNowBridge::onHide(AppHandle /*app*/) {
isShown_ = false;
if (wifiDevice_ != nullptr) {
wifi_remove_event_callback(wifiDevice_, onWifiEvent);
wifiDevice_ = nullptr;
}
}
void EspNowBridge::onResult(AppHandle /*app*/, void* /*data*/, AppLaunchId launchId, AppResult result, BundleHandle resultData) {
if (launchId != pickFileLaunchId_) {
return;
}
pickFileLaunchId_ = 0;
if (result == APP_RESULT_OK && resultData != nullptr) {
char pathBuf[256] = {};
if (tt_app_fileselection_get_result_path(resultData, pathBuf, sizeof(pathBuf))) {
pendingUpdateFilePath_ = pathBuf;
}
}
}
@@ -0,0 +1,108 @@
#pragma once
#include <TactilityCpp/App.h>
#include <atomic>
#include <optional>
#include <string>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <lvgl.h>
#include <tactility/drivers/wifi.h>
/** RAII guard: pauses WifiService's background auto-connect scan for the guard's lifetime. See
* tactility/wifi_auto_scan.h - belt-and-suspenders measure, not sufficient on its own (see the
* REBOOT comment in EspNowBridge.cpp). */
class AutoScanPauseGuard {
public:
AutoScanPauseGuard();
~AutoScanPauseGuard();
AutoScanPauseGuard(const AutoScanPauseGuard&) = delete;
AutoScanPauseGuard& operator=(const AutoScanPauseGuard&) = delete;
};
class EspNowBridge final : public App {
public:
EspNowBridge() = default;
EspNowBridge(const EspNowBridge&) = delete;
EspNowBridge& operator=(const EspNowBridge&) = delete;
void onCreate(AppHandle app) override;
void onDestroy(AppHandle app) override;
void onShow(AppHandle app, lv_obj_t* parent) override;
void onHide(AppHandle app) override;
void onResult(AppHandle app, void* data, AppLaunchId launchId, AppResult result, BundleHandle resultData) override;
// Public so the free-function dispatchToUi() work callbacks in EspNowBridge.cpp (which run
// outside any member-function's lexical scope, unlike the inline lambdas in performUpdate())
// can call them.
void setStatus(const std::string& text);
void setProgress(int percent);
private:
AppHandle appHandle_ = nullptr;
AppLaunchId pickFileLaunchId_ = 0;
std::string pendingUpdateFilePath_;
Device* wifiDevice_ = nullptr;
// Resolved once in onShow() via wifi_get_firmware_ops() - null on a WiFi device with no
// updatable co-processor (e.g. a native, non-hosted chip). All OTA/version-query calls go
// through this generic interface, not any esp_hosted-specific API directly.
const FirmwareOps* firmwareOps_ = nullptr;
void* firmwareCtx_ = nullptr;
// Set once in onShow(), false once onHide() tears the widget tree down - checked (via
// dispatchToUi(), below) before touching any lv_obj_t*, since the OTA worker task and the
// WiFi-event callback can both outlive a hide/app-switch.
std::atomic<bool> isShown_{false};
// Only one EspNowBridge instance is ever live at a time (app loader owns a single instance
// per running app), so a single static "is this instance still current" pointer, guarded by
// an atomic, substitutes for the internal app's shared_ptr-based lifetime guard - the OTA
// worker task and dispatchToUi()'s lv_async_call closures check liveInstance_ == this before
// touching any member, instead of holding a shared_ptr to keep `this` alive.
static std::atomic<EspNowBridge*> liveInstance_;
TaskHandle_t updateTask_ = nullptr;
// Number of background tasks (updateTaskEntry, waitForTransportTaskEntry) currently running
// against this instance's members. onDestroy() must wait for this to hit 0 before returning -
// the app framework frees this instance shortly after onDestroy() returns (see Loader.cpp),
// so any task still touching `this` past that point is a use-after-free.
std::atomic<int> outstandingTasks_{0};
SemaphoreHandle_t taskDoneSemaphore_ = nullptr;
// Outlives performUpdate() deliberately, so auto-scan stays paused across the async gap
// between performUpdate() returning and the automatic restart - see performUpdate().
std::optional<AutoScanPauseGuard> heldAutoScanPauseGuard_;
lv_obj_t* currentVersionLabel_ = nullptr;
lv_obj_t* statusLabel_ = nullptr;
lv_obj_t* progressBar_ = nullptr;
lv_obj_t* updateButton_ = nullptr;
lv_obj_t* updateBundledButton_ = nullptr;
lv_obj_t* enableWifiButton_ = nullptr;
void refreshCurrentVersion();
bool isWifiRadioOn();
void refreshWifiPrompt();
/** Enables/disables both update-trigger buttons together - only one performUpdate() can run
* at a time (see updateTask_), regardless of which button started it. */
void setUpdateButtonsDisabled(bool disabled);
/** Marshal a UI-touching closure onto the LVGL task. Only ever invoked if liveInstance_ is
* still this instance (checked at dispatch time and again right before running, on the LVGL
* task) and isShown_ is true (this app's widget tree exists). */
void dispatchToUi(void (*work)(EspNowBridge&, void*), void* context, void (*freeContext)(void*));
void performUpdate(const std::string& filePath);
void startUpdateTask(const std::string& filePath);
static void updateTaskEntry(void* arg);
static void onUpdateButtonClicked(lv_event_t* event);
static void onUpdateBundledButtonClicked(lv_event_t* event);
static void onEnableWifiButtonClicked(lv_event_t* event);
static void onWifiEvent(Device* device, void* callbackContext, WifiEvent event);
static void waitForTransportTaskEntry(void* arg);
};
+11
View File
@@ -0,0 +1,11 @@
#include "EspNowBridge.h"
#include <TactilityCpp/App.h>
extern "C" {
int main(int argc, char* argv[]) {
registerApp<EspNowBridge>();
return 0;
}
}
+8
View File
@@ -0,0 +1,8 @@
manifest.version=0.2
target.sdk=0.8.0-dev
target.platforms=esp32p4
app.id=one.tactility.espnowbridge
app.version.name=0.1.0
app.version.code=1
app.name=ESP-NOW Bridge
app.description=Companion app for updating P4 device C6 co-processor firmware to enable ESP-NOW bridge support.
+7 -10
View File
@@ -1,10 +1,7 @@
[manifest] manifest.version=0.2
version=0.1 target.sdk=0.8.0-dev
[target] target.platforms=esp32,esp32s3,esp32c6,esp32p4
sdk=0.7.0-dev app.id=one.tactility.gpio
platforms=esp32,esp32s3,esp32c6,esp32p4 app.version.name=0.7.0
[app] app.version.code=7
id=one.tactility.gpio app.name=GPIO
versionName=0.4.0
versionCode=4
name=GPIO
+16
View File
@@ -0,0 +1,16 @@
cmake_minimum_required(VERSION 3.20)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
if (DEFINED ENV{TACTILITY_SDK_PATH})
set(TACTILITY_SDK_PATH $ENV{TACTILITY_SDK_PATH})
else()
set(TACTILITY_SDK_PATH "../../release/TactilitySDK")
message(WARNING "⚠️ TACTILITY_SDK_PATH environment variable is not set, defaulting to ${TACTILITY_SDK_PATH}")
endif()
include("${TACTILITY_SDK_PATH}/TactilitySDK.cmake")
set(EXTRA_COMPONENT_DIRS ${TACTILITY_SDK_PATH})
project(GameBoy)
tactility_project(GameBoy)
+96
View File
@@ -0,0 +1,96 @@
# GameBoy Emulator (Tactility Prototype, No Audio)
DMG Game Boy emulator for Tactility side-loaded apps, using **Peanut-GB** (MIT) as CPU/LCD core.
## Status
- Prototype v0.1.0-dev – compiling draft focused on architecture, not yet production-hardened.
- **No audio** (ENABLE_SOUND 0). Audio path stubbed for future MiniGB APU or i2s-driven implementation.
- Supports MBC1/MBC2/MBC3/MBC5 via Peanut-GB.
- ROM loader from SD card.
- Save RAM persistence via `.sav` file next to ROM.
- LVGL framebuffer: native 160x144 RGB565, integer-scaled if display large enough, centered on black background.
- Input: on-screen D-pad + A/B + Start/Select + hardware keyboard arrows + LVGL key events (z= A, x= B).
- Timer-driven at ~16ms (~60Hz) calling `gb_run_frame()`.
## ROM Location
- Scanned directory: `/sdcard/roms/gb/` for `*.gb`, `*.gbc`, `*.bin` (up to 64 entries).
- Default quick-load: `/sdcard/roms/gb/default.gb` – if present on app show, autoloads and jumps directly to emulation.
- Place your legally dumped ROMs there; no ROMs are bundled.
## Save RAM Path Design (stubbed + implemented minimal)
- Save file = ROM path with extension replaced by `.sav` (e.g. `/sdcard/roms/gb/tetris.gb` -> `/sdcard/roms/gb/tetris.sav`).
- Loaded on ROM load, saved on:
- switching back to menu
- app hide
- error recovery path
- Size queried via `gb_get_save_size_s()` / `gb_get_save_size()`.
- Future improvement: also mirror to app user-data dir (`tt_app_get_user_data_child_path`) if SD is read-only.
## Memory Considerations (ESP32-S3 / PSRAM)
- Large buffers allocated via `heap_caps_malloc(..., MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)` with fallback to internal.
- ROM buffer: up to 2MB (MBC5 max-ish) – PSRAM preferred.
- Cart RAM: variable, often 8KB-32KB, PSRAM.
- Framebuffer: 160*144*2 = 46,080 bytes (~45KB) native RGB565. PSRAM preferred. No double buffering needed (line callback writes directly).
- No huge heap allocations.
- Emulator context `struct gb_s` is static inside AppCtx (~few KB).
## Controls / Input Mapping
| GB | On-screen | Keyboard | Remarks |
|----|-----------|----------|---------|
| D-pad | 4 arrow buttons | LV_KEY_ arrows | press/release tracked |
| A | A button (right cluster) | z | |
| B | B button (right cluster) | x | |
| Start | Sta | Enter / Space | |
| Select | Sel | Esc / Backspace | |
| Touch | Quadrants not yet separated – buttons cover |
Future: touch quadrants mapping via `pointToQuadrant` like GameKitInput.
## LCD Rendering
- Peanut-GB calls `lcd_draw_line(gb, pixels[160], line)` per scanline.
- `pixels` low 2 bits = shade 0-3.
- Mapped to olive/gray palette RGB565 (editable).
- Canvas buffer is the framebuffer itself.
- Scale: if display resolution >= 320x432 => 2x, >=480x576 => 3x via LVGL transform scale (keeps native buffer).
## No-Audio Limitation
- `ENABLE_SOUND 0` – audio callbacks not compiled.
- To add audio:
1. Vendor MiniGB APU (`minigb_apu`) or similar.
2. Implement `audio_read` / `audio_write` forwarding to APU.
3. Define ENABLE_SOUND 1, include APU, create audio task similar to BookPlayer (i2s_controller).
4. Feed APU samples in timer / separate task.
## Build
Same as other Tactility apps:
```
. $IDF_PATH/export.sh
export TACTILITY_SDK_PATH=...
python3 tactility.py Apps/GameBoy build esp32s3 --local-sdk
```
## Licensing
- App code: GPLv3 (same as Tactility Apps).
- Peanut-GB vendored lib: MIT (Copyright (c) 2018-2023 Mahyar Koshkouei). License preserved in `Libraries/PeanutGB/peanut_gb.h`.
## Next Steps
- [ ] Improve input: add touch quadrant → D-pad, repeat timers for held buttons.
- [ ] Add pause/resume UI, FPS display.
- [ ] Add palette selector (auto_assign_palette logic from peanut_sdl).
- [ ] Add file picker dialog (`tt_app_selectiondialog_start`) improvement + recursive folder browsing.
- [ ] Audio: vendoring `minigb_apu` and creating I2S task.
- [ ] Save state beyond cart RAM (full emu snapshot).
- [ ] RTC persistence for MBC3 RTC games.
- [ ] Error dialog via `tt_app_alertdialog_start`.
- [ ] Validate with Cppcheck / clang-format and ESP-IDF build.
+7
View File
@@ -0,0 +1,7 @@
file(GLOB_RECURSE SOURCE_FILES Source/*.c)
idf_component_register(
SRCS ${SOURCE_FILES}
INCLUDE_DIRS Source ../../../Libraries/PeanutGB
REQUIRES TactilitySDK
)
+679
View File
@@ -0,0 +1,679 @@
/**
* @file main.c
* @brief GameBoy DMG Emulator for Tactility (Peanut-GB prototype, no audio)
*
* MIT licensed Peanut-GB core vendored in Libraries/PeanutGB/peanut_gb.h
* See app README for notes.
*/
#include <tt_app.h>
#include <tt_lvgl.h>
#include <tt_lvgl_toolbar.h>
#include <tt_app_alertdialog.h>
#include <tt_lvgl_keyboard.h>
#include <lvgl.h>
/* lv_image_cache_drop is not in public LVGL headers but exported by Tactility firmware */
void lv_image_cache_drop(const void * src);
#include <esp_log.h>
/* Board firmware 0.8.0-dev/IDF 5.3.2 does not export esp_log for side-loaded ELFs. */
#undef ESP_LOGI
#undef ESP_LOGW
#undef ESP_LOGE
#define ESP_LOGI(tag, fmt, ...) do { (void)(tag); } while (0)
#define ESP_LOGW(tag, fmt, ...) do { (void)(tag); } while (0)
#define ESP_LOGE(tag, fmt, ...) do { (void)(tag); } while (0)
#include <esp_heap_caps.h>
#include <esp_timer.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#define ENABLE_SOUND 0
#define ENABLE_LCD 1
#include "peanut_gb.h"
#define TAG "GameBoy"
#define DEFAULT_ROM_PATH "/data/roms/gb/default.gb"
#define ROMS_DIR "/data/roms/gb"
#define MAX_ROMS 64
#define MAX_PATH 512
#define MAX_ROM_SIZE (2 * 1024 * 1024)
#define FRAME_W 160
#define FRAME_H 144
#define TICK_MS 16
/* RGB565 direct – no bitfield endian ambiguity */
static const uint16_t GB_PALETTE[4] = {
0xFFFF, // white
0x8C51, // light gray ~ 0b10001 100010 10001 but pre-tuned
0x4A49, // dark gray
0x0000 // black
};
typedef enum { APP_MODE_BROWSER, APP_MODE_EMU } AppMode;
typedef struct {
char filename[MAX_PATH];
char fullpath[MAX_PATH];
} RomEntry;
typedef struct {
struct gb_s gb;
uint8_t* rom_data;
size_t rom_size;
uint8_t* cart_ram;
size_t cart_ram_size;
char rom_path[MAX_PATH];
char rom_title[32];
uint8_t joypad_state;
uint16_t* fb_native; /* RGB565 tightly packed 160*144, raw u16 avoids lv_color16_t bitfield */
lv_draw_buf_t* fb_draw_buf; /* draw_buf that canvas src points to – owned by us so we can invalidate cache */
lv_obj_t* canvas;
lv_obj_t* root_wrapper;
lv_obj_t* browser_wrapper;
lv_obj_t* emu_wrapper;
lv_obj_t* toolbar;
lv_obj_t* status_label;
lv_obj_t* rom_list;
lv_obj_t* controls_cont;
lv_timer_t* emu_timer;
RomEntry roms[MAX_ROMS];
int rom_count;
int selected_rom_idx;
lv_obj_t* btn_up;
lv_obj_t* btn_down;
lv_obj_t* btn_left;
lv_obj_t* btn_right;
lv_obj_t* btn_a;
lv_obj_t* btn_b;
lv_obj_t* btn_start;
lv_obj_t* btn_select;
AppHandle app_handle;
AppMode mode;
bool emu_running;
bool framebuffer_allocated;
bool rom_loaded;
uint32_t fps_frames;
int64_t fps_last_us;
uint32_t lines_drawn; /* debug: should be 144 per frame */
} AppCtx;
typedef struct {
AppCtx* ctx;
uint8_t joypad_bit;
} BtnUserData;
/* PSRAM helpers */
static void* alloc_psram(size_t size) {
void* p = heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
if (!p) p = heap_caps_malloc(size, MALLOC_CAP_8BIT);
if (!p) p = malloc(size);
return p;
}
/* Peanut-GB callbacks */
static uint8_t gb_rom_read(struct gb_s* gb, const uint_fast32_t addr) {
AppCtx* ctx = (AppCtx*)gb->direct.priv;
if (!ctx || !ctx->rom_data) return 0xFF;
if (addr < ctx->rom_size) return ctx->rom_data[addr];
return 0xFF;
}
static uint8_t gb_cart_ram_read(struct gb_s* gb, const uint_fast32_t addr) {
AppCtx* ctx = (AppCtx*)gb->direct.priv;
if (!ctx || !ctx->cart_ram) return 0xFF;
if (addr < ctx->cart_ram_size) return ctx->cart_ram[addr];
return 0xFF;
}
static void gb_cart_ram_write(struct gb_s* gb, const uint_fast32_t addr, const uint8_t val) {
AppCtx* ctx = (AppCtx*)gb->direct.priv;
if (!ctx || !ctx->cart_ram) return;
if (addr < ctx->cart_ram_size) ctx->cart_ram[addr] = val;
}
static void gb_error_handler(struct gb_s* gb, const enum gb_error_e err, const uint16_t addr) {
const char* err_str = "UNKNOWN";
switch (err) {
case GB_INVALID_OPCODE: err_str = "INVALID OPCODE"; break;
case GB_INVALID_READ: err_str = "INVALID READ"; break;
case GB_INVALID_WRITE: err_str = "INVALID WRITE"; break;
default: break;
}
ESP_LOGE(TAG, "GB error %s (%d) @ %04X", err_str, err, addr);
AppCtx* ctx = (AppCtx*)gb->direct.priv;
if (ctx && ctx->cart_ram_size) {
char sp[MAX_PATH];
strncpy(sp, ctx->rom_path, MAX_PATH-1); sp[MAX_PATH-1]='\0';
char* dot=strrchr(sp,'.'); char* sl=strrchr(sp,'/');
if (dot && (!sl || dot>sl)) snprintf(dot, MAX_PATH-(dot-sp), ".sav"); else strncat(sp,".sav",MAX_PATH-strlen(sp)-1);
FILE* f=fopen(sp,"wb"); if(f){fwrite(ctx->cart_ram,1,ctx->cart_ram_size,f); fclose(f);}
}
}
static void lcd_draw_line(struct gb_s* gb, const uint8_t* pixels, const uint_fast8_t line) {
AppCtx* ctx = (AppCtx*)gb->direct.priv;
if (!ctx || !ctx->fb_native) return;
if (line >= FRAME_H) return;
uint16_t* dst = &ctx->fb_native[line * FRAME_W];
for (int x=0;x<FRAME_W;x++) {
uint8_t shade = pixels[x] & 0x03;
dst[x] = GB_PALETTE[shade];
}
ctx->lines_drawn++;
}
/* Save path */
static void get_save_path(const char* rom_path, char* out, size_t out_len) {
if (!rom_path || !out) return;
strncpy(out, rom_path, out_len-1); out[out_len-1]='\0';
char* dot=strrchr(out,'.'); char* sl=strrchr(out,'/');
if (dot && (!sl || dot>sl)) { snprintf(dot, out_len-(dot-out), ".sav"); }
else { strncat(out,".sav",out_len-strlen(out)-1); }
}
static void load_cart_ram(AppCtx* ctx) {
if (!ctx || !ctx->rom_path[0]) return;
char save_path[MAX_PATH];
get_save_path(ctx->rom_path, save_path, sizeof(save_path));
size_t save_sz=0;
if (gb_get_save_size_s(&ctx->gb, &save_sz)!=0) save_sz=gb_get_save_size(&ctx->gb);
if (save_sz==0) { ESP_LOGI(TAG,"No save RAM"); return; }
if (ctx->cart_ram) { heap_caps_free(ctx->cart_ram); ctx->cart_ram=NULL; }
ctx->cart_ram_size=save_sz;
ctx->cart_ram=alloc_psram(save_sz);
if (!ctx->cart_ram){ ESP_LOGE(TAG,"cart RAM alloc fail %zu",save_sz); ctx->cart_ram_size=0; return; }
memset(ctx->cart_ram,0,save_sz);
FILE* f=fopen(save_path,"rb");
if (!f){ ESP_LOGI(TAG,"No save %s",save_path); return; }
size_t r=fread(ctx->cart_ram,1,save_sz,f); fclose(f);
ESP_LOGI(TAG,"Loaded save %s %zu/%zu",save_path,r,save_sz);
}
static void save_cart_ram(AppCtx* ctx) {
if (!ctx || !ctx->cart_ram || ctx->cart_ram_size==0) return;
if (!ctx->rom_path[0]) return;
char save_path[MAX_PATH];
get_save_path(ctx->rom_path, save_path, sizeof(save_path));
FILE* f=fopen(save_path,"wb");
if (!f){ ESP_LOGE(TAG,"Save open fail %s",save_path); return; }
size_t w=fwrite(ctx->cart_ram,1,ctx->cart_ram_size,f); fclose(f);
ESP_LOGI(TAG,"Saved RAM %s %zu",save_path,w);
}
/* ROM loading */
static bool load_rom_file(AppCtx* ctx, const char* path) {
if (!ctx || !path) return false;
ESP_LOGI(TAG,"Loading ROM %s",path);
FILE* f=fopen(path,"rb");
if (!f){ ESP_LOGE(TAG,"Open fail %s",path); return false; }
fseek(f,0,SEEK_END); long sz=ftell(f); fseek(f,0,SEEK_SET);
if (sz<=0 || sz>MAX_ROM_SIZE){ ESP_LOGE(TAG,"Bad size %ld %s",sz,path); fclose(f); return false; }
uint8_t* buf=alloc_psram((size_t)sz);
if (!buf){ ESP_LOGE(TAG,"Alloc fail %ld",sz); fclose(f); return false; }
size_t read=fread(buf,1,(size_t)sz,f); fclose(f);
if (read!=(size_t)sz){ ESP_LOGE(TAG,"Short read %zu vs %ld",read,sz); heap_caps_free(buf); return false; }
if (ctx->rom_data) { if (ctx->cart_ram) save_cart_ram(ctx); heap_caps_free(ctx->rom_data); }
if (ctx->cart_ram){ heap_caps_free(ctx->cart_ram); ctx->cart_ram=NULL; ctx->cart_ram_size=0; }
ctx->rom_data=buf; ctx->rom_size=(size_t)sz;
strncpy(ctx->rom_path,path,sizeof(ctx->rom_path)-1); ctx->rom_path[sizeof(ctx->rom_path)-1]='\0';
memset(&ctx->gb,0,sizeof(ctx->gb));
ctx->joypad_state=0xFF;
enum gb_init_error_e err=gb_init(&ctx->gb, gb_rom_read, gb_cart_ram_read, gb_cart_ram_write, gb_error_handler, ctx);
if (err!=GB_INIT_NO_ERROR){ ESP_LOGE(TAG,"gb_init %d",err); heap_caps_free(ctx->rom_data); ctx->rom_data=NULL; ctx->rom_size=0; return false; }
gb_init_lcd(&ctx->gb, lcd_draw_line);
load_cart_ram(ctx);
gb_reset(&ctx->gb);
char title[32]={0}; gb_get_rom_name(&ctx->gb, title); strncpy(ctx->rom_title,title,sizeof(ctx->rom_title)-1);
ESP_LOGI(TAG,"ROM OK title='%s' size=%zu save=%zu",ctx->rom_title,ctx->rom_size,ctx->cart_ram_size);
ctx->rom_loaded=true;
return true;
}
static void scan_rom_dir(AppCtx* ctx) {
ctx->rom_count=0;
DIR* dir=opendir(ROMS_DIR);
if (!dir){ ESP_LOGW(TAG,"ROMS dir missing %s",ROMS_DIR); return; }
struct dirent* ent;
while ((ent=readdir(dir))!=NULL && ctx->rom_count<MAX_ROMS){
if (ent->d_name[0]=='.') continue;
size_t len=strlen(ent->d_name);
if (len<3) continue;
bool is_gb = (strcasecmp(ent->d_name+len-3,".gb")==0) || (len>=4 && (strcasecmp(ent->d_name+len-4,".gbc")==0 || strcasecmp(ent->d_name+len-4,".bin")==0));
if (!is_gb) continue;
RomEntry* e=&ctx->roms[ctx->rom_count++];
strncpy(e->filename, ent->d_name, sizeof(e->filename)-1); e->filename[sizeof(e->filename)-1]='\0';
snprintf(e->fullpath, sizeof(e->fullpath), "%s/%s", ROMS_DIR, ent->d_name);
}
closedir(dir);
ESP_LOGI(TAG,"Found %d ROMs",ctx->rom_count);
}
/* Emu timer – THIS IS WHERE "FPS but no image" WAS: missing cache drop */
static void emu_timer_cb(lv_timer_t* timer) {
AppCtx* ctx=(AppCtx*)lv_timer_get_user_data(timer);
if (!ctx || !ctx->emu_running || !ctx->rom_loaded || !ctx->canvas) return;
ctx->lines_drawn = 0;
ctx->gb.direct.joypad = ctx->joypad_state;
gb_run_frame(&ctx->gb);
/* Critical fix: raw buffer mutated, LVGL image cache is stale.
Without this, canvas shows whatever was first uploaded (gray/black) and FPS label keeps updating,
giving "FPS but no game". */
if (ctx->fb_draw_buf) {
/* Invalidate both D-Cache (PSRAM) and LVGL image cache */
lv_draw_buf_invalidate_cache(ctx->fb_draw_buf, NULL);
lv_image_cache_drop(ctx->fb_draw_buf);
/* Also invalidate area via the canvas src buf if different object */
if (ctx->canvas) {
lv_draw_buf_t* c_db = lv_canvas_get_draw_buf(ctx->canvas);
if (c_db && c_db != ctx->fb_draw_buf) {
lv_draw_buf_invalidate_cache(c_db, NULL);
lv_image_cache_drop(c_db);
}
}
}
lv_obj_invalidate(ctx->canvas);
ctx->fps_frames++;
int64_t now = esp_timer_get_time();
if (ctx->fps_last_us == 0) ctx->fps_last_us = now;
int64_t elapsed = now - ctx->fps_last_us;
if (elapsed >= 1000000) {
uint32_t fps = (uint32_t)((ctx->fps_frames * 1000000ULL) / (uint64_t)elapsed);
if (ctx->status_label) {
lv_label_set_text_fmt(ctx->status_label, "GB: %s FPS:%lu L:%lu", ctx->rom_title[0] ? ctx->rom_title : "GameBoy", (unsigned long)fps, (unsigned long)ctx->lines_drawn);
}
printf("GAMEBOY_FPS %lu LINES %lu\n", (unsigned long)fps, (unsigned long)ctx->lines_drawn);
ctx->fps_frames = 0;
ctx->fps_last_us = now;
}
}
/* Input helpers */
static void set_joypad_bit(AppCtx* ctx, uint8_t bit, bool pressed) {
if (!ctx) return;
if (pressed) ctx->joypad_state &= (uint8_t)~bit;
else ctx->joypad_state |= bit;
}
static void input_down_cb(lv_event_t* e){
BtnUserData* ud=(BtnUserData*)lv_event_get_user_data(e);
if (!ud) return;
set_joypad_bit(ud->ctx, ud->joypad_bit, true);
}
static void input_up_cb(lv_event_t* e){
BtnUserData* ud=(BtnUserData*)lv_event_get_user_data(e);
if (!ud) return;
set_joypad_bit(ud->ctx, ud->joypad_bit, false);
}
static void key_press_cb(lv_event_t* e){
AppCtx* ctx=(AppCtx*)lv_event_get_user_data(e);
uint32_t key=lv_event_get_key(e);
switch(key){
case LV_KEY_UP: set_joypad_bit(ctx, JOYPAD_UP, true); break;
case LV_KEY_DOWN: set_joypad_bit(ctx, JOYPAD_DOWN, true); break;
case LV_KEY_LEFT: set_joypad_bit(ctx, JOYPAD_LEFT, true); break;
case LV_KEY_RIGHT: set_joypad_bit(ctx, JOYPAD_RIGHT, true); break;
case LV_KEY_ENTER: set_joypad_bit(ctx, JOYPAD_START, true); break;
case LV_KEY_ESC: set_joypad_bit(ctx, JOYPAD_SELECT, true); break;
default: {
if (key== (uint32_t)'z' || key== (uint32_t)'Z') set_joypad_bit(ctx, JOYPAD_A, true);
else if (key== (uint32_t)'x' || key== (uint32_t)'X') set_joypad_bit(ctx, JOYPAD_B, true);
break;
}
}
}
/* Forward declarations for UI switching */
static void build_browser_ui(AppCtx* ctx, lv_obj_t* parent);
static void build_emu_ui(AppCtx* ctx, lv_obj_t* parent);
static void switch_to_browser(AppCtx* ctx);
static void switch_to_emu(AppCtx* ctx);
/* ROM selection events */
static void rom_button_event(lv_event_t* e){
AppCtx* ctx=(AppCtx*)lv_event_get_user_data(e);
lv_obj_t* btn=lv_event_get_target_obj(e);
int* pIdx=(int*)lv_obj_get_user_data(btn);
if (!pIdx) return;
ctx->selected_rom_idx=*pIdx;
if (ctx->selected_rom_idx<0 || ctx->selected_rom_idx>=ctx->rom_count) return;
const char* path=ctx->roms[ctx->selected_rom_idx].fullpath;
if (load_rom_file(ctx, path)){
switch_to_emu(ctx);
} else {
if (ctx->status_label) lv_label_set_text_fmt(ctx->status_label, "Failed: %s", ctx->roms[ctx->selected_rom_idx].filename);
}
}
static void default_rom_event(lv_event_t* e){
AppCtx* ctx=(AppCtx*)lv_event_get_user_data(e);
if (load_rom_file(ctx, DEFAULT_ROM_PATH)){
switch_to_emu(ctx);
} else {
if (ctx->status_label) lv_label_set_text(ctx->status_label, "default.gb not found in /data/roms/gb/");
}
}
static void back_to_menu_event(lv_event_t* e){
AppCtx* ctx=(AppCtx*)lv_event_get_user_data(e);
switch_to_browser(ctx);
}
/* UI builders */
static void build_browser_ui(AppCtx* ctx, lv_obj_t* parent){
lv_obj_clean(parent);
ctx->rom_list=NULL;
lv_obj_set_flex_flow(parent, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_pad_all(parent, 4, 0);
lv_obj_set_style_bg_color(parent, lv_color_black(), 0);
lv_obj_t* info=lv_label_create(parent);
lv_label_set_text_fmt(info, "GameBoy (no audio) - Peanut-GB\nPlace ROMs in %s\nDefault: %s\nFound %d ROMs", ROMS_DIR, DEFAULT_ROM_PATH, ctx->rom_count);
lv_label_set_long_mode(info, LV_LABEL_LONG_WRAP);
lv_obj_set_width(info, LV_PCT(100));
lv_obj_set_style_text_color(info, lv_color_white(), 0);
ctx->status_label=lv_label_create(parent);
lv_label_set_text(ctx->status_label, "Select a ROM to start");
lv_obj_set_style_text_color(ctx->status_label, lv_palette_main(LV_PALETTE_ORANGE), 0);
lv_obj_t* list=lv_list_create(parent);
lv_obj_set_width(list, LV_PCT(100));
lv_obj_set_flex_grow(list, 1);
ctx->rom_list=list;
if (ctx->rom_count==0){
lv_obj_t* lbl=lv_label_create(parent);
lv_label_set_text(lbl, "No ROMs found in /data/roms/gb\nPut .gb files there.");
lv_obj_set_style_text_color(lbl, lv_color_white(), 0);
} else {
for (int i=0;i<ctx->rom_count;i++){
lv_obj_t* btn=lv_list_add_btn(list, LV_SYMBOL_FILE, ctx->roms[i].filename);
int* idx=(int*)malloc(sizeof(int)); *idx=i;
lv_obj_set_user_data(btn, idx);
lv_obj_add_event_cb(btn, rom_button_event, LV_EVENT_CLICKED, ctx);
}
}
lv_obj_t* default_btn=lv_btn_create(parent);
lv_obj_set_width(default_btn, LV_PCT(100));
lv_obj_t* dlbl=lv_label_create(default_btn);
lv_label_set_text(dlbl, "Try default.gb");
lv_obj_center(dlbl);
lv_obj_add_event_cb(default_btn, default_rom_event, LV_EVENT_CLICKED, ctx);
}
static void build_emu_ui(AppCtx* ctx, lv_obj_t* parent){
lv_obj_clean(parent);
lv_obj_set_style_bg_color(parent, lv_color_black(), 0);
lv_obj_set_flex_flow(parent, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_pad_all(parent, 0, 0);
lv_obj_set_style_pad_row(parent, 0, 0);
lv_obj_remove_flag(parent, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_t* info_bar=lv_obj_create(parent);
lv_obj_set_width(info_bar, LV_PCT(100));
lv_obj_set_height(info_bar, LV_SIZE_CONTENT);
lv_obj_set_style_pad_all(info_bar, 2, 0);
lv_obj_set_style_border_width(info_bar, 0, 0);
lv_obj_set_flex_flow(info_bar, LV_FLEX_FLOW_ROW);
lv_obj_set_style_bg_color(info_bar, lv_color_hex(0x222222), 0);
lv_obj_t* title_lbl=lv_label_create(info_bar);
ctx->status_label = title_lbl;
lv_label_set_text_fmt(title_lbl, "GB: %s FPS:--", ctx->rom_title[0]?ctx->rom_title:"GameBoy");
lv_obj_set_style_text_color(title_lbl, lv_color_white(), 0);
lv_obj_t* spacer=lv_obj_create(info_bar);
lv_obj_set_style_bg_opa(spacer, LV_OPA_TRANSP,0);
lv_obj_set_style_border_width(spacer,0,0);
lv_obj_set_flex_grow(spacer,1);
lv_obj_t* back_btn=lv_btn_create(info_bar);
lv_obj_set_size(back_btn, 60, 28);
lv_obj_t* bl=lv_label_create(back_btn); lv_label_set_text(bl,"Menu"); lv_obj_center(bl);
lv_obj_add_event_cb(back_btn, back_to_menu_event, LV_EVENT_CLICKED, ctx);
lv_obj_t* canvas_cont=lv_obj_create(parent);
lv_obj_set_width(canvas_cont, LV_PCT(100));
lv_obj_set_flex_grow(canvas_cont,1);
lv_obj_set_style_bg_color(canvas_cont, lv_color_black(),0);
lv_obj_set_style_border_width(canvas_cont,0,0);
lv_obj_set_style_pad_all(canvas_cont,2,0);
lv_obj_set_flex_flow(canvas_cont, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(canvas_cont, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_remove_flag(canvas_cont, LV_OBJ_FLAG_SCROLLABLE);
if (!ctx->fb_native){
size_t fb_bytes=FRAME_W*FRAME_H*sizeof(uint16_t);
ctx->fb_native=(uint16_t*)alloc_psram(fb_bytes);
if (ctx->fb_native){
ctx->framebuffer_allocated=true;
memset(ctx->fb_native,0,fb_bytes);
/* Initial grey fill so we can visually confirm buffer ownership even before first gb_run_frame */
for(int i=0;i<FRAME_W*FRAME_H;i++) ctx->fb_native[i]=0x4208;
}
}
if (ctx->fb_native){
lv_coord_t disp_w = lv_display_get_horizontal_resolution(NULL);
lv_coord_t disp_h = lv_display_get_vertical_resolution(NULL);
int avail_h = disp_h - 160;
int avail_w = disp_w - 8;
int scale = 1;
if (avail_w >= FRAME_W * 3 && avail_h >= FRAME_H * 3) scale = 3;
else if (avail_w >= FRAME_W * 2 && avail_h >= FRAME_H * 2) scale = 2;
ctx->canvas = lv_canvas_create(canvas_cont);
/* lv_canvas_set_buffer creates internal static_buf header from our raw ptr */
lv_canvas_set_buffer(ctx->canvas, ctx->fb_native, FRAME_W, FRAME_H, LV_COLOR_FORMAT_RGB565);
ctx->fb_draw_buf = lv_canvas_get_draw_buf(ctx->canvas);
if (ctx->fb_draw_buf && ctx->fb_draw_buf->data) {
/* Force fresh cache state */
lv_draw_buf_invalidate_cache(ctx->fb_draw_buf, NULL);
lv_image_cache_drop(ctx->fb_draw_buf);
}
if (scale > 1) {
lv_image_set_scale(ctx->canvas, (uint32_t)(256 * scale));
lv_image_set_pivot(ctx->canvas, FRAME_W / 2, FRAME_H / 2);
}
lv_obj_set_style_border_width(ctx->canvas, 1, 0);
lv_obj_set_style_border_color(ctx->canvas, lv_color_hex(0x444444), 0);
lv_obj_center(ctx->canvas);
} else {
lv_obj_t* err=lv_label_create(canvas_cont); lv_label_set_text(err,"FB alloc failed"); lv_obj_set_style_text_color(err, lv_color_white(),0);
}
lv_obj_t* ctrl=lv_obj_create(parent);
ctx->controls_cont=ctrl;
lv_obj_set_width(ctrl, LV_PCT(100));
lv_obj_set_height(ctrl, 110);
lv_obj_set_style_pad_all(ctrl,2,0);
lv_obj_set_style_bg_color(ctrl, lv_color_hex(0x111111),0);
lv_obj_set_style_border_width(ctrl,0,0);
lv_obj_set_flex_flow(ctrl, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(ctrl, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
static BtnUserData btn_ud[8];
static bool ud_init=false;
if (!ud_init){ memset(btn_ud,0,sizeof(btn_ud)); ud_init=true; }
lv_obj_t* dpad=lv_obj_create(ctrl);
lv_obj_set_size(dpad,96,96);
lv_obj_set_style_bg_opa(dpad,LV_OPA_TRANSP,0);
lv_obj_set_style_border_width(dpad,0,0);
lv_obj_set_style_pad_all(dpad,0,0);
lv_obj_t* up=lv_btn_create(dpad); lv_obj_set_size(up,32,32); lv_obj_set_pos(up,32,0);
lv_obj_t* left=lv_btn_create(dpad); lv_obj_set_size(left,32,32); lv_obj_set_pos(left,0,32);
lv_obj_t* right=lv_btn_create(dpad); lv_obj_set_size(right,32,32); lv_obj_set_pos(right,64,32);
lv_obj_t* down=lv_btn_create(dpad); lv_obj_set_size(down,32,32); lv_obj_set_pos(down,32,64);
lv_obj_t* lbl; lbl=lv_label_create(up); lv_label_set_text(lbl, LV_SYMBOL_UP); lv_obj_center(lbl);
lbl=lv_label_create(down); lv_label_set_text(lbl, LV_SYMBOL_DOWN); lv_obj_center(lbl);
lbl=lv_label_create(left); lv_label_set_text(lbl, LV_SYMBOL_LEFT); lv_obj_center(lbl);
lbl=lv_label_create(right); lv_label_set_text(lbl, LV_SYMBOL_RIGHT); lv_obj_center(lbl);
ctx->btn_up=up; ctx->btn_down=down; ctx->btn_left=left; ctx->btn_right=right;
btn_ud[0].ctx=ctx; btn_ud[0].joypad_bit=JOYPAD_UP; lv_obj_add_event_cb(up, input_down_cb, LV_EVENT_PRESSED, &btn_ud[0]); lv_obj_add_event_cb(up, input_up_cb, LV_EVENT_RELEASED, &btn_ud[0]); lv_obj_add_event_cb(up, input_up_cb, LV_EVENT_PRESS_LOST, &btn_ud[0]);
btn_ud[1].ctx=ctx; btn_ud[1].joypad_bit=JOYPAD_DOWN; lv_obj_add_event_cb(down, input_down_cb, LV_EVENT_PRESSED, &btn_ud[1]); lv_obj_add_event_cb(down, input_up_cb, LV_EVENT_RELEASED, &btn_ud[1]); lv_obj_add_event_cb(down, input_up_cb, LV_EVENT_PRESS_LOST, &btn_ud[1]);
btn_ud[2].ctx=ctx; btn_ud[2].joypad_bit=JOYPAD_LEFT; lv_obj_add_event_cb(left, input_down_cb, LV_EVENT_PRESSED, &btn_ud[2]); lv_obj_add_event_cb(left, input_up_cb, LV_EVENT_RELEASED, &btn_ud[2]); lv_obj_add_event_cb(left, input_up_cb, LV_EVENT_PRESS_LOST, &btn_ud[2]);
btn_ud[3].ctx=ctx; btn_ud[3].joypad_bit=JOYPAD_RIGHT;lv_obj_add_event_cb(right, input_down_cb, LV_EVENT_PRESSED, &btn_ud[3]); lv_obj_add_event_cb(right, input_up_cb, LV_EVENT_RELEASED, &btn_ud[3]); lv_obj_add_event_cb(right, input_up_cb, LV_EVENT_PRESS_LOST, &btn_ud[3]);
lv_obj_t* center_col=lv_obj_create(ctrl);
lv_obj_set_size(center_col,64,96);
lv_obj_set_style_bg_opa(center_col,LV_OPA_TRANSP,0);
lv_obj_set_style_border_width(center_col,0,0);
lv_obj_set_flex_flow(center_col, LV_FLEX_FLOW_COLUMN);
lv_obj_set_flex_align(center_col, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_set_style_pad_row(center_col,4,0);
lv_obj_t* sel_btn=lv_btn_create(center_col); lv_obj_set_size(sel_btn,60,28); lbl=lv_label_create(sel_btn); lv_label_set_text(lbl,"Sel"); lv_obj_center(lbl);
lv_obj_t* sta_btn=lv_btn_create(center_col); lv_obj_set_size(sta_btn,60,28); lbl=lv_label_create(sta_btn); lv_label_set_text(lbl,"Sta"); lv_obj_center(lbl);
ctx->btn_select=sel_btn; ctx->btn_start=sta_btn;
btn_ud[4].ctx=ctx; btn_ud[4].joypad_bit=JOYPAD_SELECT; lv_obj_add_event_cb(sel_btn, input_down_cb, LV_EVENT_PRESSED, &btn_ud[4]); lv_obj_add_event_cb(sel_btn, input_up_cb, LV_EVENT_RELEASED, &btn_ud[4]); lv_obj_add_event_cb(sel_btn, input_up_cb, LV_EVENT_PRESS_LOST, &btn_ud[4]);
btn_ud[5].ctx=ctx; btn_ud[5].joypad_bit=JOYPAD_START; lv_obj_add_event_cb(sta_btn, input_down_cb, LV_EVENT_PRESSED, &btn_ud[5]); lv_obj_add_event_cb(sta_btn, input_up_cb, LV_EVENT_RELEASED, &btn_ud[5]); lv_obj_add_event_cb(sta_btn, input_up_cb, LV_EVENT_PRESS_LOST, &btn_ud[5]);
lv_obj_t* ab=lv_obj_create(ctrl);
lv_obj_set_size(ab,96,96);
lv_obj_set_style_bg_opa(ab,LV_OPA_TRANSP,0);
lv_obj_set_style_border_width(ab,0,0);
lv_obj_set_style_pad_all(ab,0,0);
lv_obj_t* b_btn=lv_btn_create(ab); lv_obj_set_size(b_btn,40,40); lv_obj_set_pos(b_btn,0,24); lv_obj_set_style_radius(b_btn,20,0);
lv_obj_t* a_btn=lv_btn_create(ab); lv_obj_set_size(a_btn,40,40); lv_obj_set_pos(a_btn,48,8); lv_obj_set_style_radius(a_btn,20,0);
lbl=lv_label_create(b_btn); lv_label_set_text(lbl,"B"); lv_obj_center(lbl);
lbl=lv_label_create(a_btn); lv_label_set_text(lbl,"A"); lv_obj_center(lbl);
ctx->btn_a=a_btn; ctx->btn_b=b_btn;
btn_ud[6].ctx=ctx; btn_ud[6].joypad_bit=JOYPAD_B; lv_obj_add_event_cb(b_btn, input_down_cb, LV_EVENT_PRESSED, &btn_ud[6]); lv_obj_add_event_cb(b_btn, input_up_cb, LV_EVENT_RELEASED, &btn_ud[6]); lv_obj_add_event_cb(b_btn, input_up_cb, LV_EVENT_PRESS_LOST, &btn_ud[6]);
btn_ud[7].ctx=ctx; btn_ud[7].joypad_bit=JOYPAD_A; lv_obj_add_event_cb(a_btn, input_down_cb, LV_EVENT_PRESSED, &btn_ud[7]); lv_obj_add_event_cb(a_btn, input_up_cb, LV_EVENT_RELEASED, &btn_ud[7]); lv_obj_add_event_cb(a_btn, input_up_cb, LV_EVENT_PRESS_LOST, &btn_ud[7]);
lv_obj_add_event_cb(parent, key_press_cb, LV_EVENT_KEY, ctx);
if (tt_lvgl_hardware_keyboard_is_available()){
lv_group_t* g=lv_group_get_default();
if (g){ lv_group_add_obj(g, parent); lv_group_focus_obj(parent); lv_group_set_editing(g, true); }
}
if (ctx->emu_timer){ lv_timer_delete(ctx->emu_timer); ctx->emu_timer=NULL; }
ctx->fps_frames = 0;
ctx->fps_last_us = esp_timer_get_time();
ctx->lines_drawn = 0;
ctx->emu_timer=lv_timer_create(emu_timer_cb, TICK_MS, ctx);
ctx->emu_running=true;
ctx->mode=APP_MODE_EMU;
}
static void switch_to_browser(AppCtx* ctx){
if (ctx->emu_timer){ lv_timer_delete(ctx->emu_timer); ctx->emu_timer=NULL; }
ctx->emu_running=false;
save_cart_ram(ctx);
ctx->mode=APP_MODE_BROWSER;
if (!ctx->browser_wrapper || !lv_obj_is_valid(ctx->browser_wrapper)) return;
if (ctx->emu_wrapper) lv_obj_add_flag(ctx->emu_wrapper, LV_OBJ_FLAG_HIDDEN);
lv_obj_remove_flag(ctx->browser_wrapper, LV_OBJ_FLAG_HIDDEN);
scan_rom_dir(ctx);
build_browser_ui(ctx, ctx->browser_wrapper);
}
static void switch_to_emu(AppCtx* ctx){
if (!ctx->rom_loaded) return;
if (ctx->browser_wrapper) lv_obj_add_flag(ctx->browser_wrapper, LV_OBJ_FLAG_HIDDEN);
if (!ctx->emu_wrapper) return;
lv_obj_remove_flag(ctx->emu_wrapper, LV_OBJ_FLAG_HIDDEN);
build_emu_ui(ctx, ctx->emu_wrapper);
}
/* Lifecycle */
static void* create_data(void){
AppCtx* ctx=(AppCtx*)calloc(1,sizeof(AppCtx));
if (ctx){ ctx->joypad_state=0xFF; ctx->mode=APP_MODE_BROWSER; ctx->selected_rom_idx=-1; }
return ctx;
}
static void destroy_data(void* data){
AppCtx* ctx=(AppCtx*)data;
if (!ctx) return;
if (ctx->emu_timer) lv_timer_delete(ctx->emu_timer);
if (ctx->fb_native) heap_caps_free(ctx->fb_native);
if (ctx->rom_data) heap_caps_free(ctx->rom_data);
if (ctx->cart_ram) heap_caps_free(ctx->cart_ram);
free(ctx);
}
static void on_create(AppHandle app, void* data){
AppCtx* ctx=(AppCtx*)data; if (ctx) ctx->app_handle=app;
}
static void on_destroy(AppHandle app, void* data){ (void)app; (void)data; }
static void on_show(AppHandle app, void* data, lv_obj_t* parent){
AppCtx* ctx=(AppCtx*)data; if (!ctx) return;
ctx->app_handle=app;
lv_obj_remove_flag(parent, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_set_flex_flow(parent, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_pad_all(parent,0,0);
lv_obj_set_style_pad_row(parent,0,0);
lv_obj_set_style_bg_color(parent, lv_color_black(),0);
ctx->toolbar=tt_lvgl_toolbar_create_for_app(parent, app);
lv_obj_set_style_bg_color(ctx->toolbar, lv_color_hex(0x111111),0);
ctx->root_wrapper=lv_obj_create(parent);
lv_obj_set_width(ctx->root_wrapper, LV_PCT(100));
lv_obj_set_flex_grow(ctx->root_wrapper,1);
lv_obj_set_style_pad_all(ctx->root_wrapper,0,0);
lv_obj_set_style_border_width(ctx->root_wrapper,0,0);
lv_obj_set_style_bg_color(ctx->root_wrapper, lv_color_black(),0);
lv_obj_set_flex_flow(ctx->root_wrapper, LV_FLEX_FLOW_COLUMN);
lv_obj_remove_flag(ctx->root_wrapper, LV_OBJ_FLAG_SCROLLABLE);
ctx->browser_wrapper=lv_obj_create(ctx->root_wrapper);
lv_obj_set_width(ctx->browser_wrapper, LV_PCT(100));
lv_obj_set_flex_grow(ctx->browser_wrapper,1);
lv_obj_set_style_pad_all(ctx->browser_wrapper,0,0);
lv_obj_set_style_border_width(ctx->browser_wrapper,0,0);
ctx->emu_wrapper=lv_obj_create(ctx->root_wrapper);
lv_obj_set_width(ctx->emu_wrapper, LV_PCT(100));
lv_obj_set_flex_grow(ctx->emu_wrapper,1);
lv_obj_set_style_pad_all(ctx->emu_wrapper,0,0);
lv_obj_set_style_border_width(ctx->emu_wrapper,0,0);
lv_obj_add_flag(ctx->emu_wrapper, LV_OBJ_FLAG_HIDDEN);
scan_rom_dir(ctx);
struct stat st;
bool default_exists=(stat(DEFAULT_ROM_PATH,&st)==0);
if (default_exists){
if (load_rom_file(ctx, DEFAULT_ROM_PATH)){
build_browser_ui(ctx, ctx->browser_wrapper);
switch_to_emu(ctx);
return;
}
}
build_browser_ui(ctx, ctx->browser_wrapper);
lv_obj_remove_flag(ctx->browser_wrapper, LV_OBJ_FLAG_HIDDEN);
ctx->mode=APP_MODE_BROWSER;
}
static void on_hide(AppHandle app, void* data){
(void)app;
AppCtx* ctx=(AppCtx*)data; if (!ctx) return;
if (ctx->emu_timer){ lv_timer_delete(ctx->emu_timer); ctx->emu_timer=NULL; }
ctx->emu_running=false;
if (ctx->rom_loaded) save_cart_ram(ctx);
ctx->canvas=NULL; ctx->fb_draw_buf=NULL; ctx->toolbar=NULL; ctx->root_wrapper=NULL; ctx->browser_wrapper=NULL; ctx->emu_wrapper=NULL;
ctx->status_label=NULL; ctx->rom_list=NULL; ctx->controls_cont=NULL;
ctx->btn_up=ctx->btn_down=ctx->btn_left=ctx->btn_right=NULL;
ctx->btn_a=ctx->btn_b=ctx->btn_start=ctx->btn_select=NULL;
ctx->app_handle=NULL;
}
int main(int argc, char* argv[]){
(void)argc; (void)argv;
tt_app_register((AppRegistration){
.createData=create_data,
.destroyData=destroy_data,
.onCreate=on_create,
.onDestroy=on_destroy,
.onShow=on_show,
.onHide=on_hide
});
return 0;
}
+11
View File
@@ -0,0 +1,11 @@
[manifest]
version=0.1
[target]
sdk=0.8.0-dev
platforms=esp32,esp32s3,esp32c6,esp32p4
[app]
id=one.tactility.gameboy
versionName=0.1.0-dev
versionCode=1
name=GameBoy
description=DMG Game Boy emulator (no audio prototype, Peanut-GB)
+7 -10
View File
@@ -1,10 +1,7 @@
[manifest] manifest.version=0.2
version=0.1 target.sdk=0.8.0-dev
[target] target.platforms=esp32,esp32s3,esp32c6,esp32p4
sdk=0.7.0-dev app.id=one.tactility.graphicsdemo
platforms=esp32,esp32s3,esp32c6,esp32p4 app.version.name=0.6.0
[app] app.version.code=6
id=one.tactility.graphicsdemo app.name=Graphics Demo
versionName=0.3.0
versionCode=3
name=Graphics Demo
+7 -10
View File
@@ -1,10 +1,7 @@
[manifest] manifest.version=0.2
version=0.1 target.sdk=0.8.0-dev
[target] target.platforms=esp32,esp32s3,esp32c6,esp32p4
sdk=0.7.0-dev app.id=one.tactility.helloworld
platforms=esp32s3 app.version.name=0.6.0
[app] app.version.code=6
id=one.tactility.helloworld app.name=Hello World
versionName=0.3.0
versionCode=3
name=Hello World
+16
View File
@@ -0,0 +1,16 @@
cmake_minimum_required(VERSION 3.20)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
if (DEFINED ENV{TACTILITY_SDK_PATH})
set(TACTILITY_SDK_PATH $ENV{TACTILITY_SDK_PATH})
else()
set(TACTILITY_SDK_PATH "../../release/TactilitySDK")
message(WARNING "TACTILITY_SDK_PATH is not set, defaulting to ${TACTILITY_SDK_PATH}")
endif()
include("${TACTILITY_SDK_PATH}/TactilitySDK.cmake")
set(EXTRA_COMPONENT_DIRS ${TACTILITY_SDK_PATH})
project(LiveCaptions)
tactility_project(LiveCaptions)
+17
View File
@@ -0,0 +1,17 @@
# Live Captions
ESP32-S3 external app that streams 16 kHz signed-16-bit mono microphone PCM to the Mac mini Hermes voice gateway and renders its live draft/final captions. It stores **only final captions** on the device SD card in `/sdcard/captions/YYYY-MM-DD.txt`.
## Configuration
Before packaging, place `config.json` in the app's user-data directory (not source control):
```json
{
"server_url": "ws://192.168.68.102:8642/api/esp32/voice/ws",
"device_id": "your-registered-device-id",
"api_key": "device-profile-key"
}
```
The app never retries automatically: connection failure remains `FAILED` until the user selects **Start** again. **Stop** sends the gateway `stop` event, waits for the final caption, appends it to that day’s text file, then returns to idle.
+8
View File
@@ -0,0 +1,8 @@
file(GLOB_RECURSE SOURCE_FILES Source/*.c)
set(CJSON_SOURCE "$ENV{IDF_PATH}/components/json/cJSON/cJSON.c")
idf_component_register(
SRCS ${SOURCE_FILES} ${CJSON_SOURCE}
INCLUDE_DIRS Source "$ENV{IDF_PATH}/components/json/cJSON"
REQUIRES TactilitySDK lwip
)
+328
View File
@@ -0,0 +1,328 @@
/* Live Captions: stream mic PCM to Mac mini and save final text on the SD card. */
#include <tt_app.h>
#include <tt_lvgl.h>
#include <tt_lvgl_toolbar.h>
#include <tactility/device.h>
#include <tactility/drivers/audio_stream.h>
#include <cJSON.h>
#include <esp_log.h>
#include <esp_random.h>
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/stat.h>
#include "websocket.h"
/* These legacy names are exported by the flashed 0.8.0-dev firmware. */
struct Device* device_find_by_name(const char* name);
struct Device* device_find_first_by_type(const struct DeviceType* type);
#define TAG "LiveCaptions"
#define DEFAULT_ENDPOINT "ws://192.168.68.102:8645/api/esp32/captions/ws"
#define DEFAULT_DEVICE_ID "tactility-14c19d1a790"
#define PCM_BUFFER_BYTES 1024U
#define EVENT_BUFFER_BYTES 4096U
#define DISPLAY_WORD_LIMIT 50
typedef enum {
CAPTION_IDLE,
CAPTION_CONNECTING,
CAPTION_LISTENING,
CAPTION_PROCESSING,
CAPTION_FAILED,
} CaptionState;
typedef struct {
AppHandle app;
volatile bool visible;
volatile bool capture_audio;
volatile bool stop_requested;
volatile bool session_active;
volatile bool socket_failed;
int fd;
CaptionState state;
char endpoint[128];
char device_id[64];
char api_key[128];
char detail[96];
char caption[768];
char last_final[768];
struct Device* stream_dev;
AudioStreamHandle input_handle;
TaskHandle_t worker;
TaskHandle_t receiver;
SemaphoreHandle_t socket_lock;
SemaphoreHandle_t audio_lock;
lv_obj_t* caption_label;
lv_obj_t* status_label;
} CaptionContext;
static void update_ui(CaptionContext* ctx) {
if (!ctx->visible || !tt_lvgl_lock(pdMS_TO_TICKS(100))) return;
lv_label_set_text(ctx->caption_label, ctx->caption);
const char* status = ctx->state == CAPTION_LISTENING ? "Connected" : (ctx->state == CAPTION_CONNECTING ? "Connecting" : (ctx->state == CAPTION_FAILED ? "Failed — Reconnecting" : "Connecting"));
lv_label_set_text(ctx->status_label, status);
tt_lvgl_unlock();
}
static void set_state(CaptionContext* ctx, CaptionState state, const char* detail) {
ctx->state = state;
snprintf(ctx->detail, sizeof(ctx->detail), "%s", detail ? detail : "");
update_ui(ctx);
}
static bool find_audio_stream_device(CaptionContext* ctx) {
ctx->stream_dev = device_find_by_name("audio-stream");
if (ctx->stream_dev == NULL) ctx->stream_dev = device_find_first_by_type(&AUDIO_STREAM_TYPE);
return ctx->stream_dev != NULL;
}
static bool open_input_stream(CaptionContext* ctx) {
if (ctx->stream_dev == NULL) return false;
if (ctx->input_handle != NULL) return true;
struct AudioStreamConfig config = {.sample_rate = 16000, .bits_per_sample = 16, .channels = 1};
if (audio_stream_open_input(ctx->stream_dev, &config, &ctx->input_handle) != ERROR_NONE) return false;
audio_stream_set_mute(ctx->stream_dev, AUDIO_CODEC_DIR_INPUT, false);
audio_stream_set_volume(ctx->stream_dev, AUDIO_CODEC_DIR_INPUT, 100.0f);
return true;
}
static void close_input_stream(CaptionContext* ctx) {
if (ctx->input_handle != NULL) {
audio_stream_close(ctx->input_handle);
ctx->input_handle = NULL;
}
}
static int send_locked(CaptionContext* ctx, const uint8_t* data, size_t length, bool binary) {
if (ctx->fd < 0 || xSemaphoreTake(ctx->socket_lock, pdMS_TO_TICKS(500)) != pdTRUE) return -1;
int result = ws_send(ctx->fd, data, length, binary);
xSemaphoreGive(ctx->socket_lock);
return result;
}
static bool parse_endpoint(const char* url, char* host, size_t host_size, int* port, char* path, size_t path_size) {
if (url == NULL || strncmp(url, "ws://", 5) != 0) return false;
const char* authority = url + 5;
const char* slash = strchr(authority, '/');
const char* end = slash ? slash : authority + strlen(authority);
const char* colon = NULL;
for (const char* p = authority; p < end; ++p) if (*p == ':') colon = p;
size_t host_len = (size_t)((colon ? colon : end) - authority);
if (host_len == 0 || host_len >= host_size) return false;
memcpy(host, authority, host_len); host[host_len] = '\0';
*port = 80;
if (colon != NULL) {
*port = atoi(colon + 1);
if (*port < 1 || *port > 65535) return false;
}
const char* wire_path = slash ? slash : "/";
if (strlen(wire_path) >= path_size) return false;
snprintf(path, path_size, "%s", wire_path);
return true;
}
static void append_final_caption(const char* text) {
if (text == NULL || !*text) return;
mkdir("/sdcard/captions", 0755);
time_t now = time(NULL);
struct tm local;
localtime_r(&now, &local);
char filename[32];
strftime(filename, sizeof(filename), "%Y-%m-%d.txt", &local);
char stamp[16];
strftime(stamp, sizeof(stamp), "%H:%M:%S", &local);
char path[128];
snprintf(path, sizeof(path), "/sdcard/captions/%s", filename);
FILE* log = fopen(path, "a");
if (log == NULL) { ESP_LOGE(TAG, "could not append %s", path); return; }
fprintf(log, "[%s] %s\n", stamp, text);
fclose(log);
}
static bool is_space_char(char value) { return value == ' ' || value == '\n' || value == '\r' || value == ' '; }
static void copy_recent_words(char* output, size_t output_size, const char* text) {
const char* starts[DISPLAY_WORD_LIMIT];
int count = 0;
bool in_word = false;
for (const char* cursor = text; *cursor; ++cursor) {
if (is_space_char(*cursor)) { in_word = false; continue; }
if (!in_word) { starts[count % DISPLAY_WORD_LIMIT] = cursor; ++count; in_word = true; }
}
const char* first = count > DISPLAY_WORD_LIMIT ? starts[count % DISPLAY_WORD_LIMIT] : text;
snprintf(output, output_size, "%s", first);
}
static void display_caption(CaptionContext* ctx, const char* text, bool final) {
if (text == NULL || !*text) return;
copy_recent_words(ctx->caption, sizeof(ctx->caption), text);
if (final && strcmp(ctx->last_final, text) != 0) {
snprintf(ctx->last_final, sizeof(ctx->last_final), "%s", text);
append_final_caption(text);
ctx->state = CAPTION_IDLE;
}
update_ui(ctx);
}
static void handle_event(CaptionContext* ctx, const char* json) {
cJSON* root = cJSON_Parse(json);
if (root == NULL) return;
cJSON* event = cJSON_GetObjectItem(root, "event");
cJSON* text = cJSON_GetObjectItem(root, "text");
if (!cJSON_IsString(event)) { cJSON_Delete(root); return; }
const char* name = event->valuestring;
if (strcmp(name, "ready") == 0) {
set_state(ctx, CAPTION_CONNECTING, "Starting caption stream");
} else if (strcmp(name, "listening") == 0) {
set_state(ctx, CAPTION_LISTENING, "Listening — press Stop when finished");
} else if (strcmp(name, "state") == 0) {
cJSON* remote_state = cJSON_GetObjectItem(root, "state");
if (cJSON_IsString(remote_state) && strcmp(remote_state->valuestring, "listening") == 0) {
set_state(ctx, CAPTION_LISTENING, "Listening");
} else if (cJSON_IsString(remote_state) && strcmp(remote_state->valuestring, "processing") == 0) {
set_state(ctx, CAPTION_PROCESSING, "Captioning…");
}
} else if (strcmp(name, "draft") == 0 || strcmp(name, "interim_transcript") == 0 || strcmp(name, "review") == 0) {
if (cJSON_IsString(text)) display_caption(ctx, text->valuestring, false);
} else if (strcmp(name, "transcript") == 0 || strcmp(name, "final") == 0) {
cJSON* is_final = cJSON_GetObjectItem(root, "isFinal");
if (cJSON_IsString(text) && (!cJSON_IsBool(is_final) || cJSON_IsTrue(is_final) || strcmp(name, "final") == 0)) {
display_caption(ctx, text->valuestring, true);
}
} else if (strcmp(name, "thinking") == 0) {
set_state(ctx, CAPTION_PROCESSING, "Final captioning…");
} else if (strcmp(name, "error") == 0) {
ctx->socket_failed = true;
set_state(ctx, CAPTION_FAILED, "Fail to connect");
}
cJSON_Delete(root);
}
static void receiver_task(void* argument) {
CaptionContext* ctx = argument;
uint8_t* buffer = malloc(EVENT_BUFFER_BYTES + 1U);
if (buffer == NULL) { ctx->socket_failed = true; ctx->receiver = NULL; vTaskDelete(NULL); }
while (ctx->visible && ctx->fd >= 0) {
int opcode = 0; bool complete = false;
int received = ws_recv(ctx->fd, &opcode, &complete, buffer, EVENT_BUFFER_BYTES);
if (received < 0 || !complete) break;
if (opcode == 0x01) { buffer[received] = '\0'; handle_event(ctx, (const char*)buffer); }
else if (opcode == 0x09) {
if (xSemaphoreTake(ctx->socket_lock, pdMS_TO_TICKS(500)) == pdTRUE) {
ws_send_pong(ctx->fd, buffer, (size_t)received); xSemaphoreGive(ctx->socket_lock);
}
} else if (opcode == 0x08) break;
}
ctx->session_active = false;
ctx->receiver = NULL;
vTaskDelete(NULL);
}
static void load_config(CaptionContext* ctx) {
snprintf(ctx->endpoint, sizeof(ctx->endpoint), "%s", DEFAULT_ENDPOINT);
snprintf(ctx->device_id, sizeof(ctx->device_id), "%s", DEFAULT_DEVICE_ID);
ctx->api_key[0] = '\0';
char path[256]; size_t size = sizeof(path);
tt_app_get_user_data_child_path(ctx->app, "config.json", path, &size);
FILE* file = fopen(path, "r");
if (file == NULL) return;
char raw[512]; size_t bytes = fread(raw, 1, sizeof(raw) - 1, file); fclose(file); raw[bytes] = '\0';
cJSON* root = cJSON_Parse(raw);
cJSON* endpoint = root ? cJSON_GetObjectItem(root, "server_url") : NULL;
cJSON* device = root ? cJSON_GetObjectItem(root, "device_id") : NULL;
cJSON* key = root ? cJSON_GetObjectItem(root, "api_key") : NULL;
if (cJSON_IsString(endpoint)) snprintf(ctx->endpoint, sizeof(ctx->endpoint), "%s", endpoint->valuestring);
if (cJSON_IsString(device)) snprintf(ctx->device_id, sizeof(ctx->device_id), "%s", device->valuestring);
if (cJSON_IsString(key)) snprintf(ctx->api_key, sizeof(ctx->api_key), "%s", key->valuestring);
cJSON_Delete(root);
}
static void worker_task(void* argument) {
CaptionContext* ctx = argument;
char host[64], path[96]; int port = 0;
if (!parse_endpoint(ctx->endpoint, host, sizeof(host), &port, path, sizeof(path))) {
set_state(ctx, CAPTION_FAILED, "Fail to connect"); ctx->worker = NULL; vTaskDelete(NULL);
}
set_state(ctx, CAPTION_CONNECTING, "Connecting to Mac mini");
ctx->fd = ws_connect(host, port, path, ctx->device_id, ctx->api_key);
if (ctx->fd < 0) { set_state(ctx, CAPTION_FAILED, "Fail to connect"); ctx->worker = NULL; vTaskDelete(NULL); }
char start[256];
snprintf(start, sizeof(start), "{\"v\":1,\"event\":\"start\",\"session_id\":\"cap-%08lx\",\"device_id\":\"%s\",\"audio\":{\"format\":\"pcm_s16le\",\"sample_rate\":16000,\"channels\":1,\"sample_width\":2}}", (unsigned long)esp_random(), ctx->device_id);
if (send_locked(ctx, (const uint8_t*)start, strlen(start), false) != 0 || !open_input_stream(ctx)) {
set_state(ctx, CAPTION_FAILED, "Fail to connect"); ws_close(ctx->fd); ctx->fd = -1; ctx->worker = NULL; vTaskDelete(NULL);
}
ctx->session_active = true;
xTaskCreate(receiver_task, "caption_rx", 6144, ctx, 6, &ctx->receiver);
set_state(ctx, CAPTION_LISTENING, "Listening — press Stop when finished");
uint8_t pcm[PCM_BUFFER_BYTES];
while (ctx->visible && ctx->capture_audio && !ctx->socket_failed) {
size_t bytes = 0;
xSemaphoreTake(ctx->audio_lock, portMAX_DELAY);
error_t result = audio_stream_read(ctx->input_handle, pcm, sizeof(pcm), &bytes, pdMS_TO_TICKS(100));
xSemaphoreGive(ctx->audio_lock);
if (result == ERROR_NONE && bytes > 0 && (bytes % 2U) == 0 && send_locked(ctx, pcm, bytes, true) != 0) ctx->socket_failed = true;
}
xSemaphoreTake(ctx->audio_lock, portMAX_DELAY); close_input_stream(ctx); xSemaphoreGive(ctx->audio_lock);
if (ctx->stop_requested && !ctx->socket_failed) {
const char* stop = "{\"event\":\"stop\"}";
send_locked(ctx, (const uint8_t*)stop, strlen(stop), false);
set_state(ctx, CAPTION_PROCESSING, "Final captioning…");
for (unsigned i = 0; ctx->session_active && i < 150; ++i) vTaskDelay(pdMS_TO_TICKS(100));
}
if (ctx->fd >= 0) { ws_send_close(ctx->fd); ws_close(ctx->fd); ctx->fd = -1; }
bool reconnect = ctx->socket_failed && ctx->visible;
if (reconnect) set_state(ctx, CAPTION_FAILED, "Reconnecting");
else if (ctx->state == CAPTION_PROCESSING) set_state(ctx, CAPTION_IDLE, "");
ctx->worker = NULL;
if (reconnect) {
vTaskDelay(pdMS_TO_TICKS(3000));
if (ctx->visible) { ctx->socket_failed = false; ctx->capture_audio = true; xTaskCreate(worker_task, "caption_tx", 8192, ctx, 5, &ctx->worker); }
}
vTaskDelete(NULL);
}
static void* create_data(void) { CaptionContext* ctx = calloc(1, sizeof(*ctx)); if (ctx) ctx->fd = -1; return ctx; }
static void destroy_data(void* data) { free(data); }
static void on_create(AppHandle app, void* data) { ((CaptionContext*)data)->app = app; }
static void on_show(AppHandle app, void* data, lv_obj_t* parent) {
CaptionContext* ctx = data; ctx->visible = true; load_config(ctx); find_audio_stream_device(ctx);
ctx->socket_lock = xSemaphoreCreateMutex(); ctx->audio_lock = xSemaphoreCreateMutex();
lv_obj_t* toolbar = tt_lvgl_toolbar_create_for_app(parent, app);
lv_obj_align(toolbar, LV_ALIGN_TOP_MID, 0, 0);
ctx->caption_label = lv_label_create(parent);
lv_obj_set_width(ctx->caption_label, lv_pct(88));
lv_label_set_long_mode(ctx->caption_label, LV_LABEL_LONG_WRAP);
lv_obj_set_style_text_align(ctx->caption_label, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_align(ctx->caption_label, LV_ALIGN_CENTER, 0, 0);
ctx->status_label = lv_label_create(parent);
lv_obj_align(ctx->status_label, LV_ALIGN_BOTTOM_MID, 0, -10);
ctx->caption[0] = '\0';
if (ctx->stream_dev != NULL && ctx->socket_lock != NULL && ctx->audio_lock != NULL) {
ctx->capture_audio = true; ctx->stop_requested = false; ctx->socket_failed = false;
xTaskCreate(worker_task, "caption_tx", 8192, ctx, 5, &ctx->worker);
}
}
static void on_hide(AppHandle app, void* data) {
(void)app; CaptionContext* ctx = data; ctx->visible = false; ctx->capture_audio = false; ctx->stop_requested = false;
if (ctx->fd >= 0) { ws_send_close(ctx->fd); ws_close(ctx->fd); ctx->fd = -1; }
for (unsigned i = 0; (ctx->worker || ctx->receiver) && i < 100; ++i) vTaskDelay(pdMS_TO_TICKS(10));
close_input_stream(ctx);
if (ctx->socket_lock) { vSemaphoreDelete(ctx->socket_lock); ctx->socket_lock = NULL; }
if (ctx->audio_lock) { vSemaphoreDelete(ctx->audio_lock); ctx->audio_lock = NULL; }
}
int main(int argc, char* argv[]) {
(void)argc; (void)argv;
tt_app_register((AppRegistration){.createData=create_data,.destroyData=destroy_data,.onCreate=on_create,.onShow=on_show,.onHide=on_hide});
return 0;
}
+167
View File
@@ -0,0 +1,167 @@
#include "websocket.h"
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <esp_log.h>
#include <esp_random.h>
#include <lwip/inet.h>
#include <lwip/sockets.h>
#define TAG "PipecatVoiceWs"
#define WS_HEADER_LIMIT 1024U
#define WS_CONTROL_LIMIT 125U
static int send_all(int fd, const uint8_t* data, size_t length) {
size_t sent = 0;
while (sent < length) {
int result = lwip_send(fd, data + sent, length - sent, 0);
if (result <= 0) return -1;
sent += (size_t)result;
}
return 0;
}
static int recv_all(int fd, uint8_t* data, size_t length) {
size_t received = 0;
while (received < length) {
int result = lwip_recv(fd, data + received, length - received, 0);
if (result <= 0) return -1;
received += (size_t)result;
}
return 0;
}
static int discard(int fd, uint64_t length) {
uint8_t buffer[256];
while (length > 0) {
size_t chunk = length > sizeof(buffer) ? sizeof(buffer) : (size_t)length;
if (recv_all(fd, buffer, chunk) < 0) return -1;
length -= chunk;
}
return 0;
}
static int send_frame(int fd, uint8_t opcode, const uint8_t* payload, size_t length) {
if (length > 65535U || ((opcode & 0x08U) && length > WS_CONTROL_LIMIT)) return -1;
uint8_t header[8];
size_t header_length = 2;
header[0] = 0x80U | opcode;
if (length < 126U) {
header[1] = 0x80U | (uint8_t)length;
} else {
header[1] = 0x80U | 126U;
header[2] = (uint8_t)(length >> 8U);
header[3] = (uint8_t)length;
header_length = 4;
}
uint8_t mask[4];
uint32_t random = esp_random();
memcpy(mask, &random, sizeof(mask));
memcpy(header + header_length, mask, sizeof(mask));
header_length += sizeof(mask);
if (send_all(fd, header, header_length) < 0) return -1;
uint8_t chunk[512];
size_t offset = 0;
while (offset < length) {
size_t count = length - offset > sizeof(chunk) ? sizeof(chunk) : length - offset;
for (size_t i = 0; i < count; ++i) chunk[i] = payload[offset + i] ^ mask[(offset + i) % sizeof(mask)];
if (send_all(fd, chunk, count) < 0) return -1;
offset += count;
}
return 0;
}
int ws_connect(const char* host, int port, const char* path, const char* device_id, const char* api_key) {
if (host == NULL || path == NULL || device_id == NULL || api_key == NULL || port < 1 || port > 65535) return -1;
int fd = lwip_socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0) {
ESP_LOGW(TAG, "socket create failed");
return -1;
}
struct sockaddr_in address = {0};
address.sin_family = AF_INET;
address.sin_port = htons((uint16_t)port);
address.sin_addr.s_addr = ipaddr_addr(host);
if (address.sin_addr.s_addr == IPADDR_NONE) {
ESP_LOGW(TAG, "endpoint address parse failed");
close(fd);
return -1;
}
if (lwip_connect(fd, (struct sockaddr*)&address, sizeof(address)) < 0) {
ESP_LOGW(TAG, "TCP connect failed");
close(fd);
return -1;
}
struct timeval timeout = {.tv_sec = 15, .tv_usec = 0};
lwip_setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
char request[WS_HEADER_LIMIT];
int request_length = snprintf(request, sizeof(request),
"GET %s HTTP/1.1\r\nHost: %s:%d\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
"Sec-WebSocket-Key: MDEyMzQ1Njc4OWFiY2RlZg==\r\nSec-WebSocket-Version: 13\r\n"
"Authorization: Bearer %s\r\nX-Device-ID: %s\r\n\r\n",
path, host, port, api_key, device_id);
if (request_length < 0 || (size_t)request_length >= sizeof(request) || send_all(fd, (const uint8_t*)request, (size_t)request_length) < 0) {
ESP_LOGW(TAG, "WebSocket upgrade request failed");
close(fd);
return -1;
}
char response[WS_HEADER_LIMIT];
size_t length = 0;
while (length + 1 < sizeof(response)) {
if (recv_all(fd, (uint8_t*)&response[length], 1) < 0) {
ESP_LOGW(TAG, "WebSocket upgrade response failed");
close(fd);
return -1;
}
response[++length] = '\0';
if (length >= 4 && memcmp(response + length - 4, "\r\n\r\n", 4) == 0) break;
}
if (length + 1 >= sizeof(response) || strstr(response, " 101 ") == NULL) {
ESP_LOGW(TAG, "WebSocket upgrade rejected");
close(fd);
return -1;
}
ESP_LOGI(TAG, "WebSocket upgrade accepted");
return fd;
}
int ws_send(int fd, const uint8_t* data, size_t length, bool binary) {
if (fd < 0 || data == NULL || length == 0) return -1;
return send_frame(fd, binary ? 0x02U : 0x01U, data, length);
}
int ws_recv(int fd, int* opcode, bool* final, uint8_t* payload, size_t maximum) {
uint8_t header[2];
if (fd < 0 || recv_all(fd, header, sizeof(header)) < 0) return -1;
uint64_t length = header[1] & 0x7fU;
if (length == 126U) {
uint8_t extended[2];
if (recv_all(fd, extended, sizeof(extended)) < 0) return -1;
length = ((uint64_t)extended[0] << 8U) | extended[1];
} else if (length == 127U) {
uint8_t extended[8];
if (recv_all(fd, extended, sizeof(extended)) < 0) return -1;
length = 0;
for (size_t i = 0; i < sizeof(extended); ++i) length = (length << 8U) | extended[i];
}
bool masked = (header[1] & 0x80U) != 0;
uint8_t mask[4] = {0};
if (masked && recv_all(fd, mask, sizeof(mask)) < 0) return -1;
uint8_t frame_opcode = header[0] & 0x0fU;
if (((frame_opcode & 0x08U) && (length > WS_CONTROL_LIMIT || !(header[0] & 0x80U))) || length > maximum) {
if (discard(fd, length) < 0) return -1;
return -2;
}
if (length > 0 && recv_all(fd, payload, (size_t)length) < 0) return -1;
if (masked) for (size_t i = 0; i < (size_t)length; ++i) payload[i] ^= mask[i % sizeof(mask)];
if (opcode) *opcode = frame_opcode;
if (final) *final = (header[0] & 0x80U) != 0;
return (int)length;
}
int ws_send_pong(int fd, const uint8_t* payload, size_t length) { return send_frame(fd, 0x0aU, payload, length); }
int ws_send_close(int fd) { return send_frame(fd, 0x08U, NULL, 0); }
void ws_close(int fd) { if (fd >= 0) close(fd); }
+62
View File
@@ -0,0 +1,62 @@
#pragma once
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Connect to a WebSocket server.
* @param host Server IP address (e.g. "192.168.68.126")
* @param port Port number (e.g. 8642)
* @param path WebSocket path (e.g. "/api/esp32/voice/ws")
* @param device_id Unique device identifier
* @param api_key Optional profile API key; never compiled into firmware
* @return Socket file descriptor on success, or -1 on failure
*/
int ws_connect(const char* host, int port, const char* path, const char* device_id, const char* api_key);
/**
* Send a WebSocket frame.
* @param fd Socket file descriptor
* @param data Data payload to send
* @param len Length of the data payload
* @param binary True for binary frame, false for text frame
* @return 0 on success, or -1 on failure
*/
int ws_send(int fd, const uint8_t* data, size_t len, bool binary);
/**
* Receive a WebSocket frame.
* @param fd Socket file descriptor
* @param out_opcode Pointer to store the received opcode (e.g. 0x01 text, 0x02 binary)
* @param payload Buffer to store the received payload
* @param max_len Maximum length of the payload buffer
* @return Received payload length on success, -1 on connection failure, or -2 on buffer overflow
*/
int ws_recv(int fd, int* out_opcode, bool* out_final, uint8_t* payload, size_t max_len);
/**
* Close a WebSocket connection.
* @param fd Socket file descriptor
*/
void ws_close(int fd);
/**
* Send a WebSocket PONG frame.
* @param fd Socket file descriptor
* @param payload Payload to reflect
* @param len Length of payload
* @return 0 on success, or -1 on failure
*/
int ws_send_pong(int fd, const uint8_t* payload, size_t len);
/** Send a clean WebSocket close control frame before closing the socket. */
int ws_send_close(int fd);
#ifdef __cplusplus
}
#endif
+7
View File
@@ -0,0 +1,7 @@
manifest.version=0.2
target.sdk=0.8.0-dev
target.platforms=esp32s3
app.id=one.tactility.livecaptions
app.version.name=1.0.0
app.version.code=1
app.name=Live Captions
+7 -10
View File
@@ -1,10 +1,7 @@
[manifest] manifest.version=0.2
version=0.1 target.sdk=0.8.0-dev
[target] target.platforms=esp32s3,esp32p4
sdk=0.7.0-dev app.id=one.tactility.m5unittest
platforms=esp32s3,esp32p4 app.version.name=0.4.0
[app] app.version.code=4
id=one.tactility.m5unittest app.name=M5 Unit Test
versionName=0.1.0
versionCode=1
name=M5 Unit Test
+7 -10
View File
@@ -1,10 +1,7 @@
[manifest] manifest.version=0.2
version=0.1 target.sdk=0.8.0-dev
[target] target.platforms=esp32,esp32s3,esp32c6,esp32p4
sdk=0.7.0-dev app.id=one.tactility.magic8ball
platforms=esp32,esp32s3,esp32c6,esp32p4 app.version.name=0.5.0
[app] app.version.code=5
id=one.tactility.magic8ball app.name=Magic 8-Ball
versionName=0.2.0
versionCode=2
name=Magic 8-Ball
+7 -10
View File
@@ -1,10 +1,7 @@
[manifest] manifest.version=0.2
version=0.1 target.sdk=0.8.0-dev
[target] target.platforms=esp32s3
sdk=0.7.0-dev app.id=one.tactility.mcpscreen
platforms=esp32s3 app.version.name=0.1.0
[app] app.version.code=1
id=one.tactility.mcpscreen app.name=MCP Screen
versionName=0.1.0
versionCode=1
name=MCP Screen
+46 -14
View File
@@ -211,12 +211,29 @@ void MediaKeys::startHid() {
if (tt_lvgl_hardware_keyboard_is_available()) enterKeyMode(); if (tt_lvgl_hardware_keyboard_is_available()) enterKeyMode();
} }
void MediaKeys::teardownBt() {
// Remove callback FIRST - stops any in-flight BT events from firing against
// our (possibly already freed) UI widget pointers after this returns.
if (_btDevice) bluetooth_remove_event_callback(_btDevice, btEventCallback);
// Do NOT call bluetooth_hid_device_stop here: it calls ble_gatts_reset() /
// ble_gatts_start() which corrupts NimBLE heap while the host task is still
// running. HID device is a persistent kernel device; hid_device_start() cleans
// up stale context on next use. Explicit stop is handled by handleSwitchToggle.
// Restore the radio/device to the state we found them in.
if (_btDevice && _radioWasOff) bluetooth_set_radio_enabled(_btDevice, false);
if (_btDevice && _deviceWasStarted) device_stop(_btDevice);
_btDevice = nullptr;
_hidDevice = nullptr;
_radioWasOff = false;
_deviceWasStarted = false;
}
void MediaKeys::handleSwitchToggle(bool enabled) { void MediaKeys::handleSwitchToggle(bool enabled) {
LOG_I(TAG, "Switch: %s", enabled ? "ON" : "OFF"); LOG_I(TAG, "Switch: %s", enabled ? "ON" : "OFF");
_isEnabled = enabled; _isEnabled = enabled;
if (enabled) { if (enabled) {
_btDevice = bluetooth_find_first_ready_device(); _btDevice = device_find_first_by_type(&BLUETOOTH_TYPE);
if (!_btDevice) { if (!_btDevice) {
LOG_E(TAG, "No Bluetooth device found"); LOG_E(TAG, "No Bluetooth device found");
_isEnabled = false; _isEnabled = false;
@@ -224,6 +241,19 @@ void MediaKeys::handleSwitchToggle(bool enabled) {
return; return;
} }
// Device may not be started yet (BT disabled in DTS by default to save memory).
if (!device_is_ready(_btDevice)) {
LOG_I(TAG, "BT device not started, starting now");
if (device_start(_btDevice) != ERROR_NONE) {
LOG_E(TAG, "Failed to start BT device");
_btDevice = nullptr;
_isEnabled = false;
if (_switchWidget) lv_obj_remove_state(_switchWidget, LV_STATE_CHECKED);
return;
}
_deviceWasStarted = true;
}
bluetooth_set_device_name(_btDevice, "Tactility Media Keys"); bluetooth_set_device_name(_btDevice, "Tactility Media Keys");
// Register callback before enabling radio so we don't miss the state-change event. // Register callback before enabling radio so we don't miss the state-change event.
@@ -247,12 +277,10 @@ void MediaKeys::handleSwitchToggle(bool enabled) {
} else { } else {
_radioEnabling = false; _radioEnabling = false;
if (tt_lvgl_hardware_keyboard_is_available()) exitKeyMode(); if (tt_lvgl_hardware_keyboard_is_available()) exitKeyMode();
// Explicit user toggle-off: stop HID cleanly (safe here since we're on the
// LVGL task and the user intentionally disabled, so no race with app teardown).
if (_hidDevice) bluetooth_hid_device_stop(_hidDevice); if (_hidDevice) bluetooth_hid_device_stop(_hidDevice);
if (_btDevice) bluetooth_remove_event_callback(_btDevice, btEventCallback); teardownBt();
if (_btDevice && _radioWasOff) bluetooth_set_radio_enabled(_btDevice, false);
_radioWasOff = false;
_btDevice = nullptr;
_hidDevice = nullptr;
if (_mainWrapper) lv_obj_add_flag(_mainWrapper, LV_OBJ_FLAG_HIDDEN); if (_mainWrapper) lv_obj_add_flag(_mainWrapper, LV_OBJ_FLAG_HIDDEN);
} }
} }
@@ -321,19 +349,23 @@ void MediaKeys::onShow(AppHandle appHandle, lv_obj_t* parent) {
} }
lv_obj_add_flag(_mainWrapper, LV_OBJ_FLAG_HIDDEN); lv_obj_add_flag(_mainWrapper, LV_OBJ_FLAG_HIDDEN);
// Auto-enable if BT is already on (turned on via QuickPanel/Settings before opening app).
struct Device* btDev = device_find_first_by_type(&BLUETOOTH_TYPE);
if (btDev && device_is_ready(btDev)) {
enum BtRadioState radioState;
if (bluetooth_get_radio_state(btDev, &radioState) == ERROR_NONE && radioState == BT_RADIO_STATE_ON) {
lv_obj_add_state(_switchWidget, LV_STATE_CHECKED);
handleSwitchToggle(true);
}
}
} }
void MediaKeys::onHide(AppHandle /*appHandle*/) { void MediaKeys::onHide(AppHandle /*appHandle*/) {
if (_hidDevice) bluetooth_hid_device_stop(_hidDevice);
if (_btDevice) bluetooth_remove_event_callback(_btDevice, btEventCallback);
if (_btDevice && _radioWasOff) bluetooth_set_radio_enabled(_btDevice, false);
_btDevice = nullptr;
_hidDevice = nullptr;
_isEnabled = false;
_radioEnabling = false; _radioEnabling = false;
_radioWasOff = false; _isEnabled = false;
if (tt_lvgl_hardware_keyboard_is_available()) exitKeyMode(); if (tt_lvgl_hardware_keyboard_is_available()) exitKeyMode();
teardownBt();
if (_keyHighlightTimer) { if (_keyHighlightTimer) {
lv_timer_delete(_keyHighlightTimer); lv_timer_delete(_keyHighlightTimer);
_keyHighlightTimer = nullptr; _keyHighlightTimer = nullptr;
+4 -1
View File
@@ -2,6 +2,7 @@
#include <TactilityCpp/App.h> #include <TactilityCpp/App.h>
#include <lvgl.h> #include <lvgl.h>
#include <tactility/device.h>
#include <tactility/drivers/bluetooth.h> #include <tactility/drivers/bluetooth.h>
#include <tactility/drivers/bluetooth_hid_device.h> #include <tactility/drivers/bluetooth_hid_device.h>
#include <tt_app.h> #include <tt_app.h>
@@ -25,7 +26,8 @@ class MediaKeys final : public App {
// State - accessed from both LVGL thread and BT callback thread // State - accessed from both LVGL thread and BT callback thread
std::atomic<bool> _isEnabled {false}; std::atomic<bool> _isEnabled {false};
std::atomic<bool> _radioEnabling {false}; // true while waiting for radio to come ON std::atomic<bool> _radioEnabling {false}; // true while waiting for radio to come ON
std::atomic<bool> _radioWasOff {false}; // true if MediaKeys turned the radio on (so we turn it off) std::atomic<bool> _radioWasOff {false}; // true if we turned the radio on (restore on exit)
std::atomic<bool> _deviceWasStarted{false}; // true if we called device_start (restore on exit)
// Static event callbacks // Static event callbacks
static void onSwitchToggled(lv_event_t* e); static void onSwitchToggled(lv_event_t* e);
@@ -36,6 +38,7 @@ class MediaKeys final : public App {
static void sendKeyTask(void* param); static void sendKeyTask(void* param);
// Instance methods called by static callbacks // Instance methods called by static callbacks
void teardownBt(); // remove callback + stop HID + restore radio/device state
void handleSwitchToggle(bool enabled); void handleSwitchToggle(bool enabled);
void handleButtonPress(uint32_t buttonId); void handleButtonPress(uint32_t buttonId);
void startHid(); // called once radio is confirmed ON void startHid(); // called once radio is confirmed ON
+8 -11
View File
@@ -1,11 +1,8 @@
[manifest] manifest.version=0.2
version=0.1 target.sdk=0.8.0-dev
[target] target.platforms=esp32s3,esp32p4
sdk=0.7.0-dev app.id=one.tactility.mediakeys
platforms=esp32s3,esp32p4 app.version.name=0.4.0
[app] app.version.code=4
id=one.tactility.mediakeys app.name=Media Keys
versionName=0.1.0 app.description=Bluetooth media keys. Touch or Physical Keyboard control\nB - previous, P - play/pause, N - next, M - mute, D - volume down, U - volume up.\nQ or ESC to exit focus.
versionCode=1
name=Media Keys
description=Bluetooth media keys. Touch or Physical Keyboard control\nB - previous, P - play/pause, N - next, M - mute, D - volume down, U - volume up.\nQ or ESC to exit focus.
File diff suppressed because it is too large Load Diff
+7 -10
View File
@@ -1,10 +1,7 @@
[manifest] manifest.version=0.2
version=0.1 target.sdk=0.8.0-dev
[target] target.platforms=esp32s3
sdk=0.8.0-dev app.id=one.tactility.mp3player
platforms=esp32s3 app.version.name=1.0.0
[app] app.version.code=1
id=one.tactility.mp3player app.name=MP3 Player
versionName=1.0.0
versionCode=1
name=MP3 Player
+7 -10
View File
@@ -1,10 +1,7 @@
[manifest] manifest.version=0.2
version=0.1 target.sdk=0.8.0-dev
[target] target.platforms=esp32,esp32s3,esp32c6,esp32p4
sdk=0.7.0-dev app.id=one.tactility.mystifydemo
platforms=esp32,esp32s3,esp32c6,esp32p4 app.version.name=0.6.0
[app] app.version.code=6
id=one.tactility.mystifydemo app.name=Mystify Demo
versionName=0.3.0
versionCode=3
name=Mystify Demo
+16
View File
@@ -0,0 +1,16 @@
cmake_minimum_required(VERSION 3.20)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
if (DEFINED ENV{TACTILITY_SDK_PATH})
set(TACTILITY_SDK_PATH $ENV{TACTILITY_SDK_PATH})
else()
set(TACTILITY_SDK_PATH "../../release/TactilitySDK")
message(WARNING "TACTILITY_SDK_PATH is not set, defaulting to ${TACTILITY_SDK_PATH}")
endif()
include("${TACTILITY_SDK_PATH}/TactilitySDK.cmake")
set(EXTRA_COMPONENT_DIRS ${TACTILITY_SDK_PATH})
project(PipecatVoice)
tactility_project(PipecatVoice)
+30
View File
@@ -0,0 +1,30 @@
# Pipecat Voice
Minimal native Tactility client for the LAN voice-adapter protocol v1. Opening the app immediately connects to `ws://192.168.68.102:8644/api/esp32/voice/ws`, sends the versioned `start` declaration, and continuously streams 16 kHz mono signed-16-bit PCM. There is no Connect button, speaker/transport picker, PTT control, text entry, transcript display, or credential on the device.
The Mac-hosted adapter owns VAD, STT, Pipecat/Hermes orchestration, TTS, and credentials. It returns metadata followed by a single PCM response frame; the app pauses capture, plays that response at the declared rate through Tactility `i2s0`, then resumes capture. The app only displays connection/streaming/reconnect/configuration state and uses the standard toolbar to exit.
## Configuration
`config.json` in app user data can override the non-secret endpoint and allowed adapter device id:
```json
{"server_url":"ws://192.168.68.102:8644/api/esp32/voice/ws","device_id":"tactility-14c19d1a790"}
```
Only `ws://` private-LAN endpoints are accepted; loopback endpoints are rejected. Invalid configuration is a terminal actionable state. Network failures use bounded 1, 2, 4, 8, 16, then 30-second reconnect delays. Protocol and payload violations close the session and reconnect; stale audio is never queued.
## Build and test
```sh
cc -std=c11 -Wall -Wextra -Werror -I main/Source tests/test_voice_protocol.c main/Source/voice_protocol.c -o /tmp/pipecatvoice-protocol-test
/tmp/pipecatvoice-protocol-test
unset PYTHONPATH PYTHONHOME
export IDF_PYTHON_ENV_PATH=/Users/adolforeyna/.espressif/python_env/idf5.3_py3.9_env
source /Users/adolforeyna/esp/esp-idf/export.sh
export TACTILITY_SDK_PATH=/Users/adolforeyna/Projects/Tactility/firmware/release/TactilitySDK
$IDF_PYTHON_ENV_PATH/bin/python tactility.py Apps/PipecatVoice build esp32s3 --local-sdk
```
The compatible adapter is documented at `/Users/adolforeyna/Projects/voice-assistant/hermes-esp32-voice-gateway/docs/lan-ws-pipecat-adapter.md`. It is the only supported endpoint; Pipecat `:7861` is not an optional device transport.
@@ -0,0 +1,89 @@
# Pipecat SmallWebRTC ESP32 feasibility spike
Date: 2026-08-10
## Decision
**NO-GO for a Tactility external ELF on the current SDK; GO only for a separate, full ESP-IDF firmware application.**
Pipecat has an official native ESP32 client, so the required transport is real and source-proven. It cannot presently be used as a Tactility runtime ELF without a firmware/SDK integration project: the client is a full ESP-IDF firmware with private, static component dependencies and system configuration that the ELF loader does not provide or export. Do not replace the rejected raw-WebSocket implementation with another transport until that integration is designed and proven.
This is not a proposal to flash anything. No device was deployed or flashed during this spike.
## Source-pinned native client
| Item | Evidence |
| --- | --- |
| Client | `https://github.com/pipecat-ai/pipecat-esp32`, commit `e70e3b1f0576e502af9e390434e1a6e8a5cd0d2e`, cloned with all recursive submodules |
| Top-level licence | MIT (`LICENSE`, copyright Daily/OpenAI) |
| Pipecat server | local installed `pipecat-ai 1.7.0`, Python 3.11 virtual environment |
| Server ESP32 support | `SmallWebRTCRequestHandler(..., esp32_mode=True, host=...)` munges the SDP; `smallwebrtc_sdp_munging()` removes SHA-384/SHA-512 fingerprints and retains only the chosen host's ICE candidates |
| ESP-IDF build used | local ESP-IDF `v5.5.2`, environment `idf5.5_py3.9_env` |
| Native build result | upstream `esp32-s3-box-3` built successfully, including `peer`, `srtp`, `esp-libopus`, Wi-Fi, HTTP client, DTLS/SRTP, Opus, and the ESP-BOX-3 BSP |
The official client is designed for ESP32-S3 and uses the `libpeer` API. Its `PeerConfiguration` sets `CODEC_OPUS`, creates a peer connection, installs ICE/data/audio callbacks, and invokes `peer_connection_create_offer()`. This is the source-proven native WebRTC implementation; it owns ICE, DTLS-SRTP, RTP, and Opus rather than hand-implementing any of them.
## Required SmallWebRTC contract
The product transport is SmallWebRTC HTTP signaling plus WebRTC media, never the old raw WebSocket PCM/JSON protocol:
1. `POST /start` with `transport: "webrtc"`, `enableDefaultIceServers: false`, and optional `body`; retain the returned `sessionId`.
2. `POST /sessions/{sessionId}/api/offer` with `{ "sdp": ..., "type": "offer", "pc_id": optional, "restart_pc": optional, "requestData": optional }`; Pipecat returns SDP answer, type, and `pc_id`.
3. `PATCH /sessions/{sessionId}/api/offer` with `{ "pc_id": ..., "candidates": [{ "candidate": ..., "sdp_mid": ..., "sdp_mline_index": ... }] }` for trickle ICE. An empty candidate is the end-of-candidates marker.
4. Use the negotiated WebRTC audio track continuously. The runner starts the bot after the offer is processed.
The local Pipecat source also supports the direct `/api/offer` route used by the current official ESP32 example. The session form above is the approved application contract because it supports Pipecat runner session lifecycle. The live endpoint returned HTTP 200 to `/status`, but it was not restarted with `--esp32`; therefore no live offer/candidate exchange is represented as ESP32 validation.
## Audio adapter boundary
The official client source (`media.cpp`) uses 16 kHz, mono, signed 16-bit PCM (`640` bytes = 320 samples = 20 ms) and encodes it as Opus for `peer_connection_send_audio()`. Inbound WebRTC audio reaches the `onaudiotrack` callback as Opus, is decoded to the same PCM shape, and is written to the speaker codec.
For a future firmware-level integration, Tactility must keep ownership at the following boundary (no hard-coded board pins):
- acquire the existing Tactility `audio_stream` / `i2s_controller` service;
- pull fixed 20 ms frames, 16 kHz mono S16LE, into the native client encoder;
- feed decoded remote S16LE frames to the existing output service;
- serialize I/O ownership, keep bounded queues, and drop stale audio rather than accumulating latency;
- close peer/media callbacks before releasing the audio device.
The current kernel exports `audio_stream_open_input`, `audio_stream_open_output`, `audio_stream_read`, `audio_stream_write`, `audio_stream_close`, and `i2s_controller_read`/`i2s_controller_write`. Those APIs are the usable boundary, not a reason to configure physical pins in the app.
## Full-firmware build evidence
The following was run in a temporary checkout; non-secret placeholder Wi-Fi values were used and no flash command was run:
```text
cd /tmp/pipecat-esp32-spike
# cloned pipecat-esp32 at e70e3b1... and initialized all recursive submodules
cd esp32-s3-box-3
unset PYTHONPATH PYTHONHOME
export IDF_PYTHON_ENV_PATH=/Users/adolforeyna/.espressif/python_env/idf5.5_py3.9_env
export WIFI_SSID=spike
export WIFI_PASSWORD=spike
export PIPECAT_SMALLWEBRTC_URL=http://192.168.68.112:7860/api/offer
source /Users/adolforeyna/esp/esp-idf/export.sh
idf.py build
```
Actual result: `src.elf` and `src.bin` were produced; the IDF build ended with `Project build complete`. `src.bin` is **1,493,408 bytes** and the upstream 1.5 MiB app partition reported **79,712 bytes (5%) free**. `xtensa-esp32s3-elf-size src.elf` reported text `1,304,360`, data `201,012`, bss `2,863,205` (total `4,368,577`). The linked firmware has no undefined dynamic symbols.
This is important capacity evidence: even before adapting it to the target board and Tactility services, the supported client nearly fills its own dedicated application partition and has a 2.86 MiB BSS footprint.
## Why this does not link as a Tactility ELF
Tactility's `TactilitySDK.cmake` calls `project_elf()`. Its loader CMake builds a PIC shared ELF with `-nostartfiles -nostdlib -shared -e app_main`, and links only `main` plus explicitly listed `ELF_COMPONENTS` / `ELF_LIBS`. The current PipecatVoice component declares only `REQUIRES TactilitySDK lwip`.
The upstream client instead requires full firmware components including `peer`, `srtp`, `esp-libopus`, `esp_http_client`, `esp_wifi`, `nvs_flash`, `esp_psram`, `esp_netif`, mbedTLS, and ESP-BOX-3 BSP. The official `peer` static archive has unresolved references to the linked firmware environment such as `mbedtls_ssl_conf_dtls_srtp_protection_profiles`, `mbedtls_ssl_config_defaults`, `lwip_inet_ntop`, and socket/ICE helpers. The Tactility kernel export table contains the audio service APIs listed above but no `peer_connection`, `opus_*`, `srtp_*`, `mbedtls_*`, `esp_http_client*`, `esp_wifi*`, or `esp_netif*` exports.
Attempting the ordinary app build also hit a concrete local SDK packaging blocker before linking: `tactility.py Apps/PipecatVoice build esp32s3 --local-sdk` reported that `Buildscripts/TactilitySDK/0.8.0-dev-esp32s3/TactilitySDK` is missing. This must be corrected for later normal ELF builds, but it is distinct from the component/loader incompatibility.
Therefore copying the client sources or merely adding `REQUIRES peer` would not make a runnable ELF: it would either fail to find the private IDF component libraries during the ELF link or produce imports that the firmware loader cannot resolve. Statically embedding all dependencies is unproven and high-risk because of ELF size, duplicate runtime/library state, SDK configuration, and Wi-Fi/codec ownership conflicts.
## Security, licensing, and follow-up gate
- Do not log SDP, ICE details, credentials, or raw audio. The source-level HTTP helper currently logs offer/answer in debug mode; any reused code must remove that logging.
- The upstream defaults deliberately disable TLS certificate verification for its demo. Production must use HTTPS with a pinned/validated trust chain; do not inherit that setting.
- Preserve MIT notices for Pipecat ESP32 and audit each pinned submodule separately (`libpeer`, SRTP/libSRTP, Opus, and Espressif managed components have their own licenses).
- Do not use the existing PipecatVoice raw WebSocket code or its historical configuration as a fallback; it is protocol-incompatible with SmallWebRTC.
A firmware-level project must first export/package the required WebRTC dependency set, prove an external ELF link with zero unresolved loader symbols (or move the client into firmware), set deterministic memory budgets, and then perform an `--esp32` SmallWebRTC live offer/ICE/media test. Only after that gate may the approved minimal auto-start UI be implemented.
+8
View File
@@ -0,0 +1,8 @@
file(GLOB_RECURSE SOURCE_FILES Source/*.c)
set(CJSON_SOURCE "$ENV{IDF_PATH}/components/json/cJSON/cJSON.c")
idf_component_register(
SRCS ${SOURCE_FILES} ${CJSON_SOURCE}
INCLUDE_DIRS Source "$ENV{IDF_PATH}/components/json/cJSON"
REQUIRES TactilitySDK lwip
)
+320
View File
@@ -0,0 +1,320 @@
#include <tt_app.h>
#include <tt_lvgl.h>
#include <tt_lvgl_toolbar.h>
#include <tactility/device.h>
#include <tactility/drivers/audio_stream.h>
#include <cJSON.h>
#include <esp_log.h>
#include <esp_random.h>
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "voice_protocol.h"
#include "websocket.h"
/* Exported by firmware 0.8.0-dev although absent from the CDN SDK header. */
struct Device* device_find_by_name(const char* name);
struct Device* device_find_first_by_type(const struct DeviceType* type);
#define TAG "PipecatVoice"
#define DEFAULT_ENDPOINT "ws://192.168.68.102:8644/api/esp32/voice/ws"
#define DEFAULT_DEVICE_ID "tactility-14c19d1a790"
typedef struct {
AppHandle app;
volatile bool visible;
volatile bool streaming;
volatile bool playing;
volatile bool socket_failed;
int fd;
PvState state;
unsigned retry_attempt;
size_t expected_audio_bytes;
char endpoint[128];
char device_id[64];
char api_key[128];
char detail[96];
lv_obj_t* state_label;
lv_obj_t* detail_label;
struct Device* stream_dev;
AudioStreamHandle input_handle;
AudioStreamHandle output_handle;
TaskHandle_t worker;
TaskHandle_t receiver;
SemaphoreHandle_t socket_lock;
SemaphoreHandle_t audio_lock;
} VoiceContext;
static void update_ui(VoiceContext* ctx) {
if (!ctx->visible || !tt_lvgl_lock(pdMS_TO_TICKS(100))) return;
lv_label_set_text(ctx->state_label, pv_state_label(ctx->state));
lv_obj_set_style_text_color(ctx->state_label,
ctx->state == PV_STREAMING ? lv_color_hex(0x32c86e) :
ctx->state == PV_FAILED ? lv_color_hex(0xd94a4a) : lv_color_hex(0xe0b64a), LV_PART_MAIN);
lv_label_set_text(ctx->detail_label, ctx->detail);
tt_lvgl_unlock();
}
static void set_state(VoiceContext* ctx, PvState state, const char* detail) {
ctx->state = state;
snprintf(ctx->detail, sizeof(ctx->detail), "%s", detail);
update_ui(ctx);
}
static bool open_input_stream(VoiceContext* ctx) {
if (ctx->stream_dev == NULL) return false;
if (ctx->output_handle) { audio_stream_close(ctx->output_handle); ctx->output_handle = NULL; }
if (ctx->input_handle) return true;
struct AudioStreamConfig cfg = {
.sample_rate = 16000,
.bits_per_sample = 16,
.channels = 1,
};
if (audio_stream_open_input(ctx->stream_dev, &cfg, &ctx->input_handle) != ERROR_NONE) {
ESP_LOGW(TAG, "audio_stream_open_input failed");
return false;
}
audio_stream_set_mute(ctx->stream_dev, AUDIO_CODEC_DIR_INPUT, false);
audio_stream_set_volume(ctx->stream_dev, AUDIO_CODEC_DIR_INPUT, 100.0f);
return true;
}
static bool open_output_stream(VoiceContext* ctx) {
if (ctx->stream_dev == NULL) return false;
if (ctx->input_handle) { audio_stream_close(ctx->input_handle); ctx->input_handle = NULL; }
if (ctx->output_handle) return true;
struct AudioStreamConfig cfg = {
.sample_rate = 16000,
.bits_per_sample = 16,
.channels = 1,
};
if (audio_stream_open_output(ctx->stream_dev, &cfg, &ctx->output_handle) != ERROR_NONE) {
ESP_LOGW(TAG, "audio_stream_open_output failed");
return false;
}
audio_stream_set_mute(ctx->stream_dev, AUDIO_CODEC_DIR_OUTPUT, false);
audio_stream_set_volume(ctx->stream_dev, AUDIO_CODEC_DIR_OUTPUT, 80.0f);
return true;
}
static void close_audio(VoiceContext* ctx) {
if (ctx->output_handle) { audio_stream_close(ctx->output_handle); ctx->output_handle = NULL; }
if (ctx->input_handle) { audio_stream_close(ctx->input_handle); ctx->input_handle = NULL; }
}
static int send_locked(VoiceContext* ctx, const uint8_t* data, size_t length, bool binary) {
if (ctx->fd < 0 || xSemaphoreTake(ctx->socket_lock, pdMS_TO_TICKS(500)) != pdTRUE) return -1;
int result = ws_send(ctx->fd, data, length, binary);
xSemaphoreGive(ctx->socket_lock);
return result;
}
static void handle_event(VoiceContext* ctx, const char* text) {
cJSON* root = cJSON_Parse(text);
if (root == NULL) return;
cJSON* version = cJSON_GetObjectItem(root, "v");
cJSON* event = cJSON_GetObjectItem(root, "event");
if (!cJSON_IsNumber(version) || version->valueint != PV_PROTOCOL_VERSION || !cJSON_IsString(event)) {
cJSON_Delete(root);
return;
}
if (strcmp(event->valuestring, "ready") == 0) {
ctx->streaming = true;
} else if (strcmp(event->valuestring, "state") == 0) {
cJSON* state = cJSON_GetObjectItem(root, "state");
if (cJSON_IsString(state) && strcmp(state->valuestring, "listening") == 0) {
ctx->streaming = true;
set_state(ctx, PV_STREAMING, "Continuous microphone streaming");
}
} else if (strcmp(event->valuestring, "audio") == 0) {
cJSON* format = cJSON_GetObjectItem(root, "format");
cJSON* rate = cJSON_GetObjectItem(root, "sample_rate");
cJSON* channels = cJSON_GetObjectItem(root, "channels");
cJSON* width = cJSON_GetObjectItem(root, "sample_width");
cJSON* length = cJSON_GetObjectItem(root, "byte_length");
if (cJSON_IsString(format) && cJSON_IsNumber(rate) && cJSON_IsNumber(channels) && cJSON_IsNumber(width) &&
cJSON_IsNumber(length) && pv_valid_downstream_audio(format->valuestring, rate->valueint, channels->valueint,
width->valueint, (size_t)length->valueint)) {
ctx->expected_audio_bytes = (size_t)length->valueint;
ctx->playing = true;
set_state(ctx, PV_STREAMING, "Playing response; microphone paused");
} else {
ctx->socket_failed = true;
}
} else if (strcmp(event->valuestring, "error") == 0) {
/* The server-provided message is intentionally not copied to display/logs. */
ctx->socket_failed = true;
}
cJSON_Delete(root);
}
static void receiver_task(void* argument) {
VoiceContext* ctx = argument;
uint8_t* buffer = malloc(PV_DOWNSTREAM_MAX + 1U);
if (buffer == NULL) { ctx->socket_failed = true; ctx->receiver = NULL; vTaskDelete(NULL); }
while (ctx->visible && ctx->fd >= 0) {
int opcode = 0;
bool final = false;
int received = ws_recv(ctx->fd, &opcode, &final, buffer, PV_DOWNSTREAM_MAX);
if (received < 0 || !final) { ctx->socket_failed = true; break; }
if (opcode == 0x01) {
buffer[received] = '\0';
handle_event(ctx, (const char*)buffer);
} else if (opcode == 0x02) {
if (!ctx->playing || !pv_binary_matches_metadata(ctx->expected_audio_bytes, (size_t)received)) { ctx->socket_failed = true; break; }
xSemaphoreTake(ctx->audio_lock, portMAX_DELAY);
bool ok = open_output_stream(ctx);
size_t written = 0;
if (ok) ok = audio_stream_write(ctx->output_handle, buffer, (size_t)received, &written, pdMS_TO_TICKS(3000)) == ERROR_NONE;
open_input_stream(ctx);
xSemaphoreGive(ctx->audio_lock);
if (!ok || written != (size_t)received) { ctx->socket_failed = true; break; }
ctx->expected_audio_bytes = 0;
ctx->playing = false;
} else if (opcode == 0x09) {
if (xSemaphoreTake(ctx->socket_lock, pdMS_TO_TICKS(500)) == pdTRUE) {
ws_send_pong(ctx->fd, buffer, (size_t)received);
xSemaphoreGive(ctx->socket_lock);
}
} else if (opcode == 0x08) {
ctx->socket_failed = true;
break;
}
}
free(buffer);
ctx->receiver = NULL;
vTaskDelete(NULL);
}
static void close_session(VoiceContext* ctx) {
int fd = ctx->fd;
ctx->fd = -1;
ctx->streaming = false;
ctx->playing = false;
ctx->expected_audio_bytes = 0;
if (fd >= 0) {
if (xSemaphoreTake(ctx->socket_lock, pdMS_TO_TICKS(100)) == pdTRUE) {
ws_send_close(fd);
xSemaphoreGive(ctx->socket_lock);
}
ws_close(fd);
}
close_audio(ctx);
}
static void worker_task(void* argument) {
VoiceContext* ctx = argument;
PvEndpoint endpoint;
if (!pv_parse_endpoint(ctx->endpoint, &endpoint)) {
set_state(ctx, PV_FAILED, "Set a private-LAN ws:// endpoint in config.json");
ctx->worker = NULL;
vTaskDelete(NULL);
}
uint8_t pcm[1024];
while (ctx->visible) {
set_state(ctx, ctx->retry_attempt ? PV_RECONNECTING : PV_CONNECTING,
ctx->retry_attempt ? "Retrying voice gateway" : "Connecting to voice gateway");
ctx->socket_failed = false;
ESP_LOGI(TAG, "Opening voice gateway session");
ctx->fd = ws_connect(endpoint.host, endpoint.port, endpoint.path, ctx->device_id, ctx->api_key);
if (ctx->fd >= 0) {
char session[64];
snprintf(session, sizeof(session), "pv-%08lx", (unsigned long)esp_random());
char start[256];
if (pv_make_start_json(start, sizeof(start), session, ctx->device_id) &&
send_locked(ctx, (const uint8_t*)start, strlen(start), false) == 0) {
if (!open_input_stream(ctx)) {
set_state(ctx, PV_FAILED, "Audio stream unavailable");
ctx->socket_failed = true;
} else {
xTaskCreate(receiver_task, "pv_rx", 6144, ctx, 6, &ctx->receiver);
uint32_t stable_ticks = 0;
while (ctx->visible && !ctx->socket_failed) {
if (!ctx->streaming || ctx->playing) { vTaskDelay(pdMS_TO_TICKS(20)); continue; }
xSemaphoreTake(ctx->audio_lock, portMAX_DELAY);
bool opened = open_input_stream(ctx);
size_t read = 0;
error_t read_result = opened ? audio_stream_read(ctx->input_handle, pcm, sizeof(pcm), &read, pdMS_TO_TICKS(100)) : ERROR_RESOURCE;
xSemaphoreGive(ctx->audio_lock);
if (!opened) { ctx->socket_failed = true; break; }
if (read_result == ERROR_NONE && pv_valid_pcm_chunk(read) && send_locked(ctx, pcm, read, true) < 0) ctx->socket_failed = true;
if (++stable_ticks >= 300) ctx->retry_attempt = 0;
}
}
}
}
close_session(ctx);
if (!ctx->visible) break;
uint32_t delay = pv_retry_delay_seconds(ctx->retry_attempt++);
ESP_LOGW(TAG, "Voice gateway session unavailable; retry in %lu seconds", (unsigned long)delay);
set_state(ctx, PV_RECONNECTING, "Gateway unavailable; retry scheduled");
for (uint32_t second = 0; ctx->visible && second < delay; ++second) vTaskDelay(pdMS_TO_TICKS(1000));
}
ctx->worker = NULL;
vTaskDelete(NULL);
}
static void load_config(VoiceContext* ctx) {
snprintf(ctx->endpoint, sizeof(ctx->endpoint), "%s", DEFAULT_ENDPOINT);
snprintf(ctx->device_id, sizeof(ctx->device_id), "%s", DEFAULT_DEVICE_ID);
ctx->api_key[0] = '\0';
char path[256]; size_t path_size = sizeof(path);
tt_app_get_user_data_child_path(ctx->app, "config.json", path, &path_size);
FILE* file = fopen(path, "r");
if (file == NULL) return;
char json[512]; size_t bytes = fread(json, 1, sizeof(json) - 1, file); fclose(file); json[bytes] = '\0';
cJSON* root = cJSON_Parse(json);
cJSON* endpoint = root ? cJSON_GetObjectItem(root, "server_url") : NULL;
cJSON* device = root ? cJSON_GetObjectItem(root, "device_id") : NULL;
cJSON* key = root ? cJSON_GetObjectItem(root, "api_key") : NULL;
if (cJSON_IsString(endpoint)) snprintf(ctx->endpoint, sizeof(ctx->endpoint), "%s", endpoint->valuestring);
if (cJSON_IsString(device)) snprintf(ctx->device_id, sizeof(ctx->device_id), "%s", device->valuestring);
if (cJSON_IsString(key)) snprintf(ctx->api_key, sizeof(ctx->api_key), "%s", key->valuestring);
cJSON_Delete(root);
}
static void* create_data(void) { VoiceContext* ctx = calloc(1, sizeof(*ctx)); if (ctx) ctx->fd = -1; return ctx; }
static void destroy_data(void* data) { free(data); }
static void on_create(AppHandle app, void* data) { ((VoiceContext*)data)->app = app; }
static void on_destroy(AppHandle app, void* data) { (void)app; (void)data; }
static void on_show(AppHandle app, void* data, lv_obj_t* parent) {
VoiceContext* ctx = data; ctx->visible = true; load_config(ctx);
ctx->stream_dev = device_find_by_name("audio-stream");
if (ctx->stream_dev == NULL) ctx->stream_dev = device_find_first_by_type(&AUDIO_STREAM_TYPE);
ctx->socket_lock = xSemaphoreCreateMutex();
ctx->audio_lock = xSemaphoreCreateMutex();
lv_obj_t* toolbar = tt_lvgl_toolbar_create_for_app(parent, app);
lv_obj_align(toolbar, LV_ALIGN_TOP_MID, 0, 0);
ctx->state_label = lv_label_create(parent);
lv_obj_align(ctx->state_label, LV_ALIGN_CENTER, 0, -30);
ctx->detail_label = lv_label_create(parent);
lv_obj_set_width(ctx->detail_label, lv_pct(88)); lv_label_set_long_mode(ctx->detail_label, LV_LABEL_LONG_WRAP);
lv_obj_set_style_text_align(ctx->detail_label, LV_TEXT_ALIGN_CENTER, LV_PART_MAIN);
lv_obj_align(ctx->detail_label, LV_ALIGN_CENTER, 0, 25);
if (ctx->stream_dev == NULL || ctx->socket_lock == NULL || ctx->audio_lock == NULL) set_state(ctx, PV_FAILED, "Audio service unavailable");
else xTaskCreate(worker_task, "pv_worker", 7168, ctx, 5, &ctx->worker);
}
static void on_hide(AppHandle app, void* data) {
(void)app; VoiceContext* ctx = data; ctx->visible = false; close_session(ctx);
for (unsigned i = 0; (ctx->worker || ctx->receiver) && i < 100; ++i) vTaskDelay(pdMS_TO_TICKS(10));
close_audio(ctx);
if (ctx->socket_lock) { vSemaphoreDelete(ctx->socket_lock); ctx->socket_lock = NULL; }
if (ctx->audio_lock) { vSemaphoreDelete(ctx->audio_lock); ctx->audio_lock = NULL; }
}
int main(int argc, char* argv[]) {
(void)argc; (void)argv;
tt_app_register((AppRegistration){.createData=create_data,.destroyData=destroy_data,.onCreate=on_create,.onDestroy=on_destroy,.onShow=on_show,.onHide=on_hide});
return 0;
}
@@ -0,0 +1,113 @@
#include "voice_protocol.h"
#include <stdio.h>
#include <string.h>
/* NOTE: Do not use ctype.h (isalnum/isalpha/isdigit/isspace) in this app. Those
* functions read the `_ctype_` table, which is resolved from the flashed firmware
* at runtime; the firmware's table does not behave correctly for side-loaded ELF
* apps, so isalnum('a') can return false. Use explicit ASCII range checks instead. */
static bool is_digit(unsigned char c) { return c >= '0' && c <= '9'; }
static bool is_space(unsigned char c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\v' || c == '\f';
}
static bool is_alnum(unsigned char c) {
return is_digit(c) || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
static bool copy_part(char* destination, size_t destination_size, const char* start, size_t length) {
if (length == 0 || length >= destination_size) return false;
memcpy(destination, start, length);
destination[length] = '\0';
return true;
}
static bool is_loopback(const char* host) {
return strcmp(host, "localhost") == 0 || strcmp(host, "::1") == 0 || strncmp(host, "127.", 4) == 0;
}
static bool valid_identifier(const char* value) {
if (value == NULL || *value == '\0') return false;
for (const unsigned char* p = (const unsigned char*)value; *p; ++p) {
if (!is_alnum(*p) && *p != '-' && *p != '_' && *p != '.') return false;
}
return true;
}
bool pv_parse_endpoint(const char* url, PvEndpoint* endpoint) {
if (url == NULL || endpoint == NULL || strncmp(url, "ws://", 5) != 0) return false;
const char* authority = url + 5;
const char* path = strchr(authority, '/');
const char* authority_end = path ? path : authority + strlen(authority);
const char* colon = NULL;
for (const char* p = authority; p < authority_end; ++p) {
if (*p == ':') {
if (colon != NULL) return false;
colon = p;
}
if (is_space((unsigned char)*p) || *p == '@' || *p == '?' || *p == '#') return false;
}
size_t host_length = (size_t)((colon ? colon : authority_end) - authority);
if (!copy_part(endpoint->host, sizeof(endpoint->host), authority, host_length) || is_loopback(endpoint->host)) return false;
endpoint->port = 80;
if (colon != NULL) {
unsigned long port = 0;
for (const char* p = colon + 1; p < authority_end; ++p) {
if (!is_digit((unsigned char)*p)) return false;
port = port * 10U + (unsigned long)(*p - '0');
if (port > 65535U) return false;
}
if (port == 0) return false;
endpoint->port = (uint16_t)port;
}
return path == NULL ? copy_part(endpoint->path, sizeof(endpoint->path), "/", 1)
: copy_part(endpoint->path, sizeof(endpoint->path), path, strlen(path));
}
bool pv_make_start_json(char* out, size_t out_size, const char* session_id, const char* device_id) {
if (out == NULL || !valid_identifier(session_id) || !valid_identifier(device_id)) return false;
int written = snprintf(out, out_size,
"{\"v\":1,\"event\":\"start\",\"session_id\":\"%s\",\"device_id\":\"%s\",\"audio\":{\"format\":\"pcm_s16le\",\"sample_rate\":16000,\"channels\":1,\"sample_width\":2}}",
session_id, device_id);
return written > 0 && (size_t)written < out_size;
}
bool pv_valid_pcm_chunk(size_t bytes) {
return bytes > 0 && bytes <= PV_PCM_CHUNK_MAX && (bytes % 2U) == 0;
}
bool pv_valid_downstream_audio(const char* format, int sample_rate, int channels, int sample_width, size_t byte_length) {
return format != NULL && strcmp(format, "pcm_s16le") == 0 && sample_rate > 0 && sample_rate <= 48000 &&
channels == 1 && sample_width == 2 && byte_length > 0 && byte_length <= PV_DOWNSTREAM_MAX &&
(byte_length % 2U) == 0;
}
bool pv_binary_matches_metadata(size_t expected_bytes, size_t received_bytes) {
return expected_bytes > 0 && expected_bytes == received_bytes;
}
uint32_t pv_retry_delay_seconds(unsigned attempt) {
uint32_t delay = 1;
while (attempt > 0 && delay < 30) {
delay *= 2;
--attempt;
}
return delay > 30 ? 30 : delay;
}
PvState pv_disconnect_state(bool endpoint_valid) {
return endpoint_valid ? PV_RECONNECTING : PV_FAILED;
}
const char* pv_state_label(PvState state) {
switch (state) {
case PV_CONNECTING: return "CONNECTING";
case PV_STREAMING: return "STREAMING";
case PV_RECONNECTING: return "RECONNECTING";
case PV_FAILED: return "FAILED";
default: return "FAILED";
}
}
@@ -0,0 +1,31 @@
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#define PV_PROTOCOL_VERSION 1
#define PV_PCM_CHUNK_MAX 16384U
#define PV_DOWNSTREAM_MAX 65536U
typedef enum {
PV_CONNECTING,
PV_STREAMING,
PV_RECONNECTING,
PV_FAILED,
} PvState;
typedef struct {
char host[64];
char path[96];
uint16_t port;
} PvEndpoint;
bool pv_parse_endpoint(const char* url, PvEndpoint* endpoint);
bool pv_make_start_json(char* out, size_t out_size, const char* session_id, const char* device_id);
bool pv_valid_pcm_chunk(size_t bytes);
bool pv_valid_downstream_audio(const char* format, int sample_rate, int channels, int sample_width, size_t byte_length);
bool pv_binary_matches_metadata(size_t expected_bytes, size_t received_bytes);
uint32_t pv_retry_delay_seconds(unsigned attempt);
PvState pv_disconnect_state(bool endpoint_valid);
const char* pv_state_label(PvState state);
+167
View File
@@ -0,0 +1,167 @@
#include "websocket.h"
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <esp_log.h>
#include <esp_random.h>
#include <lwip/inet.h>
#include <lwip/sockets.h>
#define TAG "PipecatVoiceWs"
#define WS_HEADER_LIMIT 1024U
#define WS_CONTROL_LIMIT 125U
static int send_all(int fd, const uint8_t* data, size_t length) {
size_t sent = 0;
while (sent < length) {
int result = lwip_send(fd, data + sent, length - sent, 0);
if (result <= 0) return -1;
sent += (size_t)result;
}
return 0;
}
static int recv_all(int fd, uint8_t* data, size_t length) {
size_t received = 0;
while (received < length) {
int result = lwip_recv(fd, data + received, length - received, 0);
if (result <= 0) return -1;
received += (size_t)result;
}
return 0;
}
static int discard(int fd, uint64_t length) {
uint8_t buffer[256];
while (length > 0) {
size_t chunk = length > sizeof(buffer) ? sizeof(buffer) : (size_t)length;
if (recv_all(fd, buffer, chunk) < 0) return -1;
length -= chunk;
}
return 0;
}
static int send_frame(int fd, uint8_t opcode, const uint8_t* payload, size_t length) {
if (length > 65535U || ((opcode & 0x08U) && length > WS_CONTROL_LIMIT)) return -1;
uint8_t header[8];
size_t header_length = 2;
header[0] = 0x80U | opcode;
if (length < 126U) {
header[1] = 0x80U | (uint8_t)length;
} else {
header[1] = 0x80U | 126U;
header[2] = (uint8_t)(length >> 8U);
header[3] = (uint8_t)length;
header_length = 4;
}
uint8_t mask[4];
uint32_t random = esp_random();
memcpy(mask, &random, sizeof(mask));
memcpy(header + header_length, mask, sizeof(mask));
header_length += sizeof(mask);
if (send_all(fd, header, header_length) < 0) return -1;
uint8_t chunk[512];
size_t offset = 0;
while (offset < length) {
size_t count = length - offset > sizeof(chunk) ? sizeof(chunk) : length - offset;
for (size_t i = 0; i < count; ++i) chunk[i] = payload[offset + i] ^ mask[(offset + i) % sizeof(mask)];
if (send_all(fd, chunk, count) < 0) return -1;
offset += count;
}
return 0;
}
int ws_connect(const char* host, int port, const char* path, const char* device_id, const char* api_key) {
if (host == NULL || path == NULL || device_id == NULL || api_key == NULL || port < 1 || port > 65535) return -1;
int fd = lwip_socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0) {
ESP_LOGW(TAG, "socket create failed");
return -1;
}
struct sockaddr_in address = {0};
address.sin_family = AF_INET;
address.sin_port = htons((uint16_t)port);
address.sin_addr.s_addr = ipaddr_addr(host);
if (address.sin_addr.s_addr == IPADDR_NONE) {
ESP_LOGW(TAG, "endpoint address parse failed");
close(fd);
return -1;
}
if (lwip_connect(fd, (struct sockaddr*)&address, sizeof(address)) < 0) {
ESP_LOGW(TAG, "TCP connect failed");
close(fd);
return -1;
}
struct timeval timeout = {.tv_sec = 15, .tv_usec = 0};
lwip_setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
char request[WS_HEADER_LIMIT];
int request_length = snprintf(request, sizeof(request),
"GET %s HTTP/1.1\r\nHost: %s:%d\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
"Sec-WebSocket-Key: MDEyMzQ1Njc4OWFiY2RlZg==\r\nSec-WebSocket-Version: 13\r\n"
"Authorization: Bearer %s\r\nX-Device-ID: %s\r\n\r\n",
path, host, port, api_key, device_id);
if (request_length < 0 || (size_t)request_length >= sizeof(request) || send_all(fd, (const uint8_t*)request, (size_t)request_length) < 0) {
ESP_LOGW(TAG, "WebSocket upgrade request failed");
close(fd);
return -1;
}
char response[WS_HEADER_LIMIT];
size_t length = 0;
while (length + 1 < sizeof(response)) {
if (recv_all(fd, (uint8_t*)&response[length], 1) < 0) {
ESP_LOGW(TAG, "WebSocket upgrade response failed");
close(fd);
return -1;
}
response[++length] = '\0';
if (length >= 4 && memcmp(response + length - 4, "\r\n\r\n", 4) == 0) break;
}
if (length + 1 >= sizeof(response) || strstr(response, " 101 ") == NULL) {
ESP_LOGW(TAG, "WebSocket upgrade rejected");
close(fd);
return -1;
}
ESP_LOGI(TAG, "WebSocket upgrade accepted");
return fd;
}
int ws_send(int fd, const uint8_t* data, size_t length, bool binary) {
if (fd < 0 || data == NULL || length == 0) return -1;
return send_frame(fd, binary ? 0x02U : 0x01U, data, length);
}
int ws_recv(int fd, int* opcode, bool* final, uint8_t* payload, size_t maximum) {
uint8_t header[2];
if (fd < 0 || recv_all(fd, header, sizeof(header)) < 0) return -1;
uint64_t length = header[1] & 0x7fU;
if (length == 126U) {
uint8_t extended[2];
if (recv_all(fd, extended, sizeof(extended)) < 0) return -1;
length = ((uint64_t)extended[0] << 8U) | extended[1];
} else if (length == 127U) {
uint8_t extended[8];
if (recv_all(fd, extended, sizeof(extended)) < 0) return -1;
length = 0;
for (size_t i = 0; i < sizeof(extended); ++i) length = (length << 8U) | extended[i];
}
bool masked = (header[1] & 0x80U) != 0;
uint8_t mask[4] = {0};
if (masked && recv_all(fd, mask, sizeof(mask)) < 0) return -1;
uint8_t frame_opcode = header[0] & 0x0fU;
if (((frame_opcode & 0x08U) && (length > WS_CONTROL_LIMIT || !(header[0] & 0x80U))) || length > maximum) {
if (discard(fd, length) < 0) return -1;
return -2;
}
if (length > 0 && recv_all(fd, payload, (size_t)length) < 0) return -1;
if (masked) for (size_t i = 0; i < (size_t)length; ++i) payload[i] ^= mask[i % sizeof(mask)];
if (opcode) *opcode = frame_opcode;
if (final) *final = (header[0] & 0x80U) != 0;
return (int)length;
}
int ws_send_pong(int fd, const uint8_t* payload, size_t length) { return send_frame(fd, 0x0aU, payload, length); }
int ws_send_close(int fd) { return send_frame(fd, 0x08U, NULL, 0); }
void ws_close(int fd) { if (fd >= 0) close(fd); }
+62
View File
@@ -0,0 +1,62 @@
#pragma once
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Connect to a WebSocket server.
* @param host Server IP address (e.g. "192.168.68.126")
* @param port Port number (e.g. 8642)
* @param path WebSocket path (e.g. "/api/esp32/voice/ws")
* @param device_id Unique device identifier
* @param api_key Optional profile API key; never compiled into firmware
* @return Socket file descriptor on success, or -1 on failure
*/
int ws_connect(const char* host, int port, const char* path, const char* device_id, const char* api_key);
/**
* Send a WebSocket frame.
* @param fd Socket file descriptor
* @param data Data payload to send
* @param len Length of the data payload
* @param binary True for binary frame, false for text frame
* @return 0 on success, or -1 on failure
*/
int ws_send(int fd, const uint8_t* data, size_t len, bool binary);
/**
* Receive a WebSocket frame.
* @param fd Socket file descriptor
* @param out_opcode Pointer to store the received opcode (e.g. 0x01 text, 0x02 binary)
* @param payload Buffer to store the received payload
* @param max_len Maximum length of the payload buffer
* @return Received payload length on success, -1 on connection failure, or -2 on buffer overflow
*/
int ws_recv(int fd, int* out_opcode, bool* out_final, uint8_t* payload, size_t max_len);
/**
* Close a WebSocket connection.
* @param fd Socket file descriptor
*/
void ws_close(int fd);
/**
* Send a WebSocket PONG frame.
* @param fd Socket file descriptor
* @param payload Payload to reflect
* @param len Length of payload
* @return 0 on success, or -1 on failure
*/
int ws_send_pong(int fd, const uint8_t* payload, size_t len);
/** Send a clean WebSocket close control frame before closing the socket. */
int ws_send_close(int fd);
#ifdef __cplusplus
}
#endif
+7
View File
@@ -0,0 +1,7 @@
manifest.version=0.2
target.sdk=0.8.0-dev
target.platforms=esp32s3
app.id=one.tactility.pipecatvoice
app.version.name=1.0.0
app.version.code=1
app.name=Pipecat Voice
@@ -0,0 +1,52 @@
#include "voice_protocol.h"
#include <assert.h>
#include <stdio.h>
#include <string.h>
static void test_endpoint_validation(void) {
PvEndpoint endpoint;
assert(pv_parse_endpoint("ws://192.168.68.102:8644/api/esp32/voice/ws", &endpoint));
assert(strcmp(endpoint.host, "192.168.68.102") == 0);
assert(endpoint.port == 8644);
assert(strcmp(endpoint.path, "/api/esp32/voice/ws") == 0);
assert(!pv_parse_endpoint("ws://127.0.0.1:8642/api", &endpoint));
assert(!pv_parse_endpoint("ws://localhost:8642/api", &endpoint));
assert(!pv_parse_endpoint("wss://192.168.68.102/api", &endpoint));
assert(!pv_parse_endpoint("ws://192.168.68.102:0/api", &endpoint));
}
static void test_start_and_pcm_boundaries(void) {
char json[256];
assert(pv_make_start_json(json, sizeof(json), "session-01", "tactility-14c19d1a790"));
assert(strstr(json, "\"v\":1") != NULL);
assert(strstr(json, "\"pcm_s16le\"") != NULL);
assert(!pv_make_start_json(json, sizeof(json), "bad session", "device"));
assert(pv_valid_pcm_chunk(2));
assert(pv_valid_pcm_chunk(PV_PCM_CHUNK_MAX));
assert(!pv_valid_pcm_chunk(0));
assert(!pv_valid_pcm_chunk(3));
assert(!pv_valid_pcm_chunk(PV_PCM_CHUNK_MAX + 2));
assert(pv_valid_downstream_audio("pcm_s16le", 24000, 1, 2, 48000));
assert(!pv_valid_downstream_audio("wav", 24000, 1, 2, 48000));
assert(!pv_valid_downstream_audio("pcm_s16le", 24000, 2, 2, 48000));
assert(!pv_valid_downstream_audio("pcm_s16le", 24000, 1, 2, PV_DOWNSTREAM_MAX + 2));
assert(pv_binary_matches_metadata(48000, 48000));
assert(!pv_binary_matches_metadata(48000, 47998));
}
static void test_retry_and_state(void) {
const uint32_t expected[] = {1, 2, 4, 8, 16, 30, 30};
for (unsigned i = 0; i < sizeof(expected) / sizeof(expected[0]); ++i) assert(pv_retry_delay_seconds(i) == expected[i]);
assert(pv_disconnect_state(true) == PV_RECONNECTING);
assert(pv_disconnect_state(false) == PV_FAILED);
assert(strcmp(pv_state_label(PV_STREAMING), "STREAMING") == 0);
}
int main(void) {
test_endpoint_validation();
test_start_and_pcm_boundaries();
test_retry_and_state();
puts("voice_protocol tests passed");
return 0;
}
+9 -11
View File
@@ -1,11 +1,9 @@
[manifest] manifest.version=0.2
version=0.1 target.sdk=0.8.0-dev
[target] target.platforms=esp32s3,esp32p4
sdk=0.8.0-dev app.id=one.tactility.pocketdungeon
platforms=esp32s3,esp32p4 app.version.name=0.1.2
[app] app.version.code=3
id=one.tactility.pocketdungeon app.name=Pocket Dungeon
versionName=0.1.1 app.description=Tiny paper-inspired dungeon crawler - tutorial + fullscreen
versionCode=2 app.flags=HideStatusBar
name=Pocket Dungeon
description=Tiny paper-inspired dungeon crawler - audio-stream migrated
+208 -68
View File
@@ -1,24 +1,32 @@
#include <tt_app.h> #include <tt_app.h>
#include <tt_lvgl.h> #include <tt_lvgl.h>
#include <tt_lvgl_toolbar.h> #include <tt_lvgl_toolbar.h>
#include <tt_wifi.h>
#include <tactility/device.h> #include <tactility/device.h>
#include <tactility/drivers/i2s_controller.h> #include <tactility/drivers/audio_stream.h>
#include "websocket.h" #include "websocket.h"
#include <cJSON.h> #include <cJSON.h>
#include <string.h> #include <string.h>
#include <stdlib.h> #include <stdlib.h>
#include <stdio.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <errno.h> #include <errno.h>
/* Exported by Tactility firmware 0.8.0-dev; absent from the CDN SDK header. */
struct Device* device_find_by_name(const char* name);
#include "freertos/FreeRTOS.h" #include "freertos/FreeRTOS.h"
#include "freertos/task.h" #include "freertos/task.h"
#include "esp_log.h" #include "esp_log.h"
#include "esp_random.h"
#define TAG "ReynaBot" #define TAG "ReynaBot"
#define AUDIO_SAMPLE_RATE 16000U
#define AUDIO_BITS_PER_SAMPLE 16U
#define MAX_PCM_CHUNK_BYTES 16384U
#define MAX_RESPONSE_AUDIO_BYTES 65536U
typedef enum { typedef enum {
STATE_IDLE, STATE_IDLE,
@@ -64,10 +72,19 @@ typedef struct {
TaskHandle_t worker_task; TaskHandle_t worker_task;
TaskHandle_t rx_task; TaskHandle_t rx_task;
// Hardware // Hardware/audio service
struct Device* i2s_dev; struct Device* audio_stream_dev;
AudioStreamHandle input_handle;
// WebSocket AudioStreamHandle output_handle;
uint32_t output_sample_rate;
uint8_t output_channels;
uint8_t output_bits_per_sample;
bool output_stream_pending;
size_t expected_audio_bytes;
uint32_t expected_audio_rate;
uint8_t expected_audio_channels;
uint8_t expected_audio_bits;
bool stop_sent;
int ws_fd; int ws_fd;
bool ws_connected; bool ws_connected;
bool ws_done; bool ws_done;
@@ -81,6 +98,77 @@ static void reynabot_rx_task(void* arg);
static void update_ui(ReynaBotCtx* ctx); static void update_ui(ReynaBotCtx* ctx);
static void load_config(ReynaBotCtx* ctx); static void load_config(ReynaBotCtx* ctx);
static bool find_audio_stream_device(ReynaBotCtx* ctx) {
struct Device* dev = device_find_by_name("audio-stream");
if (dev != NULL) {
ctx->audio_stream_dev = dev;
return true;
}
// The 0.8.0-dev firmware registers this shared service by name. The
// CDN SDK headers do not expose the deprecated type-search helper, so do
// not reference it from a dynamically linked app.
return false;
}
static void close_input_stream(ReynaBotCtx* ctx) {
if (ctx->input_handle != NULL) {
audio_stream_close(ctx->input_handle);
ctx->input_handle = NULL;
}
}
static void close_output_stream(ReynaBotCtx* ctx) {
if (ctx->output_handle != NULL) {
audio_stream_close(ctx->output_handle);
ctx->output_handle = NULL;
}
ctx->output_stream_pending = false;
}
static bool open_input_stream(ReynaBotCtx* ctx) {
if (ctx->audio_stream_dev == NULL) return false;
close_input_stream(ctx);
struct AudioStreamConfig config = {
.sample_rate = 16000,
.bits_per_sample = 16,
.channels = 1,
};
error_t err = audio_stream_open_input(ctx->audio_stream_dev, &config, &ctx->input_handle);
if (err != ERROR_NONE) {
ctx->input_handle = NULL;
ESP_LOGE(TAG, "audio_stream_open_input failed: %d", err);
return false;
}
audio_stream_set_mute(ctx->audio_stream_dev, AUDIO_CODEC_DIR_INPUT, false);
audio_stream_set_volume(ctx->audio_stream_dev, AUDIO_CODEC_DIR_INPUT, 100.0f);
ESP_LOGI(TAG, "Microphone opened via audio-stream at 16000 Hz mono");
return true;
}
static bool open_output_stream(ReynaBotCtx* ctx, uint32_t sample_rate, uint8_t channels, uint8_t bits_per_sample) {
if (ctx->audio_stream_dev == NULL || sample_rate == 0 || channels == 0 || bits_per_sample != 16) return false;
close_output_stream(ctx);
struct AudioStreamConfig config = {
.sample_rate = sample_rate,
.bits_per_sample = bits_per_sample,
.channels = channels,
};
error_t err = audio_stream_open_output(ctx->audio_stream_dev, &config, &ctx->output_handle);
if (err != ERROR_NONE) {
ctx->output_handle = NULL;
ESP_LOGE(TAG, "audio_stream_open_output failed: %d rate=%u ch=%u", err, (unsigned)sample_rate, channels);
return false;
}
audio_stream_set_mute(ctx->audio_stream_dev, AUDIO_CODEC_DIR_OUTPUT, false);
audio_stream_set_volume(ctx->audio_stream_dev, AUDIO_CODEC_DIR_OUTPUT, 100.0f);
ctx->output_sample_rate = sample_rate;
ctx->output_channels = channels;
ctx->output_bits_per_sample = bits_per_sample;
ctx->output_stream_pending = true;
ESP_LOGI(TAG, "Speaker opened via audio-stream at %u Hz mono", (unsigned)sample_rate);
return true;
}
/* ─── Helper for URL parsing ─── */ /* ─── Helper for URL parsing ─── */
static bool parse_ws_url(const char* url, char* host, int* port, char* path) { static bool parse_ws_url(const char* url, char* host, int* port, char* path) {
if (strncmp(url, "ws://", 5) != 0) return false; if (strncmp(url, "ws://", 5) != 0) return false;
@@ -111,9 +199,9 @@ static bool parse_ws_url(const char* url, char* host, int* port, char* path) {
/* ─── Config Loading/Saving ─── */ /* ─── Config Loading/Saving ─── */
static void load_config(ReynaBotCtx* ctx) { static void load_config(ReynaBotCtx* ctx) {
// Default fallback config // Default fallback config
snprintf(ctx->server_url, sizeof(ctx->server_url), "ws://192.168.68.126:8643/api/esp32/voice/ws"); snprintf(ctx->server_url, sizeof(ctx->server_url), "ws://192.168.68.112:8643/api/esp32/voice/ws");
snprintf(ctx->device_id, sizeof(ctx->device_id), "reynabot_screen"); snprintf(ctx->device_id, sizeof(ctx->device_id), "reynabot_screen");
snprintf(ctx->api_key, sizeof(ctx->api_key), "hmek_sXB7921bZ9FXTVKARExqUZ7ttBxtEoURHRU0JCB-gNY"); ctx->api_key[0] = '\0';
char path[256]; char path[256];
size_t path_size = sizeof(path); size_t path_size = sizeof(path);
@@ -130,7 +218,7 @@ static void load_config(ReynaBotCtx* ctx) {
// Write default config file // Write default config file
file = fopen(path, "w"); file = fopen(path, "w");
if (file != NULL) { if (file != NULL) {
fprintf(file, "{\n \"server_url\": \"ws://192.168.68.126:8643/api/esp32/voice/ws\",\n \"device_id\": \"reynabot_screen\",\n \"api_key\": \"mcT1YA1vOr9wXSiHpCYalweEGGZKX-PIfZv2drp8BSg\"\n}\n"); fprintf(file, "{\n \"server_url\": \"ws://192.168.68.112:8643/api/esp32/voice/ws\",\n \"device_id\": \"reynabot_screen\",\n \"api_key\": \"\"\n}\n");
fclose(file); fclose(file);
} }
ESP_LOGI(TAG, "Created default config.json at %s", path); ESP_LOGI(TAG, "Created default config.json at %s", path);
@@ -181,6 +269,21 @@ static void parse_json_message(ReynaBotCtx* ctx, const char* json_str) {
if (strcmp(evt, "ready") == 0) { if (strcmp(evt, "ready") == 0) {
ESP_LOGI(TAG, "Server ready"); ESP_LOGI(TAG, "Server ready");
} else if (strcmp(evt, "state") == 0) {
cJSON* state_item = cJSON_GetObjectItem(json, "state");
if (state_item != NULL && cJSON_IsString(state_item)) {
if (strcmp(state_item->valuestring, "listening") == 0) {
if (ctx->stop_sent) {
ctx->ws_done = true;
} else {
ctx->state = STATE_LISTENING;
}
ctx->ui_update_pending = true;
} else if (strcmp(state_item->valuestring, "processing") == 0) {
ctx->state = STATE_THINKING;
ctx->ui_update_pending = true;
}
}
} else if (strcmp(evt, "listening") == 0) { } else if (strcmp(evt, "listening") == 0) {
ctx->state = STATE_LISTENING; ctx->state = STATE_LISTENING;
ctx->ui_update_pending = true; ctx->ui_update_pending = true;
@@ -199,11 +302,42 @@ static void parse_json_message(ReynaBotCtx* ctx, const char* json_str) {
strncpy(ctx->last_response, txt_item->valuestring, sizeof(ctx->last_response) - 1); strncpy(ctx->last_response, txt_item->valuestring, sizeof(ctx->last_response) - 1);
ctx->ui_update_pending = true; ctx->ui_update_pending = true;
} }
} else if (strcmp(evt, "audio") == 0) {
cJSON* format_item = cJSON_GetObjectItem(json, "format");
cJSON* rate_item = cJSON_GetObjectItem(json, "sample_rate");
cJSON* channels_item = cJSON_GetObjectItem(json, "channels");
cJSON* width_item = cJSON_GetObjectItem(json, "sample_width");
cJSON* length_item = cJSON_GetObjectItem(json, "byte_length");
bool valid = format_item != NULL && cJSON_IsString(format_item) &&
strcmp(format_item->valuestring, "pcm_s16le") == 0 &&
rate_item != NULL && cJSON_IsNumber(rate_item) && rate_item->valueint > 0 && rate_item->valueint <= 48000 &&
channels_item != NULL && cJSON_IsNumber(channels_item) && channels_item->valueint == 1 &&
width_item != NULL && cJSON_IsNumber(width_item) && width_item->valueint == 2 &&
length_item != NULL && cJSON_IsNumber(length_item) && length_item->valueint > 0 &&
length_item->valueint <= MAX_RESPONSE_AUDIO_BYTES && (length_item->valueint % 2) == 0;
if (valid) {
ctx->expected_audio_rate = (uint32_t)rate_item->valueint;
ctx->expected_audio_channels = (uint8_t)channels_item->valueint;
ctx->expected_audio_bits = (uint8_t)width_item->valueint;
ctx->expected_audio_bytes = (size_t)length_item->valueint;
if (!open_output_stream(ctx, ctx->expected_audio_rate, ctx->expected_audio_channels, ctx->expected_audio_bits)) {
snprintf(ctx->error_message, sizeof(ctx->error_message), "Audio output unavailable");
ctx->state = STATE_ERROR;
ctx->expected_audio_bytes = 0;
} else {
ctx->state = STATE_SPEAKING;
}
ctx->ui_update_pending = true;
} else {
snprintf(ctx->error_message, sizeof(ctx->error_message), "Invalid audio metadata");
ctx->state = STATE_ERROR;
ctx->expected_audio_bytes = 0;
ctx->ui_update_pending = true;
}
} else if (strcmp(evt, "audio_start") == 0) { } else if (strcmp(evt, "audio_start") == 0) {
/* Legacy event: metadata must still arrive as `audio` before binary PCM. */
ctx->state = STATE_SPEAKING; ctx->state = STATE_SPEAKING;
ctx->ui_update_pending = true; ctx->ui_update_pending = true;
// I2S is already configured globally at session startup
} else if (strcmp(evt, "audio_end") == 0) { } else if (strcmp(evt, "audio_end") == 0) {
ESP_LOGI(TAG, "Audio response ended"); ESP_LOGI(TAG, "Audio response ended");
} else if (strcmp(evt, "done") == 0) { } else if (strcmp(evt, "done") == 0) {
@@ -225,7 +359,7 @@ static void parse_json_message(ReynaBotCtx* ctx, const char* json_str) {
/* ─── WebSocket RX (Receive) Task ─── */ /* ─── WebSocket RX (Receive) Task ─── */
static void reynabot_rx_task(void* arg) { static void reynabot_rx_task(void* arg) {
ReynaBotCtx* ctx = (ReynaBotCtx*)arg; ReynaBotCtx* ctx = (ReynaBotCtx*)arg;
uint8_t* rx_buf = malloc(8192); uint8_t* rx_buf = malloc(MAX_RESPONSE_AUDIO_BYTES + 1U);
if (rx_buf == NULL) { if (rx_buf == NULL) {
ESP_LOGE(TAG, "Failed to allocate RX buffer"); ESP_LOGE(TAG, "Failed to allocate RX buffer");
ctx->ws_done = true; ctx->ws_done = true;
@@ -238,7 +372,7 @@ static void reynabot_rx_task(void* arg) {
ESP_LOGI(TAG, "WS Receive task started"); ESP_LOGI(TAG, "WS Receive task started");
while (ctx->ws_fd >= 0) { while (ctx->ws_fd >= 0) {
int r = ws_recv(ctx->ws_fd, &opcode, rx_buf, 8191); int r = ws_recv(ctx->ws_fd, &opcode, rx_buf, MAX_RESPONSE_AUDIO_BYTES);
if (r < 0) { if (r < 0) {
if (r == -1) { if (r == -1) {
ESP_LOGI(TAG, "WS connection closed or read error, errno=%d", errno); ESP_LOGI(TAG, "WS connection closed or read error, errno=%d", errno);
@@ -252,21 +386,31 @@ static void reynabot_rx_task(void* arg) {
if (opcode == 0x01) { // Text frame (JSON) if (opcode == 0x01) { // Text frame (JSON)
rx_buf[r] = '\0'; rx_buf[r] = '\0';
parse_json_message(ctx, (char*)rx_buf); parse_json_message(ctx, (char*)rx_buf);
} else if (opcode == 0x02) { // Binary frame (Audio data) } else if (opcode == 0x02) { // Audio response PCM
if (ctx->state == STATE_SPEAKING && ctx->i2s_dev != NULL) { if (ctx->output_handle == NULL || ctx->expected_audio_bytes == 0 || (size_t)r != ctx->expected_audio_bytes) {
const uint8_t* payload_ptr = rx_buf; ESP_LOGE(TAG, "Audio frame does not match metadata: got=%d expected=%u", r, (unsigned)ctx->expected_audio_bytes);
size_t payload_len = r; ctx->state = STATE_ERROR;
snprintf(ctx->error_message, sizeof(ctx->error_message), "Invalid audio frame");
// Skip WAV header if present in the first chunk ctx->ui_update_pending = true;
if (payload_len > 44 && memcmp(payload_ptr, "RIFF", 4) == 0) { } else {
payload_ptr += 44; size_t written_total = 0;
payload_len -= 44; while (written_total < (size_t)r) {
}
size_t written = 0; size_t written = 0;
device_lock(ctx->i2s_dev); error_t err = audio_stream_write(ctx->output_handle, rx_buf + written_total,
i2s_controller_write(ctx->i2s_dev, payload_ptr, payload_len, &written, pdMS_TO_TICKS(100)); (size_t)r - written_total, &written, pdMS_TO_TICKS(3000));
device_unlock(ctx->i2s_dev); if (err != ERROR_NONE || written == 0) {
ESP_LOGE(TAG, "audio_stream_write failed: %d written=%u", err, (unsigned)written);
ctx->state = STATE_ERROR;
snprintf(ctx->error_message, sizeof(ctx->error_message), "Audio playback failed");
ctx->ui_update_pending = true;
break;
}
written_total += written;
}
close_output_stream(ctx);
ctx->expected_audio_bytes = 0;
ctx->state = STATE_THINKING;
ctx->ui_update_pending = true;
} }
} else if (opcode == 0x09) { // PING frame } else if (opcode == 0x09) { // PING frame
ESP_LOGI(TAG, "WS PING received, sending PONG"); ESP_LOGI(TAG, "WS PING received, sending PONG");
@@ -408,8 +552,11 @@ static void reynabot_task(void* arg) {
ctx->start_session = false; ctx->start_session = false;
ctx->stop_session = false; ctx->stop_session = false;
ctx->cancel_session = false; ctx->cancel_session = false;
ctx->stop_sent = false;
ctx->expected_audio_bytes = 0;
close_input_stream(ctx);
close_output_stream(ctx);
ctx->state = STATE_CONNECTING;
ctx->last_transcript[0] = '\0'; ctx->last_transcript[0] = '\0';
ctx->last_response[0] = '\0'; ctx->last_response[0] = '\0';
ctx->error_message[0] = '\0'; ctx->error_message[0] = '\0';
@@ -435,28 +582,17 @@ static void reynabot_task(void* arg) {
ctx->ws_fd = fd; ctx->ws_fd = fd;
ctx->ws_connected = true; ctx->ws_connected = true;
// Configure I2S on demand for this session (16 kHz, 16-bit, mono) // Spawn background RX task to read and parse events.
struct I2sConfig session_cfg = {
.communication_format = I2S_FORMAT_STAND_I2S,
.sample_rate = 16000,
.bits_per_sample = 16,
.channel_left = 0,
.channel_right = I2S_CHANNEL_NONE
};
if (ctx->i2s_dev != NULL) {
device_lock(ctx->i2s_dev);
i2s_controller_set_config(ctx->i2s_dev, &session_cfg);
device_unlock(ctx->i2s_dev);
}
// Spawn background RX task to read and parse events
xTaskCreate(reynabot_rx_task, "reynabot_rx", 4096, ctx, 6, &ctx->rx_task); xTaskCreate(reynabot_rx_task, "reynabot_rx", 4096, ctx, 6, &ctx->rx_task);
// Send start event handshake // The Kids LAN adapter requires protocol v1 and a fresh session id.
char start_json[256]; char session_id[80];
snprintf(session_id, sizeof(session_id), "reynabot-%08x%08x",
(unsigned)esp_random(), (unsigned)esp_random());
char start_json[384];
snprintf(start_json, sizeof(start_json), snprintf(start_json, sizeof(start_json),
"{\"event\":\"start\",\"device_id\":\"%s\",\"sample_rate\":16000,\"channels\":1,\"sample_width\":2,\"format\":\"pcm_s16le\"}", "{\"v\":1,\"event\":\"start\",\"session_id\":\"%s\",\"device_id\":\"%s\",\"audio\":{\"format\":\"pcm_s16le\",\"sample_rate\":16000,\"channels\":1,\"sample_width\":2}}",
ctx->device_id); session_id, ctx->device_id);
if (ws_send(ctx->ws_fd, (const uint8_t*)start_json, strlen(start_json), false) < 0) { if (ws_send(ctx->ws_fd, (const uint8_t*)start_json, strlen(start_json), false) < 0) {
ctx->state = STATE_ERROR; ctx->state = STATE_ERROR;
snprintf(ctx->error_message, sizeof(ctx->error_message), "Handshake send failed"); snprintf(ctx->error_message, sizeof(ctx->error_message), "Handshake send failed");
@@ -486,11 +622,20 @@ static void reynabot_task(void* arg) {
continue; continue;
} }
// I2S is already configured globally at session startup if (!open_input_stream(ctx)) {
ctx->state = STATE_ERROR;
snprintf(ctx->error_message, sizeof(ctx->error_message), "Microphone unavailable");
ws_close(ctx->ws_fd);
ctx->ws_fd = -1;
ctx->ws_connected = false;
update_ui(ctx);
continue;
}
uint8_t* buffer = malloc(1024); uint8_t* buffer = malloc(MAX_PCM_CHUNK_BYTES);
if (buffer == NULL) { if (buffer == NULL) {
ESP_LOGE(TAG, "Failed to allocate record buffer"); ESP_LOGE(TAG, "Failed to allocate record buffer");
close_input_stream(ctx);
ctx->state = STATE_ERROR; ctx->state = STATE_ERROR;
snprintf(ctx->error_message, sizeof(ctx->error_message), "Out of memory"); snprintf(ctx->error_message, sizeof(ctx->error_message), "Out of memory");
ws_close(ctx->ws_fd); ws_close(ctx->ws_fd);
@@ -501,11 +646,12 @@ static void reynabot_task(void* arg) {
} }
size_t total_sent_bytes = 0; size_t total_sent_bytes = 0;
// Stream audio loop while PTT is held // Stream 16 kHz mono PCM while PTT is held.
while (ctx->is_pressed && !ctx->stop_session && !ctx->cancel_session && !ctx->ws_done && total_sent_bytes < 320000) { while (ctx->is_pressed && !ctx->stop_session && !ctx->cancel_session && !ctx->ws_done && total_sent_bytes < 320000) {
size_t bytes_read = 0; size_t bytes_read = 0;
error_t r = i2s_controller_read(ctx->i2s_dev, buffer, 1024, &bytes_read, pdMS_TO_TICKS(100)); error_t r = audio_stream_read(ctx->input_handle, buffer, MAX_PCM_CHUNK_BYTES,
if (r == ERROR_NONE && bytes_read > 0) { &bytes_read, pdMS_TO_TICKS(200));
if (r == ERROR_NONE && bytes_read > 0 && bytes_read <= MAX_PCM_CHUNK_BYTES && (bytes_read % 2U) == 0) {
if (ws_send(ctx->ws_fd, buffer, bytes_read, true) < 0) { if (ws_send(ctx->ws_fd, buffer, bytes_read, true) < 0) {
ESP_LOGE(TAG, "Audio stream send failed"); ESP_LOGE(TAG, "Audio stream send failed");
break; break;
@@ -514,16 +660,19 @@ static void reynabot_task(void* arg) {
} }
} }
close_input_stream(ctx);
free(buffer); free(buffer);
if (ctx->cancel_session || total_sent_bytes < 3200) { if (ctx->cancel_session || total_sent_bytes < 3200) {
ESP_LOGI(TAG, "Cancelling audio session"); ESP_LOGI(TAG, "Cancelling audio session");
const char* cancel_json = "{\"event\":\"cancel\"}"; const char* cancel_json = "{\"event\":\"cancel\"}";
ws_send(ctx->ws_fd, (const uint8_t*)cancel_json, strlen(cancel_json), false); ws_send(ctx->ws_fd, (const uint8_t*)cancel_json, strlen(cancel_json), false);
ctx->stop_sent = true;
ctx->state = STATE_IDLE; ctx->state = STATE_IDLE;
} else { } else {
const char* stop_json = "{\"event\":\"stop\"}"; const char* stop_json = "{\"event\":\"stop\"}";
ws_send(ctx->ws_fd, (const uint8_t*)stop_json, strlen(stop_json), false); ws_send(ctx->ws_fd, (const uint8_t*)stop_json, strlen(stop_json), false);
ctx->stop_sent = true;
ctx->state = STATE_THINKING; ctx->state = STATE_THINKING;
update_ui(ctx); update_ui(ctx);
@@ -550,12 +699,8 @@ static void reynabot_task(void* arg) {
ctx->ws_connected = false; ctx->ws_connected = false;
ws_close(fd_to_close); ws_close(fd_to_close);
// Reset I2S controller to release DMA and stop white noise close_input_stream(ctx);
if (ctx->i2s_dev != NULL) { close_output_stream(ctx);
device_lock(ctx->i2s_dev);
i2s_controller_reset(ctx->i2s_dev);
device_unlock(ctx->i2s_dev);
}
// Wait for receive task to exit // Wait for receive task to exit
int rx_timeout = 100; int rx_timeout = 100;
@@ -611,10 +756,9 @@ static void on_show(AppHandle app, void* data, lv_obj_t* parent) {
load_config(ctx); load_config(ctx);
// Find I2S controller // Find the firmware Audio System service; it owns codec/native-rate conversion.
ctx->i2s_dev = device_find_by_name("i2s0"); if (!find_audio_stream_device(ctx)) {
if (ctx->i2s_dev == NULL) { ESP_LOGE(TAG, "audio-stream device not found!");
ESP_LOGE(TAG, "I2S controller 'i2s0' not found!");
} }
// Style the parent screen // Style the parent screen
@@ -800,12 +944,8 @@ static void on_hide(AppHandle app, void* data) {
ws_close(fd_to_close); ws_close(fd_to_close);
} }
// Reset I2S controller to stop DMA and looping noise close_input_stream(ctx);
if (ctx->i2s_dev != NULL) { close_output_stream(ctx);
device_lock(ctx->i2s_dev);
i2s_controller_reset(ctx->i2s_dev);
device_unlock(ctx->i2s_dev);
}
// Wait briefly for tasks to exit // Wait briefly for tasks to exit
int timeout = 100; int timeout = 100;
+2 -2
View File
@@ -56,8 +56,8 @@ int ws_connect(const char* host, int port, const char* path, const char* device_
"Connection: Upgrade\r\n" "Connection: Upgrade\r\n"
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n" "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
"Sec-WebSocket-Version: 13\r\n" "Sec-WebSocket-Version: 13\r\n"
"Authorization: Bearer %s\r\n" "Authorization: Bearer %s\\r\\n"
"X-Device-ID: %s\r\n" "X-Device-ID: %s\\r\\n"
"\r\n", "\r\n",
path, host, port, auth_key, device_id); path, host, port, auth_key, device_id);
+2 -2
View File
@@ -10,8 +10,8 @@ extern "C" {
/** /**
* Connect to a WebSocket server. * Connect to a WebSocket server.
* @param host Server IP address (e.g. "192.168.68.126") * @param host Server IP address (for example, the Mac LAN host 192.168.68.112)
* @param port Port number (e.g. 8642) * @param port Port number (e.g. 8643 for the Kids gateway)
* @param path WebSocket path (e.g. "/api/esp32/voice/ws") * @param path WebSocket path (e.g. "/api/esp32/voice/ws")
* @param device_id Unique device identifier * @param device_id Unique device identifier
* @param auth_key Hermes Bearer API key * @param auth_key Hermes Bearer API key
+7 -10
View File
@@ -1,10 +1,7 @@
[manifest] manifest.version=0.2
version=0.1 target.sdk=0.8.0-dev
[target] target.platforms=esp32s3
sdk=0.7.0-dev app.id=one.tactility.reynabot
platforms=esp32s3 app.version.name=1.0.0
[app] app.version.code=1
id=one.tactility.reynabot app.name=ReynaBot
versionName=1.0.0
versionCode=1
name=ReynaBot
+173 -79
View File
@@ -1,6 +1,7 @@
#include <tt_app.h> #include <tt_app.h>
#include <tt_lvgl_toolbar.h> #include <tt_lvgl_toolbar.h>
#include <tactility/lvgl_fonts.h> #include <tactility/lvgl_fonts.h>
#include <tt_mdns.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <stdio.h> #include <stdio.h>
@@ -8,10 +9,8 @@
#include <unistd.h> #include <unistd.h>
#include <lwip/sockets.h> #include <lwip/sockets.h>
#include <lwip/inet.h> #include <lwip/inet.h>
#include "esp_log.h"
#define TAG "RobotArm" #define TAG "RobotArm"
#define ARM_HOST "192.168.68.103"
#define ARM_PORT 80 #define ARM_PORT 80
#define ARM_PATH "/api/mcp" #define ARM_PATH "/api/mcp"
#define NUM_JOINTS 6 #define NUM_JOINTS 6
@@ -41,68 +40,68 @@ static int seq_len = 0, seq_idx = -1;
static bool seq_playing = false; static bool seq_playing = false;
static int seq_play_pos = 0; static int seq_play_pos = 0;
static char arm_host[64] = "";
static bool arm_connected = false;
typedef struct { typedef struct {
AppHandle app; AppHandle app;
lv_obj_t* root;
lv_obj_t* content; // scrollable column container
lv_obj_t* status; lv_obj_t* status;
lv_obj_t* sliders[6]; lv_obj_t* sliders[6];
lv_obj_t* vals[6]; lv_obj_t* vals[6];
lv_obj_t* seq_label; lv_obj_t* seq_label;
lv_obj_t* play_label; lv_obj_t* play_label;
lv_obj_t* blocks[SEQ_MAX]; lv_obj_t* blocks[SEQ_MAX];
lv_obj_t* connect_box;
lv_obj_t* main_box;
lv_obj_t* connect_label;
lv_obj_t* connect_spinner;
int pend[6]; int pend[6];
bool has[6]; bool has[6];
int ticks[6]; int ticks[6];
lv_timer_t* poll; lv_timer_t* poll;
lv_timer_t* seq_timer; lv_timer_t* seq_timer;
lv_timer_t* connect_timer;
int connect_attempts;
} Ctx; } Ctx;
static Ctx* g = NULL; static Ctx* g = NULL;
static uint16_t my_htons(uint16_t v){ return (v<<8)|(v>>8); } static uint16_t my_htons(uint16_t v){ return (v<<8)|(v>>8); }
static int http_post(const char* host,int port,const char* path,const char* body,char* out,size_t olen){ static int http_post(const char* host,int port,const char* path,const char* body,char* out,size_t olen){
uint32_t ip=ipaddr_addr(host);
if(ip==0 || ip==0xFFFFFFFF) return -2;
int fd=lwip_socket(AF_INET,SOCK_STREAM,0); int fd=lwip_socket(AF_INET,SOCK_STREAM,0);
if(fd<0) return -1; if(fd<0) return -1;
struct sockaddr_in s; memset(&s,0,sizeof(s)); struct sockaddr_in s; memset(&s,0,sizeof(s));
s.sin_family=AF_INET; s.sin_port=my_htons(port); s.sin_addr.s_addr=ipaddr_addr(host); s.sin_family=AF_INET; s.sin_port=my_htons(port); s.sin_addr.s_addr=ip;
struct timeval tv={5,0}; struct timeval tv={2,0};
lwip_setsockopt(fd,SOL_SOCKET,SO_RCVTIMEO,&tv,sizeof(tv)); lwip_setsockopt(fd,SOL_SOCKET,SO_RCVTIMEO,&tv,sizeof(tv));
lwip_setsockopt(fd,SOL_SOCKET,SO_SNDTIMEO,&tv,sizeof(tv)); lwip_setsockopt(fd,SOL_SOCKET,SO_SNDTIMEO,&tv,sizeof(tv));
if(lwip_connect(fd,(struct sockaddr*)&s,sizeof(s))<0){close(fd);return -2;} if(lwip_connect(fd,(struct sockaddr*)&s,sizeof(s))<0){close(fd);return -2;}
char hdr[256]; char hdr[256]; int bl=strlen(body);
int bl=strlen(body);
int hl=snprintf(hdr,sizeof(hdr),"POST %s HTTP/1.1\r\nHost: %s:%d\r\nContent-Type: application/json\r\nContent-Length: %d\r\nConnection: close\r\n\r\n",path,host,port,bl); int hl=snprintf(hdr,sizeof(hdr),"POST %s HTTP/1.1\r\nHost: %s:%d\r\nContent-Type: application/json\r\nContent-Length: %d\r\nConnection: close\r\n\r\n",path,host,port,bl);
if(lwip_send(fd,hdr,hl,0)<0){close(fd);return -3;} if(lwip_send(fd,hdr,hl,0)<0){close(fd);return -3;}
if(lwip_send(fd,body,bl,0)<0){close(fd);return -3;} if(lwip_send(fd,body,bl,0)<0){close(fd);return -3;}
int tot=0; int tot=0; while(tot<(int)olen-1){int r=lwip_recv(fd,out+tot,olen-1-tot,0); if(r<=0) break; tot+=r;}
while(tot<(int)olen-1){int r=lwip_recv(fd,out+tot,olen-1-tot,0); if(r<=0) break; tot+=r;}
out[tot]='\0'; close(fd); out[tot]='\0'; close(fd);
char* bp=strstr(out,"\r\n\r\n"); if(bp){bp+=4; memmove(out,bp,strlen(bp)+1);} char* bp=strstr(out,"\r\n\r\n"); if(bp){bp+=4; memmove(out,bp,strlen(bp)+1);}
return tot>0?0:-4; return tot>0?0:-4;
} }
static bool jget(const char* js,const char* key,int* out){ static bool jget(const char* js,const char* key,int* out){
const char* p=strstr(js,key); const char* p=strstr(js,key); if(!p) return false;
if(!p) return false; p+=strlen(key); while(*p && *p!=':'){p++; if(!*p) return false;} p++;
p+=strlen(key);
while(*p && *p!=':'){
p++;
if(!*p) return false;
}
p++;
while(*p && (*p==' '||*p=='\t'||*p=='"'||*p=='\\')) p++; while(*p && (*p==' '||*p=='\t'||*p=='"'||*p=='\\')) p++;
int sign=1; int sign=1; if(*p=='-'){sign=-1;p++;}
if(*p=='-'){sign=-1;p++;} float v=0,frac=0.1f; bool dot=false,got=false;
float v=0,frac=0.1f;
bool dot=false,got=false;
while(*p){ while(*p){
if(*p>='0'&&*p<='9'){got=true; if(!dot) v=v*10+(*p-'0'); else {v+=(*p-'0')*frac; frac*=0.1f;}} if(*p>='0'&&*p<='9'){got=true; if(!dot) v=v*10+(*p-'0'); else {v+=(*p-'0')*frac; frac*=0.1f;}}
else if(*p=='.'&&!dot) dot=true; else if(*p=='.'&&!dot) dot=true; else break; p++;
else break;
p++;
} }
if(!got) return false; if(!got) return false;
*out=(int)(v*sign+0.5f); *out=(int)(v*sign+0.5f); return true;
return true;
} }
static bool parse_state(const char* r,int* b,int* s,int* e,int* p,int* ro,int* gr){ static bool parse_state(const char* r,int* b,int* s,int* e,int* p,int* ro,int* gr){
int v; bool ok=true; int v; bool ok=true;
@@ -117,30 +116,24 @@ static bool parse_state(const char* r,int* b,int* s,int* e,int* p,int* ro,int* g
static bool rpc_get(int* b,int* s,int* e,int* p,int* ro,int* gr){ static bool rpc_get(int* b,int* s,int* e,int* p,int* ro,int* gr){
const char* body="{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"get_arm_state\",\"arguments\":{}}}"; const char* body="{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"get_arm_state\",\"arguments\":{}}}";
char resp[2048]; memset(resp,0,sizeof(resp)); char resp[2048]; memset(resp,0,sizeof(resp));
if(http_post(ARM_HOST,ARM_PORT,ARM_PATH,body,resp,sizeof(resp))!=0) return false; if(http_post(arm_host,ARM_PORT,ARM_PATH,body,resp,sizeof(resp))!=0) return false;
return parse_state(resp,b,s,e,p,ro,gr); return parse_state(resp,b,s,e,p,ro,gr);
} }
static bool rpc_move(const char* j,int a){ static bool rpc_move(const char* j,int a){
char body[300]; snprintf(body,sizeof(body), char body[300]; snprintf(body,sizeof(body),
"{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{\"name\":\"move_joint\",\"arguments\":{\"joint\":\"%s\",\"angle\":%d,\"duration\":0.5}}}", "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{\"name\":\"move_joint\",\"arguments\":{\"joint\":\"%s\",\"angle\":%d,\"duration\":0.5}}}",j,a);
j,a); char r[1024]; memset(r,0,sizeof(r)); return http_post(arm_host,ARM_PORT,ARM_PATH,body,r,sizeof(r))==0;
char r[1024]; memset(r,0,sizeof(r));
return http_post(ARM_HOST,ARM_PORT,ARM_PATH,body,r,sizeof(r))==0;
} }
static bool rpc_move_all(int b,int s,int e,int p,int ro,int gr,float dur){ static bool rpc_move_all(int b,int s,int e,int p,int ro,int gr,float dur){
char body[420]; snprintf(body,sizeof(body), char body[420]; snprintf(body,sizeof(body),
"{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"move_all_joints\",\"arguments\":{\"base\":%d,\"shoulder\":%d,\"elbow\":%d,\"pitch\":%d,\"roll\":%d,\"gripper\":%d,\"duration\":%.1f}}}", "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"move_all_joints\",\"arguments\":{\"base\":%d,\"shoulder\":%d,\"elbow\":%d,\"pitch\":%d,\"roll\":%d,\"gripper\":%d,\"duration\":%.1f}}}",
b,s,e,p,ro,gr,dur); b,s,e,p,ro,gr,dur);
char r[1024]; memset(r,0,sizeof(r)); char r[1024]; memset(r,0,sizeof(r)); return http_post(arm_host,ARM_PORT,ARM_PATH,body,r,sizeof(r))==0;
int rc=http_post(ARM_HOST,ARM_PORT,ARM_PATH,body,r,sizeof(r));
ESP_LOGI(TAG,"move_all %d %d %d rc=%d",b,s,e,rc);
return rc==0;
} }
static bool rpc_home(void){ static bool rpc_home(void){
const char* b="{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"home_arm\",\"arguments\":{\"duration\":1.0}}}"; const char* b="{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"home_arm\",\"arguments\":{\"duration\":1.0}}}";
char r[512]; memset(r,0,sizeof(r)); return http_post(ARM_HOST,ARM_PORT,ARM_PATH,b,r,sizeof(r))==0; char r[512]; memset(r,0,sizeof(r)); return http_post(arm_host,ARM_PORT,ARM_PATH,b,r,sizeof(r))==0;
} }
static void set_status(const char* t){ if(g&&g->status) lv_label_set_text(g->status,t); } static void set_status(const char* t){ if(g&&g->status) lv_label_set_text(g->status,t); }
static void apply_ui(void){ static void apply_ui(void){
if(!g) return; if(!g) return;
@@ -150,7 +143,7 @@ static void apply_ui(void){
} }
} }
static void refresh_arm(void){ static void refresh_arm(void){
set_status("Reading .103..."); set_status("Reading...");
int b,s,e,p,ro,gr; int b,s,e,p,ro,gr;
if(rpc_get(&b,&s,&e,&p,&ro,&gr)){ if(rpc_get(&b,&s,&e,&p,&ro,&gr)){
joints[0].value=b; joints[1].value=s; joints[2].value=e; joints[0].value=b; joints[1].value=s; joints[2].value=e;
@@ -158,21 +151,21 @@ static void refresh_arm(void){
for(int i=0;i<NUM_JOINTS;i++){joints[i].last_sent=joints[i].value; if(g){g->pend[i]=joints[i].value; g->has[i]=false; g->ticks[i]=0;}} for(int i=0;i<NUM_JOINTS;i++){joints[i].last_sent=joints[i].value; if(g){g->pend[i]=joints[i].value; g->has[i]=false; g->ticks[i]=0;}}
apply_ui(); apply_ui();
char buf[32]; snprintf(buf,sizeof(buf),"B%d S%d E%d",b,s,e); set_status(buf); char buf[32]; snprintf(buf,sizeof(buf),"B%d S%d E%d",b,s,e); set_status(buf);
} else set_status("No .103"); } else set_status("No arm");
} }
static void del_ref_cb(lv_timer_t* t){ lv_timer_delete(t); refresh_arm(); } static void del_ref_cb(lv_timer_t* t){ lv_timer_delete(t); refresh_arm(); }
static void init_cb(lv_timer_t* t){ lv_timer_delete(t); refresh_arm(); } static void init_cb(lv_timer_t* t){ lv_timer_delete(t); refresh_arm(); }
static void poll_cb(lv_timer_t* t){ static void poll_cb(lv_timer_t* t){
(void)t; if(!g) return; (void)t; if(!g || !arm_connected) return;
for(int i=0;i<NUM_JOINTS;i++){ for(int i=0;i<NUM_JOINTS;i++){
if(!g->has[i]) continue; if(!g->has[i]) continue;
g->ticks[i]++; if(g->ticks[i]<3) continue; g->ticks[i]++; if(g->ticks[i]<3) continue;
g->has[i]=false; g->ticks[i]=0; g->has[i]=false; g->ticks[i]=0;
int tgt=g->pend[i]; if(joints[i].last_sent==tgt) continue; int tgt=g->pend[i]; if(joints[i].last_sent==tgt) continue;
joints[i].last_sent=tgt; joints[i].value=tgt; joints[i].last_sent=tgt; joints[i].value=tgt;
char buf[20]; snprintf(buf,sizeof(buf),"%s %d",joints[i].cute,tgt); set_status(buf); char buf[24]; snprintf(buf,sizeof(buf),"%s %d",joints[i].cute,tgt); set_status(buf);
bool ok=rpc_move(joints[i].name,tgt); bool ok=rpc_move(joints[i].name,tgt);
snprintf(buf,sizeof(buf),"%s %d %s",joints[i].cute,tgt,ok?"ok":"fail"); set_status(buf); snprintf(buf,sizeof(buf),"%s %d %s",joints[i].cute,tgt,ok?"o":"x"); set_status(buf);
break; break;
} }
} }
@@ -185,8 +178,6 @@ static void slider_cb(lv_event_t* e){
g->pend[idx]=v; g->has[idx]=true; g->ticks[idx]=0; g->pend[idx]=v; g->has[idx]=true; g->ticks[idx]=0;
} }
} }
/* ── sequencer ── */
static void update_seq_ui(void){ static void update_seq_ui(void){
if(!g) return; if(!g) return;
if(g->seq_label){ if(g->seq_label){
@@ -216,26 +207,21 @@ static void load_frame(int fidx){
apply_ui(); seq_idx=fidx; update_seq_ui(); apply_ui(); seq_idx=fidx; update_seq_ui();
char b[20]; snprintf(b,sizeof(b),"Frame %d",fidx+1); set_status(b); char b[20]; snprintf(b,sizeof(b),"Frame %d",fidx+1); set_status(b);
} }
static void seq_add_cb(void){ if(seq_len>=SEQ_MAX){set_status("Seq full"); return;} for(int i=0;i<NUM_JOINTS;i++) seq[seq_len].v[i]=joints[i].value; seq_len++; seq_idx=seq_len-1; update_seq_ui(); char b[16]; snprintf(b,sizeof(b),"+ %d",seq_len); set_status(b); } static void seq_add_cb(void){ if(seq_len>=SEQ_MAX){set_status("Full"); return;} for(int i=0;i<NUM_JOINTS;i++) seq[seq_len].v[i]=joints[i].value; seq_len++; seq_idx=seq_len-1; update_seq_ui(); char b[16]; snprintf(b,sizeof(b),"+ %d",seq_len); set_status(b); }
static void seq_rem_cb(void){ static void seq_rem_cb(void){
if(seq_len==0||seq_idx<0){set_status("Nothing"); return;} if(seq_len==0||seq_idx<0){set_status("Nothing"); return;}
int rem=seq_idx; int rem=seq_idx; for(int f=rem;f<seq_len-1;f++) seq[f]=seq[f+1];
for(int f=rem;f<seq_len-1;f++) seq[f]=seq[f+1];
seq_len--; if(seq_len==0){seq_idx=-1; update_seq_ui(); set_status("- empty"); return;} seq_len--; if(seq_len==0){seq_idx=-1; update_seq_ui(); set_status("- empty"); return;}
if(seq_idx>=seq_len) seq_idx=seq_len-1; if(seq_idx>=seq_len) seq_idx=seq_len-1; load_frame(seq_idx);
load_frame(seq_idx);
} }
static void seq_prev_cb(void){ if(seq_len==0) return; int n=(seq_idx<=0)?seq_len-1:seq_idx-1; load_frame(n); } static void seq_prev_cb(void){ if(seq_len==0) return; int n=(seq_idx<=0)?seq_len-1:seq_idx-1; load_frame(n); }
static void seq_next_cb(void){ if(seq_len==0) return; int n=(seq_idx>=seq_len-1)?0:seq_idx+1; load_frame(n); } static void seq_next_cb(void){ if(seq_len==0) return; int n=(seq_idx>=seq_len-1)?0:seq_idx+1; load_frame(n); }
static void seq_timer_cb(lv_timer_t* t){ static void seq_timer_cb(lv_timer_t* t){
(void)t; if(!seq_playing||seq_len==0) return; (void)t; if(!seq_playing||seq_len==0) return;
int f=seq_play_pos%seq_len; int f=seq_play_pos%seq_len; int* v=seq[f].v;
int* v=seq[f].v;
if(!rpc_move_all(v[0],v[1],v[2],v[3],v[4],v[5],0.8f)){ if(!rpc_move_all(v[0],v[1],v[2],v[3],v[4],v[5],0.8f)){
set_status("Seq fail"); seq_playing=false; set_status("Seq fail"); seq_playing=false;
if(g&&g->play_label) lv_label_set_text(g->play_label,"Play"); if(g&&g->play_label) lv_label_set_text(g->play_label,"Play"); return;
return;
} }
for(int i=0;i<NUM_JOINTS;i++){joints[i].value=v[i]; joints[i].last_sent=v[i]; if(g){g->pend[i]=v[i]; g->has[i]=false;}} for(int i=0;i<NUM_JOINTS;i++){joints[i].value=v[i]; joints[i].last_sent=v[i]; if(g){g->pend[i]=v[i]; g->has[i]=false;}}
apply_ui(); seq_idx=f; update_seq_ui(); apply_ui(); seq_idx=f; update_seq_ui();
@@ -253,42 +239,155 @@ static void seq_rem_ev(lv_event_t* e){(void)e; seq_rem_cb();}
static void seq_prev_ev(lv_event_t* e){(void)e; seq_prev_cb();} static void seq_prev_ev(lv_event_t* e){(void)e; seq_prev_cb();}
static void seq_next_ev(lv_event_t* e){(void)e; seq_next_cb();} static void seq_next_ev(lv_event_t* e){(void)e; seq_next_cb();}
static void block_click_cb(lv_event_t* e){int idx=(int)(intptr_t)lv_event_get_user_data(e); if(idx<0||idx>=seq_len) return; load_frame(idx);} static void block_click_cb(lv_event_t* e){int idx=(int)(intptr_t)lv_event_get_user_data(e); if(idx<0||idx>=seq_len) return; load_frame(idx);}
static void home_cb(lv_event_t* e){(void)e; set_status("Homing..."); if(rpc_home()){lv_timer_create(del_ref_cb,1200,NULL); set_status("Homed :3");} else set_status("Fail");} static void home_cb(lv_event_t* e){(void)e; set_status("Homing..."); if(rpc_home()){lv_timer_create(del_ref_cb,1200,NULL); set_status("Homed :3");} else set_status("Fail");}
static void read_cb(lv_event_t* e){(void)e; refresh_arm();} static void read_cb(lv_event_t* e){(void)e; refresh_arm();}
static void open_cb(lv_event_t* e){(void)e; joints[5].value=0; apply_ui(); rpc_move("gripper",0); set_status("Open");} static void open_cb(lv_event_t* e){(void)e; joints[5].value=0; apply_ui(); rpc_move("gripper",0); set_status("Open");}
static void close_cb(lv_event_t* e){(void)e; joints[5].value=180; apply_ui(); rpc_move("gripper",180); set_status("Close");} static void close_cb(lv_event_t* e){(void)e; joints[5].value=180; apply_ui(); rpc_move("gripper",180); set_status("Close");}
static bool try_host(const char* host){
char resp[1024]; memset(resp,0,sizeof(resp));
if(http_post(host,ARM_PORT,ARM_PATH,"{\"jsonrpc\":\"2.0\",\"id\":9,\"method\":\"tools/call\",\"params\":{\"name\":\"get_arm_state\",\"arguments\":{}}}",resp,sizeof(resp))==0){
if(strstr(resp,"base")){
strncpy(arm_host,host,sizeof(arm_host)-1);
return true;
}
}
return false;
}
static void show_main_ui(void){
if(!g) return;
arm_connected=true;
if(g->connect_box) lv_obj_add_flag(g->connect_box, LV_OBJ_FLAG_HIDDEN);
if(g->main_box) lv_obj_clear_flag(g->main_box, LV_OBJ_FLAG_HIDDEN);
if(g->connect_timer){ lv_timer_delete(g->connect_timer); g->connect_timer=NULL; }
if(!g->poll) g->poll=lv_timer_create(poll_cb,100,NULL);
if(!g->seq_timer) g->seq_timer=lv_timer_create(seq_timer_cb,1300,NULL);
lv_timer_create(init_cb,500,NULL);
char buf[48]; snprintf(buf,sizeof(buf),"Conn %s",arm_host); set_status(buf);
}
static void connect_timer_cb(lv_timer_t* t){
(void)t; if(!g || arm_connected) return;
g->connect_attempts++;
char lbl[64];
if(g->connect_attempts==1) snprintf(lbl,sizeof(lbl),"mDNS browsing _robotarm._tcp...");
else snprintf(lbl,sizeof(lbl),"Searching (%d)...",g->connect_attempts);
if(g->connect_label) lv_label_set_text(g->connect_label,lbl);
// ── 1) mDNS browse for _robotarm._tcp (preferred) ──
TtMdnsBrowseResult res; memset(&res,0,sizeof(res));
if(tt_mdns_browse("_robotarm","_tcp",2500,10,&res)){
for(int i=0;i<res.count;i++){
if(res.services[i].primaryAddress[0]){
if(try_host(res.services[i].primaryAddress)){
show_main_ui(); return;
}
}
}
}
// ── 2) mDNS resolve robotarm.local hostname ──
char ipbuf[64]={0};
if(tt_mdns_resolve_hostname("robotarm.local",2000,ipbuf) || tt_mdns_resolve_hostname("robotarm",2000,ipbuf)){
if(try_host(ipbuf)){ show_main_ui(); return; }
}
// ── 3) fallback hardcoded (old behavior) ──
const char* fallbacks[]={"192.168.68.148","192.168.68.103","192.168.68.102"};
int idx = (g->connect_attempts-1) % (int)(sizeof(fallbacks)/sizeof(fallbacks[0]));
if(try_host(fallbacks[idx])){ show_main_ui(); return; }
if(g->connect_attempts>15){
if(g->connect_label) lv_label_set_text(g->connect_label,"No arm found.\nMake sure robotarm\nis powered & on WiFi.\nTap Retry.");
}
}
static void retry_cb(lv_event_t* e){(void)e; if(!g) return; g->connect_attempts=0; if(g->connect_label) lv_label_set_text(g->connect_label,"Retrying mDNS...");}
static void onShow(AppHandle app,void* data,lv_obj_t* parent){ static void onShow(AppHandle app,void* data,lv_obj_t* parent){
(void)data; (void)data;
Ctx* c=(Ctx*)calloc(1,sizeof(Ctx)); if(!c) return; Ctx* c=calloc(1,sizeof(Ctx)); if(!c) return;
c->app=app; g=c; c->app=app; g=c;
for(int i=0;i<NUM_JOINTS;i++){joints[i].last_sent=-1; c->pend[i]=joints[i].value; c->has[i]=false;} for(int i=0;i<NUM_JOINTS;i++){joints[i].last_sent=-1; c->pend[i]=joints[i].value; c->has[i]=false;}
arm_host[0]='\0'; arm_connected=false; c->connect_attempts=0;
lv_obj_t* tb=tt_lvgl_toolbar_create_for_app(parent,app); lv_obj_align(tb,LV_ALIGN_TOP_MID,0,0); lv_obj_t* tb=tt_lvgl_toolbar_create_for_app(parent,app); lv_obj_align(tb,LV_ALIGN_TOP_MID,0,0);
// Root fills screen below toolbar - NOT scrollable itself, content will be
lv_obj_t* root=lv_obj_create(parent); lv_obj_t* root=lv_obj_create(parent);
c->root=root;
lv_obj_set_size(root,LV_PCT(100),LV_PCT(100)); lv_obj_set_size(root,LV_PCT(100),LV_PCT(100));
lv_obj_set_style_pad_all(root,2,0); lv_obj_set_style_pad_top(root,34,0); lv_obj_set_style_pad_all(root,2,0); lv_obj_set_style_pad_top(root,36,0);
lv_obj_set_style_border_width(root,0,0); lv_obj_set_style_border_width(root,0,0);
lv_obj_set_style_bg_color(root,lv_color_hex(0xFFF8F0),0); lv_obj_set_style_bg_color(root,lv_color_hex(0xFFF8F0),0);
lv_obj_set_style_bg_opa(root,LV_OPA_COVER,0); lv_obj_set_style_bg_opa(root,LV_OPA_COVER,0);
lv_obj_set_scroll_dir(root, LV_DIR_VER); lv_obj_clear_flag(root, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_t* hdr=lv_obj_create(root); lv_obj_set_size(hdr,LV_PCT(100),16); // ── connecting screen (initial visible) ──
c->connect_box=lv_obj_create(root);
lv_obj_set_size(c->connect_box,LV_PCT(100),LV_PCT(100));
lv_obj_set_pos(c->connect_box,0,0);
lv_obj_set_style_border_width(c->connect_box,0,0);
lv_obj_set_style_bg_opa(c->connect_box,LV_OPA_TRANSP,0);
lv_obj_set_style_pad_all(c->connect_box,4,0);
lv_obj_clear_flag(c->connect_box, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_t* tl=lv_label_create(c->connect_box);
lv_label_set_text(tl,"Finding robotarm...");
lv_obj_set_style_text_font(tl,lvgl_get_text_font(FONT_SIZE_LARGE),0);
lv_obj_set_style_text_color(tl,lv_color_hex(0x3D2B5A),0);
lv_obj_set_pos(tl,4,4);
c->connect_label=lv_label_create(c->connect_box);
lv_label_set_text(c->connect_label,"mDNS: _robotarm._tcp / robotarm.local\nFallback: 192.168.68.148\n\nSearching...");
lv_obj_set_style_text_font(c->connect_label,lvgl_get_text_font(FONT_SIZE_SMALL),0);
lv_obj_set_style_text_color(c->connect_label,lv_color_hex(0x6A5A7A),0);
lv_obj_set_pos(c->connect_label,4,28); lv_obj_set_width(c->connect_label,260);
c->connect_spinner=lv_spinner_create(c->connect_box);
lv_obj_set_size(c->connect_spinner,40,40);
lv_obj_set_pos(c->connect_spinner,120,110);
lv_obj_t* rb=lv_btn_create(c->connect_box);
lv_obj_set_size(rb,80,28); lv_obj_set_pos(rb,80,170);
lv_obj_set_style_bg_color(rb,lv_color_hex(0xC5F5C5),0); lv_obj_set_style_radius(rb,8,0);
lv_obj_t* rbl=lv_label_create(rb); lv_label_set_text(rbl,"Retry");
lv_obj_set_style_text_font(rbl,lvgl_get_text_font(FONT_SIZE_SMALL),0);
lv_obj_set_style_text_color(rbl,lv_color_hex(0x2A2A5A),0); lv_obj_center(rbl);
lv_obj_add_event_cb(rb,retry_cb,LV_EVENT_CLICKED,NULL);
// ── main scrollable content (hidden until connected) ──
// content is the ONLY scrollable container - FIX overall app scroller lost
c->content=lv_obj_create(root);
lv_obj_set_size(c->content,LV_PCT(100),LV_PCT(100));
lv_obj_set_pos(c->content,0,0);
lv_obj_set_style_border_width(c->content,0,0);
lv_obj_set_style_bg_opa(c->content,LV_OPA_TRANSP,0);
lv_obj_set_style_pad_all(c->content,0,0);
lv_obj_set_flex_flow(c->content, LV_FLEX_FLOW_COLUMN);
lv_obj_add_flag(c->content, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_set_scrollbar_mode(c->content, LV_SCROLLBAR_MODE_AUTO);
c->main_box=lv_obj_create(c->content);
lv_obj_set_size(c->main_box,LV_PCT(100),LV_SIZE_CONTENT);
lv_obj_set_style_border_width(c->main_box,0,0);
lv_obj_set_style_bg_opa(c->main_box,LV_OPA_TRANSP,0);
lv_obj_set_style_pad_all(c->main_box,0,0);
lv_obj_clear_flag(c->main_box, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_add_flag(c->main_box, LV_OBJ_FLAG_HIDDEN);
lv_obj_t* hdr=lv_obj_create(c->main_box); lv_obj_set_size(hdr,LV_PCT(100),16);
lv_obj_set_style_border_width(hdr,0,0); lv_obj_set_style_bg_opa(hdr,LV_OPA_TRANSP,0); lv_obj_set_style_border_width(hdr,0,0); lv_obj_set_style_bg_opa(hdr,LV_OPA_TRANSP,0);
lv_obj_set_style_pad_all(hdr,0,0); lv_obj_set_pos(hdr,0,0); lv_obj_set_style_pad_all(hdr,0,0);
lv_obj_clear_flag(hdr, LV_OBJ_FLAG_SCROLLABLE); lv_obj_clear_flag(hdr, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_t* title=lv_label_create(hdr); lv_label_set_text(title,"Robot Arm :3"); lv_obj_t* title=lv_label_create(hdr); lv_label_set_text(title,"Robot Arm :3");
lv_obj_set_style_text_font(title,lvgl_get_text_font(FONT_SIZE_SMALL),0); lv_obj_set_style_text_font(title,lvgl_get_text_font(FONT_SIZE_SMALL),0);
lv_obj_set_style_text_color(title,lv_color_hex(0x3D2B5A),0); lv_obj_set_pos(title,2,0); lv_obj_set_style_text_color(title,lv_color_hex(0x3D2B5A),0);
c->status=lv_label_create(hdr); lv_label_set_text(c->status,"Conn .103..."); lv_obj_set_pos(title,2,0);
c->status=lv_label_create(hdr); lv_label_set_text(c->status,"Conn...");
lv_obj_set_style_text_font(c->status,lvgl_get_text_font(FONT_SIZE_SMALL),0); lv_obj_set_style_text_font(c->status,lvgl_get_text_font(FONT_SIZE_SMALL),0);
lv_obj_set_style_text_color(c->status,lv_color_hex(0xA08090),0); lv_obj_set_pos(c->status,90,0); lv_obj_set_style_text_color(c->status,lv_color_hex(0xA08090),0);
lv_obj_set_pos(c->status,90,0);
lv_obj_t* brow=lv_obj_create(root); lv_obj_set_size(brow,LV_PCT(100),20); lv_obj_t* brow=lv_obj_create(c->main_box); lv_obj_set_size(brow,LV_PCT(100),20);
lv_obj_set_style_border_width(brow,0,0); lv_obj_set_style_bg_opa(brow,LV_OPA_TRANSP,0); lv_obj_set_style_border_width(brow,0,0); lv_obj_set_style_bg_opa(brow,LV_OPA_TRANSP,0);
lv_obj_set_style_pad_all(brow,0,0); lv_obj_set_pos(brow,0,16); lv_obj_set_style_pad_all(brow,0,0);
lv_obj_clear_flag(brow, LV_OBJ_FLAG_SCROLLABLE); lv_obj_clear_flag(brow, LV_OBJ_FLAG_SCROLLABLE);
struct { const char* t; uint32_t col; lv_event_cb_t cb; } btns[]={ struct { const char* t; uint32_t col; lv_event_cb_t cb; } btns[]={
{"Home",0xFFD6E0,home_cb},{"Read",0xD6E8FF,read_cb},{"Open",0xD5F0D5,open_cb},{"Close",0xFFE8C5,close_cb},}; {"Home",0xFFD6E0,home_cb},{"Read",0xD6E8FF,read_cb},{"Open",0xD5F0D5,open_cb},{"Close",0xFFE8C5,close_cb},};
@@ -302,12 +401,12 @@ static void onShow(AppHandle app,void* data,lv_obj_t* parent){
lv_obj_add_event_cb(b,btns[i].cb,LV_EVENT_CLICKED,NULL); lv_obj_add_event_cb(b,btns[i].cb,LV_EVENT_CLICKED,NULL);
} }
/* ── large nice vertical sliders: 3 cols, 2x height 22x72 per request ── */ lv_obj_t* grid=lv_obj_create(c->main_box);
lv_obj_t* grid=lv_obj_create(root);
lv_obj_set_size(grid,LV_PCT(100),196); lv_obj_set_size(grid,LV_PCT(100),196);
lv_obj_set_style_border_width(grid,0,0); lv_obj_set_style_bg_opa(grid,LV_OPA_TRANSP,0); lv_obj_set_style_border_width(grid,0,0); lv_obj_set_style_bg_opa(grid,LV_OPA_TRANSP,0);
lv_obj_set_style_pad_all(grid,2,0); lv_obj_set_pos(grid,0,36); lv_obj_set_style_pad_all(grid,2,0);
lv_obj_clear_flag(grid, LV_OBJ_FLAG_SCROLLABLE); lv_obj_clear_flag(grid, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_set_scrollbar_mode(grid, LV_SCROLLBAR_MODE_OFF);
for(int i=0;i<NUM_JOINTS;i++){ for(int i=0;i<NUM_JOINTS;i++){
int col=i%3, row=i/3; int col=i%3, row=i/3;
@@ -320,6 +419,7 @@ static void onShow(AppHandle app,void* data,lv_obj_t* parent){
lv_obj_set_style_border_width(card,0,0); lv_obj_set_style_border_width(card,0,0);
lv_obj_set_style_pad_all(card,3,0); lv_obj_set_style_pad_all(card,3,0);
lv_obj_clear_flag(card, LV_OBJ_FLAG_SCROLLABLE); lv_obj_clear_flag(card, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_set_scrollbar_mode(card, LV_SCROLLBAR_MODE_OFF);
lv_obj_t* name=lv_label_create(card); lv_obj_t* name=lv_label_create(card);
lv_label_set_text(name,joints[i].cute); lv_label_set_text(name,joints[i].cute);
@@ -357,27 +457,22 @@ static void onShow(AppHandle app,void* data,lv_obj_t* parent){
lv_obj_add_event_cb(sl,slider_cb,LV_EVENT_VALUE_CHANGED,(void*)(intptr_t)i); lv_obj_add_event_cb(sl,slider_cb,LV_EVENT_VALUE_CHANGED,(void*)(intptr_t)i);
} }
/* ── sequencer at bottom, NOT fixed — scrollable with content ── lv_obj_t* seqbar=lv_obj_create(c->main_box);
visual: colored blocks, no info, current highlighted, larger buttons */
lv_obj_t* seqbar=lv_obj_create(root);
lv_obj_set_size(seqbar,316,96); lv_obj_set_size(seqbar,316,96);
lv_obj_set_pos(seqbar,2,232);
lv_obj_clear_flag(seqbar, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_set_style_bg_color(seqbar,lv_color_hex(0xF0E8FF),0); lv_obj_set_style_bg_color(seqbar,lv_color_hex(0xF0E8FF),0);
lv_obj_set_style_bg_opa(seqbar,LV_OPA_90,0); lv_obj_set_style_bg_opa(seqbar,LV_OPA_90,0);
lv_obj_set_style_radius(seqbar,12,0); lv_obj_set_style_radius(seqbar,12,0);
lv_obj_set_style_border_width(seqbar,1,0); lv_obj_set_style_border_width(seqbar,1,0);
lv_obj_set_style_border_color(seqbar,lv_color_hex(0xD0C0E0),0); lv_obj_set_style_border_color(seqbar,lv_color_hex(0xD0C0E0),0);
lv_obj_set_style_pad_all(seqbar,4,0); lv_obj_set_style_pad_all(seqbar,4,0);
lv_obj_clear_flag(seqbar, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_t* seq_t=lv_label_create(seqbar); lv_label_set_text(seq_t,"Seq"); lv_obj_t* seq_t=lv_label_create(seqbar); lv_label_set_text(seq_t,"Seq");
lv_obj_set_style_text_font(seq_t,lvgl_get_text_font(FONT_SIZE_SMALL),0); lv_obj_set_style_text_font(seq_t,lvgl_get_text_font(FONT_SIZE_SMALL),0);
lv_obj_set_style_text_color(seq_t,lv_color_hex(0x3D2B5A),0); lv_obj_set_pos(seq_t,2,0); lv_obj_set_style_text_color(seq_t,lv_color_hex(0x3D2B5A),0); lv_obj_set_pos(seq_t,2,0);
c->seq_label=lv_label_create(seqbar); lv_label_set_text(c->seq_label,"empty"); c->seq_label=lv_label_create(seqbar); lv_label_set_text(c->seq_label,"empty");
lv_obj_set_style_text_font(c->seq_label,lvgl_get_text_font(FONT_SIZE_SMALL),0); lv_obj_set_style_text_font(c->seq_label,lvgl_get_text_font(FONT_SIZE_SMALL),0);
lv_obj_set_style_text_color(c->seq_label,lv_color_hex(0x6A5A7A),0); lv_obj_set_pos(c->seq_label,30,0); lv_obj_set_style_text_color(c->seq_label,lv_color_hex(0x6A5A7A),0); lv_obj_set_pos(c->seq_label,30,0);
struct { const char* t; uint32_t col; lv_event_cb_t cb; int play; } sbtns[]={ struct { const char* t; uint32_t col; lv_event_cb_t cb; int play; } sbtns[]={
{"-",0xFFB7B7,seq_rem_ev,0},{"<",0xD6E8FF,seq_prev_ev,0}, {"-",0xFFB7B7,seq_rem_ev,0},{"<",0xD6E8FF,seq_prev_ev,0},
{"Play",0xC5F5C5,seq_play_cb,1},{">",0xD6E8FF,seq_next_ev,0},{"+",0xFFE8A0,seq_add_ev,0},}; {"Play",0xC5F5C5,seq_play_cb,1},{">",0xD6E8FF,seq_next_ev,0},{"+",0xFFE8A0,seq_add_ev,0},};
@@ -394,7 +489,6 @@ static void onShow(AppHandle app,void* data,lv_obj_t* parent){
lv_obj_set_style_text_color(l,lv_color_hex(0x2A2A5A),0); lv_obj_center(l); lv_obj_set_style_text_color(l,lv_color_hex(0x2A2A5A),0); lv_obj_center(l);
lv_obj_add_event_cb(b,sbtns[i].cb,LV_EVENT_CLICKED,NULL); lv_obj_add_event_cb(b,sbtns[i].cb,LV_EVENT_CLICKED,NULL);
} }
uint32_t blk_cols[16]={ uint32_t blk_cols[16]={
0xFF8FA8,0x8FB6FF,0xFFB86A,0x88D488,0xB088FF,0xFFD060,0xFF7AA2,0x7AC8FF, 0xFF8FA8,0x8FB6FF,0xFFB86A,0x88D488,0xB088FF,0xFFD060,0xFF7AA2,0x7AC8FF,
0xFDBA74,0x86EFAC,0xA78BFA,0xFDE68A,0xFCA5A5,0x93C5FD,0xBEF264,0xFDA4AF 0xFDBA74,0x86EFAC,0xA78BFA,0xFDE68A,0xFCA5A5,0x93C5FD,0xBEF264,0xFDA4AF
@@ -412,9 +506,8 @@ static void onShow(AppHandle app,void* data,lv_obj_t* parent){
} }
update_seq_ui(); update_seq_ui();
c->poll=lv_timer_create(poll_cb,100,NULL); c->connect_timer=lv_timer_create(connect_timer_cb, 1000, NULL);
c->seq_timer=lv_timer_create(seq_timer_cb,1300,NULL); connect_timer_cb(NULL);
lv_timer_create(init_cb,600,NULL);
} }
static void onHide(AppHandle app,void* data){ static void onHide(AppHandle app,void* data){
@@ -422,8 +515,9 @@ static void onHide(AppHandle app,void* data){
if(g){ if(g){
if(g->poll) lv_timer_delete(g->poll); if(g->poll) lv_timer_delete(g->poll);
if(g->seq_timer) lv_timer_delete(g->seq_timer); if(g->seq_timer) lv_timer_delete(g->seq_timer);
if(g->connect_timer) lv_timer_delete(g->connect_timer);
free(g); g=NULL; free(g); g=NULL;
} }
seq_playing=false; seq_playing=false; arm_connected=false;
} }
int main(int argc,char* argv[]){(void)argc;(void)argv; tt_app_register((AppRegistration){.onShow=onShow,.onHide=onHide}); return 0;} int main(int argc,char* argv[]){(void)argc;(void)argv; tt_app_register((AppRegistration){.onShow=onShow,.onHide=onHide}); return 0;}
+7 -10
View File
@@ -1,10 +1,7 @@
[manifest] manifest.version=0.2
version=0.1 target.sdk=0.8.0-dev
[target] target.platforms=esp32,esp32s3,esp32c6,esp32p4
sdk=0.7.0-dev app.id=one.tactility.serialconsole
platforms=esp32,esp32s3,esp32c6,esp32p4 app.version.name=0.7.0
[app] app.version.code=7
id=one.tactility.serialconsole app.name=Serial Console
versionName=0.4.0
versionCode=4
name=Serial Console
+8 -11
View File
@@ -1,11 +1,8 @@
[manifest] manifest.version=0.2
version=0.1 target.sdk=0.8.0-dev
[target] target.platforms=esp32,esp32s3,esp32c6,esp32p4
sdk=0.7.0-dev app.id=one.tactility.snake
platforms=esp32,esp32s3,esp32c6,esp32p4 app.version.name=0.8.0
[app] app.version.code=8
id=one.tactility.snake app.name=Snake
versionName=0.5.0 app.description=Classic Snake game
versionCode=5
name=Snake
description=Classic Snake game
-1
View File
@@ -57,7 +57,6 @@ void TamaTac::onShow(AppHandle context, lv_obj_t* parent) {
if (sfxEngine == nullptr) { if (sfxEngine == nullptr) {
sfxEngine = new SfxEngine(); sfxEngine = new SfxEngine();
sfxEngine->start(); sfxEngine->start();
sfxEngine->applyVolumePreset(SfxEngine::VolumePreset::Normal);
// Load settings // Load settings
bool soundEnabled; bool soundEnabled;
+8 -11
View File
@@ -1,11 +1,8 @@
[manifest] manifest.version=0.2
version=0.1 target.sdk=0.8.0-dev
[target] target.platforms=esp32,esp32s3,esp32c6,esp32p4
sdk=0.7.0-dev app.id=one.tactility.tamatac
platforms=esp32,esp32s3,esp32c6,esp32p4 app.version.name=0.4.0
[app] app.version.code=4
id=one.tactility.tamatac app.name=TamaTac
versionName=0.1.0 app.description=Virtual pet inspired by Tamagotchi. Only runs on devices with PSRAM.
versionCode=1
name=TamaTac
description=Virtual pet inspired by Tamagotchi. Only runs on devices with PSRAM.
+8 -11
View File
@@ -1,11 +1,8 @@
[manifest] manifest.version=0.2
version=0.1 target.sdk=0.8.0-dev
[target] target.platforms=esp32,esp32s3,esp32c6,esp32p4
sdk=0.7.0-dev app.id=one.tactility.todolist
platforms=esp32,esp32s3,esp32c6,esp32p4 app.version.name=0.5.0
[app] app.version.code=5
id=one.tactility.todolist app.name=Todo List
versionName=0.2.0 app.description=Simple task list manager
versionCode=2
name=Todo List
description=Simple task list manager
+8 -11
View File
@@ -1,11 +1,8 @@
[manifest] manifest.version=0.2
version=0.1 target.sdk=0.8.0-dev
[target] target.platforms=esp32,esp32s3,esp32c6,esp32p4
sdk=0.7.0-dev app.id=one.tactility.twoeleven
platforms=esp32,esp32s3,esp32c6,esp32p4 app.version.name=0.7.0
[app] app.version.code=7
id=one.tactility.twoeleven app.name=2048
versionName=0.4.0 app.description=A fun, customizable 2048 sliding tile game for tactility!\nSlide tiles to combine numbers and reach 2048.\nChoose grid sizes: 3x3 (easy), 4x4 (classic), 5x5, or 6x6 (expert).
versionCode=4
name=2048
description=A fun, customizable 2048 sliding tile game for tactility!\nSlide tiles to combine numbers and reach 2048.\nChoose grid sizes: 3x3 (easy), 4x4 (classic), 5x5, or 6x6 (expert).
+7 -10
View File
@@ -1,10 +1,7 @@
[manifest] manifest.version=0.2
version=0.1 target.sdk=0.8.0-dev
[target] target.platforms=esp32s3
sdk=0.8.0-dev app.id=one.tactility.voicerecorder
platforms=esp32s3 app.version.name=1.0.0
[app] app.version.code=1
id=one.tactility.voicerecorder app.name=Voice Recorder
name=Voice Recorder
versionName=1.0.0
versionCode=1
+70
View File
@@ -0,0 +1,70 @@
import os
import sys
import boto3
SHELL_COLOR_RED = "\033[91m"
SHELL_COLOR_ORANGE = "\033[93m"
SHELL_COLOR_RESET = "\033[m"
def print_warning(message):
print(f"{SHELL_COLOR_ORANGE}WARNING: {message}{SHELL_COLOR_RESET}")
def print_error(message):
print(f"{SHELL_COLOR_RED}ERROR: {message}{SHELL_COLOR_RESET}")
def print_help():
print("Usage: python upload-app-files.py [path] [sdkVersion] [cloudflareAccountId] [cloudflareTokenName] [cloudflareTokenValue]")
print("")
print("Options:")
print(" --index-only Upload only apps.json")
def exit_with_error(message):
print_error(message)
sys.exit(1)
def main(path: str, sdk_version: str, cloudflare_account_id, cloudflare_token_name: str, cloudflare_token_value: str, index_only: bool):
if not os.path.exists(path):
exit_with_error(f"Path not found: {path}")
s3 = boto3.client(
service_name="s3",
endpoint_url=f"https://{cloudflare_account_id}.r2.cloudflarestorage.com",
aws_access_key_id=cloudflare_token_name,
aws_secret_access_key=cloudflare_token_value,
region_name="auto"
)
files_to_upload = os.listdir(path)
if index_only:
files_to_upload = [f for f in files_to_upload if f == 'apps.json']
else:
# Ensure apps.json is uploaded last so it never references files that
# haven't finished uploading yet.
files_to_upload.sort(key=lambda f: f == 'apps.json')
counter = 1
total = len(files_to_upload)
for file_name in files_to_upload:
object_path = f"apps/{sdk_version}/{file_name}"
print(f"[{counter}/{total}] Uploading {file_name} to {object_path}")
file_path = os.path.join(path, file_name)
try:
s3.upload_file(file_path, "tactility", object_path)
except Exception as e:
exit_with_error(f"Failed to upload {file_name}: {str(e)}")
counter += 1
if __name__ == "__main__":
print("Tactility CDN Apps Uploader")
if "--help" in sys.argv:
print_help()
sys.exit()
# Argument validation
if len(sys.argv) < 6:
print_help()
sys.exit(1)
main(
path=sys.argv[1],
sdk_version=sys.argv[2],
cloudflare_account_id=sys.argv[3],
cloudflare_token_name=sys.argv[4],
cloudflare_token_value=sys.argv[5],
index_only="--index-only" in sys.argv
)
+23
View File
@@ -0,0 +1,23 @@
# Peanut-GB vendored library
Source: https://github.com/deltabeard/Peanut-GB
File: peanut_gb.h (single-header emulator)
License: MIT License - Copyright (c) 2018-2023 Mahyar Koshkouei
Date Vendored: 2026-07-17 UTC
Upstream: master branch latest as fetched 2026-07-17
Commit URL: https://github.com/deltabeard/Peanut-GB/tree/master
Size: ~4044 lines
MIT license text is preserved intact at top of peanut_gb.h header.
SameBoy-derived portions: Copyright (c) 2015-2019 Lior Halphon, also MIT.
Usage:
```c
#define ENABLE_SOUND 0
#define ENABLE_LCD 1
#include "peanut_gb.h"
```
No modifications applied — used as-is.
For Tactility GameBoy app, audio is disabled (ENABLE_SOUND 0) per prototype spec.
File diff suppressed because it is too large Load Diff
+4 -5
View File
@@ -35,11 +35,8 @@ if (!engine->start()) {
ESP_LOGE(TAG, "Failed to start SfxEngine"); ESP_LOGE(TAG, "Failed to start SfxEngine");
return; return;
} }
engine->applyVolumePreset(SfxEngine::VolumePreset::Normal);
engine->play(SfxId::Coin); // Predefined SFX engine->play(SfxId::Coin); // Predefined SFX
engine->playNote(0, 60, 200); // Manual: voice 0, C4, 200ms engine->playNote(0, 60, 200); // Manual: voice 0, C4, 200ms
engine->setVolume(0.7f); // Volume control
engine->stop(); engine->stop();
delete engine; delete engine;
@@ -87,9 +84,11 @@ idf_component_register(
- `void stopVoice(voice)` - Stop specific voice - `void stopVoice(voice)` - Stop specific voice
### Settings ### Settings
- `void setVolume(float)` - Master volume (0.0-1.0, exponential curve)
- `void setEnabled(bool)` - Mute/unmute - `void setEnabled(bool)` - Mute/unmute
- `void applyVolumePreset(VolumePreset)` - Apply Quiet/Normal/Loud preset (configures volume, gate, normalization)
Loudness is controlled by the system output volume (set via the audio_stream device / Settings UI),
not by SfxEngine itself -- a fixed app-side gain on top of hardware attenuation gets swamped at low
system volumes, so there's no separate volume control here.
### Mixing (consistent with SoundEngine) ### Mixing (consistent with SoundEngine)
- `void setPolyphonicGateEnabled(bool)` - Soft gate when multiple voices clip (default: on) - `void setPolyphonicGateEnabled(bool)` - Soft gate when multiple voices clip (default: on)
+4
View File
@@ -15,6 +15,10 @@
#include <cstring> #include <cstring>
#include "esp_log.h" #include "esp_log.h"
// The deployed 0.8.0-dev firmware still exports this legacy lookup API, while
// the current SDK headers only expose device_get_by_name().
extern "C" Device* device_find_by_name(const char* name);
#ifndef M_PI #ifndef M_PI
#define M_PI 3.14159265358979323846f #define M_PI 3.14159265358979323846f
#endif #endif
+55 -40
View File
@@ -1,14 +1,23 @@
import json import json
import subprocess
import tarfile import tarfile
import os import os
import tempfile import tempfile
import configparser
import sys import sys
from datetime import datetime, UTC
def read_properties_file(path): def read_properties_file(path):
config = configparser.RawConfigParser() properties = {}
config.read(path) with open(path, "r") as file:
return config for line in file:
stripped = line.strip()
if not stripped or stripped.startswith("#"):
continue
key, sep, value = line.partition("=")
if not sep:
continue
properties[key.strip()] = value.strip()
return properties
def get_manifest(appPath): def get_manifest(appPath):
"""Extract only the file named 'manifest.properties' from the given tar/tar.gz """Extract only the file named 'manifest.properties' from the given tar/tar.gz
@@ -62,51 +71,49 @@ def get_manifest(appPath):
return None return None
def get_versioned_file_name(manifest): def get_versioned_file_name(manifest):
app_id = manifest["app"]["id"] app_id = manifest["app.id"]
version_code = manifest["app"]["versionCode"] version_code = manifest["app.version.code"]
return f"{app_id}-{version_code}.app" return f"{app_id}-{version_code}.app"
def get_os_version(manifest): def get_os_version(manifest):
sdk = manifest["target"]["sdk"] sdk = manifest["target.sdk"]
# Remove trailing hyphen suffix if present # Remove trailing hyphen suffix if present
if "-" in sdk: if "-" in sdk:
return sdk.rsplit("-", 1)[0].strip() return sdk.rsplit("-", 1)[0].strip()
else: else:
return sdk return sdk
def manifest_config_to_flat_json(manifest): def check_and_get_sdk_version(manifest_map):
"""Convert a ConfigParser manifest into a flat JSON-like dict. """Ensure all apps target the same (simplified) SDK version and return it."""
versions = {get_os_version(manifest) for manifest in manifest_map.values()}
if len(versions) != 1:
print(f"ERROR: Apps target multiple SDK versions: {sorted(versions)}. All apps must target the same SDK version.")
sys.exit(1)
return next(iter(versions))
Expected sections/keys (case-insensitive for keys): def get_git_commit_hash():
- [app] return subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode('ascii').strip()
id -> appId
versionName -> appVersionName def manifest_config_to_flat_json(manifest):
versionCode -> appVersionCode (int) """Convert a flat (V2) manifest dict into a flat JSON-like dict.
name -> appName
description -> appDescription (optional; default "") Expected keys:
- [target] app.id -> appId
sdk -> targetSdk app.version.name -> appVersionName
platforms -> targetPlatforms (comma-separated list) app.version.code -> appVersionCode (int)
app.name -> appName
app.description -> appDescription (optional; default "")
target.sdk -> targetSdk
target.platforms -> targetPlatforms (comma-separated list)
Unknown/missing values fall back to sensible defaults per requirements. Unknown/missing values fall back to sensible defaults per requirements.
""" """
def get_opt(section, option, default=None):
if not manifest.has_section(section):
return default
# try exact option then lowercase (RawConfigParser lowercases by default)
if manifest.has_option(section, option):
return manifest.get(section, option)
low = option.lower()
if manifest.has_option(section, low):
return manifest.get(section, low)
return default
# Map values # Map values
app_id = get_opt("app", "id", "") app_id = manifest.get("app.id", "")
app_version_name = get_opt("app", "versionName", "") app_version_name = manifest.get("app.version.name", "")
app_version_code_raw = get_opt("app", "versionCode", "0") app_version_code_raw = manifest.get("app.version.code", "0")
app_name = get_opt("app", "name", "") app_name = manifest.get("app.name", "")
app_description = get_opt("app", "description", "") or "" app_description = manifest.get("app.description", "") or ""
# Coerce version code to int safely # Coerce version code to int safely
try: try:
@@ -114,8 +121,8 @@ def manifest_config_to_flat_json(manifest):
except Exception: except Exception:
app_version_code = 0 app_version_code = 0
target_sdk = get_opt("target", "sdk", "") target_sdk = manifest.get("target.sdk", "")
platforms_raw = get_opt("target", "platforms", "") platforms_raw = manifest.get("target.platforms", "")
target_platforms = [p.strip() for p in str(platforms_raw).split(",") if p.strip()] if platforms_raw is not None else [] target_platforms = [p.strip() for p in str(platforms_raw).split(",") if p.strip()] if platforms_raw is not None else []
filename = get_versioned_file_name(manifest) filename = get_versioned_file_name(manifest)
@@ -142,15 +149,23 @@ if __name__ == "__main__":
sys.exit() sys.exit()
app_directory = sys.argv[1] app_directory = sys.argv[1]
manifest_map = {} manifest_map = {}
output_json = {
"apps": []
}
any_manifest = None any_manifest = None
if os.path.exists(app_directory): if os.path.exists(app_directory):
for file in os.listdir(app_directory): for file in os.listdir(app_directory):
if file.endswith(".app"): if file.endswith(".app"):
file_path = os.path.join(app_directory, file) file_path = os.path.join(app_directory, file)
manifest_map[file_path] = get_manifest(file_path) manifest_map[file_path] = get_manifest(file_path)
# All bundled apps must target the same SDK version; this becomes the CDN path segment
sdk_version = check_and_get_sdk_version(manifest_map)
with open("sdk_version.txt", "w") as f:
f.write(sdk_version)
print(f"SDK version: {sdk_version}")
output_json = {
"sdkVersion": sdk_version,
"created": datetime.now(UTC).strftime('%Y-%m-%dT%H:%M:%SZ'),
"gitCommit": get_git_commit_hash(),
"apps": []
}
# Rename files and collect manifest data into output json object # Rename files and collect manifest data into output json object
for file_path in manifest_map.keys(): for file_path in manifest_map.keys():
print(f"Processing {file_path}: {manifest_map[file_path]}") print(f"Processing {file_path}: {manifest_map[file_path]}")
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env python3
"""Validate MP3 Player close-and-resume evidence captured from serial."""
from __future__ import annotations
import argparse
import re
from pathlib import Path
def evaluate_resume_trace(trace: str, fixture: str, minimum_position: int = 6) -> dict[str, int]:
"""Require real playback, persisted position, and same-file relaunch evidence."""
escaped = re.escape(fixture)
initial = re.search(rf"Starting MP3 playback: {escaped} .* resume=0\b", trace)
stream_opened = re.search(r"Audio stream opened: \d+ Hz, \d+ channels", trace)
persisted = re.search(rf"History saved on hide: {escaped} pos (\d+) total \d+", trace)
resumed = re.search(rf"Resuming last play {escaped} at (\d+) sec from history", trace)
playback_matches = list(re.finditer(rf"Starting MP3 playback: {escaped} .* resume=(\d+)\b", trace))
resumed_playback = playback_matches[-1] if playback_matches else None
if "Playback task stuck, force deleting" in trace:
raise RuntimeError("forced playback task termination invalidates the device test")
if not initial or not stream_opened:
raise RuntimeError("missing verified playback evidence for the fixture")
if not persisted or not resumed or not resumed_playback:
raise RuntimeError("missing persisted or resumed playback evidence")
persisted_position = int(persisted.group(1))
resumed_position = int(resumed.group(1))
resumed_playback_position = int(resumed_playback.group(1))
if persisted_position < minimum_position:
raise RuntimeError(f"persisted position {persisted_position} is below {minimum_position}")
if resumed_position != persisted_position or resumed_playback_position != persisted_position:
raise RuntimeError("relaunch did not resume the persisted position on the same file")
return {"persisted_position": persisted_position, "resumed_position": resumed_position}
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--trace", type=Path, required=True, help="Captured serial log")
parser.add_argument("--fixture", required=True, help="Absolute fixture path logged by MP3 Player")
parser.add_argument("--minimum-position", type=int, default=6)
args = parser.parse_args()
result = evaluate_resume_trace(args.trace.read_text(encoding="utf-8", errors="replace"), args.fixture, args.minimum_position)
print(f"PASS persisted_position={result['persisted_position']} resumed_position={result['resumed_position']}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+23 -36
View File
@@ -1,4 +1,3 @@
import configparser
import json import json
import os import os
import re import re
@@ -13,7 +12,7 @@ import tarfile
from urllib.parse import urlparse from urllib.parse import urlparse
ttbuild_path = ".tactility" ttbuild_path = ".tactility"
ttbuild_version = "3.5.1" ttbuild_version = "4.1.0"
ttbuild_cdn = "https://cdn.tactilityproject.org" ttbuild_cdn = "https://cdn.tactilityproject.org"
ttbuild_sdk_json_validity = 3600 # seconds ttbuild_sdk_json_validity = 3600 # seconds
ttport = 6666 ttport = 6666
@@ -106,9 +105,17 @@ def get_url(ip, path):
return f"http://{ip}:{ttport}{path}" return f"http://{ip}:{ttport}{path}"
def read_properties_file(path): def read_properties_file(path):
config = configparser.RawConfigParser() properties = {}
config.read(path) with open(path, "r") as file:
return config for line in file:
stripped = line.strip()
if not stripped or stripped.startswith("#"):
continue
key, sep, value = line.partition("=")
if not sep:
continue
properties[key.strip()] = value.strip()
return properties
#endregion Core #endregion Core
@@ -185,7 +192,7 @@ def fetch_sdkconfig_files(platform_targets):
for platform in platform_targets: for platform in platform_targets:
sdkconfig_filename = f"sdkconfig.app.{platform}" sdkconfig_filename = f"sdkconfig.app.{platform}"
target_path = os.path.join(ttbuild_path, sdkconfig_filename) target_path = os.path.join(ttbuild_path, sdkconfig_filename)
if not download_file(f"{ttbuild_cdn}/{sdkconfig_filename}", target_path): if not download_file(f"{ttbuild_cdn}/sdk/{sdkconfig_filename}", target_path):
exit_with_error(f"Failed to download sdkconfig file for {platform}") exit_with_error(f"Failed to download sdkconfig file for {platform}")
#endregion SDK helpers #endregion SDK helpers
@@ -231,32 +238,12 @@ def read_manifest():
return read_properties_file("manifest.properties") return read_properties_file("manifest.properties")
def validate_manifest(manifest): def validate_manifest(manifest):
# [manifest] for key in ("manifest.version", "target.sdk", "target.platforms", "app.id", "app.version.name", "app.version.code", "app.name"):
if not "manifest" in manifest: if key not in manifest:
exit_with_error("Invalid manifest format: [manifest] not found") exit_with_error(f"Invalid manifest format: {key} not found")
if not "version" in manifest["manifest"]:
exit_with_error("Invalid manifest format: [manifest] version not found")
# [target]
if not "target" in manifest:
exit_with_error("Invalid manifest format: [target] not found")
if not "sdk" in manifest["target"]:
exit_with_error("Invalid manifest format: [target] sdk not found")
if not "platforms" in manifest["target"]:
exit_with_error("Invalid manifest format: [target] platforms not found")
# [app]
if not "app" in manifest:
exit_with_error("Invalid manifest format: [app] not found")
if not "id" in manifest["app"]:
exit_with_error("Invalid manifest format: [app] id not found")
if not "versionName" in manifest["app"]:
exit_with_error("Invalid manifest format: [app] versionName not found")
if not "versionCode" in manifest["app"]:
exit_with_error("Invalid manifest format: [app] versionCode not found")
if not "name" in manifest["app"]:
exit_with_error("Invalid manifest format: [app] name not found")
def is_valid_manifest_platform(manifest, platform): def is_valid_manifest_platform(manifest, platform):
manifest_platforms = manifest["target"]["platforms"].split(",") manifest_platforms = manifest["target.platforms"].split(",")
return platform in manifest_platforms return platform in manifest_platforms
def validate_manifest_platform(manifest, platform): def validate_manifest_platform(manifest, platform):
@@ -265,7 +252,7 @@ def validate_manifest_platform(manifest, platform):
def get_manifest_target_platforms(manifest, requested_platform): def get_manifest_target_platforms(manifest, requested_platform):
if requested_platform == "" or requested_platform is None: if requested_platform == "" or requested_platform is None:
return manifest["target"]["platforms"].split(",") return manifest["target.platforms"].split(",")
else: else:
validate_manifest_platform(manifest, requested_platform) validate_manifest_platform(manifest, requested_platform)
return [requested_platform] return [requested_platform]
@@ -512,7 +499,7 @@ def build_action(manifest, platform_arg, skip_build):
if use_local_sdk: if use_local_sdk:
global local_base_path global local_base_path
local_base_path = os.environ.get("TACTILITY_SDK_PATH") local_base_path = os.environ.get("TACTILITY_SDK_PATH")
validate_local_sdks(platforms_to_build, manifest["target"]["sdk"]) validate_local_sdks(platforms_to_build, manifest["target.sdk"])
if should_fetch_sdkconfig_files(platforms_to_build): if should_fetch_sdkconfig_files(platforms_to_build):
fetch_sdkconfig_files(platforms_to_build) fetch_sdkconfig_files(platforms_to_build)
@@ -521,7 +508,7 @@ def build_action(manifest, platform_arg, skip_build):
sdk_json = read_sdk_json() sdk_json = read_sdk_json()
validate_self(sdk_json) validate_self(sdk_json)
# Build # Build
sdk_version = manifest["target"]["sdk"] sdk_version = manifest["target.sdk"]
if not use_local_sdk: if not use_local_sdk:
if not sdk_download_all(sdk_version, platforms_to_build): if not sdk_download_all(sdk_version, platforms_to_build):
exit_with_error("Failed to download one or more SDKs") exit_with_error("Failed to download one or more SDKs")
@@ -570,7 +557,7 @@ def get_device_info(ip):
print_status_error(f"Device info request failed: {e}") print_status_error(f"Device info request failed: {e}")
def run_action(manifest, ip): def run_action(manifest, ip):
app_id = manifest["app"]["id"] app_id = manifest["app.id"]
print_status_busy("Running") print_status_busy("Running")
url = get_url(ip, "/app/run") url = get_url(ip, "/app/run")
params = {'id': app_id} params = {'id': app_id}
@@ -614,7 +601,7 @@ def install_action(ip, platforms):
return False return False
def uninstall_action(manifest, ip): def uninstall_action(manifest, ip):
app_id = manifest["app"]["id"] app_id = manifest["app.id"]
print_status_busy("Uninstalling") print_status_busy("Uninstalling")
url = get_url(ip, "/app/uninstall") url = get_url(ip, "/app/uninstall")
params = {'id': app_id} params = {'id': app_id}
@@ -670,7 +657,7 @@ if __name__ == "__main__":
exit_with_error("manifest.properties not found") exit_with_error("manifest.properties not found")
manifest = read_manifest() manifest = read_manifest()
validate_manifest(manifest) validate_manifest(manifest)
all_platform_targets = manifest["target"]["platforms"].split(",") all_platform_targets = manifest["target.platforms"].split(",")
# Update SDK cache (tool.json) # Update SDK cache (tool.json)
if not use_local_sdk and should_update_tool_json() and not update_tool_json(): if not use_local_sdk and should_update_tool_json() and not update_tool_json():
exit_with_error("Failed to retrieve SDK info") exit_with_error("Failed to retrieve SDK info")
+51
View File
@@ -0,0 +1,51 @@
"""Source-level contract for the Live Captions external Tactility app.
The app is ELF-loaded firmware code, so this test guards the device protocol and
persistence requirements before an ESP32-S3 build/install test is available.
"""
from pathlib import Path
import unittest
ROOT = Path(__file__).resolve().parents[1]
APP = ROOT / "Apps" / "LiveCaptions"
class LiveCaptionsContractTests(unittest.TestCase):
def test_manifest_identifies_the_captions_app(self):
manifest = (APP / "manifest.properties").read_text()
self.assertIn("app.id=one.tactility.livecaptions", manifest)
self.assertIn("app.name=Live Captions", manifest)
self.assertIn("target.platforms=esp32s3", manifest)
def test_app_streams_audio_and_logs_final_caption_to_daily_text_file(self):
source = (APP / "main" / "Source" / "main.c").read_text()
self.assertIn("audio_stream_open_input", source)
self.assertIn("/sdcard/captions", source)
self.assertIn('"%Y-%m-%d.txt"', source)
self.assertIn("append_final_caption", source)
self.assertIn('"draft"', source)
self.assertIn('"interim_transcript"', source)
self.assertIn('"transcript"', source)
self.assertIn('"final"', source)
self.assertIn("const char* stop", source)
self.assertNotIn("i2s_controller_", source)
def test_ui_autostarts_and_keeps_only_the_latest_thirty_words(self):
source = (APP / "main" / "Source" / "main.c").read_text()
self.assertIn("#define DISPLAY_WORD_LIMIT 50", source)
self.assertIn("copy_recent_words", source)
self.assertIn("tt_lvgl_toolbar_create_for_app", source)
self.assertNotIn("lv_btn_create", source)
self.assertNotIn("start_button", source)
self.assertIn("xTaskCreate(worker_task", source)
def test_connection_failure_stays_failed_until_user_starts_again(self):
source = (APP / "main" / "Source" / "main.c").read_text()
self.assertIn("CAPTION_FAILED", source)
self.assertIn("Fail to connect", source)
self.assertNotIn("retry_attempt", source)
self.assertNotIn("retry scheduled", source)
if __name__ == "__main__":
unittest.main()
+82
View File
@@ -0,0 +1,82 @@
from pathlib import Path
MP3_SOURCE = Path(__file__).parents[1] / "Apps" / "Mp3Player" / "main" / "Source" / "main.c"
def test_mp3_player_uses_the_firmware_audio_stream_device_name():
source = MP3_SOURCE.read_text(encoding="utf-8")
assert 'device_find_by_name("audio-stream0")' in source
assert 'device_find_by_name("audio-stream")' not in source
assert "device_get_first_by_type" not in source
assert "device_find_first_by_type" not in source
def test_mp3_player_restores_a_visible_persisted_volume_control_above_the_six_button_row():
source = MP3_SOURCE.read_text(encoding="utf-8")
assert "lv_obj_t* card = lv_obj_create(parent);" not in source
assert "lv_label_set_text(icon, LV_SYMBOL_AUDIO);" not in source
assert "lv_obj_t* vol_box = lv_obj_create(parent);" in source
assert "g_ctx.slider_volume = lv_slider_create(vol_box);" in source
assert "lv_slider_set_value(g_ctx.slider_volume, g_ctx.volume, LV_ANIM_OFF);" in source
assert "on_volume_slider_changed" in source
assert "save_volume(ctx);" in source
assert "lv_obj_set_size(bottom_box, lv_pct(100), 52);" in source
assert "lv_obj_t* btn_close = lv_btn_create(ctrl_box);" in source
assert "lv_obj_t* btn_hist = lv_btn_create(ctrl_box);" in source
assert "lv_label_set_text(lbl_close, LV_SYMBOL_CLOSE);" in source
assert "lv_label_set_text(lbl_hist_btn, LV_SYMBOL_DIRECTORY);" in source
assert "lv_label_set_text(lbl_back, \"-15s\");" in source
assert "lv_label_set_text(lbl_fwd, \"+15s\");" in source
def test_mp3_player_folder_button_returns_to_the_files_list():
source = MP3_SOURCE.read_text(encoding="utf-8")
library_callback = source.split("static void on_library_click", 1)[1].split("/* ─── App Lifecycle", 1)[0]
assert "tt_app_stop();" not in library_callback
assert "show_history_screen(&g_ctx);" in library_callback
assert "load_first_sd_mp3" not in library_callback
def test_mp3_player_history_view_and_fifteen_second_seek_are_present():
source = MP3_SOURCE.read_text(encoding="utf-8")
assert "#define SEEK_SECONDS 15" in source
assert 'tt_app_get_user_data_child_path(app, "play_history.txt"' in source
assert "static void show_history_screen" in source
assert "static void on_history_selected" in source
assert "char label[640];" in source
assert "request_seek(ctx, -SEEK_SECONDS);" in source
assert "request_seek(ctx, SEEK_SECONDS);" in source
def test_mp3_player_persists_and_resumes_short_tracks_too():
source = MP3_SOURCE.read_text(encoding="utf-8")
history_selector = source.split("static void on_history_selected", 1)[1].split("static void refresh_history_list", 1)[0]
assert "Skip history: audio too short" not in source
assert "Resuming last 10min+ play" not in source
assert "Resuming last play %s at %d sec from history" in source
assert "if (he->total_sec >= 600)" not in history_selector
assert "resume_pos = he->pos_sec;" in history_selector
def test_mp3_player_close_waits_for_playback_before_stopping_the_app():
source = MP3_SOURCE.read_text(encoding="utf-8")
close_callback = source.split("static void on_close_click", 1)[1].split("static void on_library_click", 1)[0]
assert "wait_for_playback_task_to_exit(&g_ctx);" in close_callback
assert close_callback.index("wait_for_playback_task_to_exit(&g_ctx);") < close_callback.index("tt_app_stop();")
assert "tt_lvgl_unlock();" in source
assert "tt_lvgl_lock(portMAX_DELAY);" in source
def test_mp3_player_has_a_consumed_dev_autoclose_hook_for_device_tests():
source = MP3_SOURCE.read_text(encoding="utf-8")
assert '"mp3player_dev_autoclose_ms"' in source
assert "on_close_click(NULL);" in source
assert "unlink(marker_path);" in source
+69
View File
@@ -0,0 +1,69 @@
import importlib.util
from pathlib import Path
RUNNER_PATH = Path(__file__).parents[1] / "scripts" / "mp3_player_device_runner.py"
def load_runner():
spec = importlib.util.spec_from_file_location("mp3_player_device_runner", RUNNER_PATH)
module = importlib.util.module_from_spec(spec)
assert spec.loader is not None
spec.loader.exec_module(module)
return module
def test_resume_trace_requires_playback_persistence_and_same_path_resume():
runner = load_runner()
fixture = "/sdcard/download/test.mp3"
trace = "\n".join(
[
"I Mp3Player: Starting MP3 playback: /sdcard/download/test.mp3 (size: 480000 bytes) resume=0",
"I Mp3Player: Audio stream opened: 16000 Hz, 1 channels",
"I Mp3Player: History saved on hide: /sdcard/download/test.mp3 pos 9 total 30",
"I Mp3Player: Resuming last play /sdcard/download/test.mp3 at 9 sec from history",
"I Mp3Player: Starting MP3 playback: /sdcard/download/test.mp3 (size: 480000 bytes) resume=9",
]
)
result = runner.evaluate_resume_trace(trace, fixture, minimum_position=6)
assert result == {"persisted_position": 9, "resumed_position": 9}
def test_resume_trace_rejects_a_different_file_or_no_playback_evidence():
runner = load_runner()
fixture = "/sdcard/download/test.mp3"
try:
runner.evaluate_resume_trace(
"I Mp3Player: Starting MP3 playback: /sdcard/other.mp3 (size: 1 bytes) resume=0",
fixture,
minimum_position=6,
)
except RuntimeError as exc:
assert "playback" in str(exc).lower()
else:
raise AssertionError("missing playback evidence must fail")
def test_resume_trace_rejects_forced_playback_task_termination():
runner = load_runner()
fixture = "/sdcard/download/test.mp3"
trace = "\n".join(
[
f"I Mp3Player: Starting MP3 playback: {fixture} (size: 480000 bytes) resume=0",
"I Mp3Player: Audio stream opened: 16000 Hz, 1 channels",
f"I Mp3Player: History saved on hide: {fixture} pos 9 total 180",
"W Mp3Player: Playback task stuck, force deleting",
f"I Mp3Player: Resuming last play {fixture} at 9 sec from history",
f"I Mp3Player: Starting MP3 playback: {fixture} (size: 480000 bytes) resume=9",
]
)
try:
runner.evaluate_resume_trace(trace, fixture, minimum_position=6)
except RuntimeError as exc:
assert "forced" in str(exc).lower()
else:
raise AssertionError("forced task termination must fail the device test")