Compare commits
83 Commits
221b95a950
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 02c02a821d | |||
| 41103e3b5e | |||
| c641671d24 | |||
| 4c16686c6b | |||
| fd30ac3eb1 | |||
| e2721d6bd1 | |||
| d4aa9c7be1 | |||
| 5f27262b27 | |||
| ee03d9f9f1 | |||
| ec65374e8d | |||
| 214d6b2c29 | |||
| 1d613b16c1 | |||
| 05f4ce45c3 | |||
| 62b32c31ff | |||
| 5d1627f8d0 | |||
| d744a36275 | |||
| b2c5496057 | |||
| b36419477c | |||
| c4468c4af0 | |||
| 122e46e862 | |||
| bbeb7d3fd2 | |||
| c9e06da47c | |||
| faf427c897 | |||
| e5c3c0ad8a | |||
| fd88e02e96 | |||
| a55a3ce14a | |||
| 8485ecb5b7 | |||
| 9e1ca98a5d | |||
| c6ecbbeb25 | |||
| 78c480a7c2 | |||
| b8702e6faa | |||
| 5ce4588c80 | |||
| 8008aa175f | |||
| f0fe53d5d1 | |||
| 0aac7bc339 | |||
| 8ba4de5eda | |||
| cd747aec40 | |||
| 4a38254660 | |||
| 5b0d7c9ba4 | |||
| c240ac9a3c | |||
| 039ec75473 | |||
| 7bbda0a1e8 | |||
| c0e0388ff0 | |||
| 3ebb27e4bb | |||
| 8a6cb53e3b | |||
| 852c0ffa0f | |||
| d3897f3179 | |||
| 2a7ab7922d | |||
| 1961c7fe13 | |||
| e763dc81bd | |||
| 5bd1a20e43 | |||
| dcea39b216 | |||
| 08b83a069c | |||
| 6d85eb49f8 | |||
| e2dc7552c2 | |||
| f6dfa80b19 | |||
| 2dd8f60cd6 | |||
| 2522901918 | |||
| 8b3bd39857 | |||
| f3779696d5 | |||
| 044e9913a7 | |||
| bae6a8a2f9 | |||
| 3d05768f00 | |||
| 004cc6e212 | |||
| 9af6c53294 | |||
| 685060e12c | |||
| e2f4d81326 | |||
| 880437948d | |||
| 6090ceb239 | |||
| f259c5d554 | |||
| ad5a8b7545 | |||
| bbc5729cc1 | |||
| 2403a6b64b | |||
| cbfc37cde6 | |||
| 07e16e6163 | |||
| 30c32e702b | |||
| 979420a6bb | |||
| 8e52401e9c | |||
| c2621f192a | |||
| 35275b8ccf | |||
| 69b4e18118 | |||
| b391b962a7 | |||
| bbfd3506bf |
@@ -0,0 +1,6 @@
|
|||||||
|
build/
|
||||||
|
sdkconfig
|
||||||
|
sdkconfig.old
|
||||||
|
managed_components/
|
||||||
|
build-*/
|
||||||
|
tools/__pycache__/
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
[submodule "external/cspot"]
|
||||||
|
path = external/cspot
|
||||||
|
url = https://github.com/philippe44/cspot.git
|
||||||
@@ -15,6 +15,7 @@ Repo: https://gitea.apointless.space/bsncubed/aes67-ESP32-P4
|
|||||||
- After every change: `idf.py build`, flash, and check the serial monitor output. Show the relevant log lines.
|
- After every change: `idf.py build`, flash, and check the serial monitor output. Show the relevant log lines.
|
||||||
- Don't mark a step done until it has been verified on the board.
|
- Don't mark a step done until it has been verified on the board.
|
||||||
- Keep core and project separate: `components/aes67_*` must not depend on `main/` (sources/player). Project code plugs in through the config, status and route registries.
|
- Keep core and project separate: `components/aes67_*` must not depend on `main/` (sources/player). Project code plugs in through the config, status and route registries.
|
||||||
|
- Licences: core (`components/aes67_*`) and `web/` are MIT, the rest GPL-3.0-or-later (see THIRD_PARTY.md). Never pull GPL code (cspot, bell, squeezelite) into the core. New third-party code: check its licence first and add it to THIRD_PARTY.md.
|
||||||
- `web/index.html`: keep the CORE / PROJECT markers. If the firmware needs an API change, change the doc and the page together.
|
- `web/index.html`: keep the CORE / PROJECT markers. If the firmware needs an API change, change the doc and the page together.
|
||||||
- Small, focused commits per step.
|
- Small, focused commits per step.
|
||||||
|
|
||||||
@@ -23,8 +24,19 @@ Repo: https://gitea.apointless.space/bsncubed/aes67-ESP32-P4
|
|||||||
- `idf.py set-target esp32p4`, `idf.py build`, `idf.py -p <PORT> flash monitor`
|
- `idf.py set-target esp32p4`, `idf.py build`, `idf.py -p <PORT> flash monitor`
|
||||||
- Before first build: run `esptool.py chip_id` and `esptool.py flash_id`.
|
- Before first build: run `esptool.py chip_id` and `esptool.py flash_id`.
|
||||||
- Chip revision < v3.0 (engineering silicon, seen on some of these boards) needs `CONFIG_ESP32P4_SELECTS_REV_LESS_V3=y`.
|
- Chip revision < v3.0 (engineering silicon, seen on some of these boards) needs `CONFIG_ESP32P4_SELECTS_REV_LESS_V3=y`.
|
||||||
- Flash size is unconfirmed (Waveshare says 32 MB, ESPHome says 16 MB). Set it from the flash_id result.
|
Our board: **v1.3** (set in sdkconfig.defaults, min rev v1.0).
|
||||||
|
- Our board: **32 MB** flash (GigaDevice c8/4019). App slots must stay below 16 MB (cache mapping above 16 MB is experimental in IDF).
|
||||||
|
- Rev < 3 also limits Espressif's prebuilt audio libraries: `esp_audio_codec` must stay < 2.6 and `esp_audio_effects` < 1.4 (newer versions use P4 assembly that needs rev >= 3; the build fails with a message saying so). Check this for any new Espressif binary component.
|
||||||
- Embed `web/index.html` via `EMBED_TXTFILES` in `aes67_web`.
|
- Embed `web/index.html` via `EMBED_TXTFILES` in `aes67_web`.
|
||||||
|
- cspot (Spotify, `external/cspot` git submodule, philippe44 fork, pinned): after cloning run `git submodule update --init external/cspot && git -C external/cspot submodule update --init cspot/bell`. Its nanopb code generator needs, in the IDF Python env: `python -m pip install protobuf grpcio-tools 'setuptools<81'` (after `. export.sh`). Our fixes to cspot/bell live in `components/spotify/patches/{cspot,bell}/*.patch` and are applied automatically at configure time; don't edit the submodule directly, add a patch.
|
||||||
|
- Firmware version: `<version.txt>-<git short hash>`, e.g. `0.0.1-1d613b1`. Bump `version.txt` for a release; the hash is the commit that was built (commit first, then build, so it matches). No dirty flag.
|
||||||
|
- Flash over the network (normal way since step 2b; keep USB for recovery):
|
||||||
|
`curl -f --data-binary @build/aes67_p4.bin -H 'Content-Type: application/octet-stream' http://p4-aes67/api/ota`
|
||||||
|
The board reboots into the new image on trial; check `GET /api/ota` shows the new version with `pending_verify: false`.
|
||||||
|
- Another board, over USB: `tools/flash_board.py` (checks chip revision and flash size, optional erase, flashes, finds the IP in the boot log, sets hostname / stream name / multicast so boards don't clash). Needs a build and esptool (IDF env or `pip install esptool`).
|
||||||
|
- Serial: opening /dev/ttyACM0 can reset the board. Don't open it while an OTA image is on trial (a reset then counts as a failed boot and rolls back).
|
||||||
|
- Rollback test build (self-test always fails), in its own build dir:
|
||||||
|
`idf.py -B build-selftest-fail -DSDKCONFIG=build-selftest-fail/sdkconfig -DSDKCONFIG_DEFAULTS="sdkconfig.defaults;sdkconfig.selftest_fail" build`
|
||||||
|
|
||||||
## Board quick reference (full details in docs)
|
## Board quick reference (full details in docs)
|
||||||
- Ethernet: IP101GRI, RMII, PHY addr 1, ref clock from PHY into GPIO50 (EMAC_CLK_EXT_IN).
|
- Ethernet: IP101GRI, RMII, PHY addr 1, ref clock from PHY into GPIO50 (EMAC_CLK_EXT_IN).
|
||||||
@@ -33,13 +45,59 @@ Repo: https://gitea.apointless.space/bsncubed/aes67-ESP32-P4
|
|||||||
- On-die temperature sensor only (driver/temperature_sensor.h).
|
- On-die temperature sensor only (driver/temperature_sensor.h).
|
||||||
|
|
||||||
## Build order / status
|
## Build order / status
|
||||||
- [ ] 0. Check chip revision and flash size; create IDF project and empty component stubs (layout in aes67-core-base.md). Set up the OTA partition table (two app slots, no factory) and PROJECT_VER from git now, so the layout never changes later.
|
- [x] 0. Check chip revision and flash size; create IDF project and empty component stubs (layout in aes67-core-base.md). Set up the OTA partition table (two app slots, no factory) and PROJECT_VER now, so the layout never changes later. (PROJECT_VER = `version.txt` + git short hash.)
|
||||||
- [ ] 1. Ethernet: IP101 up, DHCP, IP logged. Ping works.
|
- [x] 1. Ethernet: IP101 up, DHCP, IP logged. Ping works.
|
||||||
- [ ] 2. Web server + config store (cJSON in NVS) + embedded index.html; /api/config, /api/status (stub values), /api/reboot.
|
- [x] 2. Web server + config store (cJSON in NVS) + embedded index.html; /api/config, /api/status (stub values), /api/reboot.
|
||||||
- [ ] 2b. Firmware update: /api/ota upload + rollback self-test. Test: update to a new build, then deliberately flash a build that fails its self-test and confirm it rolls back. After this, flash over the network; keep USB for recovery.
|
- [x] 2a. Finding the device: mDNS (hostname.local + _http._tcp), then LLDP (switch shows name + IP).
|
||||||
- [ ] 3. PTP TimeReceiver: lock to an existing GM (Riedel), fill `status.ptp`. Confirm EMAC hardware timestamps work. First check whether the installed ESP-IDF has a PTP example/component for the P4 before writing one.
|
- [x] 2b. Firmware update: /api/ota upload + rollback self-test. Test: update to a new build, then deliberately flash a build that fails its self-test and confirm it rolls back. After this, flash over the network; keep USB for recovery.
|
||||||
|
- [x] 3. PTP TimeReceiver: lock to an existing GM (Riedel), fill `status.ptp`. Confirm EMAC hardware timestamps work. First check whether the installed ESP-IDF has a PTP example/component for the P4 before writing one.
|
||||||
- [ ] 4. AES67 TX with a 1 kHz test tone, PTP-paced; /stream.sdp. Verify: import SDP on a Riedel Artist 4-wire AES67 port, and check packets/timestamps in Wireshark.
|
- [ ] 4. AES67 TX with a 1 kHz test tone, PTP-paced; /stream.sdp. Verify: import SDP on a Riedel Artist 4-wire AES67 port, and check packets/timestamps in Wireshark.
|
||||||
- [ ] 5. SAP discovery, then syslog, then health/temperatures, then VLAN split (one at a time).
|
Done and checked with a receiver script (all ptimes, L16/L24, tone phase-locked to PTP); still open: the Riedel import and a Wireshark capture.
|
||||||
- [ ] 6. PTP TimeTransmitter: BMCA roles (auto/master), hybrid mode.
|
- [x] 5. SAP discovery, then syslog, then health/temperatures (one at a time). VLAN split moved to phase 2.
|
||||||
|
- [x] 6. PTP TimeTransmitter: BMCA roles (slave/auto; the separate "master" role was dropped later, auto with a low priority1 does the same), hybrid mode.
|
||||||
- [ ] 7. Sources: HLS player, then cspot (Spotify Connect), then failover + /api/player.
|
- [ ] 7. Sources: HLS player, then cspot (Spotify Connect), then failover + /api/player.
|
||||||
|
- [x] 7.1-7.4 HLS plays on AES67 (PSRAM ring, TS demux + AAC, 44.1 -> 48 kHz). Tested with Triple J Hottest (TS, AAC-LC 44.1k).
|
||||||
|
- [ ] Come back to HLS (open items):
|
||||||
|
- Clock drift: the station's encoder clock vs our PTP clock is not corrected. Starts 3 segments (~30 s) behind live, so it shows after hours/days (skip when falling out of the live window, or buffering). Fix: steer the 44.1 -> 48 kHz ratio by a few ppm from the distance to the live edge / ring level.
|
||||||
|
- Download speed ~1.4 Mbit/s over TLS (fine for ~250 kbit/s; tune buffer sizes / per-chunk overhead).
|
||||||
|
- Not yet tested: HE-AAC variant (140k), other stations, fMP4/ADTS-only playlists, discontinuities (#EXT-X-DISCONTINUITY), network loss and recovery, long runs.
|
||||||
|
- Audio starts only after PTP lock (~20 s after boot): intended, TX needs PTP.
|
||||||
|
- [ ] cspot (Spotify Connect): login, audio, pause/skip/seek, app volume, live mode switching work; stays connected across track changes and past 6 min (7.5b). Fixed so far: logger NULL crash, Vorbis symbol clash, volume starting at 0, reconnect race (PR #3 patch), 6-minute AP resets (delayed Pong patch), app dropping the device (notifyAudioReachedPlayback). Open:
|
||||||
|
- OTA with a session: now ends the session first; 2 of 2 uploads with a running session were clean since. Flash writes still stall TX > 20 ms during uploads (stream stutters while updating).
|
||||||
|
- First connects sometimes fail ("Can't connect to spotify servers"), a retry works.
|
||||||
|
- Internal heap drops from ~365 KB to ~231 KB with a session; check what can move to PSRAM.
|
||||||
|
- Track display in the app can switch ~3-5 s early.
|
||||||
|
- Mute at 0 % volume not yet confirmed.
|
||||||
|
- Consider offering the delayed-Pong fix upstream (philippe44/cspot).
|
||||||
|
- An old, long-idle session can get out of sync with the app: it sends empty Load frames ("No tracks in frame") instead of Pause/Play, so controls do nothing. Quitting and reopening Spotify on the Mac fixes it.
|
||||||
|
- [x] failover (auto mode): no session or (with `failover_on_pause`) paused for `failover_delay_s` -> HLS; Spotify playing -> Spotify within ~1 s; 30 ms fades; HLS suspended while Spotify plays; cspot is held back (not drained) while it isn't Spotify's turn, so it resumes where it paused. Verified: no session -> HLS, play -> Spotify, pause stays (on_pause off), pause -> HLS after 5 s (on_pause on), play -> Spotify at the paused position.
|
||||||
|
- Open: `aes67_tx resync` (TX 20-27 ms late) ~11 s after each switch to Spotify (seen 3 times); clicks at switches not yet checked in a recording; HLS start sometimes hits CDN read timeouts.
|
||||||
|
- [x] /api/player: GET, transport, seek, volume (the app follows), source override and url (runtime, not saved); web UI progress bar.
|
||||||
- [ ] 8. Mono sum, gain, polish.
|
- [ ] 8. Mono sum, gain, polish.
|
||||||
|
- [x] Mono sum: stereo source mapped to a 1-channel stream in the core ((L+R)/2, 64 bit). Checked: 156 B packets, SDP L24/48000/1.
|
||||||
|
- [x] Gain: source.gain_db as a trim on top of the volume, saturating. Checked: -12 dB = -12 dB peak, +12 dB clips at 0 dBFS.
|
||||||
|
- [x] Pink noise source (-18 dBFS RMS, octaves flat within 0.4 dB 63 Hz-4 kHz).
|
||||||
|
- [x] 48 kHz only (96 kHz dropped: all sources are 48 kHz).
|
||||||
|
- [x] Network: status mask/gw/dns, UI shows the lease; static IP (reboot on change, validation).
|
||||||
|
- [x] Web UI: sticky save bar, dark default + light toggle, progress bar, PTP panel (2 min average offset, details), uptime d/h/m/s, VLAN option hidden, no hw_ts / preferred-TimeTransmitter options.
|
||||||
|
- [x] Versioning `<version.txt>-<git hash>`; tools/flash_board.py (tested on this board); docs/user-guide.md.
|
||||||
|
- [ ] Mute at 0 % volume: confirm on the board.
|
||||||
|
|
||||||
|
## Phase 2 (parked)
|
||||||
|
- [ ] Replace the Espressif binary audio libraries (GPL-3 conflict, see THIRD_PARTY.md): AAC via opencore-aacdec (Apache-2.0, in bell/external), 44.1 -> 48 kHz via the Speex resampler (BSD). Do together with / right before the clock-drift correction (Speex can steer the ratio).
|
||||||
|
- [ ] Clock-drift correction (do before AirPlay): steer the 44.1 -> 48 kHz converter by a few ppm from the ring level / distance to the live edge, so push sources that run on the sender's clock don't slowly over- or underrun. Closes the HLS clock-drift item in step 7; AirPlay needs the same.
|
||||||
|
- [ ] AirPlay 1 (RAOP) as a source: `_raop._tcp` via our mDNS, RTSP control, AES (mbedTLS), ALAC decode, RTP audio + timing, 44.1 kHz into the existing converter, uses the clock-drift correction. Start from philippe44's RAOP code in squeezelite-esp32 (`components/raop`, checked 2026-09-27 at commit 1d542bd):
|
||||||
|
- Take `raop.c`, `util.c` (MIT, philippe44) and `rtp.c` (MIT, James Laird/shairport); keep their headers. Write our own glue to the player (their `raop_sink.c` has no licence header and the repo has no LICENSE file; it's specific to squeezelite anyway).
|
||||||
|
- ALAC: they link a prebuilt `libalac.a`; build Apple's ALAC from source instead (Apache-2.0, already in `external/cspot/cspot/bell/external/alac`).
|
||||||
|
- `dmap_parser.c` (track metadata) has no header: confirm its origin (likely the MIT dmap-parser project) or leave it out.
|
||||||
|
- `raop.c` contains the AirPort Express RSA private key (reverse-engineered in 2011, in every AirPlay 1 receiver): known grey area.
|
||||||
|
- Code is written for squeezelite-esp32's platform (pthreads, their logging, OpenSSL/mbedTLS switches, NVS): needs porting like cspot. `rtp.c` hands each frame to the sink with its play time (NTP-synced to the sender); following the sender's clock is the sink's job, i.e. our clock-drift correction. Covers iPhone/iPad/Mac (incl. Tidal and Apple Music apps) and Windows via AirPlay senders (TuneBlade, Airfoil). Not AirPlay 2 (HomeKit pairing, its own PTP on ports 319/320 clashes with ours). Then: auto mode as a priority list (whichever source plays wins, HLS as fallback). Check internal heap with Spotify + AirPlay sessions (buffers to PSRAM).
|
||||||
|
- [ ] VLAN split: AES67 untagged + internet tagged (inet.vlan_id/pcp), per aes67-core-base.md "Network". Needs a tagged VLAN with DHCP on the switch port. Config group `inet` and the UI fields exist already; nothing is applied yet. The "VLAN split" checkbox is hidden in web/index.html (`<label hidden>`); unhide it when this is done.
|
||||||
|
- [ ] NTP (SNTP): servers as hostnames or IPs (e.g. `pool.ntp.org`, several allowed; names resolved via DNS, re-resolved on failure). Uses: seed the PTP clock with real time before becoming GM (today it starts at 1970), syslog timestamps. Needs a `time` config group + UI fields (change doc and page together).
|
||||||
|
- [ ] Factory reset buton in the webgui with a confromation popup.
|
||||||
|
|
||||||
|
## Phase 3 (parked)
|
||||||
|
- [ ] Remote access via VPN / Tailscale. There is no official Tailscale client for ESP32; options to evaluate first:
|
||||||
|
(a) no firmware change: a Tailscale subnet router on the LAN (e.g. the dev PC or a Pi) advertising the device's subnet;
|
||||||
|
(b) WireGuard on the device (e.g. the `esp_wireguard` component) to a WireGuard server or a Tailscale/Headscale-compatible peer.
|
||||||
|
Before exposing the web/API remotely: add authentication (bearer token) as noted in the OTA/security section of aes67-core-base.md. Keep AES67/PTP traffic off the tunnel.
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
cmake_minimum_required(VERSION 3.16)
|
||||||
|
|
||||||
|
# Firmware version = "<version.txt>-<git short hash>", e.g. 0.0.1-1d613b1. The first part is set by
|
||||||
|
# hand in version.txt; the hash says which commit was built (no dirty flag: the build always patches
|
||||||
|
# the cspot submodule). Reported by esp_app_get_description(), status.fw and GET /api/ota.
|
||||||
|
# CMake re-runs when version.txt or the checked-out commit changes.
|
||||||
|
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/version.txt
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/.git/logs/HEAD)
|
||||||
|
file(STRINGS ${CMAKE_CURRENT_LIST_DIR}/version.txt PROJECT_VER LIMIT_COUNT 1)
|
||||||
|
execute_process(
|
||||||
|
COMMAND git rev-parse --short HEAD
|
||||||
|
WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}
|
||||||
|
OUTPUT_VARIABLE GIT_HASH
|
||||||
|
OUTPUT_STRIP_TRAILING_WHITESPACE
|
||||||
|
ERROR_QUIET)
|
||||||
|
if(GIT_HASH)
|
||||||
|
set(PROJECT_VER "${PROJECT_VER}-${GIT_HASH}")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||||
|
project(aes67_p4)
|
||||||
@@ -0,0 +1,674 @@
|
|||||||
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
|
GNU General Public License for most of our software; it applies also to
|
||||||
|
any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you
|
||||||
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether
|
||||||
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
|
or can get the source code. And you must show them these terms so they
|
||||||
|
know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
|
that there is no warranty for this free software. For both users' and
|
||||||
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
|
changed, so that their problems will not be attributed erroneously to
|
||||||
|
authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run
|
||||||
|
modified versions of the software inside them, although the manufacturer
|
||||||
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
|
protecting users' freedom to change the software. The systematic
|
||||||
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents.
|
||||||
|
States should not allow patents to restrict development and use of
|
||||||
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
|
avoid the special danger that patents applied to a free program could
|
||||||
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
|
patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the special requirements of the GNU Affero General Public License,
|
||||||
|
section 13, concerning interaction through a network will apply to the
|
||||||
|
combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short
|
||||||
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
<program> Copyright (C) <year> <name of author>
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, your program's commands
|
||||||
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program
|
||||||
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License. But first, please read
|
||||||
|
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||||
@@ -1,10 +1,28 @@
|
|||||||
# aes67-ESP32-P4
|
# aes67-ESP32-P4
|
||||||
|
|
||||||
AES67 sender for the Waveshare ESP32-P4-ETH (PoE): Spotify Connect and HLS/m3u8 streams out as an AES67 multicast stream, PTP-locked, with a simple web UI for settings and SDP export.
|
AES67 sender for the Waveshare ESP32-P4-ETH (PoE): Spotify Connect and HLS/m3u8 internet radio (with failover between them) go out as an AES67 multicast stream, locked to PTP. Everything is set up from a built-in web page, with SAP announcements and SDP export for receivers (tested with Riedel PTP).
|
||||||
|
|
||||||
- `docs/aes67-core-base.md` — reusable AES67 core design (PTP, RTP, SDP/SAP, VLAN, syslog, web UI contract)
|
**Using it:** see the [user guide](docs/user-guide.md).
|
||||||
- `docs/hardware-and-design-notes.md` — board details and project-specific design
|
|
||||||
- `web/index.html` — web UI (served by the device)
|
|
||||||
- `CLAUDE.md` — working rules and build order
|
|
||||||
|
|
||||||
Status: design complete, firmware not started. See the build order in CLAUDE.md.
|
**Quick start:** power the board over PoE and open http://p4-aes67.local/. Pick a source and save. Then find "P4 AES67" via SAP on the receiver, or import the SDP from the page.
|
||||||
|
|
||||||
|
## Building and flashing
|
||||||
|
|
||||||
|
- ESP-IDF 5.5 or later, target `esp32p4`: `idf.py set-target esp32p4 && idf.py build`
|
||||||
|
- cspot submodule: `git submodule update --init external/cspot && git -C external/cspot submodule update --init cspot/bell`
|
||||||
|
- New board over USB: `tools/flash_board.py`
|
||||||
|
- Update over the network: web page → Firmware, or `curl -f --data-binary @build/aes67_p4.bin -H 'Content-Type: application/octet-stream' http://p4-aes67.local/api/ota`
|
||||||
|
|
||||||
|
Toolchain details and caveats (chip revision, Python packages for cspot) are in `CLAUDE.md`.
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
- `docs/user-guide.md`: setup, web page, sources, Spotify, AES67, PTP, network, updates, player API, troubleshooting
|
||||||
|
- `docs/aes67-core-base.md`: reusable AES67 core design (PTP, RTP, SDP/SAP, syslog, web UI and API contract)
|
||||||
|
- `docs/hardware-and-design-notes.md`: board details and project-specific design
|
||||||
|
- `web/index.html`: the web page (served by the device)
|
||||||
|
- `CLAUDE.md`: working rules, build order and status
|
||||||
|
|
||||||
|
## Licence
|
||||||
|
|
||||||
|
The AES67 core (`components/aes67_*`) and the web page (`web/`) are MIT. Everything else is GPL-3.0-or-later (`LICENSE`). The firmware image contains cspot (GPL-3.0), so distributing it falls under GPL-3.0. Third-party code, its licences and a known conflict with two Espressif binary libraries: [THIRD_PARTY.md](THIRD_PARTY.md).
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
# Licences
|
||||||
|
|
||||||
|
## This project
|
||||||
|
|
||||||
|
| Part | Licence |
|
||||||
|
|---|---|
|
||||||
|
| AES67 core: `components/aes67_*` (each has its own `LICENSE`) | MIT |
|
||||||
|
| Web page: `web/index.html` (`web/LICENSE`) | MIT |
|
||||||
|
| Everything else: `main/`, `components/spotify/` (incl. our cspot/bell patches), `tools/`, docs, build files | GPL-3.0-or-later (`LICENSE`) |
|
||||||
|
|
||||||
|
The core is MIT so it can be reused in other AES67 projects, including closed ones. It must not depend on GPL code: nothing in `components/aes67_*` may include or link cspot or `main/`.
|
||||||
|
|
||||||
|
The firmware image as a whole contains cspot (GPL-3.0), so anyone who distributes the firmware (a `.bin` or a flashed board) must do so under GPL-3.0, with the complete corresponding source.
|
||||||
|
|
||||||
|
## Third-party code in the firmware
|
||||||
|
|
||||||
|
| Code | Used for | Licence | Notes |
|
||||||
|
|---|---|---|---|
|
||||||
|
| [cspot](https://github.com/philippe44/cspot) (philippe44 fork, `external/cspot`) | Spotify Connect | GPL-3.0-or-later | Our patches: `components/spotify/patches/cspot` |
|
||||||
|
| [bell](https://github.com/philippe44/bell) (cspot submodule) | cspot's I/O and utilities | no licence file | Part of the cspot project; licence to be confirmed with the author |
|
||||||
|
| tremor (via bell) | Vorbis decoding (Spotify) | BSD-3-Clause (Xiph.Org) | |
|
||||||
|
| nanopb (via bell) | Protobuf (Spotify protocol) | zlib | |
|
||||||
|
| ESP-IDF, incl. mbedTLS, esp_http_server, esp_eth | Platform, TLS, web server, Ethernet | Apache-2.0 | mbedTLS is dual Apache-2.0 / GPL-2.0-or-later |
|
||||||
|
| lwIP | TCP/IP | BSD-3-Clause | |
|
||||||
|
| FreeRTOS | RTOS | MIT | |
|
||||||
|
| cJSON | JSON | MIT | |
|
||||||
|
| espressif/mdns | mDNS | Apache-2.0 | |
|
||||||
|
| **espressif/esp_audio_codec** | AAC decoding (HLS) | **Espressif Modified MIT, prebuilt binary** | Only allowed with Espressif chips; no source |
|
||||||
|
| **espressif/esp_audio_effects**, gmf_fft | 44.1 → 48 kHz conversion | **Espressif Modified MIT**; esp_audio_effects is a prebuilt binary | as above |
|
||||||
|
|
||||||
|
Algorithms: pink noise uses Paul Kellet's filter and a xorshift32 generator (both public domain).
|
||||||
|
|
||||||
|
## Known conflict
|
||||||
|
|
||||||
|
The two Espressif binary libraries can't be distributed under GPL-3.0: there is no source, and "Espressif chips only" is an additional restriction that GPL-3.0 forbids. A firmware image containing both them and cspot therefore can't be distributed in line with GPL-3.0. Private use is not affected.
|
||||||
|
|
||||||
|
Planned fix (phase 2 in `CLAUDE.md`): replace them with open code, e.g. opencore-aacdec (Apache-2.0, already in `bell/external`) for AAC and the Speex resampler (BSD) for the sample-rate conversion. The Speex resampler can also do the fine rate steering the clock-drift correction needs.
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
idf_component_register(SRCS "aes67_board.c"
|
||||||
|
INCLUDE_DIRS "include"
|
||||||
|
REQUIRES esp_eth)
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 Ben Nicholson
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
#include "aes67_board.h"
|
||||||
|
|
||||||
|
#include "esp_eth.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "boards/waveshare_esp32p4_eth.h"
|
||||||
|
|
||||||
|
static const char *TAG = "board";
|
||||||
|
|
||||||
|
esp_err_t aes67_board_eth_init(esp_eth_handle_t *out_eth)
|
||||||
|
{
|
||||||
|
eth_mac_config_t mac_cfg = ETH_MAC_DEFAULT_CONFIG();
|
||||||
|
eth_esp32_emac_config_t emac_cfg = ETH_ESP32_EMAC_DEFAULT_CONFIG();
|
||||||
|
emac_cfg.smi_gpio.mdc_num = BOARD_ETH_MDC;
|
||||||
|
emac_cfg.smi_gpio.mdio_num = BOARD_ETH_MDIO;
|
||||||
|
emac_cfg.interface = EMAC_DATA_INTERFACE_RMII;
|
||||||
|
emac_cfg.clock_config.rmii.clock_mode = EMAC_CLK_EXT_IN;
|
||||||
|
emac_cfg.clock_config.rmii.clock_gpio = (emac_rmii_clock_gpio_t)BOARD_ETH_REF_CLK;
|
||||||
|
emac_cfg.emac_dataif_gpio.rmii.tx_en_num = BOARD_ETH_TX_EN;
|
||||||
|
emac_cfg.emac_dataif_gpio.rmii.txd0_num = BOARD_ETH_TXD0;
|
||||||
|
emac_cfg.emac_dataif_gpio.rmii.txd1_num = BOARD_ETH_TXD1;
|
||||||
|
emac_cfg.emac_dataif_gpio.rmii.crs_dv_num = BOARD_ETH_CRS_DV;
|
||||||
|
emac_cfg.emac_dataif_gpio.rmii.rxd0_num = BOARD_ETH_RXD0;
|
||||||
|
emac_cfg.emac_dataif_gpio.rmii.rxd1_num = BOARD_ETH_RXD1;
|
||||||
|
|
||||||
|
eth_phy_config_t phy_cfg = ETH_PHY_DEFAULT_CONFIG();
|
||||||
|
phy_cfg.phy_addr = BOARD_ETH_PHY_ADDR;
|
||||||
|
phy_cfg.reset_gpio_num = BOARD_ETH_PHY_RST;
|
||||||
|
|
||||||
|
esp_eth_mac_t *mac = esp_eth_mac_new_esp32(&emac_cfg, &mac_cfg);
|
||||||
|
esp_eth_phy_t *phy = esp_eth_phy_new_ip101(&phy_cfg);
|
||||||
|
if (!mac || !phy) {
|
||||||
|
ESP_LOGE(TAG, "EMAC/PHY create failed");
|
||||||
|
return ESP_FAIL;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_eth_config_t eth_cfg = ETH_DEFAULT_CONFIG(mac, phy);
|
||||||
|
esp_err_t err = esp_eth_driver_install(ð_cfg, out_eth);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
ESP_LOGE(TAG, "driver install failed: %s", esp_err_to_name(err));
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
ESP_LOGI(TAG, "%s: IP101 at PHY addr %d, RMII", BOARD_NAME, BOARD_ETH_PHY_ADDR);
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
// aes67_board: Board pin profiles (waveshare_esp32p4_eth.h, ...) and Ethernet init.
|
||||||
|
// Core component: must not depend on main/ (project code).
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "esp_err.h"
|
||||||
|
#include "esp_eth_driver.h"
|
||||||
|
|
||||||
|
// Create and install the Ethernet driver (EMAC + PHY) for this board. Does not start it.
|
||||||
|
esp_err_t aes67_board_eth_init(esp_eth_handle_t *out_eth);
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
// Waveshare ESP32-P4-ETH (PoE): pin profile.
|
||||||
|
// IP101GRI PHY over RMII, 50 MHz ref clock from the PHY into the EMAC.
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#define BOARD_NAME "Waveshare ESP32-P4-ETH"
|
||||||
|
|
||||||
|
#define BOARD_ETH_PHY_ADDR 1
|
||||||
|
#define BOARD_ETH_PHY_RST 51 // PHY reset/power
|
||||||
|
#define BOARD_ETH_MDC 31
|
||||||
|
#define BOARD_ETH_MDIO 52
|
||||||
|
#define BOARD_ETH_REF_CLK 50 // EMAC_CLK_EXT_IN
|
||||||
|
#define BOARD_ETH_TX_EN 49
|
||||||
|
#define BOARD_ETH_TXD0 34
|
||||||
|
#define BOARD_ETH_TXD1 35
|
||||||
|
#define BOARD_ETH_CRS_DV 28
|
||||||
|
#define BOARD_ETH_RXD0 29
|
||||||
|
#define BOARD_ETH_RXD1 30
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
idf_component_register(SRCS "aes67_health.c"
|
||||||
|
INCLUDE_DIRS "include"
|
||||||
|
PRIV_REQUIRES aes67_web esp_app_format esp_driver_tsens esp_timer heap)
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 Ben Nicholson
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
#include "aes67_health.h"
|
||||||
|
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "aes67_web.h"
|
||||||
|
#include "driver/temperature_sensor.h"
|
||||||
|
#include "esp_app_desc.h"
|
||||||
|
#include "esp_heap_caps.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_timer.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/semphr.h"
|
||||||
|
#include "freertos/task.h"
|
||||||
|
|
||||||
|
#define MAX_SENSORS 8
|
||||||
|
#define SAMPLE_MS 2000
|
||||||
|
#define HYSTERESIS_C 5.0f
|
||||||
|
#define SOC_WARN_C 85.0f
|
||||||
|
|
||||||
|
static const char *TAG = "health";
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
char name[16];
|
||||||
|
health_temp_read_cb_t read;
|
||||||
|
float warn_c;
|
||||||
|
bool valid, hot;
|
||||||
|
float c, min_c, max_c;
|
||||||
|
} sensor_t;
|
||||||
|
|
||||||
|
static sensor_t s_sensors[MAX_SENSORS];
|
||||||
|
static int s_n;
|
||||||
|
static SemaphoreHandle_t s_lock;
|
||||||
|
static temperature_sensor_handle_t s_tsens;
|
||||||
|
|
||||||
|
esp_err_t health_temp_register(const char *name, health_temp_read_cb_t read, float warn_c)
|
||||||
|
{
|
||||||
|
if (!s_lock || s_n >= MAX_SENSORS) {
|
||||||
|
return ESP_ERR_INVALID_STATE;
|
||||||
|
}
|
||||||
|
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||||
|
sensor_t *t = &s_sensors[s_n++];
|
||||||
|
strlcpy(t->name, name, sizeof(t->name));
|
||||||
|
t->read = read;
|
||||||
|
t->warn_c = warn_c;
|
||||||
|
xSemaphoreGive(s_lock);
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
// On-die sensor: measures the die, not ambient; expect well above room temperature.
|
||||||
|
static esp_err_t soc_read(float *c)
|
||||||
|
{
|
||||||
|
return temperature_sensor_get_celsius(s_tsens, c);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void health_task(void *arg)
|
||||||
|
{
|
||||||
|
while (1) {
|
||||||
|
for (int i = 0; i < s_n; i++) {
|
||||||
|
float c;
|
||||||
|
if (s_sensors[i].read(&c) != ESP_OK) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||||
|
sensor_t *t = &s_sensors[i];
|
||||||
|
t->c = c;
|
||||||
|
t->min_c = t->valid && t->min_c < c ? t->min_c : c;
|
||||||
|
t->max_c = t->valid && t->max_c > c ? t->max_c : c;
|
||||||
|
t->valid = true;
|
||||||
|
bool was_hot = t->hot;
|
||||||
|
if (t->warn_c > 0) {
|
||||||
|
if (!t->hot && c >= t->warn_c) {
|
||||||
|
t->hot = true;
|
||||||
|
} else if (t->hot && c < t->warn_c - HYSTERESIS_C) {
|
||||||
|
t->hot = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
xSemaphoreGive(s_lock);
|
||||||
|
// Logged outside the lock; goes to syslog like any warning.
|
||||||
|
if (t->hot != was_hot) {
|
||||||
|
if (t->hot) {
|
||||||
|
ESP_LOGW(TAG, "temperature %s %.1f °C: at or above %.0f °C", t->name, c, t->warn_c);
|
||||||
|
} else {
|
||||||
|
ESP_LOGI(TAG, "temperature %s %.1f °C: back below %.0f °C", t->name, c,
|
||||||
|
t->warn_c - HYSTERESIS_C);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(SAMPLE_MS));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static double round1(float v)
|
||||||
|
{
|
||||||
|
return (double)(int)(v * 10.0f + (v < 0 ? -0.5f : 0.5f)) / 10.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void health_status(cJSON *st)
|
||||||
|
{
|
||||||
|
cJSON_AddStringToObject(st, "fw", esp_app_get_description()->version);
|
||||||
|
cJSON_AddNumberToObject(st, "uptime_s", (double)(esp_timer_get_time() / 1000000));
|
||||||
|
cJSON_AddNumberToObject(st, "heap_free", heap_caps_get_free_size(MALLOC_CAP_INTERNAL));
|
||||||
|
cJSON_AddNumberToObject(st, "psram_free", heap_caps_get_free_size(MALLOC_CAP_SPIRAM));
|
||||||
|
|
||||||
|
cJSON *temps = cJSON_AddArrayToObject(st, "temps");
|
||||||
|
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||||
|
for (int i = 0; i < s_n; i++) {
|
||||||
|
const sensor_t *t = &s_sensors[i];
|
||||||
|
if (!t->valid) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
cJSON *o = cJSON_CreateObject();
|
||||||
|
cJSON_AddStringToObject(o, "name", t->name);
|
||||||
|
cJSON_AddNumberToObject(o, "c", round1(t->c));
|
||||||
|
cJSON_AddNumberToObject(o, "min_c", round1(t->min_c));
|
||||||
|
cJSON_AddNumberToObject(o, "max_c", round1(t->max_c));
|
||||||
|
if (t->warn_c > 0) {
|
||||||
|
cJSON_AddNumberToObject(o, "warn_c", t->warn_c);
|
||||||
|
}
|
||||||
|
cJSON_AddItemToArray(temps, o);
|
||||||
|
}
|
||||||
|
xSemaphoreGive(s_lock);
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t aes67_health_init(void)
|
||||||
|
{
|
||||||
|
s_lock = xSemaphoreCreateMutex();
|
||||||
|
if (!s_lock) {
|
||||||
|
return ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
|
// 20..100 °C (+-2 °C): the die runs well above ambient and the warning level must be in range.
|
||||||
|
temperature_sensor_config_t cfg = TEMPERATURE_SENSOR_CONFIG_DEFAULT(20, 100);
|
||||||
|
esp_err_t err = temperature_sensor_install(&cfg, &s_tsens);
|
||||||
|
if (err == ESP_OK) {
|
||||||
|
err = temperature_sensor_enable(s_tsens);
|
||||||
|
}
|
||||||
|
if (err == ESP_OK) {
|
||||||
|
health_temp_register("SoC", soc_read, SOC_WARN_C);
|
||||||
|
} else {
|
||||||
|
ESP_LOGE(TAG, "on-die temperature sensor: %s", esp_err_to_name(err));
|
||||||
|
}
|
||||||
|
if (xTaskCreate(health_task, "health", 3072, NULL, 2, NULL) != pdPASS) {
|
||||||
|
return ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
|
return status_register(health_status);
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
// aes67_health: Uptime, heap/PSRAM, temperature sensors (temps[] with min/max/warn).
|
||||||
|
// Core component: must not depend on main/ (project code).
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "esp_err.h"
|
||||||
|
|
||||||
|
// Read one temperature in °C. Return ESP_OK on success.
|
||||||
|
typedef esp_err_t (*health_temp_read_cb_t)(float *celsius);
|
||||||
|
|
||||||
|
// Registers the health fields (fw, uptime_s, heap_free, psram_free, temps) in /api/status,
|
||||||
|
// adds the on-die "SoC" sensor and starts the 2 s sampling task.
|
||||||
|
esp_err_t aes67_health_init(void);
|
||||||
|
// Add a temperature sensor (e.g. an external I2C one from the board). warn_c <= 0: no warning.
|
||||||
|
esp_err_t health_temp_register(const char *name, health_temp_read_cb_t read, float warn_c);
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
idf_component_register(SRCS "aes67_net.c" "lldp.c"
|
||||||
|
INCLUDE_DIRS "include"
|
||||||
|
REQUIRES esp_eth esp_netif esp_event
|
||||||
|
PRIV_REQUIRES aes67_web lwip espressif__mdns esp_app_format esp_timer)
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 Ben Nicholson
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -0,0 +1,279 @@
|
|||||||
|
#include "aes67_net.h"
|
||||||
|
|
||||||
|
#include <ctype.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "aes67_cfg.h"
|
||||||
|
#include "aes67_web.h"
|
||||||
|
#include "esp_eth.h"
|
||||||
|
#include "esp_event.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_netif.h"
|
||||||
|
#include "lldp.h"
|
||||||
|
#include "lwip/inet.h"
|
||||||
|
#include "mdns.h"
|
||||||
|
|
||||||
|
static const char *TAG = "net";
|
||||||
|
|
||||||
|
static const char *const ADDR_KEYS[] = { "dhcp", "ip", "mask", "gw", "dns" };
|
||||||
|
|
||||||
|
// AES67 / untagged interface.
|
||||||
|
static const char NET_DEFAULTS[] =
|
||||||
|
"{\"hostname\":\"aes67\",\"vlan\":false,\"web_on\":\"both\",\"dhcp\":true,"
|
||||||
|
"\"ip\":\"\",\"mask\":\"\",\"gw\":\"\",\"dns\":\"\"}";
|
||||||
|
// Internet / tagged interface, only used with net.vlan.
|
||||||
|
static const char INET_DEFAULTS[] =
|
||||||
|
"{\"vlan_id\":10,\"pcp\":0,\"dhcp\":true,\"ip\":\"\",\"mask\":\"\",\"gw\":\"\",\"dns\":\"\"}";
|
||||||
|
|
||||||
|
static esp_netif_t *s_netif;
|
||||||
|
static char s_link[24] = "down";
|
||||||
|
static cJSON *s_addr; // addressing in use since boot (ADDR_KEYS of "net")
|
||||||
|
|
||||||
|
// The keys that define the IP setup. With DHCP the static fields don't matter (the UI fills them
|
||||||
|
// with the lease), so they don't count as a change.
|
||||||
|
static cJSON *addressing(const cJSON *g)
|
||||||
|
{
|
||||||
|
cJSON *a = cJSON_CreateObject();
|
||||||
|
int n = cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(g, "dhcp")) ? 1 : sizeof(ADDR_KEYS) / sizeof(ADDR_KEYS[0]);
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
cJSON_AddItemToObject(a, ADDR_KEYS[i], cJSON_Duplicate(cJSON_GetObjectItemCaseSensitive(g, ADDR_KEYS[i]), true));
|
||||||
|
}
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
|
||||||
|
static uint32_t addr_of(const cJSON *g, const char *key)
|
||||||
|
{
|
||||||
|
const cJSON *v = cJSON_GetObjectItemCaseSensitive(g, key);
|
||||||
|
return cJSON_IsString(v) && v->valuestring[0] ? inet_addr(v->valuestring) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Static addressing: stop the DHCP client and set ours. On link up, like IDF's static IP example.
|
||||||
|
static void set_static(void)
|
||||||
|
{
|
||||||
|
if (cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(s_addr, "dhcp"))) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
esp_err_t err = esp_netif_dhcpc_stop(s_netif);
|
||||||
|
if (err != ESP_OK && err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED) {
|
||||||
|
ESP_LOGE(TAG, "DHCP client stop: %s", esp_err_to_name(err));
|
||||||
|
}
|
||||||
|
esp_netif_ip_info_t ip = {
|
||||||
|
.ip.addr = addr_of(s_addr, "ip"), .netmask.addr = addr_of(s_addr, "mask"), .gw.addr = addr_of(s_addr, "gw"),
|
||||||
|
};
|
||||||
|
err = esp_netif_set_ip_info(s_netif, &ip);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
ESP_LOGE(TAG, "static IP: %s", esp_err_to_name(err));
|
||||||
|
}
|
||||||
|
esp_netif_dns_info_t dns = { .ip.type = ESP_IPADDR_TYPE_V4, .ip.u_addr.ip4.addr = addr_of(s_addr, "dns") };
|
||||||
|
if (dns.ip.u_addr.ip4.addr) {
|
||||||
|
esp_netif_set_dns_info(s_netif, ESP_NETIF_DNS_MAIN, &dns);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void eth_event(void *arg, esp_event_base_t base, int32_t id, void *data)
|
||||||
|
{
|
||||||
|
esp_eth_handle_t eth = *(esp_eth_handle_t *)data;
|
||||||
|
|
||||||
|
switch (id) {
|
||||||
|
case ETHERNET_EVENT_CONNECTED: {
|
||||||
|
uint8_t mac[6];
|
||||||
|
eth_speed_t speed;
|
||||||
|
eth_duplex_t duplex;
|
||||||
|
esp_eth_ioctl(eth, ETH_CMD_G_MAC_ADDR, mac);
|
||||||
|
esp_eth_ioctl(eth, ETH_CMD_G_SPEED, &speed);
|
||||||
|
esp_eth_ioctl(eth, ETH_CMD_G_DUPLEX_MODE, &duplex);
|
||||||
|
ESP_LOGI(TAG, "link up: %s Mbps %s duplex, MAC %02x:%02x:%02x:%02x:%02x:%02x",
|
||||||
|
speed == ETH_SPEED_100M ? "100" : "10", duplex == ETH_DUPLEX_FULL ? "full" : "half",
|
||||||
|
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
|
||||||
|
snprintf(s_link, sizeof(s_link), "up, %s Mbps %s", speed == ETH_SPEED_100M ? "100" : "10",
|
||||||
|
duplex == ETH_DUPLEX_FULL ? "full" : "half");
|
||||||
|
set_static();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case ETHERNET_EVENT_DISCONNECTED:
|
||||||
|
ESP_LOGW(TAG, "link down");
|
||||||
|
snprintf(s_link, sizeof(s_link), "down");
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void ip_event(void *arg, esp_event_base_t base, int32_t id, void *data)
|
||||||
|
{
|
||||||
|
const ip_event_got_ip_t *ev = data;
|
||||||
|
ESP_LOGI(TAG, "got IP " IPSTR " mask " IPSTR " gw " IPSTR,
|
||||||
|
IP2STR(&ev->ip_info.ip), IP2STR(&ev->ip_info.netmask), IP2STR(&ev->ip_info.gw));
|
||||||
|
lldp_changed();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Static addressing needs ip + mask; gw/dns are optional (none on the AES67 side with VLAN split).
|
||||||
|
static bool check_addr(const cJSON *g, char *err, size_t n)
|
||||||
|
{
|
||||||
|
bool dhcp = cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(g, "dhcp"));
|
||||||
|
if (!cfg_check_ipv4(g, "ip", dhcp, err, n) || !cfg_check_ipv4(g, "mask", dhcp, err, n) ||
|
||||||
|
!cfg_check_ipv4(g, "gw", true, err, n) || !cfg_check_ipv4(g, "dns", true, err, n)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (dhcp) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
uint32_t ip = ntohl(addr_of(g, "ip")), mask = ntohl(addr_of(g, "mask")), gw = ntohl(addr_of(g, "gw"));
|
||||||
|
if (mask == 0 || (~mask & (~mask + 1)) != 0 || mask == 0xffffffff) {
|
||||||
|
snprintf(err, n, "mask: not a valid netmask");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if ((ip & ~mask) == 0 || (ip & ~mask) == ~mask) {
|
||||||
|
snprintf(err, n, "ip: network or broadcast address of the subnet");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (gw && ((gw & mask) != (ip & mask) || gw == ip)) {
|
||||||
|
snprintf(err, n, "gw: must be another address in the IP's subnet");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// RFC 1123 label: letters, digits, hyphen; not starting or ending with a hyphen.
|
||||||
|
static bool check_hostname(const cJSON *g, char *err, size_t n)
|
||||||
|
{
|
||||||
|
if (!cfg_check_str(g, "hostname", 1, 63, err, n)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const char *h = cJSON_GetObjectItemCaseSensitive(g, "hostname")->valuestring;
|
||||||
|
size_t len = strlen(h);
|
||||||
|
for (size_t i = 0; i < len; i++) {
|
||||||
|
if (!isalnum((unsigned char)h[i]) && h[i] != '-') {
|
||||||
|
snprintf(err, n, "hostname: only letters, digits and '-'");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (h[0] == '-' || h[len - 1] == '-') {
|
||||||
|
snprintf(err, n, "hostname: must not start or end with '-'");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool net_validate(const cJSON *g, char *err, size_t n)
|
||||||
|
{
|
||||||
|
static const char *const web_on[] = { "both", "inet", "aes67", NULL };
|
||||||
|
return check_hostname(g, err, n) &&
|
||||||
|
cfg_check_enum(g, "web_on", web_on, err, n) &&
|
||||||
|
check_addr(g, err, n);
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool inet_validate(const cJSON *g, char *err, size_t n)
|
||||||
|
{
|
||||||
|
return cfg_check_int(g, "vlan_id", 1, 4094, err, n) &&
|
||||||
|
cfg_check_int(g, "pcp", 0, 7, err, n) &&
|
||||||
|
check_addr(g, err, n);
|
||||||
|
}
|
||||||
|
|
||||||
|
// mDNS: <hostname>.local plus the web UI as _http._tcp.
|
||||||
|
static void mdns_setup(void)
|
||||||
|
{
|
||||||
|
cJSON *net = cfg_get("net");
|
||||||
|
const char *host = cJSON_GetObjectItemCaseSensitive(net, "hostname")->valuestring;
|
||||||
|
esp_err_t err = mdns_init();
|
||||||
|
if (err == ESP_OK) {
|
||||||
|
mdns_hostname_set(host);
|
||||||
|
mdns_instance_name_set(host);
|
||||||
|
mdns_service_add(NULL, "_http", "_tcp", 80, NULL, 0);
|
||||||
|
ESP_LOGI(TAG, "mDNS: %s.local, _http._tcp port 80", host);
|
||||||
|
} else {
|
||||||
|
ESP_LOGE(TAG, "mDNS init failed: %s", esp_err_to_name(err));
|
||||||
|
}
|
||||||
|
cJSON_Delete(net);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void net_apply(const cJSON *g)
|
||||||
|
{
|
||||||
|
const char *host = cJSON_GetObjectItemCaseSensitive(g, "hostname")->valuestring;
|
||||||
|
// DHCP server sees the new name at the next lease renewal.
|
||||||
|
esp_netif_set_hostname(s_netif, host);
|
||||||
|
if (mdns_hostname_set(host) == ESP_OK && mdns_instance_name_set(host) == ESP_OK) {
|
||||||
|
ESP_LOGI(TAG, "mDNS: now %s.local", host);
|
||||||
|
}
|
||||||
|
lldp_changed();
|
||||||
|
// New addressing: PTP/TX/SAP sockets are bound to the address, so it takes a reboot.
|
||||||
|
cJSON *a = addressing(g);
|
||||||
|
if (!cJSON_Compare(a, s_addr, true)) {
|
||||||
|
ESP_LOGW(TAG, "IP setup changed: rebooting to apply it");
|
||||||
|
web_reboot_later(1500);
|
||||||
|
}
|
||||||
|
cJSON_Delete(a);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void net_status(cJSON *st)
|
||||||
|
{
|
||||||
|
char ip[16] = "", mask[16] = "", gw[16] = "", dns[16] = "", mac_s[18] = "";
|
||||||
|
esp_netif_ip_info_t info;
|
||||||
|
if (esp_netif_get_ip_info(s_netif, &info) == ESP_OK && info.ip.addr) {
|
||||||
|
snprintf(ip, sizeof(ip), IPSTR, IP2STR(&info.ip));
|
||||||
|
snprintf(mask, sizeof(mask), IPSTR, IP2STR(&info.netmask));
|
||||||
|
if (info.gw.addr) {
|
||||||
|
snprintf(gw, sizeof(gw), IPSTR, IP2STR(&info.gw));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
esp_netif_dns_info_t d;
|
||||||
|
if (esp_netif_get_dns_info(s_netif, ESP_NETIF_DNS_MAIN, &d) == ESP_OK && d.ip.type == ESP_IPADDR_TYPE_V4 &&
|
||||||
|
d.ip.u_addr.ip4.addr) {
|
||||||
|
snprintf(dns, sizeof(dns), IPSTR, IP2STR(&d.ip.u_addr.ip4));
|
||||||
|
}
|
||||||
|
uint8_t mac[6];
|
||||||
|
if (esp_netif_get_mac(s_netif, mac) == ESP_OK) {
|
||||||
|
snprintf(mac_s, sizeof(mac_s), "%02x:%02x:%02x:%02x:%02x:%02x",
|
||||||
|
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
|
||||||
|
}
|
||||||
|
// Single untagged interface until the VLAN split: AES67 and web share it.
|
||||||
|
cJSON_AddStringToObject(st, "ip", ip);
|
||||||
|
cJSON_AddStringToObject(st, "aes67_ip", ip);
|
||||||
|
cJSON_AddStringToObject(st, "mask", mask); // in use (from DHCP or static)
|
||||||
|
cJSON_AddStringToObject(st, "gw", gw);
|
||||||
|
cJSON_AddStringToObject(st, "dns", dns);
|
||||||
|
cJSON_AddStringToObject(st, "mac", mac_s);
|
||||||
|
cJSON_AddStringToObject(st, "link", s_link);
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t aes67_net_init(esp_eth_handle_t eth)
|
||||||
|
{
|
||||||
|
// Applied: hostname (DHCP, mDNS, LLDP) live; DHCP/static addressing at boot. VLAN comes later.
|
||||||
|
ESP_ERROR_CHECK(cfg_register("net", NET_DEFAULTS, net_validate, net_apply));
|
||||||
|
ESP_ERROR_CHECK(cfg_register("inet", INET_DEFAULTS, inet_validate, NULL));
|
||||||
|
|
||||||
|
ESP_ERROR_CHECK(esp_netif_init());
|
||||||
|
esp_err_t err = esp_event_loop_create_default();
|
||||||
|
if (err != ESP_OK && err != ESP_ERR_INVALID_STATE) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_netif_config_t netif_cfg = ESP_NETIF_DEFAULT_ETH();
|
||||||
|
s_netif = esp_netif_new(&netif_cfg);
|
||||||
|
ESP_ERROR_CHECK(esp_netif_attach(s_netif, esp_eth_new_netif_glue(eth)));
|
||||||
|
|
||||||
|
ESP_ERROR_CHECK(esp_event_handler_register(ETH_EVENT, ESP_EVENT_ANY_ID, eth_event, NULL));
|
||||||
|
ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_ETH_GOT_IP, ip_event, NULL));
|
||||||
|
|
||||||
|
// Hostname in DHCP requests (option 12), so the router's lease list shows it.
|
||||||
|
cJSON *net = cfg_get("net");
|
||||||
|
ESP_ERROR_CHECK(esp_netif_set_hostname(s_netif, cJSON_GetObjectItemCaseSensitive(net, "hostname")->valuestring));
|
||||||
|
s_addr = addressing(net);
|
||||||
|
if (!cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(net, "dhcp"))) {
|
||||||
|
ESP_LOGI(TAG, "static IP %s/%s gw %s dns %s", cJSON_GetObjectItemCaseSensitive(net, "ip")->valuestring,
|
||||||
|
cJSON_GetObjectItemCaseSensitive(net, "mask")->valuestring,
|
||||||
|
cJSON_GetObjectItemCaseSensitive(net, "gw")->valuestring,
|
||||||
|
cJSON_GetObjectItemCaseSensitive(net, "dns")->valuestring);
|
||||||
|
}
|
||||||
|
cJSON_Delete(net);
|
||||||
|
mdns_setup();
|
||||||
|
ESP_ERROR_CHECK(lldp_start(eth, s_netif));
|
||||||
|
status_register(net_status);
|
||||||
|
return esp_eth_start(eth);
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_netif_t *aes67_net_netif(void)
|
||||||
|
{
|
||||||
|
return s_netif;
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
dependencies:
|
||||||
|
espressif/mdns: "^1.13.1"
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
// aes67_net: Netif setup, optional VLAN split, DSCP/PCP helpers.
|
||||||
|
// Core component: must not depend on main/ (project code).
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "esp_err.h"
|
||||||
|
#include "esp_eth_driver.h"
|
||||||
|
#include "esp_netif.h"
|
||||||
|
|
||||||
|
// Attach a netif (DHCP client) to the Ethernet driver and start it. Logs link and IP events.
|
||||||
|
esp_err_t aes67_net_init(esp_eth_handle_t eth);
|
||||||
|
|
||||||
|
// The AES67 interface (untagged side once the VLAN split exists). NULL before aes67_net_init().
|
||||||
|
esp_netif_t *aes67_net_netif(void);
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
// LLDP (IEEE 802.1AB) transmit only: tells the switch our name and management IP.
|
||||||
|
#include "lldp.h"
|
||||||
|
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "aes67_cfg.h"
|
||||||
|
#include "esp_app_desc.h"
|
||||||
|
#include "esp_eth.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_timer.h"
|
||||||
|
|
||||||
|
#define LLDP_INTERVAL_S 30
|
||||||
|
#define LLDP_TTL_S (4 * LLDP_INTERVAL_S)
|
||||||
|
#define FRAME_MAX 512
|
||||||
|
#define FRAME_MIN 60 // without FCS
|
||||||
|
|
||||||
|
enum { TLV_END, TLV_CHASSIS_ID, TLV_PORT_ID, TLV_TTL, TLV_PORT_DESC, TLV_SYS_NAME, TLV_SYS_DESC,
|
||||||
|
TLV_SYS_CAP, TLV_MGMT_ADDR };
|
||||||
|
|
||||||
|
static const char *TAG = "lldp";
|
||||||
|
static const uint8_t LLDP_MCAST[6] = { 0x01, 0x80, 0xc2, 0x00, 0x00, 0x0e };
|
||||||
|
|
||||||
|
static esp_eth_handle_t s_eth;
|
||||||
|
static esp_netif_t *s_netif;
|
||||||
|
static esp_timer_handle_t s_timer;
|
||||||
|
static bool s_logged;
|
||||||
|
|
||||||
|
static size_t tlv(uint8_t *p, int type, const void *val, size_t len)
|
||||||
|
{
|
||||||
|
p[0] = (type << 1) | ((len >> 8) & 1);
|
||||||
|
p[1] = len & 0xff;
|
||||||
|
memcpy(p + 2, val, len);
|
||||||
|
return 2 + len;
|
||||||
|
}
|
||||||
|
|
||||||
|
static size_t tlv_str(uint8_t *p, int type, const char *s)
|
||||||
|
{
|
||||||
|
size_t len = strlen(s);
|
||||||
|
return tlv(p, type, s, len > 255 ? 255 : len);
|
||||||
|
}
|
||||||
|
|
||||||
|
void lldp_send(void)
|
||||||
|
{
|
||||||
|
if (!s_eth) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
uint8_t mac[6];
|
||||||
|
if (esp_eth_ioctl(s_eth, ETH_CMD_G_MAC_ADDR, mac) != ESP_OK) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
cJSON *net = cfg_get("net");
|
||||||
|
const char *host = cJSON_GetObjectItemCaseSensitive(net, "hostname")->valuestring;
|
||||||
|
const esp_app_desc_t *app = esp_app_get_description();
|
||||||
|
|
||||||
|
uint8_t f[FRAME_MAX] = { 0 };
|
||||||
|
size_t n = 0;
|
||||||
|
memcpy(f, LLDP_MCAST, 6);
|
||||||
|
memcpy(f + 6, mac, 6);
|
||||||
|
f[12] = 0x88;
|
||||||
|
f[13] = 0xcc;
|
||||||
|
n = 14;
|
||||||
|
|
||||||
|
uint8_t id[7] = { 4 }; // chassis ID subtype 4: MAC address
|
||||||
|
memcpy(id + 1, mac, 6);
|
||||||
|
n += tlv(f + n, TLV_CHASSIS_ID, id, sizeof(id));
|
||||||
|
id[0] = 3; // port ID subtype 3: MAC address
|
||||||
|
n += tlv(f + n, TLV_PORT_ID, id, sizeof(id));
|
||||||
|
uint8_t ttl[2] = { LLDP_TTL_S >> 8, LLDP_TTL_S & 0xff };
|
||||||
|
n += tlv(f + n, TLV_TTL, ttl, sizeof(ttl));
|
||||||
|
n += tlv_str(f + n, TLV_PORT_DESC, "eth0");
|
||||||
|
n += tlv_str(f + n, TLV_SYS_NAME, host);
|
||||||
|
char desc[128];
|
||||||
|
snprintf(desc, sizeof(desc), "AES67 device, %s %s (ESP-IDF %s)", app->project_name, app->version, app->idf_ver);
|
||||||
|
n += tlv_str(f + n, TLV_SYS_DESC, desc);
|
||||||
|
uint8_t cap[4] = { 0x00, 0x80, 0x00, 0x80 }; // capabilities: station only (supported, enabled)
|
||||||
|
n += tlv(f + n, TLV_SYS_CAP, cap, sizeof(cap));
|
||||||
|
|
||||||
|
esp_netif_ip_info_t ip = { 0 };
|
||||||
|
bool have_ip = esp_netif_get_ip_info(s_netif, &ip) == ESP_OK && ip.ip.addr;
|
||||||
|
if (have_ip) {
|
||||||
|
// addr len 5, subtype IPv4, address, interface subtype ifIndex, ifIndex 1, OID len 0
|
||||||
|
uint8_t m[12] = { 5, 1 };
|
||||||
|
memcpy(m + 2, &ip.ip.addr, 4); // already network byte order
|
||||||
|
m[6] = 2;
|
||||||
|
m[10] = 1;
|
||||||
|
n += tlv(f + n, TLV_MGMT_ADDR, m, sizeof(m));
|
||||||
|
}
|
||||||
|
n += tlv(f + n, TLV_END, NULL, 0);
|
||||||
|
if (n < FRAME_MIN) {
|
||||||
|
n = FRAME_MIN;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t err = esp_eth_transmit(s_eth, f, n);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
ESP_LOGW(TAG, "transmit failed: %s", esp_err_to_name(err));
|
||||||
|
} else if (!s_logged || !have_ip) {
|
||||||
|
// Log once per name/IP change, not every 30 s.
|
||||||
|
ESP_LOGI(TAG, "sent: name %s, mgmt " IPSTR ", %u bytes", host, IP2STR(&ip.ip), (unsigned)n);
|
||||||
|
s_logged = have_ip;
|
||||||
|
}
|
||||||
|
cJSON_Delete(net);
|
||||||
|
}
|
||||||
|
|
||||||
|
void lldp_changed(void)
|
||||||
|
{
|
||||||
|
s_logged = false;
|
||||||
|
lldp_send();
|
||||||
|
}
|
||||||
|
|
||||||
|
static void timer_cb(void *arg)
|
||||||
|
{
|
||||||
|
lldp_send();
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t lldp_start(esp_eth_handle_t eth, esp_netif_t *netif)
|
||||||
|
{
|
||||||
|
s_eth = eth;
|
||||||
|
s_netif = netif;
|
||||||
|
const esp_timer_create_args_t args = { .callback = timer_cb, .name = "lldp" };
|
||||||
|
esp_err_t err = esp_timer_create(&args, &s_timer);
|
||||||
|
if (err == ESP_OK) {
|
||||||
|
err = esp_timer_start_periodic(s_timer, LLDP_INTERVAL_S * 1000000ULL);
|
||||||
|
}
|
||||||
|
return err;
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "esp_eth_driver.h"
|
||||||
|
#include "esp_netif.h"
|
||||||
|
|
||||||
|
// Send an LLDPDU every 30 s (TTL 120 s).
|
||||||
|
esp_err_t lldp_start(esp_eth_handle_t eth, esp_netif_t *netif);
|
||||||
|
// Send now (e.g. after an IP or hostname change) and log the next one.
|
||||||
|
void lldp_changed(void);
|
||||||
|
void lldp_send(void);
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
idf_component_register(SRCS "aes67_ota.c"
|
||||||
|
INCLUDE_DIRS "include"
|
||||||
|
PRIV_REQUIRES aes67_web app_update bootloader_support esp_app_format
|
||||||
|
esp_http_client esp_netif esp_timer hal)
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
menu "AES67 OTA"
|
||||||
|
|
||||||
|
config AES67_OTA_SELFTEST_FORCE_FAIL
|
||||||
|
bool "Force the OTA self-test to fail (rollback test only)"
|
||||||
|
default n
|
||||||
|
help
|
||||||
|
Test builds only: the self-test always fails, so a freshly installed
|
||||||
|
image rolls back. Build with sdkconfig.selftest_fail in a separate
|
||||||
|
build directory; never enable in the normal build.
|
||||||
|
|
||||||
|
endmenu
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 Ben Nicholson
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -0,0 +1,305 @@
|
|||||||
|
#include "aes67_ota.h"
|
||||||
|
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "aes67_web.h"
|
||||||
|
#include "esp_app_desc.h"
|
||||||
|
#include "esp_app_format.h"
|
||||||
|
#include "esp_http_client.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_netif.h"
|
||||||
|
#include "esp_ota_ops.h"
|
||||||
|
#include "esp_timer.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/task.h"
|
||||||
|
#include "hal/efuse_hal.h"
|
||||||
|
|
||||||
|
#define CHUNK 4096
|
||||||
|
#define SELFTEST_TIMEOUT_S 60
|
||||||
|
// Image header, first segment header, then the app description.
|
||||||
|
#define DESC_OFFSET (sizeof(esp_image_header_t) + sizeof(esp_image_segment_header_t))
|
||||||
|
#define HEAD_LEN (DESC_OFFSET + sizeof(esp_app_desc_t))
|
||||||
|
|
||||||
|
static const char *TAG = "ota";
|
||||||
|
|
||||||
|
#define MAX_UPDATE_CBS 4
|
||||||
|
static aes67_ota_update_cb_t s_update_cbs[MAX_UPDATE_CBS];
|
||||||
|
static int s_update_n;
|
||||||
|
|
||||||
|
esp_err_t aes67_ota_on_update(aes67_ota_update_cb_t cb)
|
||||||
|
{
|
||||||
|
if (s_update_n >= MAX_UPDATE_CBS) {
|
||||||
|
return ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
|
s_update_cbs[s_update_n++] = cb;
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void notify_update(bool starting)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < s_update_n; i++) {
|
||||||
|
s_update_cbs[i](starting);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool is_pending(void)
|
||||||
|
{
|
||||||
|
esp_ota_img_states_t st;
|
||||||
|
return esp_ota_get_state_partition(esp_ota_get_running_partition(), &st) == ESP_OK &&
|
||||||
|
st == ESP_OTA_IMG_PENDING_VERIFY;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----- GET /api/ota ----- */
|
||||||
|
|
||||||
|
static esp_err_t ota_get(httpd_req_t *req)
|
||||||
|
{
|
||||||
|
const esp_app_desc_t *app = esp_app_get_description();
|
||||||
|
const esp_partition_t *run = esp_ota_get_running_partition();
|
||||||
|
const esp_partition_t *other = esp_ota_get_next_update_partition(NULL);
|
||||||
|
char built[40];
|
||||||
|
snprintf(built, sizeof(built), "%s %s", app->date, app->time);
|
||||||
|
|
||||||
|
cJSON *o = cJSON_CreateObject();
|
||||||
|
cJSON_AddStringToObject(o, "version", app->version);
|
||||||
|
cJSON_AddStringToObject(o, "project", app->project_name);
|
||||||
|
cJSON_AddStringToObject(o, "build_date", built);
|
||||||
|
cJSON_AddStringToObject(o, "idf", app->idf_ver);
|
||||||
|
cJSON_AddStringToObject(o, "running", run->label);
|
||||||
|
// Only a bootable image counts as "previous" (not a half-written upload or a rolled-back
|
||||||
|
// one). With two slots, rollback is possible exactly when the other slot is bootable.
|
||||||
|
bool can_rollback = esp_ota_check_rollback_is_possible();
|
||||||
|
esp_app_desc_t prev;
|
||||||
|
if (can_rollback && other && esp_ota_get_partition_description(other, &prev) == ESP_OK) {
|
||||||
|
cJSON_AddStringToObject(o, "previous", other->label);
|
||||||
|
cJSON_AddStringToObject(o, "previous_version", prev.version);
|
||||||
|
}
|
||||||
|
cJSON_AddBoolToObject(o, "pending_verify", is_pending());
|
||||||
|
cJSON_AddBoolToObject(o, "can_rollback", can_rollback);
|
||||||
|
esp_err_t err = web_send_json(req, o);
|
||||||
|
cJSON_Delete(o);
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----- POST /api/ota ----- */
|
||||||
|
|
||||||
|
// Checks on the first bytes, before anything is written to flash.
|
||||||
|
static const char *check_head(const uint8_t *buf)
|
||||||
|
{
|
||||||
|
const esp_image_header_t *h = (const esp_image_header_t *)buf;
|
||||||
|
const esp_app_desc_t *d = (const esp_app_desc_t *)(buf + DESC_OFFSET);
|
||||||
|
static char msg[96];
|
||||||
|
|
||||||
|
if (h->magic != ESP_IMAGE_HEADER_MAGIC || d->magic_word != ESP_APP_DESC_MAGIC_WORD) {
|
||||||
|
return "not an ESP-IDF app image";
|
||||||
|
}
|
||||||
|
if (h->chip_id != CONFIG_IDF_FIRMWARE_CHIP_ID) {
|
||||||
|
return "image is for a different chip";
|
||||||
|
}
|
||||||
|
if (strncmp(d->project_name, esp_app_get_description()->project_name, sizeof(d->project_name)) != 0) {
|
||||||
|
snprintf(msg, sizeof(msg), "wrong project '%.32s'", d->project_name);
|
||||||
|
return msg;
|
||||||
|
}
|
||||||
|
unsigned rev = efuse_hal_chip_revision();
|
||||||
|
if (rev < h->min_chip_rev_full || rev > h->max_chip_rev_full) {
|
||||||
|
snprintf(msg, sizeof(msg), "image supports chip rev v%u.%u-v%u.%u, this chip is v%u.%u",
|
||||||
|
h->min_chip_rev_full / 100, h->min_chip_rev_full % 100,
|
||||||
|
h->max_chip_rev_full / 100, h->max_chip_rev_full % 100, rev / 100, rev % 100);
|
||||||
|
return msg;
|
||||||
|
}
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
static esp_err_t reject(httpd_req_t *req, const char *msg)
|
||||||
|
{
|
||||||
|
ESP_LOGW(TAG, "upload rejected: %s", msg);
|
||||||
|
return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
static esp_err_t ota_post(httpd_req_t *req)
|
||||||
|
{
|
||||||
|
const esp_partition_t *dst = esp_ota_get_next_update_partition(NULL);
|
||||||
|
if (!dst) {
|
||||||
|
return reject(req, "no OTA partition");
|
||||||
|
}
|
||||||
|
if (req->content_len < HEAD_LEN || req->content_len > dst->size) {
|
||||||
|
return reject(req, "image size out of range");
|
||||||
|
}
|
||||||
|
uint8_t *buf = malloc(CHUNK);
|
||||||
|
if (!buf) {
|
||||||
|
return httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "out of memory");
|
||||||
|
}
|
||||||
|
|
||||||
|
ESP_LOGI(TAG, "upload %u bytes to %s", (unsigned)req->content_len, dst->label);
|
||||||
|
esp_ota_handle_t ota = 0;
|
||||||
|
size_t total = 0, fill = 0;
|
||||||
|
const char *err_msg = NULL;
|
||||||
|
bool notified = false;
|
||||||
|
int64_t t0 = esp_timer_get_time();
|
||||||
|
|
||||||
|
while (total < req->content_len) {
|
||||||
|
int r = httpd_req_recv(req, (char *)buf + fill, CHUNK - fill);
|
||||||
|
if (r == HTTPD_SOCK_ERR_TIMEOUT) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (r <= 0) {
|
||||||
|
err_msg = "connection lost";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
fill += r;
|
||||||
|
total += r;
|
||||||
|
if (!ota) {
|
||||||
|
// Collect the header before deciding anything.
|
||||||
|
if (fill < HEAD_LEN && total < req->content_len) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if ((err_msg = check_head(buf)) != NULL) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
const esp_app_desc_t *d = (const esp_app_desc_t *)(buf + DESC_OFFSET);
|
||||||
|
ESP_LOGI(TAG, "image %.32s %.32s", d->project_name, d->version);
|
||||||
|
notify_update(true); // project quiets streaming/decoding before the flash writes
|
||||||
|
notified = true;
|
||||||
|
if (esp_ota_begin(dst, OTA_WITH_SEQUENTIAL_WRITES, &ota) != ESP_OK) {
|
||||||
|
err_msg = "ota begin failed";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (esp_ota_write(ota, buf, fill) != ESP_OK) {
|
||||||
|
err_msg = "flash write failed";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
fill = 0;
|
||||||
|
}
|
||||||
|
free(buf);
|
||||||
|
|
||||||
|
if (err_msg) {
|
||||||
|
if (ota) {
|
||||||
|
esp_ota_abort(ota);
|
||||||
|
}
|
||||||
|
if (notified) {
|
||||||
|
notify_update(false);
|
||||||
|
}
|
||||||
|
// Rejected before the whole body was read: close instead of draining it.
|
||||||
|
httpd_resp_set_hdr(req, "Connection", "close");
|
||||||
|
return reject(req, err_msg);
|
||||||
|
}
|
||||||
|
esp_err_t err = esp_ota_end(ota); // verifies the image (checksum/hash, chip)
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
notify_update(false);
|
||||||
|
return reject(req, err == ESP_ERR_OTA_VALIDATE_FAILED ? "image verification failed" : "ota end failed");
|
||||||
|
}
|
||||||
|
if (esp_ota_set_boot_partition(dst) != ESP_OK) {
|
||||||
|
notify_update(false);
|
||||||
|
return httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "could not set boot partition");
|
||||||
|
}
|
||||||
|
ESP_LOGW(TAG, "installed to %s in %.1f s, rebooting", dst->label,
|
||||||
|
(esp_timer_get_time() - t0) / 1e6);
|
||||||
|
httpd_resp_sendstr(req, "ok");
|
||||||
|
web_reboot_later(500);
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----- confirm / rollback ----- */
|
||||||
|
|
||||||
|
static esp_err_t confirm_post(httpd_req_t *req)
|
||||||
|
{
|
||||||
|
if (!is_pending()) {
|
||||||
|
return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "running firmware is already confirmed");
|
||||||
|
}
|
||||||
|
esp_ota_mark_app_valid_cancel_rollback();
|
||||||
|
ESP_LOGI(TAG, "firmware confirmed via API");
|
||||||
|
return httpd_resp_sendstr(req, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
static void rollback_cb(void *arg)
|
||||||
|
{
|
||||||
|
esp_ota_mark_app_invalid_rollback_and_reboot();
|
||||||
|
ESP_LOGE(TAG, "rollback failed");
|
||||||
|
}
|
||||||
|
|
||||||
|
static esp_err_t rollback_post(httpd_req_t *req)
|
||||||
|
{
|
||||||
|
if (!esp_ota_check_rollback_is_possible()) {
|
||||||
|
return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "no previous firmware to roll back to");
|
||||||
|
}
|
||||||
|
ESP_LOGW(TAG, "rollback requested via API");
|
||||||
|
httpd_resp_sendstr(req, "");
|
||||||
|
const esp_timer_create_args_t args = { .callback = rollback_cb, .name = "rollback" };
|
||||||
|
esp_timer_handle_t t;
|
||||||
|
if (esp_timer_create(&args, &t) == ESP_OK) {
|
||||||
|
esp_timer_start_once(t, 500 * 1000);
|
||||||
|
}
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----- Self-test after an update ----- */
|
||||||
|
|
||||||
|
static bool web_answers(const esp_netif_ip_info_t *ip)
|
||||||
|
{
|
||||||
|
char url[48];
|
||||||
|
snprintf(url, sizeof(url), "http://" IPSTR "/api/status", IP2STR(&ip->ip));
|
||||||
|
esp_http_client_config_t cfg = { .url = url, .timeout_ms = 3000 };
|
||||||
|
esp_http_client_handle_t c = esp_http_client_init(&cfg);
|
||||||
|
bool ok = c && esp_http_client_perform(c) == ESP_OK && esp_http_client_get_status_code(c) == 200;
|
||||||
|
esp_http_client_cleanup(c);
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void selftest_task(void *arg)
|
||||||
|
{
|
||||||
|
const char *fail = NULL;
|
||||||
|
int64_t deadline = esp_timer_get_time() + SELFTEST_TIMEOUT_S * 1000000LL;
|
||||||
|
esp_netif_t *netif = esp_netif_get_handle_from_ifkey("ETH_DEF");
|
||||||
|
bool passed = false;
|
||||||
|
|
||||||
|
while (!passed && esp_timer_get_time() < deadline) {
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(1000));
|
||||||
|
esp_netif_ip_info_t ip;
|
||||||
|
if (!netif || esp_netif_get_ip_info(netif, &ip) != ESP_OK || !ip.ip.addr) {
|
||||||
|
fail = "no IP address";
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!web_answers(&ip)) {
|
||||||
|
fail = "web server not answering";
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
passed = true;
|
||||||
|
}
|
||||||
|
#if CONFIG_AES67_OTA_SELFTEST_FORCE_FAIL
|
||||||
|
passed = false;
|
||||||
|
fail = "forced failure (CONFIG_AES67_OTA_SELFTEST_FORCE_FAIL)";
|
||||||
|
#endif
|
||||||
|
if (passed) {
|
||||||
|
esp_ota_mark_app_valid_cancel_rollback();
|
||||||
|
ESP_LOGI(TAG, "self-test passed, firmware confirmed");
|
||||||
|
} else if (is_pending()) { // not confirmed manually in the meantime
|
||||||
|
ESP_LOGE(TAG, "self-test failed (%s), rolling back", fail);
|
||||||
|
esp_ota_mark_app_invalid_rollback_and_reboot();
|
||||||
|
}
|
||||||
|
vTaskDelete(NULL);
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t aes67_ota_init(void)
|
||||||
|
{
|
||||||
|
static const httpd_uri_t uris[] = {
|
||||||
|
{ .uri = "/api/ota", .method = HTTP_GET, .handler = ota_get },
|
||||||
|
{ .uri = "/api/ota", .method = HTTP_POST, .handler = ota_post },
|
||||||
|
{ .uri = "/api/ota/confirm", .method = HTTP_POST, .handler = confirm_post },
|
||||||
|
{ .uri = "/api/ota/rollback", .method = HTTP_POST, .handler = rollback_post },
|
||||||
|
};
|
||||||
|
for (int i = 0; i < sizeof(uris) / sizeof(uris[0]); i++) {
|
||||||
|
esp_err_t err = web_register_uri(&uris[i]);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const esp_app_desc_t *app = esp_app_get_description();
|
||||||
|
ESP_LOGI(TAG, "running %s from %s", app->version, esp_ota_get_running_partition()->label);
|
||||||
|
if (is_pending()) {
|
||||||
|
ESP_LOGW(TAG, "new firmware on trial: self-test (IP + web) within %d s", SELFTEST_TIMEOUT_S);
|
||||||
|
xTaskCreate(selftest_task, "ota_selftest", 4096, NULL, 2, NULL);
|
||||||
|
}
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
// aes67_ota: Firmware upload, image checks, rollback self-test.
|
||||||
|
// Core component: must not depend on main/ (project code).
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <stdbool.h>
|
||||||
|
|
||||||
|
#include "esp_err.h"
|
||||||
|
|
||||||
|
// Registers /api/ota routes. If the running image is pending verification, starts the
|
||||||
|
// self-test: IP address + own web server answering within 60 s, else roll back.
|
||||||
|
esp_err_t aes67_ota_init(void);
|
||||||
|
|
||||||
|
// Called with true right before an accepted upload starts writing flash, and with false if that
|
||||||
|
// upload then fails (on success the device reboots). Lets the project quiet heavy work (streaming,
|
||||||
|
// decoding) during the flash writes. Up to 4 callbacks.
|
||||||
|
typedef void (*aes67_ota_update_cb_t)(bool starting);
|
||||||
|
esp_err_t aes67_ota_on_update(aes67_ota_update_cb_t cb);
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
idf_component_register(SRCS "aes67_ptp.c" "ptp_clock.c" "ptp_hw.c"
|
||||||
|
INCLUDE_DIRS "include"
|
||||||
|
REQUIRES esp_eth
|
||||||
|
PRIV_REQUIRES aes67_web esp_netif esp_timer lwip hal soc)
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 Ben Nicholson
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
#include "aes67_ptp.h"
|
||||||
|
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "aes67_cfg.h"
|
||||||
|
#include "aes67_web.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "ptp_clock.h"
|
||||||
|
#include "ptp_hw.h"
|
||||||
|
|
||||||
|
// Core defaults: Riedel SIC intervals, role auto with fallback priorities (docs/aes67-core-base.md).
|
||||||
|
static const char PTP_DEFAULTS[] =
|
||||||
|
"{\"mode\":\"multicast\",\"role\":\"auto\",\"domain\":0,\"priority1\":250,\"priority2\":250,"
|
||||||
|
"\"log_sync\":0,\"log_announce\":1,\"announce_timeout\":3,\"log_delay_req\":0,"
|
||||||
|
"\"dscp\":46}"; // hardware timestamps always (status.ptp.hw_ts)
|
||||||
|
|
||||||
|
static bool ptp_validate(const cJSON *g, char *err, size_t n)
|
||||||
|
{
|
||||||
|
static const char *const modes[] = { "multicast", "hybrid", NULL };
|
||||||
|
static const char *const roles[] = { "slave", "auto", NULL };
|
||||||
|
return cfg_check_enum(g, "mode", modes, err, n) &&
|
||||||
|
cfg_check_enum(g, "role", roles, err, n) &&
|
||||||
|
cfg_check_int(g, "domain", 0, 127, err, n) &&
|
||||||
|
cfg_check_int(g, "priority1", 0, 255, err, n) &&
|
||||||
|
cfg_check_int(g, "priority2", 0, 255, err, n) &&
|
||||||
|
cfg_check_int(g, "log_sync", -4, 1, err, n) &&
|
||||||
|
cfg_check_int(g, "log_announce", 0, 4, err, n) &&
|
||||||
|
cfg_check_int(g, "announce_timeout", 2, 10, err, n) &&
|
||||||
|
cfg_check_int(g, "log_delay_req", -4, 1, err, n) &&
|
||||||
|
cfg_check_int(g, "dscp", 0, 63, err, n);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void ptp_apply(const cJSON *g)
|
||||||
|
{
|
||||||
|
ptp_clock_reconfig();
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t aes67_ptp_init(void)
|
||||||
|
{
|
||||||
|
esp_err_t err = cfg_register("ptp", PTP_DEFAULTS, ptp_validate, ptp_apply);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
// Role "master" was dropped (it behaved like auto; a low priority1 does the same). Stored values
|
||||||
|
// aren't re-validated, so convert it here.
|
||||||
|
cJSON *c = cfg_get("ptp");
|
||||||
|
bool master = !strcmp(cJSON_GetObjectItemCaseSensitive(c, "role")->valuestring, "master");
|
||||||
|
cJSON_Delete(c);
|
||||||
|
if (master) {
|
||||||
|
ESP_LOGW("ptp", "stored role \"master\" is no longer offered: now \"auto\" (same behaviour)");
|
||||||
|
cfg_set_string("ptp", "role", "auto", false);
|
||||||
|
}
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t aes67_ptp_start(esp_eth_handle_t eth)
|
||||||
|
{
|
||||||
|
esp_netif_t *netif = esp_netif_get_handle_from_ifkey("ETH_DEF");
|
||||||
|
esp_err_t err = ptp_hw_init(eth, netif);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
err = ptp_clock_start(netif);
|
||||||
|
if (err == ESP_OK) {
|
||||||
|
err = status_register(ptp_clock_status);
|
||||||
|
}
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool aes67_ptp_gm_id(char out[24])
|
||||||
|
{
|
||||||
|
return ptp_clock_gm_id(out);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool aes67_ptp_locked(void)
|
||||||
|
{
|
||||||
|
return ptp_clock_locked();
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t aes67_ptp_now_ns(int64_t *ns)
|
||||||
|
{
|
||||||
|
eth_mac_time_t t;
|
||||||
|
esp_err_t err = ptp_hw_get_time(&t);
|
||||||
|
if (err == ESP_OK) {
|
||||||
|
*ns = (int64_t)t.seconds * 1000000000LL + t.nanoseconds;
|
||||||
|
}
|
||||||
|
return err;
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
// aes67_ptp: PTPv2 ordinary clock: BMCA, servo, master, multicast/hybrid, EMAC HW timestamps, stats.
|
||||||
|
// Core component: must not depend on main/ (project code).
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <stdbool.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
#include "esp_err.h"
|
||||||
|
#include "esp_eth_driver.h"
|
||||||
|
|
||||||
|
// Registers the "ptp" config group. Call early, before the config is used.
|
||||||
|
esp_err_t aes67_ptp_init(void);
|
||||||
|
// Start the EMAC PTP clock and the PTP task on this Ethernet interface.
|
||||||
|
esp_err_t aes67_ptp_start(esp_eth_handle_t eth);
|
||||||
|
|
||||||
|
// Current GM clockIdentity as "XX-XX-XX-XX-XX-XX-XX-XX" (RFC 7273 form). false if none selected.
|
||||||
|
bool aes67_ptp_gm_id(char out[24]);
|
||||||
|
// Servo locked to the GM.
|
||||||
|
bool aes67_ptp_locked(void);
|
||||||
|
// PTP time (EMAC hardware clock) in ns.
|
||||||
|
esp_err_t aes67_ptp_now_ns(int64_t *ns);
|
||||||
@@ -0,0 +1,919 @@
|
|||||||
|
#include "ptp_clock.h"
|
||||||
|
|
||||||
|
#include <math.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "aes67_cfg.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_random.h"
|
||||||
|
#include "esp_timer.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/semphr.h"
|
||||||
|
#include "freertos/task.h"
|
||||||
|
#include "lwip/sockets.h"
|
||||||
|
#include "ptp_hw.h"
|
||||||
|
|
||||||
|
#define PTP_MCAST "224.0.1.129"
|
||||||
|
#define PTP_EVENT_PORT 319
|
||||||
|
#define PTP_GENERAL_PORT 320
|
||||||
|
#define HDR_LEN 34
|
||||||
|
#define FLAG_TWO_STEP 0x0200
|
||||||
|
#define STEP_NS 1000000 // re-step instead of slewing above 1 ms
|
||||||
|
#define LOCK_NS 1000 // |offset| below this counts as good
|
||||||
|
#define LOCK_GOOD 8 // consecutive good Syncs to lock
|
||||||
|
#define LOCK_BAD 3 // consecutive bad Syncs to unlock
|
||||||
|
#define MAX_DRIFT_PPB 500000.0
|
||||||
|
#define WINDOW 64 // samples for interval/delay statistics
|
||||||
|
#define SUMMARY_US (60 * 1000000LL)
|
||||||
|
#define AVG_S 120 // status.ptp.offset_avg_ns: mean |offset| over 2 min
|
||||||
|
#define FLAG_PTP_TIMESCALE 0x0008 // flagField octet 1 bit 3
|
||||||
|
#define FLAG_UNICAST 0x0400 // flagField octet 0 bit 2
|
||||||
|
#define UTC_OFFSET 37 // TAI - UTC (s), announced as information only
|
||||||
|
#define TIME_SOURCE_OSC 0xA0 // internal oscillator
|
||||||
|
|
||||||
|
static const char *TAG = "ptp";
|
||||||
|
static const uint8_t PTP_MCAST_MAC[6] = { 0x01, 0x00, 0x5e, 0x00, 0x01, 0x81 };
|
||||||
|
|
||||||
|
// Rolling window of int64 samples.
|
||||||
|
typedef struct {
|
||||||
|
int64_t v[WINDOW];
|
||||||
|
int n, next;
|
||||||
|
} window_t;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
bool valid;
|
||||||
|
uint8_t port_id[10]; // sourcePortIdentity of the GM (clockId + port)
|
||||||
|
uint32_t ip; // source address, for hybrid mode later
|
||||||
|
uint8_t p1, cls, acc, p2;
|
||||||
|
uint16_t var;
|
||||||
|
uint8_t gm_id[8];
|
||||||
|
uint16_t steps;
|
||||||
|
uint8_t flags; // flagField octet 1: timeTraceable 0x10, frequencyTraceable 0x20
|
||||||
|
int8_t log_announce;
|
||||||
|
int64_t last_us; // last Announce (esp_timer)
|
||||||
|
} master_t;
|
||||||
|
|
||||||
|
static struct {
|
||||||
|
esp_netif_t *netif;
|
||||||
|
int ev, gen;
|
||||||
|
uint8_t domain, dscp, timeout;
|
||||||
|
uint8_t port_id[10]; // our clockId (EUI-64 from MAC) + port 1
|
||||||
|
master_t gm; // foreign TimeTransmitter we follow (valid = TimeReceiver)
|
||||||
|
master_t own; // our own dataset for BMCA
|
||||||
|
bool slave_only; // role "slave": never TimeTransmitter
|
||||||
|
bool hybrid; // mode "hybrid": Delay_Req/Resp unicast as TimeReceiver
|
||||||
|
uint8_t gm_mac[6]; // Ethernet source of the GM's Sync (for unicast Delay_Req)
|
||||||
|
bool have_gm_mac;
|
||||||
|
uint32_t dreq_logged_ip; // last Delay_Req destination logged
|
||||||
|
bool master; // we are the TimeTransmitter
|
||||||
|
int64_t listen_since_us; // start of LISTENING (for the announce receipt timeout)
|
||||||
|
volatile bool reconfig;
|
||||||
|
int8_t cfg_log_sync, cfg_log_announce, cfg_log_dreq;
|
||||||
|
// TimeTransmitter
|
||||||
|
uint16_t tx_sync_seq, tx_announce_seq;
|
||||||
|
int64_t next_sync_us, next_announce_us, prev_t1_tx;
|
||||||
|
// Sync / Follow_Up
|
||||||
|
uint16_t sync_seq;
|
||||||
|
bool sync_pending;
|
||||||
|
int64_t t1, t2, sync_corr;
|
||||||
|
// Delay_Req / Delay_Resp
|
||||||
|
uint16_t dreq_seq;
|
||||||
|
bool dreq_pending;
|
||||||
|
int64_t t3;
|
||||||
|
int8_t log_dreq; // from Delay_Resp logMessageInterval
|
||||||
|
int64_t next_dreq_us;
|
||||||
|
int64_t delay_ns; // mean path delay, 0 = not measured yet
|
||||||
|
// Drift of (t2 - t1) between Syncs: corrects the delay for the time between t2 and t3
|
||||||
|
// while the local clock is not yet syntonised.
|
||||||
|
int64_t raw, prev_raw, prev_t2;
|
||||||
|
double rate;
|
||||||
|
int8_t log_sync; // GM's Sync interval (from Sync logMessageInterval)
|
||||||
|
// Servo (PI, linuxptp-style gains)
|
||||||
|
bool stepped; // clock set to GM time since this GM was selected
|
||||||
|
double drift_ppb; // integral term
|
||||||
|
double freq_ppb; // correction currently applied (positive = faster)
|
||||||
|
int64_t offset_ns;
|
||||||
|
int good, bad;
|
||||||
|
bool locked;
|
||||||
|
// Statistics for status.ptp (guarded by lock)
|
||||||
|
SemaphoreHandle_t lock;
|
||||||
|
window_t sync_iv, announce_iv, delays; // RX intervals as receiver, TX intervals as transmitter
|
||||||
|
int64_t last_announce_us;
|
||||||
|
uint32_t delay_req, delay_resp;
|
||||||
|
uint8_t own_class;
|
||||||
|
int64_t sum_max_ns, sum_start_us;
|
||||||
|
// Mean |offset| over the last AVG_S seconds (status.ptp.offset_avg_ns): one bucket per second.
|
||||||
|
struct {
|
||||||
|
int64_t sec, sum;
|
||||||
|
uint32_t n;
|
||||||
|
} avg[AVG_S];
|
||||||
|
} s;
|
||||||
|
|
||||||
|
static void avg_add(int64_t offset)
|
||||||
|
{
|
||||||
|
int64_t sec = esp_timer_get_time() / 1000000;
|
||||||
|
typeof(s.avg[0]) *b = &s.avg[sec % AVG_S];
|
||||||
|
if (b->sec != sec) {
|
||||||
|
b->sec = sec;
|
||||||
|
b->sum = 0;
|
||||||
|
b->n = 0;
|
||||||
|
}
|
||||||
|
b->sum += llabs(offset);
|
||||||
|
b->n++;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void avg_clear(void)
|
||||||
|
{
|
||||||
|
memset(s.avg, 0, sizeof(s.avg));
|
||||||
|
}
|
||||||
|
|
||||||
|
// False while no offset was measured in the window.
|
||||||
|
static bool avg_get(double *mean)
|
||||||
|
{
|
||||||
|
int64_t now = esp_timer_get_time() / 1000000, sum = 0;
|
||||||
|
uint32_t n = 0;
|
||||||
|
for (int i = 0; i < AVG_S; i++) {
|
||||||
|
if (s.avg[i].n && now - s.avg[i].sec < AVG_S) {
|
||||||
|
sum += s.avg[i].sum;
|
||||||
|
n += s.avg[i].n;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (n) {
|
||||||
|
*mean = (double)sum / n;
|
||||||
|
}
|
||||||
|
return n > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void win_add(window_t *w, int64_t v)
|
||||||
|
{
|
||||||
|
w->v[w->next] = v;
|
||||||
|
w->next = (w->next + 1) % WINDOW;
|
||||||
|
if (w->n < WINDOW) {
|
||||||
|
w->n++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void win_clear(window_t *w)
|
||||||
|
{
|
||||||
|
w->n = w->next = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// mean, min, max and standard deviation of a window
|
||||||
|
static void win_stats(const window_t *w, double *mean, double *min, double *max, double *sd)
|
||||||
|
{
|
||||||
|
double sum = 0, sq = 0, lo = 0, hi = 0;
|
||||||
|
for (int i = 0; i < w->n; i++) {
|
||||||
|
double x = (double)w->v[i];
|
||||||
|
sum += x;
|
||||||
|
sq += x * x;
|
||||||
|
lo = i ? fmin(lo, x) : x;
|
||||||
|
hi = i ? fmax(hi, x) : x;
|
||||||
|
}
|
||||||
|
double m = w->n ? sum / w->n : 0;
|
||||||
|
*mean = m;
|
||||||
|
if (min) *min = lo;
|
||||||
|
if (max) *max = hi;
|
||||||
|
if (sd) *sd = w->n > 1 ? sqrt(fmax(0, sq / w->n - m * m)) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
#define LOCKED(stmt) do { xSemaphoreTake(s.lock, portMAX_DELAY); stmt; xSemaphoreGive(s.lock); } while (0)
|
||||||
|
|
||||||
|
static void set_locked(bool locked);
|
||||||
|
static void become_master(void);
|
||||||
|
|
||||||
|
/* ----- helpers ----- */
|
||||||
|
|
||||||
|
// 2^log seconds in us; log clamped to the sane PTP range (-7..6).
|
||||||
|
static int64_t log_us(int8_t log)
|
||||||
|
{
|
||||||
|
log = log < -7 ? -7 : log > 6 ? 6 : log;
|
||||||
|
return log >= 0 ? 1000000LL << log : 1000000LL >> -log;
|
||||||
|
}
|
||||||
|
|
||||||
|
static uint16_t rd16(const uint8_t *p) { return (p[0] << 8) | p[1]; }
|
||||||
|
|
||||||
|
static int64_t rd_ts(const uint8_t *p) // 48-bit seconds + 32-bit ns
|
||||||
|
{
|
||||||
|
uint64_t sec = ((uint64_t)rd16(p) << 32) | ((uint32_t)p[2] << 24) | (p[3] << 16) | (p[4] << 8) | p[5];
|
||||||
|
uint32_t ns = ((uint32_t)p[6] << 24) | (p[7] << 16) | (p[8] << 8) | p[9];
|
||||||
|
return (int64_t)sec * 1000000000LL + ns;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int64_t rd_corr_ns(const uint8_t *p) // correctionField: ns * 2^16
|
||||||
|
{
|
||||||
|
int64_t v = 0;
|
||||||
|
for (int i = 0; i < 8; i++) {
|
||||||
|
v = (v << 8) | p[i];
|
||||||
|
}
|
||||||
|
return v >> 16;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int64_t mac_ns(const eth_mac_time_t *t)
|
||||||
|
{
|
||||||
|
return (int64_t)t->seconds * 1000000000LL + t->nanoseconds;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void fmt_id(char *out, const uint8_t *id)
|
||||||
|
{
|
||||||
|
sprintf(out, "%02X-%02X-%02X-%02X-%02X-%02X-%02X-%02X", id[0], id[1], id[2], id[3], id[4], id[5], id[6], id[7]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// IEEE 1588 dataset comparison (without the topology part): <0 if a is better.
|
||||||
|
static int compare(const master_t *a, const master_t *b)
|
||||||
|
{
|
||||||
|
if (a->p1 != b->p1) return a->p1 - b->p1;
|
||||||
|
if (a->cls != b->cls) return a->cls - b->cls;
|
||||||
|
if (a->acc != b->acc) return a->acc - b->acc;
|
||||||
|
if (a->var != b->var) return a->var - b->var;
|
||||||
|
if (a->p2 != b->p2) return a->p2 - b->p2;
|
||||||
|
int c = memcmp(a->gm_id, b->gm_id, 8);
|
||||||
|
if (c) return c;
|
||||||
|
return a->steps - b->steps;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int open_socket(uint16_t port, struct in_addr ifaddr)
|
||||||
|
{
|
||||||
|
int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
|
||||||
|
int one = 1;
|
||||||
|
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
|
||||||
|
struct sockaddr_in a = { .sin_family = AF_INET, .sin_port = htons(port), .sin_addr.s_addr = htonl(INADDR_ANY) };
|
||||||
|
struct ip_mreq m = { .imr_interface = ifaddr };
|
||||||
|
inet_aton(PTP_MCAST, &m.imr_multiaddr);
|
||||||
|
if (bind(fd, (struct sockaddr *)&a, sizeof(a)) < 0 ||
|
||||||
|
setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &m, sizeof(m)) < 0) {
|
||||||
|
ESP_LOGE(TAG, "socket %u: bind/join failed (errno %d)", port, errno);
|
||||||
|
close(fd);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
return fd;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool from_gm(const uint8_t *b)
|
||||||
|
{
|
||||||
|
return s.gm.valid && memcmp(b + 20, s.gm.port_id, 10) == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----- message handling ----- */
|
||||||
|
|
||||||
|
static void on_announce(const uint8_t *b, int len, uint32_t src_ip)
|
||||||
|
{
|
||||||
|
if (len < 64) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
master_t m = {
|
||||||
|
.valid = true, .ip = src_ip, .p1 = b[47], .cls = b[48], .acc = b[49], .var = rd16(b + 50),
|
||||||
|
.p2 = b[52], .steps = rd16(b + 61), .flags = b[7], .log_announce = (int8_t)b[33],
|
||||||
|
.last_us = esp_timer_get_time(),
|
||||||
|
};
|
||||||
|
memcpy(m.port_id, b + 20, 10);
|
||||||
|
memcpy(m.gm_id, b + 53, 8);
|
||||||
|
if (memcmp(m.port_id, s.port_id, 10) == 0) {
|
||||||
|
return; // our own
|
||||||
|
}
|
||||||
|
// BMCA: follow a foreign TimeTransmitter only if it beats our own dataset (always when slave-only).
|
||||||
|
bool better = s.slave_only || compare(&m, &s.own) < 0;
|
||||||
|
if (!better) {
|
||||||
|
if (from_gm(b)) {
|
||||||
|
ESP_LOGI(TAG, "TimeTransmitter's dataset is now worse than ours");
|
||||||
|
become_master();
|
||||||
|
}
|
||||||
|
return; // as TimeTransmitter a worse one should yield; nothing to do
|
||||||
|
}
|
||||||
|
if (s.master) {
|
||||||
|
s.master = false;
|
||||||
|
ESP_LOGI(TAG, "better TimeTransmitter seen: leaving TimeTransmitter state");
|
||||||
|
}
|
||||||
|
if (from_gm(b)) {
|
||||||
|
LOCKED({
|
||||||
|
if (s.last_announce_us) {
|
||||||
|
win_add(&s.announce_iv, m.last_us - s.last_announce_us);
|
||||||
|
}
|
||||||
|
s.last_announce_us = m.last_us;
|
||||||
|
s.gm = m; // refresh dataset and timeout
|
||||||
|
});
|
||||||
|
} else if (!s.gm.valid || compare(&m, &s.gm) < 0) {
|
||||||
|
char id[24];
|
||||||
|
fmt_id(id, m.gm_id);
|
||||||
|
ESP_LOGI(TAG, "TimeTransmitter %s (p1 %u class %u p2 %u, %u hops) from " IPSTR,
|
||||||
|
id, m.p1, m.cls, m.p2, m.steps, IP2STR((esp_ip4_addr_t *)&src_ip));
|
||||||
|
LOCKED({
|
||||||
|
s.gm = m;
|
||||||
|
s.last_announce_us = m.last_us;
|
||||||
|
win_clear(&s.announce_iv);
|
||||||
|
win_clear(&s.sync_iv);
|
||||||
|
win_clear(&s.delays);
|
||||||
|
});
|
||||||
|
s.sync_pending = s.dreq_pending = false;
|
||||||
|
s.have_gm_mac = false;
|
||||||
|
LOCKED({
|
||||||
|
s.delay_ns = s.prev_t2 = 0;
|
||||||
|
s.stepped = false;
|
||||||
|
set_locked(false);
|
||||||
|
});
|
||||||
|
s.log_dreq = 0;
|
||||||
|
s.next_dreq_us = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void set_locked(bool locked)
|
||||||
|
{
|
||||||
|
if (locked != s.locked) {
|
||||||
|
s.locked = locked;
|
||||||
|
if (locked) {
|
||||||
|
win_clear(&s.delays); // delay statistics cover the locked period, not the pull-in
|
||||||
|
ESP_LOGI(TAG, "locked: offset %+lld ns, frequency %+.3f ppm, path delay %lld ns",
|
||||||
|
s.offset_ns, s.freq_ppb / 1000, s.delay_ns);
|
||||||
|
} else {
|
||||||
|
ESP_LOGW(TAG, "unlocked");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!locked) {
|
||||||
|
s.good = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// offset = local - GM (ns)
|
||||||
|
static void servo(int64_t offset)
|
||||||
|
{
|
||||||
|
s.offset_ns = offset;
|
||||||
|
if (!s.stepped || llabs(offset) > STEP_NS) {
|
||||||
|
if (!s.stepped) {
|
||||||
|
// Seed the integral with the measured rate error (measured with the current correction applied).
|
||||||
|
s.drift_ppb += s.rate * 1e9;
|
||||||
|
}
|
||||||
|
s.freq_ppb = -s.drift_ppb;
|
||||||
|
ptp_hw_adj_freq(s.freq_ppb);
|
||||||
|
esp_err_t err = ptp_hw_step(offset);
|
||||||
|
ESP_LOGI(TAG, "clock stepped by %+lld ns (%s), frequency %+.3f ppm", -offset, esp_err_to_name(err),
|
||||||
|
s.freq_ppb / 1000);
|
||||||
|
s.stepped = true;
|
||||||
|
s.offset_ns = 0; // the pre-step offset is history: not for status or the summary
|
||||||
|
s.sum_max_ns = 0;
|
||||||
|
avg_clear();
|
||||||
|
s.sum_start_us = 0;
|
||||||
|
s.prev_t2 = 0; // rate across the step is meaningless
|
||||||
|
s.bad = 0;
|
||||||
|
set_locked(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// linuxptp PI gains for hardware timestamps, scaled by the Sync interval
|
||||||
|
double iv = ldexp(1.0, s.log_sync);
|
||||||
|
double kp = fmin(0.7 * pow(iv, -0.3), 0.7 / iv);
|
||||||
|
double ki = fmin(0.3 * pow(iv, 0.4), 0.3 / iv);
|
||||||
|
double ppb = kp * offset + s.drift_ppb;
|
||||||
|
s.drift_ppb = fmax(-MAX_DRIFT_PPB, fmin(MAX_DRIFT_PPB, s.drift_ppb + ki * offset));
|
||||||
|
s.freq_ppb = -ppb;
|
||||||
|
ptp_hw_adj_freq(s.freq_ppb);
|
||||||
|
avg_add(offset);
|
||||||
|
|
||||||
|
if (llabs(offset) < LOCK_NS) {
|
||||||
|
s.bad = 0;
|
||||||
|
if (++s.good >= LOCK_GOOD) {
|
||||||
|
set_locked(true);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
s.good = 0;
|
||||||
|
if (s.locked && ++s.bad >= LOCK_BAD) {
|
||||||
|
set_locked(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void sync_complete(void)
|
||||||
|
{
|
||||||
|
s.sync_pending = false;
|
||||||
|
s.raw = s.t2 - s.t1 - s.sync_corr;
|
||||||
|
if (s.prev_t2 && s.t2 > s.prev_t2) {
|
||||||
|
s.rate = (double)(s.raw - s.prev_raw) / (double)(s.t2 - s.prev_t2);
|
||||||
|
LOCKED(win_add(&s.sync_iv, s.t2 - s.prev_t2));
|
||||||
|
}
|
||||||
|
s.prev_raw = s.raw;
|
||||||
|
s.prev_t2 = s.t2;
|
||||||
|
if (!s.delay_ns) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// offset = t2 - t1 - corrections - mean path delay
|
||||||
|
LOCKED(servo(s.raw - s.delay_ns));
|
||||||
|
ESP_LOGD(TAG, "seq %u: offset %+lld ns, freq %+.3f ppm, path delay %lld ns%s", s.sync_seq, s.offset_ns,
|
||||||
|
s.freq_ppb / 1000, s.delay_ns, s.locked ? ", locked" : "");
|
||||||
|
// Info-level summary once a minute: worst offset in the period.
|
||||||
|
int64_t now = esp_timer_get_time();
|
||||||
|
s.sum_max_ns = llabs(s.offset_ns) > s.sum_max_ns ? llabs(s.offset_ns) : s.sum_max_ns;
|
||||||
|
if (!s.sum_start_us) {
|
||||||
|
s.sum_start_us = now;
|
||||||
|
} else if (now - s.sum_start_us >= SUMMARY_US) {
|
||||||
|
ESP_LOGI(TAG, "%s: max |offset| %lld ns, freq %+.3f ppm, path delay %lld ns (last 60 s)",
|
||||||
|
s.locked ? "locked" : "unlocked", s.sum_max_ns, s.freq_ppb / 1000, s.delay_ns);
|
||||||
|
s.sum_max_ns = 0;
|
||||||
|
s.sum_start_us = now;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void on_sync(const uint8_t *b, int len)
|
||||||
|
{
|
||||||
|
if (len < 44 || !from_gm(b)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
eth_mac_time_t t2;
|
||||||
|
uint16_t seq = rd16(b + 30);
|
||||||
|
if (!ptp_hw_rx_ts_mac(PTP_MSG_SYNC, seq, b + 20, &t2, s.gm_mac)) {
|
||||||
|
ESP_LOGW(TAG, "Sync %u: no HW RX timestamp", seq);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
s.have_gm_mac = true;
|
||||||
|
s.sync_seq = seq;
|
||||||
|
s.log_sync = (int8_t)b[33];
|
||||||
|
s.t2 = mac_ns(&t2);
|
||||||
|
s.sync_corr = rd_corr_ns(b + 8);
|
||||||
|
if (rd16(b + 6) & FLAG_TWO_STEP) {
|
||||||
|
s.sync_pending = true; // wait for Follow_Up
|
||||||
|
} else {
|
||||||
|
s.t1 = rd_ts(b + 34);
|
||||||
|
sync_complete();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void on_follow_up(const uint8_t *b, int len)
|
||||||
|
{
|
||||||
|
if (len < 44 || !from_gm(b) || !s.sync_pending || rd16(b + 30) != s.sync_seq) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
s.t1 = rd_ts(b + 34);
|
||||||
|
s.sync_corr += rd_corr_ns(b + 8);
|
||||||
|
sync_complete();
|
||||||
|
}
|
||||||
|
|
||||||
|
static void send_delay_req(void)
|
||||||
|
{
|
||||||
|
uint8_t m[44] = { 0 };
|
||||||
|
m[0] = PTP_MSG_DELAY_REQ;
|
||||||
|
m[1] = 2;
|
||||||
|
m[3] = sizeof(m);
|
||||||
|
m[4] = s.domain;
|
||||||
|
memcpy(m + 20, s.port_id, 10);
|
||||||
|
s.dreq_seq++;
|
||||||
|
m[30] = s.dreq_seq >> 8;
|
||||||
|
m[31] = s.dreq_seq & 0xff;
|
||||||
|
m[32] = 1; // controlField: Delay_Req
|
||||||
|
m[33] = 0x7f;
|
||||||
|
uint32_t dst;
|
||||||
|
const uint8_t *dst_mac = PTP_MCAST_MAC;
|
||||||
|
inet_aton(PTP_MCAST, (struct in_addr *)&dst);
|
||||||
|
if (s.hybrid && s.gm.ip && s.have_gm_mac) {
|
||||||
|
// Hybrid: unicast to the GM (address from its Announce, MAC from its Sync frames).
|
||||||
|
dst = s.gm.ip;
|
||||||
|
dst_mac = s.gm_mac;
|
||||||
|
m[6] |= FLAG_UNICAST >> 8;
|
||||||
|
}
|
||||||
|
if (dst != s.dreq_logged_ip) {
|
||||||
|
s.dreq_logged_ip = dst;
|
||||||
|
ESP_LOGI(TAG, "Delay_Req %s to " IPSTR " (%02x:%02x:%02x:%02x:%02x:%02x)",
|
||||||
|
dst_mac == PTP_MCAST_MAC ? "multicast" : "unicast", IP2STR((esp_ip4_addr_t *)&dst),
|
||||||
|
dst_mac[0], dst_mac[1], dst_mac[2], dst_mac[3], dst_mac[4], dst_mac[5]);
|
||||||
|
}
|
||||||
|
eth_mac_time_t t3;
|
||||||
|
esp_err_t err = ptp_hw_send_event(dst_mac, dst, s.dscp, m, sizeof(m), &t3);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
ESP_LOGW(TAG, "Delay_Req %u: %s", s.dreq_seq, esp_err_to_name(err));
|
||||||
|
s.dreq_pending = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
s.t3 = mac_ns(&t3);
|
||||||
|
s.dreq_pending = true;
|
||||||
|
LOCKED(s.delay_req++);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void on_delay_resp(const uint8_t *b, int len)
|
||||||
|
{
|
||||||
|
if (len < 54 || !from_gm(b) || !s.dreq_pending || rd16(b + 30) != s.dreq_seq ||
|
||||||
|
memcmp(b + 44, s.port_id, 10) != 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
s.dreq_pending = false;
|
||||||
|
LOCKED(s.delay_resp++);
|
||||||
|
int64_t t4 = rd_ts(b + 34) - rd_corr_ns(b + 8);
|
||||||
|
// Delay_Req interval from the GM; a unicast Delay_Resp carries 0x7F ("not specified"):
|
||||||
|
// then use our configured interval.
|
||||||
|
int8_t l = (int8_t)b[33];
|
||||||
|
s.log_dreq = l >= -7 && l <= 6 ? l : s.cfg_log_dreq;
|
||||||
|
if (!s.prev_t2) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// mean path delay = ((t2 - t1 - corr) + (t4 - t3)) / 2, plus the offset drift between t2 and t3
|
||||||
|
int64_t d = (s.raw + (t4 - s.t3) + (int64_t)(s.rate * (double)(s.t3 - s.t2))) / 2;
|
||||||
|
LOCKED({
|
||||||
|
s.delay_ns = s.delay_ns ? (s.delay_ns * 7 + d) / 8 : d; // light smoothing for the servo
|
||||||
|
win_add(&s.delays, d); // raw samples for status
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----- TimeTransmitter ----- */
|
||||||
|
|
||||||
|
|
||||||
|
static void wr_ts(uint8_t *p, int64_t ns)
|
||||||
|
{
|
||||||
|
uint64_t sec = ns / 1000000000LL;
|
||||||
|
uint32_t n = ns % 1000000000LL;
|
||||||
|
p[0] = sec >> 40; p[1] = sec >> 32; p[2] = sec >> 24; p[3] = sec >> 16; p[4] = sec >> 8; p[5] = sec;
|
||||||
|
p[6] = n >> 24; p[7] = n >> 16; p[8] = n >> 8; p[9] = n;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void hdr(uint8_t *m, uint8_t type, uint16_t len, uint16_t flags, uint16_t seq, uint8_t control, int8_t log)
|
||||||
|
{
|
||||||
|
memset(m, 0, len);
|
||||||
|
m[0] = type;
|
||||||
|
m[1] = 2;
|
||||||
|
m[2] = len >> 8;
|
||||||
|
m[3] = len & 0xff;
|
||||||
|
m[4] = s.domain;
|
||||||
|
m[6] = flags >> 8;
|
||||||
|
m[7] = flags & 0xff;
|
||||||
|
memcpy(m + 20, s.port_id, 10);
|
||||||
|
m[30] = seq >> 8;
|
||||||
|
m[31] = seq & 0xff;
|
||||||
|
m[32] = control;
|
||||||
|
m[33] = (uint8_t)log;
|
||||||
|
}
|
||||||
|
|
||||||
|
// General messages (Announce, Follow_Up, Delay_Resp) go through the lwIP socket on port 320.
|
||||||
|
static void send_general(const uint8_t *m, size_t len, uint32_t dst_ip)
|
||||||
|
{
|
||||||
|
struct sockaddr_in dst = { .sin_family = AF_INET, .sin_port = htons(PTP_GENERAL_PORT), .sin_addr.s_addr = dst_ip };
|
||||||
|
if (sendto(s.gen, m, len, 0, (struct sockaddr *)&dst, sizeof(dst)) < 0) {
|
||||||
|
ESP_LOGW(TAG, "send type %u failed (errno %d)", m[0] & 0x0f, errno);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static uint32_t mcast_ip(void)
|
||||||
|
{
|
||||||
|
struct in_addr a;
|
||||||
|
inet_aton(PTP_MCAST, &a);
|
||||||
|
return a.s_addr;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void send_announce(void)
|
||||||
|
{
|
||||||
|
uint8_t m[64];
|
||||||
|
hdr(m, PTP_MSG_ANNOUNCE, sizeof(m), FLAG_PTP_TIMESCALE, s.tx_announce_seq++, 5, s.cfg_log_announce);
|
||||||
|
m[44] = UTC_OFFSET >> 8;
|
||||||
|
m[45] = UTC_OFFSET & 0xff;
|
||||||
|
m[47] = s.own.p1;
|
||||||
|
m[48] = s.own.cls;
|
||||||
|
m[49] = s.own.acc;
|
||||||
|
m[50] = s.own.var >> 8;
|
||||||
|
m[51] = s.own.var & 0xff;
|
||||||
|
m[52] = s.own.p2;
|
||||||
|
memcpy(m + 53, s.own.gm_id, 8);
|
||||||
|
m[63] = TIME_SOURCE_OSC;
|
||||||
|
send_general(m, sizeof(m), mcast_ip());
|
||||||
|
int64_t now = esp_timer_get_time();
|
||||||
|
LOCKED({
|
||||||
|
if (s.last_announce_us) {
|
||||||
|
win_add(&s.announce_iv, now - s.last_announce_us);
|
||||||
|
}
|
||||||
|
s.last_announce_us = now;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Two-step: Sync as a raw frame for its hardware TX timestamp, then Follow_Up with that time.
|
||||||
|
static void send_sync(void)
|
||||||
|
{
|
||||||
|
uint8_t m[44];
|
||||||
|
uint16_t seq = s.tx_sync_seq++;
|
||||||
|
hdr(m, PTP_MSG_SYNC, sizeof(m), FLAG_TWO_STEP, seq, 0, s.cfg_log_sync);
|
||||||
|
eth_mac_time_t t1;
|
||||||
|
esp_err_t err = ptp_hw_send_event(PTP_MCAST_MAC, mcast_ip(), s.dscp, m, sizeof(m), &t1);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
ESP_LOGW(TAG, "Sync %u: %s", seq, esp_err_to_name(err));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
hdr(m, PTP_MSG_FOLLOW_UP, sizeof(m), 0, seq, 2, s.cfg_log_sync);
|
||||||
|
int64_t t1n = mac_ns(&t1);
|
||||||
|
wr_ts(m + 34, t1n);
|
||||||
|
send_general(m, sizeof(m), mcast_ip());
|
||||||
|
LOCKED({
|
||||||
|
if (s.prev_t1_tx) {
|
||||||
|
win_add(&s.sync_iv, t1n - s.prev_t1_tx);
|
||||||
|
}
|
||||||
|
s.prev_t1_tx = t1n;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
static void on_delay_req(const uint8_t *b, int len, uint32_t src_ip)
|
||||||
|
{
|
||||||
|
if (!s.master || len < 44) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
eth_mac_time_t t4;
|
||||||
|
uint16_t seq = rd16(b + 30);
|
||||||
|
if (!ptp_hw_rx_ts(PTP_MSG_DELAY_REQ, seq, b + 20, &t4)) {
|
||||||
|
ESP_LOGW(TAG, "Delay_Req %u: no HW RX timestamp", seq);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
uint8_t m[54];
|
||||||
|
hdr(m, PTP_MSG_DELAY_RESP, sizeof(m), 0, seq, 3, s.cfg_log_dreq);
|
||||||
|
memcpy(m + 8, b + 8, 8); // correctionField of the Delay_Req
|
||||||
|
wr_ts(m + 34, mac_ns(&t4));
|
||||||
|
memcpy(m + 44, b + 20, 10); // requestingPortIdentity
|
||||||
|
// Unicast Delay_Req (hybrid TimeReceiver) -> unicast Delay_Resp; multicast -> multicast.
|
||||||
|
bool unicast = rd16(b + 6) & FLAG_UNICAST;
|
||||||
|
if (unicast) {
|
||||||
|
m[6] |= FLAG_UNICAST >> 8;
|
||||||
|
}
|
||||||
|
send_general(m, sizeof(m), unicast ? src_ip : mcast_ip());
|
||||||
|
LOCKED({
|
||||||
|
s.delay_req++;
|
||||||
|
s.delay_resp++;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
static void become_master(void)
|
||||||
|
{
|
||||||
|
char id[24];
|
||||||
|
fmt_id(id, s.own.gm_id);
|
||||||
|
ESP_LOGI(TAG, "no better TimeTransmitter: this device is TimeTransmitter %s (p1 %u class %u p2 %u)",
|
||||||
|
id, s.own.p1, s.own.cls, s.own.p2);
|
||||||
|
LOCKED({
|
||||||
|
memset(&s.gm, 0, sizeof(s.gm));
|
||||||
|
s.master = true;
|
||||||
|
s.delay_ns = s.prev_t2 = 0;
|
||||||
|
s.stepped = false;
|
||||||
|
set_locked(false); // servo state; the frequency correction stays (holdover)
|
||||||
|
s.last_announce_us = s.prev_t1_tx = 0;
|
||||||
|
win_clear(&s.announce_iv);
|
||||||
|
win_clear(&s.sync_iv);
|
||||||
|
win_clear(&s.delays);
|
||||||
|
});
|
||||||
|
s.sync_pending = s.dreq_pending = false;
|
||||||
|
s.next_sync_us = s.next_announce_us = esp_timer_get_time();
|
||||||
|
}
|
||||||
|
|
||||||
|
static void enter_listening(void)
|
||||||
|
{
|
||||||
|
s.listen_since_us = esp_timer_get_time();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----- task ----- */
|
||||||
|
|
||||||
|
static void load_config(void)
|
||||||
|
{
|
||||||
|
cJSON *c = cfg_get("ptp");
|
||||||
|
s.domain = cJSON_GetObjectItem(c, "domain")->valueint;
|
||||||
|
s.dscp = cJSON_GetObjectItem(c, "dscp")->valueint;
|
||||||
|
s.timeout = cJSON_GetObjectItem(c, "announce_timeout")->valueint;
|
||||||
|
s.cfg_log_sync = cJSON_GetObjectItem(c, "log_sync")->valueint;
|
||||||
|
s.cfg_log_announce = cJSON_GetObjectItem(c, "log_announce")->valueint;
|
||||||
|
s.cfg_log_dreq = cJSON_GetObjectItem(c, "log_delay_req")->valueint;
|
||||||
|
// Roles (docs): slave = clockClass 255, never transmits; auto = 248 with the configured priorities
|
||||||
|
// (250/250 by default: loses to any real GM; a lower priority1 prefers this device).
|
||||||
|
s.slave_only = strcmp(cJSON_GetObjectItem(c, "role")->valuestring, "slave") == 0;
|
||||||
|
s.hybrid = strcmp(cJSON_GetObjectItem(c, "mode")->valuestring, "hybrid") == 0;
|
||||||
|
s.own_class = s.slave_only ? 255 : 248;
|
||||||
|
s.own = (master_t){
|
||||||
|
.valid = true, .p1 = cJSON_GetObjectItem(c, "priority1")->valueint, .cls = s.own_class,
|
||||||
|
.acc = 0xFE, .var = 0xFFFF, .p2 = cJSON_GetObjectItem(c, "priority2")->valueint, .steps = 0,
|
||||||
|
.log_announce = s.cfg_log_announce,
|
||||||
|
};
|
||||||
|
memcpy(s.own.gm_id, s.port_id, 8);
|
||||||
|
memcpy(s.own.port_id, s.port_id, 10);
|
||||||
|
cJSON_Delete(c);
|
||||||
|
}
|
||||||
|
|
||||||
|
void ptp_clock_reconfig(void)
|
||||||
|
{
|
||||||
|
s.reconfig = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void ptp_task(void *arg)
|
||||||
|
{
|
||||||
|
esp_netif_ip_info_t ip = { 0 };
|
||||||
|
while (esp_netif_get_ip_info(s.netif, &ip) != ESP_OK || !ip.ip.addr) {
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(500));
|
||||||
|
}
|
||||||
|
struct in_addr ifaddr = { .s_addr = ip.ip.addr };
|
||||||
|
s.ev = open_socket(PTP_EVENT_PORT, ifaddr);
|
||||||
|
s.gen = open_socket(PTP_GENERAL_PORT, ifaddr);
|
||||||
|
if (s.ev < 0 || s.gen < 0) {
|
||||||
|
vTaskDelete(NULL);
|
||||||
|
}
|
||||||
|
// General messages we send as TimeTransmitter: subnet only, PTP DSCP, no loopback.
|
||||||
|
uint8_t ttl = 1, loop = 0;
|
||||||
|
int tos = s.dscp << 2;
|
||||||
|
setsockopt(s.gen, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl));
|
||||||
|
setsockopt(s.gen, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop));
|
||||||
|
setsockopt(s.gen, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr, sizeof(ifaddr));
|
||||||
|
setsockopt(s.gen, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
|
||||||
|
enter_listening();
|
||||||
|
char id[24];
|
||||||
|
fmt_id(id, s.port_id);
|
||||||
|
ESP_LOGI(TAG, "PTP on " IPSTR ", domain %u, clock %s, role %s, listening", IP2STR(&ip.ip), s.domain, id,
|
||||||
|
s.slave_only ? "TimeReceiver only" : "auto/TimeTransmitter capable");
|
||||||
|
|
||||||
|
uint8_t b[128];
|
||||||
|
while (1) {
|
||||||
|
fd_set fds;
|
||||||
|
FD_ZERO(&fds);
|
||||||
|
FD_SET(s.ev, &fds);
|
||||||
|
FD_SET(s.gen, &fds);
|
||||||
|
// Sleep until the next message is due as TimeTransmitter, at most 100 ms.
|
||||||
|
int64_t wait = 100000;
|
||||||
|
if (s.master) {
|
||||||
|
int64_t now = esp_timer_get_time();
|
||||||
|
int64_t due = s.next_sync_us < s.next_announce_us ? s.next_sync_us : s.next_announce_us;
|
||||||
|
wait = due - now < 0 ? 0 : due - now < wait ? due - now : wait;
|
||||||
|
}
|
||||||
|
struct timeval tv = { .tv_sec = 0, .tv_usec = wait };
|
||||||
|
if (select((s.ev > s.gen ? s.ev : s.gen) + 1, &fds, NULL, NULL, &tv) > 0) {
|
||||||
|
for (int k = 0; k < 2; k++) {
|
||||||
|
int fd = k ? s.gen : s.ev;
|
||||||
|
if (!FD_ISSET(fd, &fds)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
struct sockaddr_in src;
|
||||||
|
socklen_t sl = sizeof(src);
|
||||||
|
int len = recvfrom(fd, b, sizeof(b), 0, (struct sockaddr *)&src, &sl);
|
||||||
|
if (len < HDR_LEN || (b[1] & 0x0f) != 2 || b[4] != s.domain) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
switch (b[0] & 0x0f) {
|
||||||
|
case PTP_MSG_ANNOUNCE: on_announce(b, len, src.sin_addr.s_addr); break;
|
||||||
|
case PTP_MSG_SYNC: on_sync(b, len); break;
|
||||||
|
case PTP_MSG_FOLLOW_UP: on_follow_up(b, len); break;
|
||||||
|
case PTP_MSG_DELAY_RESP: on_delay_resp(b, len); break;
|
||||||
|
case PTP_MSG_DELAY_REQ: on_delay_req(b, len, src.sin_addr.s_addr); break;
|
||||||
|
default: break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (s.reconfig) {
|
||||||
|
s.reconfig = false;
|
||||||
|
bool was_slave_only = s.slave_only;
|
||||||
|
load_config();
|
||||||
|
int tos2 = s.dscp << 2;
|
||||||
|
setsockopt(s.gen, IPPROTO_IP, IP_TOS, &tos2, sizeof(tos2));
|
||||||
|
ESP_LOGI(TAG, "config applied: role %s, mode %s, p1 %u p2 %u, domain %u",
|
||||||
|
s.slave_only ? "slave" : "auto", s.hybrid ? "hybrid" : "multicast",
|
||||||
|
s.own.p1, s.own.p2, s.domain);
|
||||||
|
// Re-run the decision: a foreign GM worse than our new dataset is dropped; as
|
||||||
|
// TimeTransmitter with role slave we stop.
|
||||||
|
if (s.master && s.slave_only) {
|
||||||
|
s.master = false;
|
||||||
|
ESP_LOGI(TAG, "role slave: leaving TimeTransmitter state");
|
||||||
|
enter_listening();
|
||||||
|
} else if (s.gm.valid && !s.slave_only && compare(&s.gm, &s.own) > 0) {
|
||||||
|
become_master();
|
||||||
|
} else if (!s.gm.valid && was_slave_only != s.slave_only) {
|
||||||
|
enter_listening();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int64_t now = esp_timer_get_time();
|
||||||
|
if (s.master) {
|
||||||
|
if (now >= s.next_announce_us) {
|
||||||
|
send_announce();
|
||||||
|
s.next_announce_us += log_us(s.cfg_log_announce);
|
||||||
|
if (s.next_announce_us < now) {
|
||||||
|
s.next_announce_us = now + log_us(s.cfg_log_announce);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (now >= s.next_sync_us) {
|
||||||
|
send_sync();
|
||||||
|
s.next_sync_us += log_us(s.cfg_log_sync);
|
||||||
|
if (s.next_sync_us < now) {
|
||||||
|
s.next_sync_us = now + log_us(s.cfg_log_sync);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (!s.gm.valid) {
|
||||||
|
// LISTENING: no better TimeTransmitter within announceReceiptTimeout -> become one
|
||||||
|
if (!s.slave_only && now - s.listen_since_us > (int64_t)s.timeout * log_us(s.cfg_log_announce)) {
|
||||||
|
become_master();
|
||||||
|
}
|
||||||
|
} else if (s.gm.valid) {
|
||||||
|
// announceReceiptTimeout x the GM's announce interval
|
||||||
|
int64_t window = (int64_t)s.timeout * log_us(s.gm.log_announce);
|
||||||
|
if (now - s.gm.last_us > window) {
|
||||||
|
ESP_LOGW(TAG, "TimeTransmitter lost (no Announce for %lld ms), listening", window / 1000);
|
||||||
|
LOCKED({
|
||||||
|
memset(&s.gm, 0, sizeof(s.gm));
|
||||||
|
s.delay_ns = s.prev_t2 = 0;
|
||||||
|
s.stepped = false;
|
||||||
|
set_locked(false); // frequency correction stays (holdover)
|
||||||
|
});
|
||||||
|
enter_listening();
|
||||||
|
} else if (now >= s.next_dreq_us && s.prev_t2) {
|
||||||
|
send_delay_req();
|
||||||
|
// Delay_Req interval from the GM's Delay_Resp; randomised 0.5..1.5x
|
||||||
|
int64_t iv = log_us(s.log_dreq);
|
||||||
|
s.next_dreq_us = now + iv / 2 + (esp_random() % (uint32_t)iv);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ptp_clock_gm_id(char out[24])
|
||||||
|
{
|
||||||
|
xSemaphoreTake(s.lock, portMAX_DELAY);
|
||||||
|
bool valid = s.gm.valid || s.master;
|
||||||
|
if (valid) {
|
||||||
|
fmt_id(out, s.master ? s.own.gm_id : s.gm.gm_id);
|
||||||
|
}
|
||||||
|
xSemaphoreGive(s.lock);
|
||||||
|
return valid;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Media may be timed from our clock: locked to a GM, or we are the GM.
|
||||||
|
bool ptp_clock_locked(void)
|
||||||
|
{
|
||||||
|
return s.locked || s.master;
|
||||||
|
}
|
||||||
|
|
||||||
|
void ptp_clock_status(cJSON *st)
|
||||||
|
{
|
||||||
|
cJSON *p = cJSON_AddObjectToObject(st, "ptp");
|
||||||
|
char id[24];
|
||||||
|
double mean, min, max, sd;
|
||||||
|
|
||||||
|
xSemaphoreTake(s.lock, portMAX_DELAY);
|
||||||
|
const char *state = s.master ? "MASTER" : !s.gm.valid ? "LISTENING" : s.locked ? "SLAVE" : "UNCALIBRATED";
|
||||||
|
cJSON_AddStringToObject(p, "state", state);
|
||||||
|
cJSON_AddBoolToObject(p, "locked", s.locked || s.master);
|
||||||
|
cJSON_AddNumberToObject(p, "version", 2);
|
||||||
|
cJSON_AddNumberToObject(p, "own_class", s.own_class);
|
||||||
|
fmt_id(id, s.port_id);
|
||||||
|
cJSON_AddStringToObject(p, "clock_id", id);
|
||||||
|
cJSON_AddBoolToObject(p, "hw_ts", true);
|
||||||
|
cJSON_AddNumberToObject(p, "window", WINDOW);
|
||||||
|
cJSON_AddNumberToObject(p, "delay_req", s.delay_req);
|
||||||
|
cJSON_AddNumberToObject(p, "delay_resp", s.delay_resp);
|
||||||
|
if (s.master) {
|
||||||
|
// We are the GM: the UI shows "(this device)" and "-" for offset/frequency/delay.
|
||||||
|
fmt_id(id, s.own.gm_id);
|
||||||
|
cJSON_AddStringToObject(p, "gm_id", id);
|
||||||
|
cJSON_AddNumberToObject(p, "gm_class", s.own.cls);
|
||||||
|
cJSON_AddNumberToObject(p, "gm_accuracy", s.own.acc);
|
||||||
|
cJSON_AddNumberToObject(p, "gm_p1", s.own.p1);
|
||||||
|
cJSON_AddNumberToObject(p, "gm_p2", s.own.p2);
|
||||||
|
cJSON_AddNumberToObject(p, "steps_removed", 0);
|
||||||
|
cJSON_AddBoolToObject(p, "gm_time_traceable", false);
|
||||||
|
cJSON_AddBoolToObject(p, "gm_freq_traceable", false);
|
||||||
|
if (s.sync_iv.n) {
|
||||||
|
win_stats(&s.sync_iv, &mean, &min, &max, &sd);
|
||||||
|
cJSON_AddNumberToObject(p, "sync_avg_ms", mean / 1e6);
|
||||||
|
cJSON_AddNumberToObject(p, "sync_min_ms", min / 1e6);
|
||||||
|
cJSON_AddNumberToObject(p, "sync_max_ms", max / 1e6);
|
||||||
|
cJSON_AddNumberToObject(p, "sync_jitter_us", sd / 1e3);
|
||||||
|
}
|
||||||
|
if (s.announce_iv.n) {
|
||||||
|
win_stats(&s.announce_iv, &mean, NULL, NULL, NULL);
|
||||||
|
cJSON_AddNumberToObject(p, "announce_avg_ms", mean / 1e3);
|
||||||
|
}
|
||||||
|
} else if (s.gm.valid) {
|
||||||
|
fmt_id(id, s.gm.gm_id);
|
||||||
|
cJSON_AddStringToObject(p, "gm_id", id);
|
||||||
|
cJSON_AddNumberToObject(p, "gm_class", s.gm.cls);
|
||||||
|
cJSON_AddNumberToObject(p, "gm_accuracy", s.gm.acc);
|
||||||
|
cJSON_AddNumberToObject(p, "gm_p1", s.gm.p1);
|
||||||
|
cJSON_AddNumberToObject(p, "gm_p2", s.gm.p2);
|
||||||
|
cJSON_AddNumberToObject(p, "steps_removed", s.gm.steps);
|
||||||
|
cJSON_AddBoolToObject(p, "gm_time_traceable", s.gm.flags & 0x10);
|
||||||
|
cJSON_AddBoolToObject(p, "gm_freq_traceable", s.gm.flags & 0x20);
|
||||||
|
if (s.stepped) {
|
||||||
|
cJSON_AddNumberToObject(p, "offset_ns", s.offset_ns);
|
||||||
|
if (avg_get(&mean)) {
|
||||||
|
cJSON_AddNumberToObject(p, "offset_avg_ns", round(mean));
|
||||||
|
}
|
||||||
|
cJSON_AddNumberToObject(p, "freq_ppb", round(s.freq_ppb));
|
||||||
|
}
|
||||||
|
if (s.delays.n) {
|
||||||
|
win_stats(&s.delays, &mean, NULL, NULL, &sd);
|
||||||
|
cJSON_AddNumberToObject(p, "path_delay_ns", round(mean));
|
||||||
|
cJSON_AddNumberToObject(p, "path_delay_sd_ns", round(sd));
|
||||||
|
}
|
||||||
|
if (s.sync_iv.n) {
|
||||||
|
win_stats(&s.sync_iv, &mean, &min, &max, &sd);
|
||||||
|
cJSON_AddNumberToObject(p, "sync_avg_ms", mean / 1e6);
|
||||||
|
cJSON_AddNumberToObject(p, "sync_min_ms", min / 1e6);
|
||||||
|
cJSON_AddNumberToObject(p, "sync_max_ms", max / 1e6);
|
||||||
|
cJSON_AddNumberToObject(p, "sync_jitter_us", sd / 1e3);
|
||||||
|
}
|
||||||
|
if (s.announce_iv.n) {
|
||||||
|
win_stats(&s.announce_iv, &mean, NULL, NULL, NULL);
|
||||||
|
cJSON_AddNumberToObject(p, "announce_avg_ms", mean / 1e3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
xSemaphoreGive(s.lock);
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t ptp_clock_start(esp_netif_t *netif)
|
||||||
|
{
|
||||||
|
s.netif = netif;
|
||||||
|
s.lock = xSemaphoreCreateMutex();
|
||||||
|
uint8_t mac[6];
|
||||||
|
esp_netif_get_mac(netif, mac);
|
||||||
|
const uint8_t pid[10] = { mac[0], mac[1], mac[2], 0xff, 0xfe, mac[3], mac[4], mac[5], 0, 1 };
|
||||||
|
memcpy(s.port_id, pid, sizeof(pid));
|
||||||
|
load_config(); // after port_id: the own dataset uses it
|
||||||
|
return xTaskCreate(ptp_task, "ptp", 4096, NULL, 10, NULL) == pdPASS ? ESP_OK : ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
// PTPv2 ordinary clock over UDP/IPv4 (E2E). TimeReceiver and TimeTransmitter (BMCA).
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "cJSON.h"
|
||||||
|
#include "esp_err.h"
|
||||||
|
#include "esp_netif.h"
|
||||||
|
|
||||||
|
esp_err_t ptp_clock_start(esp_netif_t *netif);
|
||||||
|
// Re-read the "ptp" config group (role, priorities, intervals, domain, DSCP) in the PTP task.
|
||||||
|
void ptp_clock_reconfig(void);
|
||||||
|
bool ptp_clock_gm_id(char out[24]);
|
||||||
|
bool ptp_clock_locked(void);
|
||||||
|
// Adds the "ptp" object to /api/status.
|
||||||
|
void ptp_clock_status(cJSON *st);
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
#include "ptp_hw.h"
|
||||||
|
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "esp_eth_mac_esp.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "hal/emac_ll.h"
|
||||||
|
#include "soc/emac_ptp_struct.h"
|
||||||
|
|
||||||
|
#define RX_RING 16
|
||||||
|
#define PTP_EVENT_PORT 319
|
||||||
|
|
||||||
|
static const char *TAG = "ptp_hw";
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
bool used;
|
||||||
|
uint8_t type;
|
||||||
|
uint16_t seq;
|
||||||
|
uint8_t port_id[10];
|
||||||
|
uint8_t mac[6]; // Ethernet source
|
||||||
|
eth_mac_time_t ts;
|
||||||
|
} rx_rec_t;
|
||||||
|
|
||||||
|
static esp_eth_handle_t s_eth;
|
||||||
|
static esp_netif_t *s_netif;
|
||||||
|
static uint16_t s_ip_id;
|
||||||
|
static rx_rec_t s_rx[RX_RING];
|
||||||
|
static int s_rx_next;
|
||||||
|
static portMUX_TYPE s_lock = portMUX_INITIALIZER_UNLOCKED;
|
||||||
|
|
||||||
|
// Runs in the EMAC RX task for every frame: note PTP event timestamps, then pass to lwIP.
|
||||||
|
static esp_err_t rx_hook(esp_eth_handle_t eth, uint8_t *buf, uint32_t len, void *priv, void *info)
|
||||||
|
{
|
||||||
|
const eth_mac_time_t *ts = info;
|
||||||
|
// Ethernet (untagged) + IPv4 + UDP to port 319 + PTP header (34 bytes)
|
||||||
|
if (ts && (ts->seconds | ts->nanoseconds) && len >= 14 + 20 + 8 + 34 &&
|
||||||
|
buf[12] == 0x08 && buf[13] == 0x00 && buf[23] == 17) {
|
||||||
|
const uint8_t *ip = buf + 14;
|
||||||
|
size_t ihl = (ip[0] & 0x0f) * 4;
|
||||||
|
const uint8_t *udp = ip + ihl;
|
||||||
|
const uint8_t *ptp = udp + 8;
|
||||||
|
if (ihl >= 20 && ptp + 34 <= buf + len && ((udp[2] << 8) | udp[3]) == PTP_EVENT_PORT &&
|
||||||
|
(ptp[1] & 0x0f) == 2) {
|
||||||
|
portENTER_CRITICAL(&s_lock);
|
||||||
|
rx_rec_t *r = &s_rx[s_rx_next];
|
||||||
|
s_rx_next = (s_rx_next + 1) % RX_RING;
|
||||||
|
r->used = true;
|
||||||
|
r->type = ptp[0] & 0x0f;
|
||||||
|
r->seq = (ptp[30] << 8) | ptp[31];
|
||||||
|
memcpy(r->port_id, ptp + 20, 10);
|
||||||
|
memcpy(r->mac, buf + 6, 6);
|
||||||
|
r->ts = *ts;
|
||||||
|
portEXIT_CRITICAL(&s_lock);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return esp_netif_receive((esp_netif_t *)priv, buf, len, NULL);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ptp_hw_rx_ts(uint8_t msg_type, uint16_t seq, const uint8_t *src_port_id, eth_mac_time_t *ts)
|
||||||
|
{
|
||||||
|
return ptp_hw_rx_ts_mac(msg_type, seq, src_port_id, ts, NULL);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ptp_hw_rx_ts_mac(uint8_t msg_type, uint16_t seq, const uint8_t *src_port_id, eth_mac_time_t *ts,
|
||||||
|
uint8_t src_mac[6])
|
||||||
|
{
|
||||||
|
bool found = false;
|
||||||
|
portENTER_CRITICAL(&s_lock);
|
||||||
|
for (int i = 0; i < RX_RING; i++) {
|
||||||
|
rx_rec_t *r = &s_rx[i];
|
||||||
|
if (r->used && r->type == msg_type && r->seq == seq && memcmp(r->port_id, src_port_id, 10) == 0) {
|
||||||
|
*ts = r->ts;
|
||||||
|
if (src_mac) {
|
||||||
|
memcpy(src_mac, r->mac, 6);
|
||||||
|
}
|
||||||
|
r->used = false;
|
||||||
|
found = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
portEXIT_CRITICAL(&s_lock);
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t ptp_hw_get_time(eth_mac_time_t *t)
|
||||||
|
{
|
||||||
|
return esp_eth_ioctl(s_eth, ETH_MAC_ESP_CMD_G_PTP_TIME, t);
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t ptp_hw_adj_freq(double ppb)
|
||||||
|
{
|
||||||
|
if (ppb > 500000) {
|
||||||
|
ppb = 500000; // +-500 ppm is far outside any sane crystal
|
||||||
|
} else if (ppb < -500000) {
|
||||||
|
ppb = -500000;
|
||||||
|
}
|
||||||
|
int32_t v = (int32_t)(ppb >= 0 ? ppb + 0.5 : ppb - 0.5);
|
||||||
|
esp_err_t err = ESP_ERR_INVALID_STATE;
|
||||||
|
// The previous addend update may still be in progress: retry briefly.
|
||||||
|
for (int i = 0; i < 10 && err == ESP_ERR_INVALID_STATE; i++) {
|
||||||
|
err = esp_eth_ioctl(s_eth, ETH_MAC_ESP_CMD_ADJ_PTP_TIME, &v);
|
||||||
|
}
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t ptp_hw_step(int64_t offset_ns)
|
||||||
|
{
|
||||||
|
eth_mac_time_t t;
|
||||||
|
esp_err_t err = ptp_hw_get_time(&t);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
int64_t ns = (int64_t)t.seconds * 1000000000LL + t.nanoseconds - offset_ns;
|
||||||
|
if (ns < 0) {
|
||||||
|
return ESP_ERR_INVALID_ARG;
|
||||||
|
}
|
||||||
|
t.seconds = ns / 1000000000LL;
|
||||||
|
t.nanoseconds = ns % 1000000000LL;
|
||||||
|
return esp_eth_ioctl(s_eth, ETH_MAC_ESP_CMD_S_PTP_TIME, &t);
|
||||||
|
}
|
||||||
|
|
||||||
|
static uint16_t ip_checksum(const uint8_t *h, size_t len)
|
||||||
|
{
|
||||||
|
uint32_t sum = 0;
|
||||||
|
for (size_t i = 0; i < len; i += 2) {
|
||||||
|
sum += (h[i] << 8) | h[i + 1];
|
||||||
|
}
|
||||||
|
while (sum >> 16) {
|
||||||
|
sum = (sum & 0xffff) + (sum >> 16);
|
||||||
|
}
|
||||||
|
return ~sum;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t ptp_hw_send_event(const uint8_t dst_mac[6], uint32_t dst_ip, uint8_t dscp,
|
||||||
|
const uint8_t *msg, size_t len, eth_mac_time_t *tx_ts)
|
||||||
|
{
|
||||||
|
uint8_t f[14 + 20 + 8 + 64];
|
||||||
|
esp_netif_ip_info_t ip;
|
||||||
|
if (len > 64 || esp_netif_get_ip_info(s_netif, &ip) != ESP_OK || !ip.ip.addr) {
|
||||||
|
return ESP_ERR_INVALID_STATE;
|
||||||
|
}
|
||||||
|
// Ethernet
|
||||||
|
memcpy(f, dst_mac, 6);
|
||||||
|
esp_eth_ioctl(s_eth, ETH_CMD_G_MAC_ADDR, f + 6);
|
||||||
|
f[12] = 0x08;
|
||||||
|
f[13] = 0x00;
|
||||||
|
// IPv4: no options, DF, TTL 1 (PTP stays in the subnet), UDP
|
||||||
|
uint8_t *h = f + 14;
|
||||||
|
size_t ip_len = 20 + 8 + len;
|
||||||
|
uint16_t id = s_ip_id++;
|
||||||
|
const uint8_t hdr[20] = { 0x45, (uint8_t)(dscp << 2), ip_len >> 8, ip_len & 0xff, id >> 8, id & 0xff,
|
||||||
|
0x40, 0x00, 1, 17, 0, 0 };
|
||||||
|
memcpy(h, hdr, 12);
|
||||||
|
memcpy(h + 12, &ip.ip.addr, 4); // network byte order already
|
||||||
|
memcpy(h + 16, &dst_ip, 4);
|
||||||
|
uint16_t cs = ip_checksum(h, 20);
|
||||||
|
h[10] = cs >> 8;
|
||||||
|
h[11] = cs & 0xff;
|
||||||
|
// UDP 319 -> 319, checksum 0 (allowed for IPv4)
|
||||||
|
uint8_t *u = h + 20;
|
||||||
|
u[0] = PTP_EVENT_PORT >> 8;
|
||||||
|
u[1] = PTP_EVENT_PORT & 0xff;
|
||||||
|
u[2] = PTP_EVENT_PORT >> 8;
|
||||||
|
u[3] = PTP_EVENT_PORT & 0xff;
|
||||||
|
u[4] = (8 + len) >> 8;
|
||||||
|
u[5] = (8 + len) & 0xff;
|
||||||
|
u[6] = u[7] = 0;
|
||||||
|
memcpy(u + 8, msg, len);
|
||||||
|
|
||||||
|
size_t total = 14 + ip_len;
|
||||||
|
if (total < 60) {
|
||||||
|
memset(f + total, 0, 60 - total);
|
||||||
|
total = 60;
|
||||||
|
}
|
||||||
|
esp_err_t err = esp_eth_transmit_ctrl_vargs(s_eth, tx_ts, 2, f, (uint32_t)total);
|
||||||
|
if (err == ESP_OK && !(tx_ts->seconds | tx_ts->nanoseconds)) {
|
||||||
|
err = ESP_ERR_TIMEOUT; // sent, but no TX timestamp
|
||||||
|
}
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t ptp_hw_init(esp_eth_handle_t eth, esp_netif_t *netif)
|
||||||
|
{
|
||||||
|
s_eth = eth;
|
||||||
|
s_netif = netif;
|
||||||
|
bool on = true;
|
||||||
|
esp_err_t err = esp_eth_ioctl(eth, ETH_MAC_ESP_CMD_PTP_ENABLE, &on);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
ESP_LOGE(TAG, "EMAC PTP enable failed: %s", esp_err_to_name(err));
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
// IDF enables timestamping for PTP over Ethernet (L2) only; AES67 uses UDP/IPv4.
|
||||||
|
emac_ll_ts_ptp_ip4_enable(&EMAC_PTP, true);
|
||||||
|
// The PTP packet filter only stamps multicast PTP; unicast Delay_Req (hybrid mode) would get
|
||||||
|
// no timestamp. Stamp every frame instead; rx_hook picks the PTP event messages.
|
||||||
|
emac_ll_ts_all_enable(&EMAC_PTP, true);
|
||||||
|
|
||||||
|
// The netif glue registered its own input path; take it over and forward to the netif.
|
||||||
|
err = esp_eth_update_input_path_info(eth, rx_hook, netif);
|
||||||
|
if (err == ESP_OK) {
|
||||||
|
ESP_LOGI(TAG, "EMAC IEEE 1588 clock running, HW timestamps for PTP over UDP/IPv4");
|
||||||
|
}
|
||||||
|
return err;
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
// EMAC IEEE 1588 clock and hardware timestamps for PTP over UDP/IPv4.
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <stdbool.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
#include "esp_eth_driver.h"
|
||||||
|
#include "esp_eth_mac.h"
|
||||||
|
#include "esp_netif.h"
|
||||||
|
|
||||||
|
#define PTP_MSG_SYNC 0x0
|
||||||
|
#define PTP_MSG_DELAY_REQ 0x1
|
||||||
|
#define PTP_MSG_FOLLOW_UP 0x8
|
||||||
|
#define PTP_MSG_DELAY_RESP 0x9
|
||||||
|
#define PTP_MSG_ANNOUNCE 0xB
|
||||||
|
|
||||||
|
// Start the EMAC PTP clock, enable IPv4/UDP timestamping and hook the RX path.
|
||||||
|
esp_err_t ptp_hw_init(esp_eth_handle_t eth, esp_netif_t *netif);
|
||||||
|
// Hardware RX timestamp of an event message (UDP port 319), looked up by type,
|
||||||
|
// sequence ID and sourcePortIdentity (10 bytes). Each record is returned once.
|
||||||
|
bool ptp_hw_rx_ts(uint8_t msg_type, uint16_t seq, const uint8_t *src_port_id, eth_mac_time_t *ts);
|
||||||
|
// Same, also returning the sender's Ethernet MAC (for unicast replies as raw frames). src_mac may be NULL.
|
||||||
|
bool ptp_hw_rx_ts_mac(uint8_t msg_type, uint16_t seq, const uint8_t *src_port_id, eth_mac_time_t *ts,
|
||||||
|
uint8_t src_mac[6]);
|
||||||
|
esp_err_t ptp_hw_get_time(eth_mac_time_t *t);
|
||||||
|
// Frequency correction relative to the nominal rate, in ppb (positive = faster).
|
||||||
|
esp_err_t ptp_hw_adj_freq(double ppb);
|
||||||
|
// Step the clock back by offset_ns (offset = local - GM), via read + write.
|
||||||
|
esp_err_t ptp_hw_step(int64_t offset_ns);
|
||||||
|
// Send a PTP event message as a raw Ethernet/IPv4/UDP frame (port 319 -> 319) and return its
|
||||||
|
// hardware TX timestamp. dst_ip/dst_mac: 224.0.1.129 / 01:00:5e:00:01:81 or the GM unicast.
|
||||||
|
esp_err_t ptp_hw_send_event(const uint8_t dst_mac[6], uint32_t dst_ip, uint8_t dscp,
|
||||||
|
const uint8_t *msg, size_t len, eth_mac_time_t *tx_ts);
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
idf_component_register(SRCS "aes67_sdp_sap.c"
|
||||||
|
INCLUDE_DIRS "include"
|
||||||
|
PRIV_REQUIRES aes67_net aes67_ptp aes67_web esp_netif esp_timer lwip)
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 Ben Nicholson
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -0,0 +1,254 @@
|
|||||||
|
#include "aes67_sdp_sap.h"
|
||||||
|
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "aes67_cfg.h"
|
||||||
|
#include "aes67_net.h"
|
||||||
|
#include "aes67_ptp.h"
|
||||||
|
#include "aes67_web.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_netif.h"
|
||||||
|
#include "esp_system.h"
|
||||||
|
#include "esp_timer.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/task.h"
|
||||||
|
#include "lwip/sockets.h"
|
||||||
|
|
||||||
|
#define SDP_MAX 1024
|
||||||
|
#define SAP_ADDR "239.255.255.255"
|
||||||
|
#define SAP_PORT 9875
|
||||||
|
#define SAP_INTERVAL_US (30 * 1000000LL)
|
||||||
|
#define SAP_MIME "application/sdp"
|
||||||
|
|
||||||
|
static const char *TAG = "sap";
|
||||||
|
|
||||||
|
// Same lines, in the same order, as the SDP preview in web/index.html.
|
||||||
|
size_t aes67_sdp_build(char *buf, size_t size)
|
||||||
|
{
|
||||||
|
cJSON *a = cfg_get("aes67");
|
||||||
|
cJSON *p = cfg_get("ptp");
|
||||||
|
if (!a || !p) {
|
||||||
|
cJSON_Delete(a);
|
||||||
|
cJSON_Delete(p);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
#define NUM(o, k) cJSON_GetObjectItemCaseSensitive(o, k)->valuedouble
|
||||||
|
#define STR(o, k) cJSON_GetObjectItemCaseSensitive(o, k)->valuestring
|
||||||
|
char ip[16] = "0.0.0.0";
|
||||||
|
esp_netif_ip_info_t info;
|
||||||
|
esp_netif_t *netif = aes67_net_netif();
|
||||||
|
if (netif && esp_netif_get_ip_info(netif, &info) == ESP_OK && info.ip.addr) {
|
||||||
|
snprintf(ip, sizeof(ip), IPSTR, IP2STR(&info.ip));
|
||||||
|
}
|
||||||
|
char gm[24];
|
||||||
|
if (!aes67_ptp_gm_id(gm)) {
|
||||||
|
strcpy(gm, "00-00-00-00-00-00-00-00");
|
||||||
|
}
|
||||||
|
int ch = (int)NUM(a, "channels");
|
||||||
|
char info_ch[16];
|
||||||
|
snprintf(info_ch, sizeof(info_ch), ch == 1 ? "mono" : ch == 2 ? "stereo" : "%d ch", ch);
|
||||||
|
int dom = (int)NUM(p, "domain");
|
||||||
|
int pt = (int)NUM(a, "pt");
|
||||||
|
|
||||||
|
int n = snprintf(buf, size,
|
||||||
|
"v=0\r\n"
|
||||||
|
"o=- %.0f %.0f IN IP4 %s\r\n"
|
||||||
|
"s=%s\r\n"
|
||||||
|
"c=IN IP4 %s/%d\r\n"
|
||||||
|
"t=0 0\r\n"
|
||||||
|
"a=clock-domain:PTPv2 %d\r\n"
|
||||||
|
"m=audio %d RTP/AVP %d\r\n"
|
||||||
|
"i=%s\r\n"
|
||||||
|
"a=rtpmap:%d %s/%d/%d\r\n"
|
||||||
|
"a=recvonly\r\n"
|
||||||
|
"a=ptime:%g\r\n"
|
||||||
|
"a=ts-refclk:ptp=IEEE1588-2008:%s:%d\r\n"
|
||||||
|
"a=mediaclk:direct=%.0f\r\n",
|
||||||
|
NUM(a, "session_id"), NUM(a, "session_ver"), ip,
|
||||||
|
STR(a, "name"),
|
||||||
|
STR(a, "mcast"), (int)NUM(a, "ttl"),
|
||||||
|
dom,
|
||||||
|
(int)NUM(a, "port"), pt,
|
||||||
|
info_ch,
|
||||||
|
pt, STR(a, "encoding"), (int)NUM(a, "rate"), ch,
|
||||||
|
NUM(a, "ptime"),
|
||||||
|
gm, dom,
|
||||||
|
NUM(a, "clk_offset"));
|
||||||
|
#undef NUM
|
||||||
|
#undef STR
|
||||||
|
cJSON_Delete(a);
|
||||||
|
cJSON_Delete(p);
|
||||||
|
return n > 0 && (size_t)n < size ? (size_t)n : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
static esp_err_t sdp_get(httpd_req_t *req)
|
||||||
|
{
|
||||||
|
char buf[SDP_MAX];
|
||||||
|
size_t len = aes67_sdp_build(buf, sizeof(buf));
|
||||||
|
if (!len) {
|
||||||
|
return httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "SDP build failed");
|
||||||
|
}
|
||||||
|
httpd_resp_set_type(req, "application/sdp");
|
||||||
|
httpd_resp_set_hdr(req, "Cache-Control", "no-store");
|
||||||
|
return httpd_resp_send(req, buf, len);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----- SAP (RFC 2974) ----- */
|
||||||
|
|
||||||
|
static struct {
|
||||||
|
int fd;
|
||||||
|
uint8_t ttl;
|
||||||
|
uint32_t origin; // IPv4 of the announcement (network order)
|
||||||
|
char sdp[SDP_MAX]; // what is currently announced ("" = nothing)
|
||||||
|
size_t len;
|
||||||
|
uint16_t hash;
|
||||||
|
} s_sap = { .fd = -1 };
|
||||||
|
|
||||||
|
static uint16_t sdp_hash(const char *sdp, size_t len)
|
||||||
|
{
|
||||||
|
uint32_t h = 2166136261u; // FNV-1a folded to 16 bits; 0 is not allowed
|
||||||
|
for (size_t i = 0; i < len; i++) {
|
||||||
|
h = (h ^ (uint8_t)sdp[i]) * 16777619u;
|
||||||
|
}
|
||||||
|
uint16_t v = (uint16_t)(h ^ (h >> 16));
|
||||||
|
return v ? v : 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void sap_send(bool deletion)
|
||||||
|
{
|
||||||
|
static uint8_t pkt[8 + sizeof(SAP_MIME) + SDP_MAX];
|
||||||
|
pkt[0] = deletion ? 0x24 : 0x20; // V=1, IPv4, announce / delete (T bit)
|
||||||
|
pkt[1] = 0; // no authentication
|
||||||
|
pkt[2] = s_sap.hash >> 8;
|
||||||
|
pkt[3] = s_sap.hash & 0xff;
|
||||||
|
memcpy(pkt + 4, &s_sap.origin, 4);
|
||||||
|
memcpy(pkt + 8, SAP_MIME, sizeof(SAP_MIME)); // includes the terminating NUL
|
||||||
|
size_t n = 8 + sizeof(SAP_MIME);
|
||||||
|
memcpy(pkt + n, s_sap.sdp, s_sap.len);
|
||||||
|
n += s_sap.len;
|
||||||
|
|
||||||
|
struct sockaddr_in dst = { .sin_family = AF_INET, .sin_port = htons(SAP_PORT) };
|
||||||
|
inet_aton(SAP_ADDR, &dst.sin_addr);
|
||||||
|
if (sendto(s_sap.fd, pkt, n, 0, (struct sockaddr *)&dst, sizeof(dst)) < 0) {
|
||||||
|
ESP_LOGW(TAG, "send failed (errno %d)", errno);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void sap_delete(const char *why)
|
||||||
|
{
|
||||||
|
if (s_sap.len && s_sap.fd >= 0) {
|
||||||
|
sap_send(true);
|
||||||
|
ESP_LOGI(TAG, "deleted announcement %04x (%s)", s_sap.hash, why);
|
||||||
|
}
|
||||||
|
s_sap.len = 0;
|
||||||
|
s_sap.sdp[0] = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Runs from esp_restart() (reboot, OTA): withdraw the session so receivers drop it now.
|
||||||
|
static void sap_shutdown(void)
|
||||||
|
{
|
||||||
|
if (s_sap.len) {
|
||||||
|
sap_delete("shutdown");
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(20)); // let lwIP put it on the wire
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool sap_wanted(uint8_t *ttl)
|
||||||
|
{
|
||||||
|
cJSON *a = cfg_get("aes67");
|
||||||
|
bool on = cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(a, "enabled")) &&
|
||||||
|
strcmp(cJSON_GetObjectItemCaseSensitive(a, "discovery")->valuestring, "sap") == 0;
|
||||||
|
*ttl = (uint8_t)cJSON_GetObjectItemCaseSensitive(a, "ttl")->valuedouble;
|
||||||
|
cJSON_Delete(a);
|
||||||
|
return on;
|
||||||
|
}
|
||||||
|
|
||||||
|
// When the PTP GM changes, the SDP's ts-refclk changes: bump the session version (RFC 4566 o=)
|
||||||
|
// so receivers see a new description. Runs whether or not SAP is on (manual SDP users too).
|
||||||
|
static void check_gm_change(void)
|
||||||
|
{
|
||||||
|
static char last[24];
|
||||||
|
char gm[24];
|
||||||
|
if (!aes67_ptp_gm_id(gm) || strcmp(gm, last) == 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (last[0]) {
|
||||||
|
cJSON *a = cfg_get("aes67");
|
||||||
|
double ver = cJSON_GetObjectItemCaseSensitive(a, "session_ver")->valuedouble + 1;
|
||||||
|
cJSON_Delete(a);
|
||||||
|
// Not applied: re-applying the aes67 group would restart the stream.
|
||||||
|
esp_err_t err = cfg_set_number("aes67", "session_ver", ver, false);
|
||||||
|
ESP_LOGI(TAG, "PTP TimeTransmitter %s -> %s: session_ver %.0f (%s)", last, gm, ver, esp_err_to_name(err));
|
||||||
|
}
|
||||||
|
strcpy(last, gm);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void sap_task(void *arg)
|
||||||
|
{
|
||||||
|
static char sdp[SDP_MAX];
|
||||||
|
int64_t last_us = 0;
|
||||||
|
uint8_t ttl_set = 0;
|
||||||
|
|
||||||
|
while (1) {
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(1000));
|
||||||
|
check_gm_change();
|
||||||
|
esp_netif_ip_info_t ip;
|
||||||
|
esp_netif_t *netif = aes67_net_netif();
|
||||||
|
bool have_ip = netif && esp_netif_get_ip_info(netif, &ip) == ESP_OK && ip.ip.addr;
|
||||||
|
uint8_t ttl;
|
||||||
|
char gm[24];
|
||||||
|
if (!sap_wanted(&ttl) || !have_ip) {
|
||||||
|
sap_delete(have_ip ? "discovery off or stream disabled" : "no IP");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!aes67_ptp_gm_id(gm)) {
|
||||||
|
// Without a GM the SDP's ts-refclk would be all zeros: don't advertise that.
|
||||||
|
sap_delete("no PTP TimeTransmitter");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (s_sap.fd < 0) {
|
||||||
|
s_sap.fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
|
||||||
|
uint8_t loop = 0;
|
||||||
|
setsockopt(s_sap.fd, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop));
|
||||||
|
}
|
||||||
|
if (ttl != ttl_set) { // same scope as the session
|
||||||
|
setsockopt(s_sap.fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl));
|
||||||
|
ttl_set = ttl;
|
||||||
|
}
|
||||||
|
struct in_addr ifa = { .s_addr = ip.ip.addr };
|
||||||
|
setsockopt(s_sap.fd, IPPROTO_IP, IP_MULTICAST_IF, &ifa, sizeof(ifa));
|
||||||
|
|
||||||
|
size_t len = aes67_sdp_build(sdp, sizeof(sdp));
|
||||||
|
if (!len) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
int64_t now = esp_timer_get_time();
|
||||||
|
if (len != s_sap.len || memcmp(sdp, s_sap.sdp, len) != 0 || ip.ip.addr != s_sap.origin) {
|
||||||
|
sap_delete("SDP changed");
|
||||||
|
memcpy(s_sap.sdp, sdp, len);
|
||||||
|
s_sap.len = len;
|
||||||
|
s_sap.hash = sdp_hash(sdp, len);
|
||||||
|
s_sap.origin = ip.ip.addr;
|
||||||
|
sap_send(false);
|
||||||
|
last_us = now;
|
||||||
|
ESP_LOGI(TAG, "announcing %04x to " SAP_ADDR ":%d every 30 s", s_sap.hash, SAP_PORT);
|
||||||
|
} else if (now - last_us >= SAP_INTERVAL_US) {
|
||||||
|
sap_send(false);
|
||||||
|
last_us = now;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t aes67_sdp_sap_init(void)
|
||||||
|
{
|
||||||
|
static const httpd_uri_t uri = { .uri = "/stream.sdp", .method = HTTP_GET, .handler = sdp_get };
|
||||||
|
esp_err_t err = web_register_uri(&uri);
|
||||||
|
if (err == ESP_OK) {
|
||||||
|
err = esp_register_shutdown_handler(sap_shutdown);
|
||||||
|
}
|
||||||
|
if (err == ESP_OK && xTaskCreate(sap_task, "sap", 4096, NULL, 3, NULL) != pdPASS) {
|
||||||
|
err = ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
|
return err;
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
// aes67_sdp_sap: SDP builder/parser and SAP announcer.
|
||||||
|
// Core component: must not depend on main/ (project code).
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <stddef.h>
|
||||||
|
|
||||||
|
#include "esp_err.h"
|
||||||
|
|
||||||
|
// Registers GET /stream.sdp and starts the SAP announcer (RFC 2974): 239.255.255.255:9875 every
|
||||||
|
// 30 s and on SDP change while aes67.discovery is "sap", the stream is enabled and a PTP GM is
|
||||||
|
// known (else ts-refclk would be all zeros); deletion
|
||||||
|
// when that stops and at shutdown.
|
||||||
|
esp_err_t aes67_sdp_sap_init(void);
|
||||||
|
// Build the current SDP (RFC 4566 + RFC 7273, AES67). Returns the length, or 0 if it didn't fit.
|
||||||
|
size_t aes67_sdp_build(char *buf, size_t size);
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
idf_component_register(SRCS "aes67_syslog.c"
|
||||||
|
INCLUDE_DIRS "include"
|
||||||
|
PRIV_REQUIRES aes67_net aes67_web esp_netif log lwip)
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 Ben Nicholson
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -0,0 +1,280 @@
|
|||||||
|
#include "aes67_syslog.h"
|
||||||
|
|
||||||
|
#include <stdarg.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "aes67_cfg.h"
|
||||||
|
#include "aes67_net.h"
|
||||||
|
#include "aes67_web.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/queue.h"
|
||||||
|
#include "freertos/semphr.h"
|
||||||
|
#include "freertos/task.h"
|
||||||
|
#include "lwip/netdb.h"
|
||||||
|
#include "lwip/sockets.h"
|
||||||
|
|
||||||
|
#define QUEUE_LEN 48
|
||||||
|
#define MSG_MAX 240
|
||||||
|
|
||||||
|
// facility: 16 = local0 (PRI = facility * 8 + severity).
|
||||||
|
static const char LOG_DEFAULTS[] =
|
||||||
|
"{\"syslog\":false,\"host\":\"\",\"port\":514,\"level\":\"info\",\"facility\":16,\"format\":\"rfc5424\"}";
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
uint8_t severity; // 3 error, 4 warning, 6 info, 7 debug
|
||||||
|
char text[MSG_MAX]; // "tag: message" without the level/timestamp prefix
|
||||||
|
} msg_t;
|
||||||
|
|
||||||
|
static QueueHandle_t s_queue;
|
||||||
|
static SemaphoreHandle_t s_fmt_lock;
|
||||||
|
static TaskHandle_t s_task;
|
||||||
|
static vprintf_like_t s_uart;
|
||||||
|
static volatile bool s_enabled;
|
||||||
|
static volatile uint8_t s_min_severity = 6;
|
||||||
|
static volatile bool s_reconfig = true;
|
||||||
|
static volatile uint32_t s_dropped;
|
||||||
|
|
||||||
|
static bool log_validate(const cJSON *g, char *err, size_t n)
|
||||||
|
{
|
||||||
|
static const char *const levels[] = { "error", "warn", "info", "debug", NULL };
|
||||||
|
static const char *const formats[] = { "rfc5424", "rfc3164", NULL };
|
||||||
|
static const double facilities[] = { 1, 3, 16, 17, 18, 19, 20, 21, 22, 23 };
|
||||||
|
|
||||||
|
bool on = cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(g, "syslog"));
|
||||||
|
return cfg_check_str(g, "host", on ? 1 : 0, 63, err, n) &&
|
||||||
|
cfg_check_int(g, "port", 1, 65535, err, n) &&
|
||||||
|
cfg_check_enum(g, "level", levels, err, n) &&
|
||||||
|
cfg_check_num_in(g, "facility", facilities, 10, err, n) &&
|
||||||
|
cfg_check_enum(g, "format", formats, err, n);
|
||||||
|
}
|
||||||
|
|
||||||
|
static uint8_t severity_of(const char *level)
|
||||||
|
{
|
||||||
|
return level[0] == 'e' ? 3 : level[0] == 'w' ? 4 : level[0] == 'i' ? 6 : 7;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void read_filter(void)
|
||||||
|
{
|
||||||
|
cJSON *l = cfg_get("log");
|
||||||
|
s_enabled = cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(l, "syslog"));
|
||||||
|
s_min_severity = severity_of(cJSON_GetObjectItemCaseSensitive(l, "level")->valuestring);
|
||||||
|
cJSON_Delete(l);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void log_apply(const cJSON *g)
|
||||||
|
{
|
||||||
|
read_filter();
|
||||||
|
s_reconfig = true;
|
||||||
|
if (s_task) {
|
||||||
|
xTaskNotifyGive(s_task);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----- esp_log hook ----- */
|
||||||
|
|
||||||
|
// "\033[0;32mI (1234) tag: message\033[0m\n" -> severity + "tag: message"
|
||||||
|
static bool parse_line(const char *in, msg_t *m)
|
||||||
|
{
|
||||||
|
char *o = m->text, *end = m->text + MSG_MAX - 1;
|
||||||
|
const char *p = in;
|
||||||
|
char level = 0;
|
||||||
|
bool prefix_done = false;
|
||||||
|
while (*p && o < end) {
|
||||||
|
if (*p == '\033') { // skip ANSI colour codes
|
||||||
|
while (*p && *p != 'm') {
|
||||||
|
p++;
|
||||||
|
}
|
||||||
|
if (*p) {
|
||||||
|
p++;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!level) {
|
||||||
|
level = *p++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!prefix_done) { // skip " (1234) "
|
||||||
|
if (*p == ')') {
|
||||||
|
prefix_done = true;
|
||||||
|
p++;
|
||||||
|
if (*p == ' ') {
|
||||||
|
p++;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
p++;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (*p == '\n' || *p == '\r') {
|
||||||
|
p++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
*o++ = *p++;
|
||||||
|
}
|
||||||
|
*o = 0;
|
||||||
|
m->severity = level == 'E' ? 3 : level == 'W' ? 4 : level == 'I' ? 6 : 7;
|
||||||
|
return prefix_done && m->text[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
static int log_hook(const char *fmt, va_list ap)
|
||||||
|
{
|
||||||
|
va_list copy;
|
||||||
|
va_copy(copy, ap);
|
||||||
|
int ret = s_uart(fmt, ap); // UART output unchanged
|
||||||
|
|
||||||
|
if (s_enabled && xTaskGetCurrentTaskHandle() != s_task &&
|
||||||
|
xSemaphoreTake(s_fmt_lock, 0) == pdTRUE) {
|
||||||
|
static char line[MSG_MAX + 32];
|
||||||
|
static msg_t m;
|
||||||
|
vsnprintf(line, sizeof(line), fmt, copy);
|
||||||
|
if (parse_line(line, &m) && m.severity <= s_min_severity &&
|
||||||
|
xQueueSend(s_queue, &m, 0) != pdTRUE) {
|
||||||
|
s_dropped++;
|
||||||
|
}
|
||||||
|
xSemaphoreGive(s_fmt_lock);
|
||||||
|
} else if (s_enabled && xTaskGetCurrentTaskHandle() != s_task) {
|
||||||
|
s_dropped++; // formatter busy: drop rather than block
|
||||||
|
}
|
||||||
|
va_end(copy);
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----- sender ----- */
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
struct sockaddr_in dst;
|
||||||
|
bool have_dst;
|
||||||
|
uint8_t facility;
|
||||||
|
bool rfc5424;
|
||||||
|
char host[64];
|
||||||
|
char hostname[64];
|
||||||
|
} sender_cfg_t;
|
||||||
|
|
||||||
|
static void load_sender(sender_cfg_t *c)
|
||||||
|
{
|
||||||
|
cJSON *l = cfg_get("log"), *n = cfg_get("net");
|
||||||
|
strlcpy(c->host, cJSON_GetObjectItemCaseSensitive(l, "host")->valuestring, sizeof(c->host));
|
||||||
|
c->facility = (uint8_t)cJSON_GetObjectItemCaseSensitive(l, "facility")->valuedouble;
|
||||||
|
c->rfc5424 = strcmp(cJSON_GetObjectItemCaseSensitive(l, "format")->valuestring, "rfc5424") == 0;
|
||||||
|
uint16_t port = (uint16_t)cJSON_GetObjectItemCaseSensitive(l, "port")->valuedouble;
|
||||||
|
strlcpy(c->hostname, cJSON_GetObjectItemCaseSensitive(n, "hostname")->valuestring, sizeof(c->hostname));
|
||||||
|
cJSON_Delete(l);
|
||||||
|
cJSON_Delete(n);
|
||||||
|
|
||||||
|
c->have_dst = false;
|
||||||
|
memset(&c->dst, 0, sizeof(c->dst));
|
||||||
|
c->dst.sin_family = AF_INET;
|
||||||
|
c->dst.sin_port = htons(port);
|
||||||
|
if (inet_aton(c->host, &c->dst.sin_addr)) {
|
||||||
|
c->have_dst = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
struct addrinfo hints = { .ai_family = AF_INET, .ai_socktype = SOCK_DGRAM }, *res = NULL;
|
||||||
|
if (c->host[0] && getaddrinfo(c->host, NULL, &hints, &res) == 0 && res) {
|
||||||
|
c->dst.sin_addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
|
||||||
|
c->have_dst = true;
|
||||||
|
}
|
||||||
|
if (res) {
|
||||||
|
freeaddrinfo(res);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RFC 5424: <PRI>1 - HOSTNAME APP-NAME - - - MSG (no wall-clock time yet: NILVALUE)
|
||||||
|
// RFC 3164: <PRI>HOSTNAME TAG: MSG (TIMESTAMP omitted; the server adds it)
|
||||||
|
static int format_msg(char *out, size_t size, const sender_cfg_t *c, const msg_t *m)
|
||||||
|
{
|
||||||
|
const char *colon = strstr(m->text, ": ");
|
||||||
|
char tag[33] = "-";
|
||||||
|
const char *msg = m->text;
|
||||||
|
if (colon && colon - m->text < (int)sizeof(tag)) {
|
||||||
|
memcpy(tag, m->text, colon - m->text);
|
||||||
|
tag[colon - m->text] = 0;
|
||||||
|
msg = colon + 2;
|
||||||
|
}
|
||||||
|
int pri = c->facility * 8 + m->severity;
|
||||||
|
if (c->rfc5424) {
|
||||||
|
return snprintf(out, size, "<%d>1 - %s %s - - - %s", pri, c->hostname, tag, msg);
|
||||||
|
}
|
||||||
|
return snprintf(out, size, "<%d>%s %s: %s", pri, c->hostname, tag, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void syslog_task(void *arg)
|
||||||
|
{
|
||||||
|
sender_cfg_t c = { 0 };
|
||||||
|
int fd = -1; // created once the interface is up: lwIP may not be running yet at init
|
||||||
|
msg_t m;
|
||||||
|
char out[MSG_MAX + 128];
|
||||||
|
|
||||||
|
while (1) {
|
||||||
|
// Hold messages until the interface has an IP (early boot logs stay queued).
|
||||||
|
esp_netif_ip_info_t ip;
|
||||||
|
esp_netif_t *netif = aes67_net_netif();
|
||||||
|
if (!netif || esp_netif_get_ip_info(netif, &ip) != ESP_OK || !ip.ip.addr) {
|
||||||
|
ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(500));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (fd < 0 && (fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(1000));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (s_reconfig) {
|
||||||
|
s_reconfig = false;
|
||||||
|
load_sender(&c);
|
||||||
|
if (s_enabled && !c.have_dst) {
|
||||||
|
ESP_LOGW("syslog", "cannot resolve '%s'", c.host); // not sent: logged from this task
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (xQueueReceive(s_queue, &m, pdMS_TO_TICKS(1000)) != pdTRUE) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (s_enabled && c.have_dst) {
|
||||||
|
int n = format_msg(out, sizeof(out), &c, &m);
|
||||||
|
sendto(fd, out, n < (int)sizeof(out) ? n : (int)sizeof(out) - 1, 0,
|
||||||
|
(struct sockaddr *)&c.dst, sizeof(c.dst));
|
||||||
|
}
|
||||||
|
static uint32_t reported;
|
||||||
|
if (s_dropped != reported) {
|
||||||
|
reported = s_dropped;
|
||||||
|
msg_t d = { .severity = 4 };
|
||||||
|
snprintf(d.text, sizeof(d.text), "syslog: %lu messages dropped so far (queue full)",
|
||||||
|
(unsigned long)reported);
|
||||||
|
xQueueSend(s_queue, &d, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static esp_err_t test_post(httpd_req_t *req)
|
||||||
|
{
|
||||||
|
if (!s_enabled) {
|
||||||
|
return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "syslog is disabled");
|
||||||
|
}
|
||||||
|
msg_t m = { .severity = 6 }; // info, regardless of the level filter
|
||||||
|
snprintf(m.text, sizeof(m.text), "syslog: test message from the web UI");
|
||||||
|
if (xQueueSend(s_queue, &m, 0) != pdTRUE) {
|
||||||
|
return httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "syslog queue full");
|
||||||
|
}
|
||||||
|
return httpd_resp_sendstr(req, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t aes67_syslog_init(void)
|
||||||
|
{
|
||||||
|
esp_err_t err = cfg_register("log", LOG_DEFAULTS, log_validate, log_apply);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
s_queue = xQueueCreate(QUEUE_LEN, sizeof(msg_t));
|
||||||
|
s_fmt_lock = xSemaphoreCreateMutex();
|
||||||
|
if (!s_queue || !s_fmt_lock) {
|
||||||
|
return ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
|
read_filter();
|
||||||
|
if (xTaskCreate(syslog_task, "syslog", 4096, NULL, 2, &s_task) != pdPASS) {
|
||||||
|
return ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
|
static const httpd_uri_t uri = { .uri = "/api/log/test", .method = HTTP_POST, .handler = test_post };
|
||||||
|
err = web_register_uri(&uri);
|
||||||
|
s_uart = esp_log_set_vprintf(log_hook);
|
||||||
|
return err;
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
// aes67_syslog: Remote syslog (esp_log hook -> queue -> UDP).
|
||||||
|
// Core component: must not depend on main/ (project code).
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "esp_err.h"
|
||||||
|
|
||||||
|
// Registers the "log" config group, hooks esp_log (still printed on the UART) and starts the
|
||||||
|
// sender task. Messages logged before the interface has an IP are queued (up to the queue size).
|
||||||
|
esp_err_t aes67_syslog_init(void);
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
idf_component_register(SRCS "aes67_tx.c"
|
||||||
|
INCLUDE_DIRS "include"
|
||||||
|
PRIV_REQUIRES aes67_net aes67_ptp aes67_web esp_netif esp_timer lwip)
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 Ben Nicholson
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -0,0 +1,374 @@
|
|||||||
|
#include "aes67_tx.h"
|
||||||
|
|
||||||
|
#include <math.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "aes67_cfg.h"
|
||||||
|
#include "aes67_net.h"
|
||||||
|
#include "aes67_ptp.h"
|
||||||
|
#include "aes67_web.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_random.h"
|
||||||
|
#include "esp_timer.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/task.h"
|
||||||
|
#include "lwip/inet.h"
|
||||||
|
#include "lwip/sockets.h"
|
||||||
|
|
||||||
|
#define AES67_RATE 48000 // the only sample rate (all sources are 48 kHz)
|
||||||
|
#define MAX_FRAMES 192 // 4 ms at 48 kHz
|
||||||
|
#define MAX_CH 2
|
||||||
|
#define RTP_HDR 12
|
||||||
|
#define MAX_LAG_NS 20000000 // more than 20 ms behind: resync instead of bursting
|
||||||
|
#define TONE_HZ 1000
|
||||||
|
#define TONE_DBFS -18.0
|
||||||
|
#define WAKE_MARGIN_US 20 // wake just after a packet's last sample is due
|
||||||
|
|
||||||
|
static const char *TAG = "aes67_tx";
|
||||||
|
|
||||||
|
static TaskHandle_t s_task;
|
||||||
|
static volatile aes67_tx_read_cb_t s_read;
|
||||||
|
static volatile bool s_reconfig = true;
|
||||||
|
static volatile uint32_t s_packets, s_underruns;
|
||||||
|
// Defaults follow the Riedel Director 4-wire AES67 output; channels 2 (core default).
|
||||||
|
static const char AES67_DEFAULTS[] =
|
||||||
|
"{\"name\":\"AES67\",\"enabled\":true,\"discovery\":\"sap\",\"mcast\":\"239.69.1.10\","
|
||||||
|
"\"port\":5004,\"ttl\":32,\"dscp\":34,\"channels\":2,\"mono_sum\":false,\"encoding\":\"L24\","
|
||||||
|
"\"rate\":48000,\"ptime\":1,\"pt\":96,\"ssrc\":0,\"clk_offset\":0,"
|
||||||
|
"\"session_id\":1,\"session_ver\":1}";
|
||||||
|
|
||||||
|
// RTP multicast range 224.0.2.0 - 239.255.255.255 (keeps clear of 224.0.0.x/224.0.1.x, where PTP lives).
|
||||||
|
static bool check_mcast(const cJSON *g, char *err, size_t n)
|
||||||
|
{
|
||||||
|
const cJSON *v = cJSON_GetObjectItemCaseSensitive(g, "mcast");
|
||||||
|
struct in_addr a;
|
||||||
|
if (cJSON_IsString(v) && inet_aton(v->valuestring, &a)) {
|
||||||
|
uint32_t ip = ntohl(a.s_addr);
|
||||||
|
if (ip >= 0xE0000200 && ip <= 0xEFFFFFFF) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
snprintf(err, n, "mcast: must be 224.0.2.0 - 239.255.255.255");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool aes67_validate(const cJSON *g, char *err, size_t n)
|
||||||
|
{
|
||||||
|
static const char *const discovery[] = { "manual", "sap", NULL };
|
||||||
|
static const char *const encodings[] = { "L16", "L24", NULL };
|
||||||
|
static const double rates[] = { AES67_RATE }; // the sources (player, test signals) are 48 kHz
|
||||||
|
static const double ptimes[] = { 0.125, 0.25, 0.333, 1, 4 };
|
||||||
|
|
||||||
|
bool ok = cfg_check_str(g, "name", 1, 63, err, n) &&
|
||||||
|
cfg_check_enum(g, "discovery", discovery, err, n) &&
|
||||||
|
check_mcast(g, err, n) &&
|
||||||
|
cfg_check_int(g, "port", 1024, 65535, err, n) &&
|
||||||
|
cfg_check_int(g, "ttl", 1, 255, err, n) &&
|
||||||
|
cfg_check_int(g, "dscp", 0, 63, err, n) &&
|
||||||
|
cfg_check_int(g, "channels", 1, 2, err, n) &&
|
||||||
|
cfg_check_enum(g, "encoding", encodings, err, n) &&
|
||||||
|
cfg_check_num_in(g, "rate", rates, 1, err, n) &&
|
||||||
|
cfg_check_num_in(g, "ptime", ptimes, 5, err, n) &&
|
||||||
|
cfg_check_int(g, "pt", 96, 127, err, n) &&
|
||||||
|
cfg_check_int(g, "ssrc", 0, 4294967295.0, err, n) &&
|
||||||
|
cfg_check_int(g, "clk_offset", 0, 4294967295.0, err, n) &&
|
||||||
|
cfg_check_int(g, "session_id", 0, 4294967295.0, err, n) &&
|
||||||
|
cfg_check_int(g, "session_ver", 0, 4294967295.0, err, n);
|
||||||
|
if (ok && cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(g, "mono_sum")) &&
|
||||||
|
cJSON_GetObjectItemCaseSensitive(g, "channels")->valuedouble != 1) {
|
||||||
|
snprintf(err, n, "channels: must be 1 with mono_sum");
|
||||||
|
ok = false;
|
||||||
|
}
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void tx_status(cJSON *st)
|
||||||
|
{
|
||||||
|
cJSON_AddNumberToObject(st, "tx_packets", s_packets);
|
||||||
|
cJSON_AddNumberToObject(st, "underruns", s_underruns);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void aes67_apply(const cJSON *g)
|
||||||
|
{
|
||||||
|
s_reconfig = true; // the TX task picks up the new settings
|
||||||
|
}
|
||||||
|
|
||||||
|
void aes67_tx_set_source(aes67_tx_read_cb_t read)
|
||||||
|
{
|
||||||
|
s_read = read;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----- sender ----- */
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
bool enabled;
|
||||||
|
struct sockaddr_in dst;
|
||||||
|
uint8_t ttl, dscp, pt;
|
||||||
|
uint32_t ssrc, clk_offset;
|
||||||
|
int channels, rate, bytes; // bytes per sample: 3 (L24) or 2 (L16)
|
||||||
|
bool mono_sum; // 1-channel stream carries (L + R) / 2, else L
|
||||||
|
int frames; // samples per channel per packet
|
||||||
|
} tx_cfg_t;
|
||||||
|
|
||||||
|
static bool load(tx_cfg_t *c)
|
||||||
|
{
|
||||||
|
cJSON *a = cfg_get("aes67");
|
||||||
|
if (!a) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
#define NUM(k) cJSON_GetObjectItemCaseSensitive(a, k)->valuedouble
|
||||||
|
c->enabled = cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(a, "enabled"));
|
||||||
|
memset(&c->dst, 0, sizeof(c->dst));
|
||||||
|
c->dst.sin_family = AF_INET;
|
||||||
|
c->dst.sin_port = htons((uint16_t)NUM("port"));
|
||||||
|
inet_aton(cJSON_GetObjectItemCaseSensitive(a, "mcast")->valuestring, &c->dst.sin_addr);
|
||||||
|
c->ttl = (uint8_t)NUM("ttl");
|
||||||
|
c->dscp = (uint8_t)NUM("dscp");
|
||||||
|
c->pt = (uint8_t)NUM("pt");
|
||||||
|
c->ssrc = (uint32_t)NUM("ssrc");
|
||||||
|
c->clk_offset = (uint32_t)NUM("clk_offset");
|
||||||
|
c->channels = (int)NUM("channels");
|
||||||
|
c->mono_sum = cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(a, "mono_sum"));
|
||||||
|
c->rate = (int)NUM("rate");
|
||||||
|
c->bytes = strcmp(cJSON_GetObjectItemCaseSensitive(a, "encoding")->valuestring, "L16") == 0 ? 2 : 3;
|
||||||
|
c->frames = (int)lround(NUM("ptime") * c->rate / 1000.0); // 0.333 ms -> 16 at 48 kHz
|
||||||
|
#undef NUM
|
||||||
|
cJSON_Delete(a);
|
||||||
|
return c->frames > 0 && c->frames <= MAX_FRAMES && c->channels <= MAX_CH;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int open_socket(const tx_cfg_t *c)
|
||||||
|
{
|
||||||
|
int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
|
||||||
|
if (fd < 0) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
int tos = c->dscp << 2;
|
||||||
|
uint8_t ttl = c->ttl, loop = 0;
|
||||||
|
setsockopt(fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
|
||||||
|
setsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl));
|
||||||
|
setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop));
|
||||||
|
esp_netif_ip_info_t ip;
|
||||||
|
if (esp_netif_get_ip_info(aes67_net_netif(), &ip) == ESP_OK) {
|
||||||
|
struct in_addr ifa = { .s_addr = ip.ip.addr };
|
||||||
|
setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, &ifa, sizeof(ifa));
|
||||||
|
}
|
||||||
|
return fd;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sample index since the PTP epoch (no overflow: seconds * rate first).
|
||||||
|
static int64_t ns_to_samples(int64_t ns, int rate)
|
||||||
|
{
|
||||||
|
return (ns / 1000000000LL) * rate + (ns % 1000000000LL) * rate / 1000000000LL;
|
||||||
|
}
|
||||||
|
|
||||||
|
// PTP time at which sample index s starts (rounded up).
|
||||||
|
static int64_t samples_to_ns(int64_t s, int rate)
|
||||||
|
{
|
||||||
|
return (s / rate) * 1000000000LL + ((s % rate) * 1000000000LL + rate - 1) / rate;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pink noise: xorshift32 white noise through Paul Kellet's refined pink filter (within 0.05 dB
|
||||||
|
// above 9 Hz). The scale gives -18 dBFS RMS (measured over 10 s; peaks about -6 dBFS).
|
||||||
|
#define PINK_SCALE 0.0714f
|
||||||
|
|
||||||
|
size_t aes67_tx_pink_noise(int32_t *buf, size_t frames)
|
||||||
|
{
|
||||||
|
static uint32_t rnd = 0x12345678;
|
||||||
|
static float b0, b1, b2, b3, b4, b5, b6;
|
||||||
|
for (size_t i = 0; i < frames; i++) {
|
||||||
|
rnd ^= rnd << 13;
|
||||||
|
rnd ^= rnd >> 17;
|
||||||
|
rnd ^= rnd << 5;
|
||||||
|
float w = (int32_t)rnd * (1.0f / 2147483648.0f); // -1..1
|
||||||
|
b0 = 0.99886f * b0 + w * 0.0555179f;
|
||||||
|
b1 = 0.99332f * b1 + w * 0.0750759f;
|
||||||
|
b2 = 0.96900f * b2 + w * 0.1538520f;
|
||||||
|
b3 = 0.86650f * b3 + w * 0.3104856f;
|
||||||
|
b4 = 0.55000f * b4 + w * 0.5329522f;
|
||||||
|
b5 = -0.7616f * b5 - w * 0.0168980f;
|
||||||
|
float pink = b0 + b1 + b2 + b3 + b4 + b5 + b6 + w * 0.5362f;
|
||||||
|
b6 = w * 0.115926f;
|
||||||
|
float x = pink * PINK_SCALE;
|
||||||
|
x = x > 0.999f ? 0.999f : x < -0.999f ? -0.999f : x; // never reached in practice
|
||||||
|
int32_t v = (int32_t)(x * 2147483647.0f);
|
||||||
|
buf[i * AES67_TX_SRC_CHANNELS] = v;
|
||||||
|
buf[i * AES67_TX_SRC_CHANNELS + 1] = v;
|
||||||
|
}
|
||||||
|
return frames;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stereo source -> 1-channel stream, in place. The sum is in 64 bit, so it can't clip; identical
|
||||||
|
// L/R comes out at the same level.
|
||||||
|
static void to_mono(int32_t *buf, int frames, bool sum)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < frames; i++) {
|
||||||
|
buf[i] = sum ? (int32_t)(((int64_t)buf[2 * i] + buf[2 * i + 1]) / 2) : buf[2 * i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1 kHz tone, phase from the PTP sample index, so every sender's tone lines up.
|
||||||
|
// One period is rate / 1000 samples (48 at 48 kHz): precomputed table.
|
||||||
|
static void tone(int32_t *buf, int frames, int channels, int rate, int64_t s0)
|
||||||
|
{
|
||||||
|
static int32_t table[AES67_RATE / TONE_HZ];
|
||||||
|
static int table_rate;
|
||||||
|
int period = rate / TONE_HZ;
|
||||||
|
if (table_rate != rate) {
|
||||||
|
double amp = pow(10.0, TONE_DBFS / 20.0) * 2147483647.0;
|
||||||
|
for (int i = 0; i < period; i++) {
|
||||||
|
table[i] = (int32_t)(amp * sin(2.0 * M_PI * i / period));
|
||||||
|
}
|
||||||
|
table_rate = rate;
|
||||||
|
}
|
||||||
|
int ph = (int)(s0 % period);
|
||||||
|
for (int i = 0; i < frames; i++) {
|
||||||
|
int32_t v = table[ph];
|
||||||
|
ph = ph + 1 == period ? 0 : ph + 1;
|
||||||
|
for (int ch = 0; ch < channels; ch++) {
|
||||||
|
buf[i * channels + ch] = v;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void timer_cb(void *arg)
|
||||||
|
{
|
||||||
|
xTaskNotifyGive(s_task);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void tx_task(void *arg)
|
||||||
|
{
|
||||||
|
tx_cfg_t c = { 0 };
|
||||||
|
int fd = -1;
|
||||||
|
esp_timer_handle_t timer = NULL;
|
||||||
|
const esp_timer_create_args_t targs = { .callback = timer_cb, .name = "aes67_tx" };
|
||||||
|
esp_timer_create(&targs, &timer);
|
||||||
|
static int32_t pcm[MAX_FRAMES * (MAX_CH > AES67_TX_SRC_CHANNELS ? MAX_CH : AES67_TX_SRC_CHANNELS)];
|
||||||
|
static uint8_t pkt[RTP_HDR + MAX_FRAMES * MAX_CH * 3];
|
||||||
|
uint16_t seq = (uint16_t)esp_random();
|
||||||
|
int64_t next = 0; // sample index of the next packet; 0 = resync needed
|
||||||
|
const char *state = NULL, *new_state;
|
||||||
|
|
||||||
|
while (1) {
|
||||||
|
ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(100));
|
||||||
|
|
||||||
|
if (s_reconfig) {
|
||||||
|
s_reconfig = false;
|
||||||
|
if (fd >= 0) {
|
||||||
|
close(fd);
|
||||||
|
fd = -1;
|
||||||
|
}
|
||||||
|
esp_timer_stop(timer);
|
||||||
|
if (!load(&c)) {
|
||||||
|
ESP_LOGE(TAG, "unsupported config (ptime/rate/channels)");
|
||||||
|
c.enabled = false;
|
||||||
|
}
|
||||||
|
next = 0;
|
||||||
|
if (c.enabled) {
|
||||||
|
fd = open_socket(&c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int64_t now;
|
||||||
|
if (!c.enabled || fd < 0) {
|
||||||
|
new_state = "disabled";
|
||||||
|
} else if (!aes67_ptp_locked() || aes67_ptp_now_ns(&now) != ESP_OK) {
|
||||||
|
new_state = "waiting for PTP lock";
|
||||||
|
next = 0;
|
||||||
|
} else {
|
||||||
|
new_state = "sending";
|
||||||
|
int64_t due = ns_to_samples(now, c.rate);
|
||||||
|
// (Re)start aligned to a packet boundary, or after falling behind / a clock step back.
|
||||||
|
if (!next || due - next > (int64_t)c.rate * MAX_LAG_NS / 1000000000LL || next - due > 2 * c.frames) {
|
||||||
|
if (next) {
|
||||||
|
ESP_LOGW(TAG, "resync (%lld samples off)", due - next);
|
||||||
|
}
|
||||||
|
next = (due / c.frames + 1) * c.frames;
|
||||||
|
}
|
||||||
|
// Send every packet whose last sample is in the past.
|
||||||
|
while (samples_to_ns(next + c.frames, c.rate) <= now) {
|
||||||
|
aes67_tx_read_cb_t read = s_read;
|
||||||
|
if (read) {
|
||||||
|
size_t got = read(pcm, c.frames);
|
||||||
|
if (got < (size_t)c.frames) {
|
||||||
|
memset(pcm + got * AES67_TX_SRC_CHANNELS, 0,
|
||||||
|
(c.frames - got) * AES67_TX_SRC_CHANNELS * sizeof(int32_t));
|
||||||
|
s_underruns++;
|
||||||
|
}
|
||||||
|
if (c.channels == 1) {
|
||||||
|
to_mono(pcm, c.frames, c.mono_sum);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
tone(pcm, c.frames, c.channels, c.rate, next);
|
||||||
|
}
|
||||||
|
uint32_t ts = (uint32_t)next + c.clk_offset;
|
||||||
|
pkt[0] = 0x80; // V=2
|
||||||
|
pkt[1] = c.pt & 0x7f;
|
||||||
|
pkt[2] = seq >> 8;
|
||||||
|
pkt[3] = seq & 0xff;
|
||||||
|
pkt[4] = ts >> 24;
|
||||||
|
pkt[5] = ts >> 16;
|
||||||
|
pkt[6] = ts >> 8;
|
||||||
|
pkt[7] = ts;
|
||||||
|
pkt[8] = c.ssrc >> 24;
|
||||||
|
pkt[9] = c.ssrc >> 16;
|
||||||
|
pkt[10] = c.ssrc >> 8;
|
||||||
|
pkt[11] = c.ssrc;
|
||||||
|
uint8_t *p = pkt + RTP_HDR;
|
||||||
|
for (int i = 0; i < c.frames * c.channels; i++) {
|
||||||
|
uint32_t v = (uint32_t)pcm[i]; // big-endian, top bytes of the 32-bit sample
|
||||||
|
*p++ = v >> 24;
|
||||||
|
*p++ = v >> 16;
|
||||||
|
if (c.bytes == 3) {
|
||||||
|
*p++ = v >> 8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (sendto(fd, pkt, p - pkt, 0, (struct sockaddr *)&c.dst, sizeof(c.dst)) > 0) {
|
||||||
|
s_packets++;
|
||||||
|
}
|
||||||
|
seq++;
|
||||||
|
next += c.frames;
|
||||||
|
}
|
||||||
|
// Wake when the next packet's last sample is due (PTP time), not on a free-running
|
||||||
|
// period, so each packet leaves right after it is complete. Re-read the clock:
|
||||||
|
// building and sending took time.
|
||||||
|
aes67_ptp_now_ns(&now);
|
||||||
|
int64_t wait_us = (samples_to_ns(next + c.frames, c.rate) - now) / 1000 + WAKE_MARGIN_US;
|
||||||
|
esp_timer_stop(timer);
|
||||||
|
esp_timer_start_once(timer, wait_us < 50 ? 50 : wait_us > 10000 ? 10000 : wait_us);
|
||||||
|
}
|
||||||
|
if (new_state != state) {
|
||||||
|
state = new_state;
|
||||||
|
if (c.enabled && state[0] == 's') {
|
||||||
|
ESP_LOGI(TAG, "%s: %s:%u, %s/%d/%d, %d samples per packet, %s", state,
|
||||||
|
inet_ntoa(c.dst.sin_addr), ntohs(c.dst.sin_port), c.bytes == 3 ? "L24" : "L16",
|
||||||
|
c.rate, c.channels, c.frames, s_read ? "source" : "1 kHz test tone");
|
||||||
|
} else {
|
||||||
|
ESP_LOGI(TAG, "%s", state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t aes67_tx_start(void)
|
||||||
|
{
|
||||||
|
return xTaskCreate(tx_task, "aes67_tx", 4096, NULL, 16, &s_task) == pdPASS ? ESP_OK : ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t aes67_tx_init(void)
|
||||||
|
{
|
||||||
|
esp_err_t err = cfg_register("aes67", AES67_DEFAULTS, aes67_validate, aes67_apply);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
// Stored before 96 kHz was dropped: stored values aren't re-validated, so fix it here (SDP too).
|
||||||
|
cJSON *a = cfg_get("aes67");
|
||||||
|
double rate = cJSON_GetObjectItemCaseSensitive(a, "rate")->valuedouble;
|
||||||
|
cJSON_Delete(a);
|
||||||
|
if (rate != AES67_RATE) {
|
||||||
|
ESP_LOGW(TAG, "stored sample rate %.0f not supported: using %d", rate, AES67_RATE);
|
||||||
|
cfg_set_number("aes67", "rate", AES67_RATE, false);
|
||||||
|
}
|
||||||
|
return status_register(tx_status);
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
// aes67_tx: RTP sender task, PTP-paced, pull callback; optional mono sum.
|
||||||
|
// Core component: must not depend on main/ (project code).
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <stddef.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
#include "esp_err.h"
|
||||||
|
|
||||||
|
// Audio source: fill buf with frames x AES67_TX_SRC_CHANNELS interleaved samples (stereo, full scale =
|
||||||
|
// INT32_MAX), whatever the stream's channel count: TX maps it (mono stream: L, or (L+R)/2 with mono_sum).
|
||||||
|
// Return the number of frames delivered; fewer than asked counts as an underrun (padded with silence).
|
||||||
|
#define AES67_TX_SRC_CHANNELS 2
|
||||||
|
typedef size_t (*aes67_tx_read_cb_t)(int32_t *buf, size_t frames);
|
||||||
|
|
||||||
|
// Registers the "aes67" config group and the TX status fields.
|
||||||
|
esp_err_t aes67_tx_init(void);
|
||||||
|
// Start the sender task. Sends while PTP is locked and aes67.enabled is set.
|
||||||
|
esp_err_t aes67_tx_start(void);
|
||||||
|
// Set the audio source. NULL = built-in 1 kHz test tone at -18 dBFS, phase-locked to PTP time.
|
||||||
|
void aes67_tx_set_source(aes67_tx_read_cb_t read);
|
||||||
|
// Ready-made source: pink noise at -18 dBFS RMS (peaks about -6 dBFS), same on L and R.
|
||||||
|
// Pass it to aes67_tx_set_source(). Keeps state: use for one stream only.
|
||||||
|
size_t aes67_tx_pink_noise(int32_t *buf, size_t frames);
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
idf_component_register(SRCS "aes67_web.c" "cfg.c"
|
||||||
|
INCLUDE_DIRS "include"
|
||||||
|
REQUIRES esp_http_server json
|
||||||
|
PRIV_REQUIRES esp_timer nvs_flash lwip
|
||||||
|
EMBED_TXTFILES "${PROJECT_DIR}/web/index.html")
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 Ben Nicholson
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
#include "aes67_web.h"
|
||||||
|
|
||||||
|
#include "aes67_cfg.h"
|
||||||
|
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_system.h"
|
||||||
|
#include "esp_timer.h"
|
||||||
|
|
||||||
|
#define MAX_STATUS_CBS 16
|
||||||
|
#define MAX_URIS 32
|
||||||
|
#define MAX_EARLY_URIS 16
|
||||||
|
|
||||||
|
static const char *TAG = "web";
|
||||||
|
|
||||||
|
extern const char index_html_start[] asm("_binary_index_html_start");
|
||||||
|
extern const char index_html_end[] asm("_binary_index_html_end");
|
||||||
|
|
||||||
|
esp_err_t cfg_web_register(void); // cfg.c
|
||||||
|
|
||||||
|
static httpd_handle_t s_httpd;
|
||||||
|
static status_cb_t s_status_cbs[MAX_STATUS_CBS];
|
||||||
|
static int s_status_n;
|
||||||
|
static httpd_uri_t s_early_uris[MAX_EARLY_URIS];
|
||||||
|
static int s_early_n;
|
||||||
|
|
||||||
|
esp_err_t status_register(status_cb_t cb)
|
||||||
|
{
|
||||||
|
if (s_status_n >= MAX_STATUS_CBS) {
|
||||||
|
return ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
|
s_status_cbs[s_status_n++] = cb;
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t web_register_uri(const httpd_uri_t *uri)
|
||||||
|
{
|
||||||
|
if (s_httpd) {
|
||||||
|
return httpd_register_uri_handler(s_httpd, uri);
|
||||||
|
}
|
||||||
|
if (s_early_n >= MAX_EARLY_URIS) {
|
||||||
|
return ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
|
s_early_uris[s_early_n++] = *uri;
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t web_send_json(httpd_req_t *req, const cJSON *json)
|
||||||
|
{
|
||||||
|
char *body = cJSON_PrintUnformatted(json);
|
||||||
|
if (!body) {
|
||||||
|
return httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "out of memory");
|
||||||
|
}
|
||||||
|
httpd_resp_set_type(req, "application/json");
|
||||||
|
httpd_resp_set_hdr(req, "Cache-Control", "no-store");
|
||||||
|
esp_err_t err = httpd_resp_sendstr(req, body);
|
||||||
|
cJSON_free(body);
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
static esp_err_t index_get(httpd_req_t *req)
|
||||||
|
{
|
||||||
|
httpd_resp_set_type(req, "text/html; charset=utf-8");
|
||||||
|
// EMBED_TXTFILES appends a NUL; don't send it.
|
||||||
|
return httpd_resp_send(req, index_html_start, index_html_end - index_html_start - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
static esp_err_t status_get(httpd_req_t *req)
|
||||||
|
{
|
||||||
|
cJSON *st = cJSON_CreateObject();
|
||||||
|
for (int i = 0; i < s_status_n; i++) {
|
||||||
|
s_status_cbs[i](st);
|
||||||
|
}
|
||||||
|
esp_err_t err = web_send_json(req, st);
|
||||||
|
cJSON_Delete(st);
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void reboot_cb(void *arg)
|
||||||
|
{
|
||||||
|
esp_restart();
|
||||||
|
}
|
||||||
|
|
||||||
|
void web_reboot_later(uint32_t ms)
|
||||||
|
{
|
||||||
|
const esp_timer_create_args_t args = { .callback = reboot_cb, .name = "reboot" };
|
||||||
|
esp_timer_handle_t t;
|
||||||
|
if (esp_timer_create(&args, &t) == ESP_OK) {
|
||||||
|
esp_timer_start_once(t, ms * 1000ULL);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static esp_err_t reboot_post(httpd_req_t *req)
|
||||||
|
{
|
||||||
|
ESP_LOGW(TAG, "reboot requested via API");
|
||||||
|
httpd_resp_sendstr(req, "");
|
||||||
|
web_reboot_later(500); // let the response go out first
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t aes67_web_start(void)
|
||||||
|
{
|
||||||
|
esp_err_t err = cfg_web_register();
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
// httpd warns on every client reset (errno 104) and every 404 (e.g. UI polling a route the
|
||||||
|
// firmware doesn't have yet): noise in syslog. Our handlers log the 4xx cases that matter.
|
||||||
|
esp_log_level_set("httpd_txrx", ESP_LOG_ERROR);
|
||||||
|
esp_log_level_set("httpd_uri", ESP_LOG_ERROR);
|
||||||
|
|
||||||
|
httpd_config_t cfg = HTTPD_DEFAULT_CONFIG();
|
||||||
|
cfg.max_uri_handlers = MAX_URIS;
|
||||||
|
cfg.stack_size = 8192;
|
||||||
|
cfg.lru_purge_enable = true;
|
||||||
|
cfg.uri_match_fn = httpd_uri_match_wildcard;
|
||||||
|
|
||||||
|
err = httpd_start(&s_httpd, &cfg);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
ESP_LOGE(TAG, "httpd start failed: %s", esp_err_to_name(err));
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
static const httpd_uri_t core[] = {
|
||||||
|
{ .uri = "/", .method = HTTP_GET, .handler = index_get },
|
||||||
|
{ .uri = "/index.html", .method = HTTP_GET, .handler = index_get },
|
||||||
|
{ .uri = "/api/status", .method = HTTP_GET, .handler = status_get },
|
||||||
|
{ .uri = "/api/reboot", .method = HTTP_POST, .handler = reboot_post },
|
||||||
|
};
|
||||||
|
for (int i = 0; i < sizeof(core) / sizeof(core[0]); i++) {
|
||||||
|
httpd_register_uri_handler(s_httpd, &core[i]);
|
||||||
|
}
|
||||||
|
for (int i = 0; i < s_early_n; i++) {
|
||||||
|
httpd_register_uri_handler(s_httpd, &s_early_uris[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
ESP_LOGI(TAG, "httpd started, index.html %d bytes, %d extra routes",
|
||||||
|
(int)(index_html_end - index_html_start - 1), s_early_n);
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
@@ -0,0 +1,577 @@
|
|||||||
|
#include "aes67_cfg.h"
|
||||||
|
|
||||||
|
#include <math.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "aes67_web.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/semphr.h"
|
||||||
|
#include "lwip/inet.h"
|
||||||
|
#include "nvs.h"
|
||||||
|
#include "nvs_flash.h"
|
||||||
|
|
||||||
|
#define MAX_GROUPS 12
|
||||||
|
#define MAX_SECRETS 4
|
||||||
|
#define MAX_BODY 8192
|
||||||
|
#define NVS_NAMESPACE "cfg"
|
||||||
|
|
||||||
|
static const char *TAG = "cfg";
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
char name[16]; // also the NVS key (max 15 chars)
|
||||||
|
cJSON *defaults;
|
||||||
|
cJSON *values;
|
||||||
|
cfg_validate_cb_t validate;
|
||||||
|
cfg_apply_cb_t apply;
|
||||||
|
char secrets[MAX_SECRETS][24]; // write-only keys
|
||||||
|
int n_secrets;
|
||||||
|
} cfg_group_t;
|
||||||
|
|
||||||
|
static cfg_group_t s_groups[MAX_GROUPS];
|
||||||
|
static int s_group_n;
|
||||||
|
static cJSON *s_overrides; // {group: {...}} from cfg_override_defaults
|
||||||
|
static SemaphoreHandle_t s_lock;
|
||||||
|
static bool s_nvs_ok;
|
||||||
|
|
||||||
|
static void cfg_init_once(void)
|
||||||
|
{
|
||||||
|
if (s_lock) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
s_lock = xSemaphoreCreateMutex();
|
||||||
|
s_overrides = cJSON_CreateObject();
|
||||||
|
esp_err_t err = nvs_flash_init();
|
||||||
|
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
|
||||||
|
ESP_LOGW(TAG, "NVS needs erase (%s), config reset to defaults", esp_err_to_name(err));
|
||||||
|
nvs_flash_erase();
|
||||||
|
err = nvs_flash_init();
|
||||||
|
}
|
||||||
|
s_nvs_ok = err == ESP_OK;
|
||||||
|
if (!s_nvs_ok) {
|
||||||
|
ESP_LOGE(TAG, "NVS init failed: %s; config will not persist", esp_err_to_name(err));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static cfg_group_t *find(const char *name)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < s_group_n; i++) {
|
||||||
|
if (strcmp(s_groups[i].name, name) == 0) {
|
||||||
|
return &s_groups[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Same JSON kind for our purposes: number, string or bool.
|
||||||
|
static bool same_type(const cJSON *a, const cJSON *b)
|
||||||
|
{
|
||||||
|
if (cJSON_IsBool(a)) {
|
||||||
|
return cJSON_IsBool(b);
|
||||||
|
}
|
||||||
|
return (a->type & 0xFF) == (b->type & 0xFF);
|
||||||
|
}
|
||||||
|
|
||||||
|
static const char *type_name(const cJSON *v)
|
||||||
|
{
|
||||||
|
return cJSON_IsBool(v) ? "boolean" : cJSON_IsNumber(v) ? "number" : cJSON_IsString(v) ? "string" : "value";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Copy known keys of src over dst (keys must exist in defs with the same type).
|
||||||
|
// With err set, a type mismatch is an error; otherwise it is skipped with a warning.
|
||||||
|
static bool merge_known(cJSON *dst, const cJSON *defs, const cJSON *src, const char *group,
|
||||||
|
char *err, size_t err_len)
|
||||||
|
{
|
||||||
|
const cJSON *v;
|
||||||
|
cJSON_ArrayForEach(v, src) {
|
||||||
|
const cJSON *d = cJSON_GetObjectItemCaseSensitive(defs, v->string);
|
||||||
|
if (!d) {
|
||||||
|
ESP_LOGW(TAG, "%s.%s: unknown key, ignored", group, v->string);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!same_type(d, v)) {
|
||||||
|
if (err) {
|
||||||
|
snprintf(err, err_len, "%s.%s: expected %s", group, v->string, type_name(d));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
ESP_LOGW(TAG, "%s.%s: stored type differs from default, ignored", group, v->string);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
cJSON_ReplaceItemInObjectCaseSensitive(dst, v->string, cJSON_Duplicate(v, true));
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void load_stored(cfg_group_t *g)
|
||||||
|
{
|
||||||
|
if (!s_nvs_ok) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
nvs_handle_t h;
|
||||||
|
if (nvs_open(NVS_NAMESPACE, NVS_READONLY, &h) != ESP_OK) {
|
||||||
|
return; // nothing stored yet
|
||||||
|
}
|
||||||
|
size_t len = 0;
|
||||||
|
if (nvs_get_str(h, g->name, NULL, &len) == ESP_OK && len > 0) {
|
||||||
|
char *buf = malloc(len);
|
||||||
|
if (buf && nvs_get_str(h, g->name, buf, &len) == ESP_OK) {
|
||||||
|
cJSON *stored = cJSON_Parse(buf);
|
||||||
|
if (cJSON_IsObject(stored)) {
|
||||||
|
merge_known(g->values, g->defaults, stored, g->name, NULL, 0);
|
||||||
|
ESP_LOGI(TAG, "%s: loaded %d stored value(s)", g->name, cJSON_GetArraySize(stored));
|
||||||
|
} else {
|
||||||
|
ESP_LOGW(TAG, "%s: stored config unreadable, using defaults", g->name);
|
||||||
|
}
|
||||||
|
cJSON_Delete(stored);
|
||||||
|
}
|
||||||
|
free(buf);
|
||||||
|
}
|
||||||
|
nvs_close(h);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Store only the keys that differ from the defaults, so new firmware defaults still apply
|
||||||
|
// to settings the user never changed.
|
||||||
|
static esp_err_t store(nvs_handle_t h, const cfg_group_t *g)
|
||||||
|
{
|
||||||
|
cJSON *diff = cJSON_CreateObject();
|
||||||
|
const cJSON *v;
|
||||||
|
cJSON_ArrayForEach(v, g->values) {
|
||||||
|
const cJSON *d = cJSON_GetObjectItemCaseSensitive(g->defaults, v->string);
|
||||||
|
if (!d || !cJSON_Compare(d, v, true)) {
|
||||||
|
cJSON_AddItemToObject(diff, v->string, cJSON_Duplicate(v, true));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
esp_err_t err;
|
||||||
|
if (cJSON_GetArraySize(diff) == 0) {
|
||||||
|
err = nvs_erase_key(h, g->name);
|
||||||
|
if (err == ESP_ERR_NVS_NOT_FOUND) {
|
||||||
|
err = ESP_OK;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
char *s = cJSON_PrintUnformatted(diff);
|
||||||
|
err = s ? nvs_set_str(h, g->name, s) : ESP_ERR_NO_MEM;
|
||||||
|
cJSON_free(s);
|
||||||
|
}
|
||||||
|
cJSON_Delete(diff);
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t cfg_override_defaults(const char *group, const char *json)
|
||||||
|
{
|
||||||
|
cfg_init_once();
|
||||||
|
cJSON *o = cJSON_Parse(json);
|
||||||
|
if (!cJSON_IsObject(o)) {
|
||||||
|
cJSON_Delete(o);
|
||||||
|
ESP_LOGE(TAG, "%s: bad override JSON", group);
|
||||||
|
return ESP_ERR_INVALID_ARG;
|
||||||
|
}
|
||||||
|
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||||
|
cJSON *prev = cJSON_GetObjectItemCaseSensitive(s_overrides, group);
|
||||||
|
if (prev) {
|
||||||
|
const cJSON *v;
|
||||||
|
cJSON_ArrayForEach(v, o) {
|
||||||
|
cJSON_DeleteItemFromObjectCaseSensitive(prev, v->string);
|
||||||
|
cJSON_AddItemToObject(prev, v->string, cJSON_Duplicate(v, true));
|
||||||
|
}
|
||||||
|
cJSON_Delete(o);
|
||||||
|
} else {
|
||||||
|
cJSON_AddItemToObject(s_overrides, group, o);
|
||||||
|
}
|
||||||
|
bool late = find(group) != NULL;
|
||||||
|
xSemaphoreGive(s_lock);
|
||||||
|
if (late) {
|
||||||
|
ESP_LOGE(TAG, "%s: override after register has no effect", group);
|
||||||
|
return ESP_ERR_INVALID_STATE;
|
||||||
|
}
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t cfg_register(const char *group, const char *defaults_json,
|
||||||
|
cfg_validate_cb_t validate, cfg_apply_cb_t apply)
|
||||||
|
{
|
||||||
|
cfg_init_once();
|
||||||
|
if (strlen(group) >= sizeof(s_groups[0].name)) {
|
||||||
|
return ESP_ERR_INVALID_ARG;
|
||||||
|
}
|
||||||
|
cJSON *defs = cJSON_Parse(defaults_json);
|
||||||
|
if (!cJSON_IsObject(defs)) {
|
||||||
|
cJSON_Delete(defs);
|
||||||
|
ESP_LOGE(TAG, "%s: bad defaults JSON", group);
|
||||||
|
return ESP_ERR_INVALID_ARG;
|
||||||
|
}
|
||||||
|
|
||||||
|
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||||
|
if (find(group) || s_group_n >= MAX_GROUPS) {
|
||||||
|
xSemaphoreGive(s_lock);
|
||||||
|
cJSON_Delete(defs);
|
||||||
|
ESP_LOGE(TAG, "%s: already registered or registry full", group);
|
||||||
|
return ESP_ERR_INVALID_STATE;
|
||||||
|
}
|
||||||
|
const cJSON *ov = cJSON_GetObjectItemCaseSensitive(s_overrides, group);
|
||||||
|
if (ov) {
|
||||||
|
merge_known(defs, defs, ov, group, NULL, 0);
|
||||||
|
}
|
||||||
|
cfg_group_t *g = &s_groups[s_group_n++];
|
||||||
|
strcpy(g->name, group);
|
||||||
|
g->defaults = defs;
|
||||||
|
g->values = cJSON_Duplicate(defs, true);
|
||||||
|
g->validate = validate;
|
||||||
|
g->apply = apply;
|
||||||
|
load_stored(g);
|
||||||
|
xSemaphoreGive(s_lock);
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t cfg_mark_secret(const char *group, const char *key)
|
||||||
|
{
|
||||||
|
if (!s_lock) {
|
||||||
|
return ESP_ERR_INVALID_STATE;
|
||||||
|
}
|
||||||
|
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||||
|
cfg_group_t *g = find(group);
|
||||||
|
esp_err_t err = ESP_OK;
|
||||||
|
if (!g || !cJSON_IsString(cJSON_GetObjectItemCaseSensitive(g->defaults, key))) {
|
||||||
|
err = ESP_ERR_NOT_FOUND;
|
||||||
|
} else if (g->n_secrets >= MAX_SECRETS || strlen(key) >= sizeof(g->secrets[0])) {
|
||||||
|
err = ESP_ERR_NO_MEM;
|
||||||
|
} else {
|
||||||
|
strcpy(g->secrets[g->n_secrets++], key);
|
||||||
|
}
|
||||||
|
xSemaphoreGive(s_lock);
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Group values for the API: secrets blanked.
|
||||||
|
static cJSON *public_values(const cfg_group_t *g)
|
||||||
|
{
|
||||||
|
cJSON *v = cJSON_Duplicate(g->values, true);
|
||||||
|
for (int i = 0; i < g->n_secrets; i++) {
|
||||||
|
cJSON_ReplaceItemInObjectCaseSensitive(v, g->secrets[i], cJSON_CreateString(""));
|
||||||
|
}
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
cJSON *cfg_get(const char *group)
|
||||||
|
{
|
||||||
|
if (!s_lock) {
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||||
|
cfg_group_t *g = find(group);
|
||||||
|
cJSON *copy = g ? cJSON_Duplicate(g->values, true) : NULL;
|
||||||
|
xSemaphoreGive(s_lock);
|
||||||
|
return copy;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t cfg_set_number(const char *group, const char *key, double value, bool apply)
|
||||||
|
{
|
||||||
|
if (!s_lock) {
|
||||||
|
return ESP_ERR_INVALID_STATE;
|
||||||
|
}
|
||||||
|
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||||
|
cfg_group_t *g = find(group);
|
||||||
|
cJSON *cur = g ? cJSON_GetObjectItemCaseSensitive(g->values, key) : NULL;
|
||||||
|
esp_err_t err = ESP_OK;
|
||||||
|
if (!cur || !cJSON_IsNumber(cur)) {
|
||||||
|
err = ESP_ERR_NOT_FOUND;
|
||||||
|
} else {
|
||||||
|
cJSON_SetNumberValue(cur, value);
|
||||||
|
nvs_handle_t h;
|
||||||
|
if (s_nvs_ok && (err = nvs_open(NVS_NAMESPACE, NVS_READWRITE, &h)) == ESP_OK) {
|
||||||
|
err = store(h, g);
|
||||||
|
if (err == ESP_OK) {
|
||||||
|
err = nvs_commit(h);
|
||||||
|
}
|
||||||
|
nvs_close(h);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cJSON *copy = err == ESP_OK && apply && g->apply ? cJSON_Duplicate(g->values, true) : NULL;
|
||||||
|
xSemaphoreGive(s_lock);
|
||||||
|
if (copy) {
|
||||||
|
g->apply(copy);
|
||||||
|
cJSON_Delete(copy);
|
||||||
|
}
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t cfg_set_string(const char *group, const char *key, const char *value, bool apply)
|
||||||
|
{
|
||||||
|
if (!s_lock) {
|
||||||
|
return ESP_ERR_INVALID_STATE;
|
||||||
|
}
|
||||||
|
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||||
|
cfg_group_t *g = find(group);
|
||||||
|
cJSON *cur = g ? cJSON_GetObjectItemCaseSensitive(g->values, key) : NULL;
|
||||||
|
esp_err_t err = ESP_OK;
|
||||||
|
if (!cur || !cJSON_IsString(cur)) {
|
||||||
|
err = ESP_ERR_NOT_FOUND;
|
||||||
|
} else {
|
||||||
|
cJSON_ReplaceItemInObjectCaseSensitive(g->values, key, cJSON_CreateString(value));
|
||||||
|
nvs_handle_t h;
|
||||||
|
if (s_nvs_ok && (err = nvs_open(NVS_NAMESPACE, NVS_READWRITE, &h)) == ESP_OK) {
|
||||||
|
err = store(h, g);
|
||||||
|
if (err == ESP_OK) {
|
||||||
|
err = nvs_commit(h);
|
||||||
|
}
|
||||||
|
nvs_close(h);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cJSON *copy = err == ESP_OK && apply && g->apply ? cJSON_Duplicate(g->values, true) : NULL;
|
||||||
|
xSemaphoreGive(s_lock);
|
||||||
|
if (copy) {
|
||||||
|
g->apply(copy);
|
||||||
|
cJSON_Delete(copy);
|
||||||
|
}
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----- HTTP ----- */
|
||||||
|
|
||||||
|
static esp_err_t config_get(httpd_req_t *req)
|
||||||
|
{
|
||||||
|
cJSON *all = cJSON_CreateObject();
|
||||||
|
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||||
|
for (int i = 0; i < s_group_n; i++) {
|
||||||
|
cJSON_AddItemToObject(all, s_groups[i].name, public_values(&s_groups[i]));
|
||||||
|
}
|
||||||
|
xSemaphoreGive(s_lock);
|
||||||
|
esp_err_t err = web_send_json(req, all);
|
||||||
|
cJSON_Delete(all);
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
static esp_err_t bad_request(httpd_req_t *req, const char *msg)
|
||||||
|
{
|
||||||
|
ESP_LOGW(TAG, "POST /api/config rejected: %s", msg);
|
||||||
|
return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
static esp_err_t config_post(httpd_req_t *req)
|
||||||
|
{
|
||||||
|
if (req->content_len == 0 || req->content_len > MAX_BODY) {
|
||||||
|
return bad_request(req, "body missing or too large");
|
||||||
|
}
|
||||||
|
char *body = malloc(req->content_len + 1);
|
||||||
|
if (!body) {
|
||||||
|
return httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "out of memory");
|
||||||
|
}
|
||||||
|
size_t got = 0;
|
||||||
|
while (got < req->content_len) {
|
||||||
|
int r = httpd_req_recv(req, body + got, req->content_len - got);
|
||||||
|
if (r == HTTPD_SOCK_ERR_TIMEOUT) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (r <= 0) {
|
||||||
|
free(body);
|
||||||
|
return ESP_FAIL;
|
||||||
|
}
|
||||||
|
got += r;
|
||||||
|
}
|
||||||
|
body[got] = 0;
|
||||||
|
cJSON *in = cJSON_Parse(body);
|
||||||
|
free(body);
|
||||||
|
if (!cJSON_IsObject(in)) {
|
||||||
|
cJSON_Delete(in);
|
||||||
|
return bad_request(req, "body is not a JSON object");
|
||||||
|
}
|
||||||
|
|
||||||
|
char err[128] = "";
|
||||||
|
cJSON *cand[MAX_GROUPS] = { 0 };
|
||||||
|
bool ok = true;
|
||||||
|
|
||||||
|
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||||
|
// Build and validate every candidate group before storing anything.
|
||||||
|
for (int i = 0; ok && i < s_group_n; i++) {
|
||||||
|
cfg_group_t *g = &s_groups[i];
|
||||||
|
const cJSON *src = cJSON_GetObjectItemCaseSensitive(in, g->name);
|
||||||
|
if (!src) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!cJSON_IsObject(src)) {
|
||||||
|
snprintf(err, sizeof(err), "%s: expected object", g->name);
|
||||||
|
ok = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
cand[i] = cJSON_Duplicate(g->values, true);
|
||||||
|
// Secrets: "" = unchanged (the API never returns the stored value), null = clear.
|
||||||
|
cJSON *in_g = cJSON_Duplicate(src, true);
|
||||||
|
for (int k = 0; k < g->n_secrets; k++) {
|
||||||
|
const cJSON *sv = cJSON_GetObjectItemCaseSensitive(in_g, g->secrets[k]);
|
||||||
|
if (cJSON_IsString(sv) && !sv->valuestring[0]) {
|
||||||
|
cJSON_DeleteItemFromObjectCaseSensitive(in_g, g->secrets[k]);
|
||||||
|
} else if (cJSON_IsNull(sv)) {
|
||||||
|
cJSON_ReplaceItemInObjectCaseSensitive(in_g, g->secrets[k], cJSON_CreateString(""));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ok = merge_known(cand[i], g->defaults, in_g, g->name, err, sizeof(err));
|
||||||
|
cJSON_Delete(in_g);
|
||||||
|
if (ok && g->validate) {
|
||||||
|
char verr[96] = "";
|
||||||
|
ok = g->validate(cand[i], verr, sizeof(verr));
|
||||||
|
if (!ok) {
|
||||||
|
snprintf(err, sizeof(err), "%s.%s", g->name, verr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const cJSON *v;
|
||||||
|
cJSON_ArrayForEach(v, in) {
|
||||||
|
if (!find(v->string)) {
|
||||||
|
ESP_LOGW(TAG, "%s: unknown group, ignored", v->string);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t serr = ESP_OK;
|
||||||
|
int changed = 0;
|
||||||
|
if (ok && s_nvs_ok) {
|
||||||
|
nvs_handle_t h;
|
||||||
|
serr = nvs_open(NVS_NAMESPACE, NVS_READWRITE, &h);
|
||||||
|
for (int i = 0; serr == ESP_OK && i < s_group_n; i++) {
|
||||||
|
if (cand[i] && !cJSON_Compare(cand[i], s_groups[i].values, true)) {
|
||||||
|
cJSON *old = s_groups[i].values;
|
||||||
|
s_groups[i].values = cand[i];
|
||||||
|
serr = store(h, &s_groups[i]);
|
||||||
|
if (serr != ESP_OK) {
|
||||||
|
s_groups[i].values = old;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
cand[i] = old; // freed below
|
||||||
|
changed |= 1 << i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (serr == ESP_OK) {
|
||||||
|
serr = nvs_commit(h);
|
||||||
|
}
|
||||||
|
nvs_close(h);
|
||||||
|
}
|
||||||
|
for (int i = 0; i < s_group_n; i++) {
|
||||||
|
cJSON_Delete(cand[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply after the lock is released; callbacks may call cfg_get().
|
||||||
|
cJSON *applied[MAX_GROUPS] = { 0 };
|
||||||
|
for (int i = 0; i < s_group_n; i++) {
|
||||||
|
if ((changed & (1 << i)) && s_groups[i].apply) {
|
||||||
|
applied[i] = cJSON_Duplicate(s_groups[i].values, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
int group_n = s_group_n;
|
||||||
|
xSemaphoreGive(s_lock);
|
||||||
|
cJSON_Delete(in);
|
||||||
|
|
||||||
|
if (!ok) {
|
||||||
|
return bad_request(req, err);
|
||||||
|
}
|
||||||
|
if (!s_nvs_ok || serr != ESP_OK) {
|
||||||
|
ESP_LOGE(TAG, "store failed: %s", s_nvs_ok ? esp_err_to_name(serr) : "NVS unavailable");
|
||||||
|
return httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "could not store config");
|
||||||
|
}
|
||||||
|
for (int i = 0; i < group_n; i++) {
|
||||||
|
if (changed & (1 << i)) {
|
||||||
|
ESP_LOGI(TAG, "%s: saved", s_groups[i].name);
|
||||||
|
}
|
||||||
|
if (applied[i]) {
|
||||||
|
s_groups[i].apply(applied[i]);
|
||||||
|
cJSON_Delete(applied[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return config_get(req);
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t cfg_web_register(void)
|
||||||
|
{
|
||||||
|
static const httpd_uri_t uris[] = {
|
||||||
|
{ .uri = "/api/config", .method = HTTP_GET, .handler = config_get },
|
||||||
|
{ .uri = "/api/config", .method = HTTP_POST, .handler = config_post },
|
||||||
|
};
|
||||||
|
cfg_init_once();
|
||||||
|
for (int i = 0; i < 2; i++) {
|
||||||
|
esp_err_t err = web_register_uri(&uris[i]);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----- Validation helpers ----- */
|
||||||
|
|
||||||
|
static const cJSON *item(const cJSON *g, const char *key)
|
||||||
|
{
|
||||||
|
return cJSON_GetObjectItemCaseSensitive(g, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool cfg_check_num(const cJSON *g, const char *key, double min, double max, char *err, size_t n)
|
||||||
|
{
|
||||||
|
const cJSON *v = item(g, key);
|
||||||
|
if (!cJSON_IsNumber(v) || v->valuedouble < min || v->valuedouble > max) {
|
||||||
|
snprintf(err, n, "%s: must be %g..%g", key, min, max);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool cfg_check_int(const cJSON *g, const char *key, double min, double max, char *err, size_t n)
|
||||||
|
{
|
||||||
|
if (!cfg_check_num(g, key, min, max, err, n)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
double d = item(g, key)->valuedouble;
|
||||||
|
if (d != floor(d)) {
|
||||||
|
snprintf(err, n, "%s: must be a whole number", key);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool cfg_check_num_in(const cJSON *g, const char *key, const double *vals, int count, char *err, size_t n)
|
||||||
|
{
|
||||||
|
const cJSON *v = item(g, key);
|
||||||
|
for (int i = 0; cJSON_IsNumber(v) && i < count; i++) {
|
||||||
|
if (v->valuedouble == vals[i]) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
int off = snprintf(err, n, "%s: must be one of", key);
|
||||||
|
for (int i = 0; i < count && off > 0 && off < (int)n; i++) {
|
||||||
|
off += snprintf(err + off, n - off, " %g", vals[i]);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool cfg_check_enum(const cJSON *g, const char *key, const char *const *opts, char *err, size_t n)
|
||||||
|
{
|
||||||
|
const cJSON *v = item(g, key);
|
||||||
|
for (int i = 0; cJSON_IsString(v) && opts[i]; i++) {
|
||||||
|
if (strcmp(v->valuestring, opts[i]) == 0) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
int off = snprintf(err, n, "%s: must be one of", key);
|
||||||
|
for (int i = 0; opts[i] && off > 0 && off < (int)n; i++) {
|
||||||
|
off += snprintf(err + off, n - off, " %s", opts[i]);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool cfg_check_str(const cJSON *g, const char *key, size_t min_len, size_t max_len, char *err, size_t n)
|
||||||
|
{
|
||||||
|
const cJSON *v = item(g, key);
|
||||||
|
size_t len = cJSON_IsString(v) ? strlen(v->valuestring) : 0;
|
||||||
|
if (!cJSON_IsString(v) || len < min_len || len > max_len) {
|
||||||
|
snprintf(err, n, "%s: length must be %u..%u", key, (unsigned)min_len, (unsigned)max_len);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool cfg_check_ipv4(const cJSON *g, const char *key, bool allow_empty, char *err, size_t n)
|
||||||
|
{
|
||||||
|
const cJSON *v = item(g, key);
|
||||||
|
struct in_addr a;
|
||||||
|
if (cJSON_IsString(v) && ((allow_empty && !v->valuestring[0]) || inet_aton(v->valuestring, &a))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
snprintf(err, n, "%s: not a valid IPv4 address", key);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
// Config registry and store (cJSON in NVS), part of aes67_web.
|
||||||
|
// Each component registers its group; /api/config is built from the registry.
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <stdbool.h>
|
||||||
|
#include <stddef.h>
|
||||||
|
|
||||||
|
#include "cJSON.h"
|
||||||
|
#include "esp_err.h"
|
||||||
|
|
||||||
|
// Validate a candidate group object. On failure write "key: reason" to err and return false.
|
||||||
|
typedef bool (*cfg_validate_cb_t)(const cJSON *group, char *err, size_t err_len);
|
||||||
|
// Called with the new group values after a successful save (apply live where possible).
|
||||||
|
typedef void (*cfg_apply_cb_t)(const cJSON *group);
|
||||||
|
|
||||||
|
// Project defaults merged over a group's core defaults. Call before that group is registered.
|
||||||
|
esp_err_t cfg_override_defaults(const char *group, const char *json);
|
||||||
|
// Register a group. Stored values (NVS) are loaded immediately, merged over the defaults.
|
||||||
|
esp_err_t cfg_register(const char *group, const char *defaults_json,
|
||||||
|
cfg_validate_cb_t validate, cfg_apply_cb_t apply);
|
||||||
|
// Write-only key (e.g. a password): GET /api/config returns "" for it; a POST with "" keeps the
|
||||||
|
// stored value, null clears it. cfg_get() still returns the real value. Call after cfg_register().
|
||||||
|
esp_err_t cfg_mark_secret(const char *group, const char *key);
|
||||||
|
// Copy of a group's current values; caller frees with cJSON_Delete. NULL if not registered.
|
||||||
|
cJSON *cfg_get(const char *group);
|
||||||
|
// Firmware-side change of one number (e.g. aes67.session_ver): stored like a POST, no validation.
|
||||||
|
// apply = false skips the group's apply callback (e.g. to avoid restarting the stream).
|
||||||
|
esp_err_t cfg_set_number(const char *group, const char *key, double value, bool apply);
|
||||||
|
// Same for a string value.
|
||||||
|
esp_err_t cfg_set_string(const char *group, const char *key, const char *value, bool apply);
|
||||||
|
|
||||||
|
// Validation helpers for validate callbacks. Each returns false and fills err on failure.
|
||||||
|
bool cfg_check_num(const cJSON *g, const char *key, double min, double max, char *err, size_t n);
|
||||||
|
bool cfg_check_int(const cJSON *g, const char *key, double min, double max, char *err, size_t n);
|
||||||
|
bool cfg_check_num_in(const cJSON *g, const char *key, const double *vals, int count, char *err, size_t n);
|
||||||
|
bool cfg_check_enum(const cJSON *g, const char *key, const char *const *opts, char *err, size_t n);
|
||||||
|
bool cfg_check_str(const cJSON *g, const char *key, size_t min_len, size_t max_len, char *err, size_t n);
|
||||||
|
bool cfg_check_ipv4(const cJSON *g, const char *key, bool allow_empty, char *err, size_t n);
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
// aes67_web: httpd, embedded index.html, config store (cJSON in NVS), core routes.
|
||||||
|
// Core component: must not depend on main/ (project code).
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "cJSON.h"
|
||||||
|
#include "esp_err.h"
|
||||||
|
#include "esp_http_server.h"
|
||||||
|
|
||||||
|
// Adds fields to the /api/status object. Called on every GET /api/status.
|
||||||
|
typedef void (*status_cb_t)(cJSON *status);
|
||||||
|
|
||||||
|
// Registries: call before or after aes67_web_start(); routes registered early are added on start.
|
||||||
|
esp_err_t status_register(status_cb_t cb);
|
||||||
|
esp_err_t web_register_uri(const httpd_uri_t *uri);
|
||||||
|
|
||||||
|
// Start httpd on port 80 with the core routes (/, /api/status, /api/config, /api/reboot).
|
||||||
|
esp_err_t aes67_web_start(void);
|
||||||
|
|
||||||
|
// Restart after ms (lets an HTTP response go out first).
|
||||||
|
void web_reboot_later(uint32_t ms);
|
||||||
|
|
||||||
|
// Send a cJSON object as the response body (application/json).
|
||||||
|
esp_err_t web_send_json(httpd_req_t *req, const cJSON *json);
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
# Spotify Connect via cspot (philippe44 fork, git submodule external/cspot). GPL-3.0.
|
||||||
|
# Project component (not part of the reusable aes67_* core).
|
||||||
|
idf_component_register(SRCS "spotify.cpp"
|
||||||
|
INCLUDE_DIRS "include"
|
||||||
|
PRIV_REQUIRES aes67_web espressif__mdns mbedtls json pthread lwip esp_timer esp_http_server)
|
||||||
|
|
||||||
|
# bell: only what cspot needs (Tremor Vorbis inside; no codec wrapper, sinks, MQTT, web server).
|
||||||
|
set(BELL_DISABLE_CODECS ON CACHE BOOL "" FORCE)
|
||||||
|
set(BELL_DISABLE_SINKS ON CACHE BOOL "" FORCE)
|
||||||
|
set(BELL_DISABLE_MQTT ON CACHE BOOL "" FORCE)
|
||||||
|
set(BELL_DISABLE_WEBSERVER ON CACHE BOOL "" FORCE)
|
||||||
|
set(BELL_DISABLE_FMT ON CACHE BOOL "" FORCE)
|
||||||
|
set(BELL_DISABLE_REGEX ON CACHE BOOL "" FORCE)
|
||||||
|
set(BELL_ONLY_CJSON ON CACHE BOOL "" FORCE)
|
||||||
|
set(BELL_EXTERNAL_CJSON idf::json CACHE STRING "" FORCE)
|
||||||
|
option(BUILD_TESTING OFF)
|
||||||
|
|
||||||
|
# Our fixes to the pinned cspot / bell sources (newer GCC, protobuf, CMake), kept as patch files:
|
||||||
|
# patches/cspot/*.patch apply in external/cspot, patches/bell/*.patch in external/cspot/cspot/bell.
|
||||||
|
# Each is applied once (skipped when it already reverse-applies).
|
||||||
|
function(spotify_apply_patches dir repo)
|
||||||
|
file(GLOB patches "${CMAKE_CURRENT_LIST_DIR}/patches/${dir}/*.patch")
|
||||||
|
list(SORT patches)
|
||||||
|
foreach(p ${patches})
|
||||||
|
execute_process(COMMAND git apply --reverse --check "${p}" WORKING_DIRECTORY "${repo}"
|
||||||
|
RESULT_VARIABLE applied OUTPUT_QUIET ERROR_QUIET)
|
||||||
|
if(NOT applied EQUAL 0)
|
||||||
|
execute_process(COMMAND git apply "${p}" WORKING_DIRECTORY "${repo}" RESULT_VARIABLE rc)
|
||||||
|
if(NOT rc EQUAL 0)
|
||||||
|
message(FATAL_ERROR "spotify: patch does not apply: ${p}")
|
||||||
|
endif()
|
||||||
|
message(STATUS "spotify: applied ${p}")
|
||||||
|
endif()
|
||||||
|
endforeach()
|
||||||
|
endfunction()
|
||||||
|
spotify_apply_patches(cspot "${PROJECT_DIR}/external/cspot")
|
||||||
|
spotify_apply_patches(bell "${PROJECT_DIR}/external/cspot/cspot/bell")
|
||||||
|
|
||||||
|
# cspot/bell declare cmake_minimum_required(2.8.12); CMake 4 rejects < 3.5 unless told otherwise.
|
||||||
|
set(CMAKE_POLICY_VERSION_MINIMUM 3.5)
|
||||||
|
add_subdirectory(${PROJECT_DIR}/external/cspot/cspot ${CMAKE_CURRENT_BINARY_DIR}/cspot)
|
||||||
|
|
||||||
|
# bell adds Xtensa (ESP32) assembly for a DSP biquad; the P4 is RISC-V and cspot does not use it.
|
||||||
|
get_target_property(BELL_SRCS bell SOURCES)
|
||||||
|
list(FILTER BELL_SRCS EXCLUDE REGEX "\\.S$")
|
||||||
|
set_target_properties(bell PROPERTIES SOURCES "${BELL_SRCS}")
|
||||||
|
|
||||||
|
target_link_libraries(${COMPONENT_LIB} PRIVATE cspot)
|
||||||
|
target_compile_options(${COMPONENT_LIB} PRIVATE -std=gnu++20)
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
// Spotify Connect (cspot). Project code; GPL-3.0 through cspot.
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <stdbool.h>
|
||||||
|
#include <stddef.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
#include "esp_err.h"
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
typedef enum {
|
||||||
|
SPOTIFY_EV_PLAY, // playback (re)started or resumed
|
||||||
|
SPOTIFY_EV_PAUSE,
|
||||||
|
SPOTIFY_EV_FLUSH, // skip, seek, new track: drop buffered audio
|
||||||
|
SPOTIFY_EV_VOLUME, // value: 0..65535
|
||||||
|
} spotify_event_t;
|
||||||
|
|
||||||
|
// PCM from Spotify: 44.1 kHz stereo s16 interleaved. Return the frames taken (may block).
|
||||||
|
typedef size_t (*spotify_pcm_cb_t)(const int16_t *pcm, size_t frames);
|
||||||
|
typedef void (*spotify_event_cb_t)(spotify_event_t ev, int value);
|
||||||
|
// Output positions in frames (monotonic, wrap at 2^32): written into the output buffer so far, and
|
||||||
|
// played out so far. Used to tell Spotify when a new track actually becomes audible.
|
||||||
|
typedef uint32_t (*spotify_pos_cb_t)(void);
|
||||||
|
|
||||||
|
// Registers the zeroconf endpoints (/spotify_info) and starts the session task (disabled until
|
||||||
|
// spotify_apply(true)).
|
||||||
|
esp_err_t spotify_init(spotify_pcm_cb_t pcm, spotify_event_cb_t event, spotify_pos_cb_t written,
|
||||||
|
spotify_pos_cb_t played);
|
||||||
|
// Enable (advertised, sessions accepted) when the player's mode needs Spotify and the client
|
||||||
|
// credentials are set; otherwise not advertised and a running session is ended. Re-reads name and
|
||||||
|
// credentials from the "source" config: a new device name ends the session and re-advertises.
|
||||||
|
void spotify_apply(bool enable);
|
||||||
|
typedef enum {
|
||||||
|
SPOTIFY_CMD_PLAY, SPOTIFY_CMD_PAUSE, SPOTIFY_CMD_NEXT, SPOTIFY_CMD_PREV,
|
||||||
|
SPOTIFY_CMD_SEEK, // arg: position in ms
|
||||||
|
} spotify_cmd_t;
|
||||||
|
// Control the running session (the Spotify app follows). Runs on the session task; waits until it
|
||||||
|
// has run (max 1 s). Returns false without a session.
|
||||||
|
bool spotify_command(spotify_cmd_t cmd, uint32_t arg);
|
||||||
|
// Suspend: end any running session (waits until its tasks are gone, max ~3 s) and refuse new ones.
|
||||||
|
// Resume: back to what the config says. Used around firmware uploads.
|
||||||
|
void spotify_suspend(bool suspend);
|
||||||
|
// The player's volume (0..100 %): reported to the Spotify app when a session starts (else the app
|
||||||
|
// shows 0 while we play at the player's level), and pushed to a running session.
|
||||||
|
void spotify_set_volume(int pct);
|
||||||
|
// A session is running (an app is connected to this device).
|
||||||
|
bool spotify_session_active(void);
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
char artist[96], title[128], album[96]; // "" until the first track is audible
|
||||||
|
uint32_t duration_ms, position_ms; // position as the Spotify app sees it
|
||||||
|
bool paused;
|
||||||
|
} spotify_track_t;
|
||||||
|
// The current track of the running session. False without a session.
|
||||||
|
bool spotify_now_playing(spotify_track_t *t);
|
||||||
|
// Current state for status.spotify_state.
|
||||||
|
const char *spotify_state(void);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
diff --git a/external/nanopb/generator/nanopb_generator.py b/external/nanopb/generator/nanopb_generator.py
|
||||||
|
index e40f18b..64dad5e 100755
|
||||||
|
--- a/external/nanopb/generator/nanopb_generator.py
|
||||||
|
+++ b/external/nanopb/generator/nanopb_generator.py
|
||||||
|
@@ -1463,7 +1463,12 @@ class Message(ProtoElement):
|
||||||
|
optional_only.ClearField(str('extension'))
|
||||||
|
optional_only.ClearField(str('enum_type'))
|
||||||
|
desc = google.protobuf.descriptor.MakeDescriptor(optional_only)
|
||||||
|
- msg = reflection.MakeClass(desc)()
|
||||||
|
+ # protobuf >= 5 removed reflection.MakeClass (patch for this project)
|
||||||
|
+ try:
|
||||||
|
+ msg = reflection.MakeClass(desc)()
|
||||||
|
+ except AttributeError:
|
||||||
|
+ from google.protobuf import message_factory
|
||||||
|
+ msg = message_factory.GetMessageClass(desc)()
|
||||||
|
|
||||||
|
for field in optional_only.field:
|
||||||
|
if field.type == FieldD.TYPE_STRING:
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
diff --git a/main/io/URLParser.cpp b/main/io/URLParser.cpp
|
||||||
|
index 4a50ab1..af679ec 100644
|
||||||
|
--- a/main/io/URLParser.cpp
|
||||||
|
+++ b/main/io/URLParser.cpp
|
||||||
|
@@ -1,5 +1,8 @@
|
||||||
|
#include "URLParser.h"
|
||||||
|
|
||||||
|
+#include <cstdio> // sscanf (GCC 14 / ESP-IDF 5.5: not included transitively)
|
||||||
|
+#include <cstring> // strstr
|
||||||
|
+
|
||||||
|
namespace bell {
|
||||||
|
|
||||||
|
#ifdef BELL_DISABLE_REGEX
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
From philippe44/cspot PR #3 (open, 2026-08): "MercurySession: crash when a request
|
||||||
|
races the reconnection (null conn/shanConn)". Our sessions reconnect every ~6 min, so the
|
||||||
|
race is hit regularly. Drop this patch once the fix is in the pinned cspot commit.
|
||||||
|
|
||||||
|
diff --git a/cspot/include/Session.h b/cspot/include/Session.h
|
||||||
|
index df7f03c8..7cc8e32f 100644
|
||||||
|
--- a/cspot/include/Session.h
|
||||||
|
+++ b/cspot/include/Session.h
|
||||||
|
@@ -2,6 +2,7 @@
|
||||||
|
|
||||||
|
#include <stdint.h> // for uint8_t
|
||||||
|
#include <memory> // for shared_ptr, unique_ptr
|
||||||
|
+#include <mutex> // for mutex
|
||||||
|
#include <string> // for string
|
||||||
|
#include <vector> // for vector
|
||||||
|
|
||||||
|
@@ -23,6 +24,11 @@ class Session {
|
||||||
|
std::shared_ptr<cspot::PlainConnection> conn;
|
||||||
|
std::shared_ptr<LoginBlob> authBlob;
|
||||||
|
|
||||||
|
+ /* conn and shanConn are swapped by the session's task during reconnection,
|
||||||
|
+ * but other tasks send through them; they must hold this while copying the
|
||||||
|
+ * pointers, and the session's task while replacing them */
|
||||||
|
+ std::mutex connMutex;
|
||||||
|
+
|
||||||
|
std::string deviceId = "142137fd329622137a14901634264e6f332e2411";
|
||||||
|
|
||||||
|
public:
|
||||||
|
diff --git a/cspot/src/MercurySession.cpp b/cspot/src/MercurySession.cpp
|
||||||
|
index 7aafbb76..29a6e546 100644
|
||||||
|
--- a/cspot/src/MercurySession.cpp
|
||||||
|
+++ b/cspot/src/MercurySession.cpp
|
||||||
|
@@ -66,8 +66,11 @@ void MercurySession::reconnect() {
|
||||||
|
isReconnecting = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
- this->conn = nullptr;
|
||||||
|
- this->shanConn = nullptr;
|
||||||
|
+ {
|
||||||
|
+ std::scoped_lock lock(connMutex);
|
||||||
|
+ this->conn = nullptr;
|
||||||
|
+ this->shanConn = nullptr;
|
||||||
|
+ }
|
||||||
|
|
||||||
|
this->connectWithRandomAp();
|
||||||
|
this->authenticate(this->authBlob);
|
||||||
|
@@ -127,7 +130,17 @@ void MercurySession::unregisterAudioKey(uint32_t sequenceId) {
|
||||||
|
void MercurySession::disconnect() {
|
||||||
|
CSPOT_LOG(info, "Disconnecting mercury session");
|
||||||
|
this->isRunning = false;
|
||||||
|
- conn->close();
|
||||||
|
+
|
||||||
|
+ /* conn is null while a reconnection is in flight; isRunning above already
|
||||||
|
+ * makes the retry loop exit, closing is just to unblock a pending read */
|
||||||
|
+ std::shared_ptr<PlainConnection> conn;
|
||||||
|
+ {
|
||||||
|
+ std::scoped_lock lock(connMutex);
|
||||||
|
+ conn = this->conn;
|
||||||
|
+ }
|
||||||
|
+ if (conn)
|
||||||
|
+ conn->close();
|
||||||
|
+
|
||||||
|
std::scoped_lock lock(this->isRunningMutex);
|
||||||
|
}
|
||||||
|
|
||||||
|
@@ -305,8 +318,22 @@ uint64_t MercurySession::executeSubscription(RequestType method,
|
||||||
|
// Bump sequence id
|
||||||
|
this->sequenceId += 1;
|
||||||
|
|
||||||
|
+ /* the session's task may be swapping shanConn for a reconnection right now,
|
||||||
|
+ * and dereferencing it here would not be a catchable failure, so take a
|
||||||
|
+ * snapshot; when disconnected, the request is simply lost */
|
||||||
|
+ std::shared_ptr<ShannonConnection> shanConn;
|
||||||
|
+ {
|
||||||
|
+ std::scoped_lock lock(connMutex);
|
||||||
|
+ shanConn = this->shanConn;
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
+ if (!shanConn) {
|
||||||
|
+ CSPOT_LOG(info, "Mercury request skipped, session is reconnecting");
|
||||||
|
+ return this->sequenceId - 1;
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
try {
|
||||||
|
- this->shanConn->sendPacket(
|
||||||
|
+ shanConn->sendPacket(
|
||||||
|
static_cast<std::underlying_type<RequestType>::type>(method),
|
||||||
|
sequenceIdBytes);
|
||||||
|
} catch (...) {
|
||||||
|
@@ -337,8 +364,21 @@ uint32_t MercurySession::requestAudioKey(const std::vector<uint8_t>& trackId,
|
||||||
|
|
||||||
|
// Used for broken connection detection
|
||||||
|
// this->lastRequestTimestamp = timeProvider->getSyncedTimestamp();
|
||||||
|
+
|
||||||
|
+ // same snapshot as executeSubscription: this runs on the track queue's task
|
||||||
|
+ std::shared_ptr<ShannonConnection> shanConn;
|
||||||
|
+ {
|
||||||
|
+ std::scoped_lock lock(connMutex);
|
||||||
|
+ shanConn = this->shanConn;
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
+ if (!shanConn) {
|
||||||
|
+ CSPOT_LOG(info, "Audio key request skipped, session is reconnecting");
|
||||||
|
+ return audioKeySequence - 1;
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
try {
|
||||||
|
- this->shanConn->sendPacket(
|
||||||
|
+ shanConn->sendPacket(
|
||||||
|
static_cast<uint8_t>(RequestType::AUDIO_KEY_REQUEST_COMMAND), buffer);
|
||||||
|
} catch (...) {
|
||||||
|
// @TODO: Handle disconnect
|
||||||
|
diff --git a/cspot/src/Session.cpp b/cspot/src/Session.cpp
|
||||||
|
index 74bd0633..be154bbe 100644
|
||||||
|
--- a/cspot/src/Session.cpp
|
||||||
|
+++ b/cspot/src/Session.cpp
|
||||||
|
@@ -4,6 +4,7 @@
|
||||||
|
#include <cstdint> // for uint8_t
|
||||||
|
#include <functional> // for __base
|
||||||
|
#include <memory> // for shared_ptr, unique_ptr, make_unique
|
||||||
|
+#include <mutex> // for scoped_lock
|
||||||
|
#include <random> // for default_random_engine, independent_bi...
|
||||||
|
#include <type_traits> // for remove_extent_t
|
||||||
|
#include <utility> // for move
|
||||||
|
@@ -33,7 +34,10 @@ Session::Session() {
|
||||||
|
Session::~Session() {}
|
||||||
|
|
||||||
|
void Session::connect(std::unique_ptr<cspot::PlainConnection> connection) {
|
||||||
|
- this->conn = std::move(connection);
|
||||||
|
+ {
|
||||||
|
+ std::scoped_lock lock(connMutex);
|
||||||
|
+ this->conn = std::move(connection);
|
||||||
|
+ }
|
||||||
|
conn->timeoutHandler = [this]() {
|
||||||
|
return this->triggerTimeout();
|
||||||
|
};
|
||||||
|
@@ -48,11 +52,15 @@ void Session::connect(std::unique_ptr<cspot::PlainConnection> connection) {
|
||||||
|
CSPOT_LOG(debug, "Received shannon keys");
|
||||||
|
|
||||||
|
// Generates the public and priv key
|
||||||
|
- this->shanConn = std::make_shared<ShannonConnection>();
|
||||||
|
+ auto shanConn = std::make_shared<ShannonConnection>();
|
||||||
|
+
|
||||||
|
+ // Init shanno-encrypted connection, and only then publish it so another
|
||||||
|
+ // task cannot pick up a connection that is not wrapped yet
|
||||||
|
+ shanConn->wrapConnection(this->conn, challenges->shanSendKey,
|
||||||
|
+ challenges->shanRecvKey);
|
||||||
|
|
||||||
|
- // Init shanno-encrypted connection
|
||||||
|
- this->shanConn->wrapConnection(this->conn, challenges->shanSendKey,
|
||||||
|
- challenges->shanRecvKey);
|
||||||
|
+ std::scoped_lock lock(connMutex);
|
||||||
|
+ this->shanConn = shanConn;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Session::connectWithRandomAp() {
|
||||||
|
diff --git a/cspot/src/TrackReference.cpp b/cspot/src/TrackReference.cpp
|
||||||
|
index b4fafcb5..203fe041 100644
|
||||||
|
--- a/cspot/src/TrackReference.cpp
|
||||||
|
+++ b/cspot/src/TrackReference.cpp
|
||||||
|
@@ -43,9 +43,9 @@ bool TrackReference::pbEncodeTrackList(pb_ostream_t* stream,
|
||||||
|
// concurrent rebuild cannot reallocate the vector under us
|
||||||
|
std::scoped_lock lock(*locked->mutex);
|
||||||
|
auto& trackQueue = *locked->tracks;
|
||||||
|
-#ifdef ESP_PLATFORM
|
||||||
|
+#ifdef ESP_PLATFORM
|
||||||
|
static TrackRef msg = TrackRef_init_zero;
|
||||||
|
-#else
|
||||||
|
+#else
|
||||||
|
TrackRef msg = TrackRef_init_zero;
|
||||||
|
#endif
|
||||||
|
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
diff --git a/cspot/src/PlainConnection.cpp b/cspot/src/PlainConnection.cpp
|
||||||
|
index 1bff6cf..b4ee6ff 100644
|
||||||
|
--- a/cspot/src/PlainConnection.cpp
|
||||||
|
+++ b/cspot/src/PlainConnection.cpp
|
||||||
|
@@ -150,6 +150,10 @@ void PlainConnection::readBlock(const uint8_t* dst, size_t size) {
|
||||||
|
case EINTR:
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
+ // diagnostic (project patch): n == 0 means the peer closed (FIN); n < 0 with errno
|
||||||
|
+ // e.g. ECONNRESET (RST). Note errno is not updated when n == 0.
|
||||||
|
+ CSPOT_LOG(error, "recv returned %d, errno %d, %u of %u bytes, retry %d", (int)n,
|
||||||
|
+ getErrno(), idx, (unsigned)size, retries);
|
||||||
|
if (retries++ > 4)
|
||||||
|
throw std::runtime_error("Error in read");
|
||||||
|
goto READ;
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
Keep-alive like librespot (core/src/session.rs): the server sends a Ping every ~2 min; send
|
||||||
|
the Pong 60 s later, not at once. With an immediate Pong the server reset the AP connection
|
||||||
|
(ECONNRESET) on the third Ping, i.e. every 6 minutes, and the Spotify app lost the device.
|
||||||
|
|
||||||
|
--- a/cspot/include/MercurySession.h
|
||||||
|
+++ b/cspot/include/MercurySession.h
|
||||||
|
@@ -120,6 +120,14 @@
|
||||||
|
|
||||||
|
unsigned long long timestampDiff;
|
||||||
|
unsigned long long lastPingTimestamp = -1;
|
||||||
|
+
|
||||||
|
+ // Keep-alive as librespot does it: Ping -> wait 60 s -> Pong -> PongAck. Answering at once made
|
||||||
|
+ // the server reset the connection on the third Ping (every 6 minutes).
|
||||||
|
+ const int PONG_DELAY_MS = 60 * 1000;
|
||||||
|
+ bool pongPending = false;
|
||||||
|
+ unsigned long long pongDueTimestamp = 0;
|
||||||
|
+ std::vector<uint8_t> pongData;
|
||||||
|
+ void sendPendingPong();
|
||||||
|
std::string countryCode = "";
|
||||||
|
|
||||||
|
std::mutex isRunningMutex;
|
||||||
|
--- a/cspot/src/MercurySession.cpp
|
||||||
|
+++ b/cspot/src/MercurySession.cpp
|
||||||
|
@@ -45,7 +45,10 @@
|
||||||
|
timeProvider->syncWithPingPacket(packet.data);
|
||||||
|
|
||||||
|
this->lastPingTimestamp = timeProvider->getSyncedTimestamp();
|
||||||
|
- this->shanConn->sendPacket(0x49, packet.data);
|
||||||
|
+ // Pong 60 s later (sent from triggerTimeout(), called on every 3 s receive timeout)
|
||||||
|
+ this->pongData = packet.data;
|
||||||
|
+ this->pongDueTimestamp = this->lastPingTimestamp + PONG_DELAY_MS;
|
||||||
|
+ this->pongPending = true;
|
||||||
|
} else {
|
||||||
|
this->packetQueue.push(packet);
|
||||||
|
}
|
||||||
|
@@ -80,6 +83,7 @@
|
||||||
|
BELL_SLEEP_MS(100);
|
||||||
|
|
||||||
|
lastPingTimestamp = timeProvider->getSyncedTimestamp();
|
||||||
|
+ pongPending = false; // a Ping on the old connection needs no Pong on the new one
|
||||||
|
isReconnecting = false;
|
||||||
|
|
||||||
|
this->executeEstabilishedCallback = true;
|
||||||
|
@@ -98,9 +102,30 @@
|
||||||
|
this->connectionReadyCallback = callback;
|
||||||
|
}
|
||||||
|
|
||||||
|
+void MercurySession::sendPendingPong() {
|
||||||
|
+ if (!pongPending ||
|
||||||
|
+ timeProvider->getSyncedTimestamp() < pongDueTimestamp)
|
||||||
|
+ return;
|
||||||
|
+ pongPending = false;
|
||||||
|
+ std::shared_ptr<ShannonConnection> shanConn;
|
||||||
|
+ {
|
||||||
|
+ std::scoped_lock lock(connMutex);
|
||||||
|
+ shanConn = this->shanConn;
|
||||||
|
+ }
|
||||||
|
+ if (!shanConn)
|
||||||
|
+ return;
|
||||||
|
+ try {
|
||||||
|
+ shanConn->sendPacket(0x49, pongData);
|
||||||
|
+ CSPOT_LOG(info, "Sent delayed Pong");
|
||||||
|
+ } catch (...) {
|
||||||
|
+ CSPOT_LOG(error, "Failed to send Pong");
|
||||||
|
+ }
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
bool MercurySession::triggerTimeout() {
|
||||||
|
if (!isRunning)
|
||||||
|
return true;
|
||||||
|
+ sendPendingPong();
|
||||||
|
auto currentTimestamp = timeProvider->getSyncedTimestamp();
|
||||||
|
|
||||||
|
if (currentTimestamp - this->lastPingTimestamp > PING_TIMEOUT_MS) {
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
diff --git a/cspot/include/SpircHandler.h b/cspot/include/SpircHandler.h
|
||||||
|
index 7ff930b..c17caa0 100644
|
||||||
|
--- a/cspot/include/SpircHandler.h
|
||||||
|
+++ b/cspot/include/SpircHandler.h
|
||||||
|
@@ -44,6 +44,9 @@ class SpircHandler {
|
||||||
|
|
||||||
|
void subscribeToMercury();
|
||||||
|
std::shared_ptr<TrackPlayer> getTrackPlayer();
|
||||||
|
+ // Read access for the host (now-playing info: track position, play state).
|
||||||
|
+ std::shared_ptr<PlaybackState> getPlaybackState() { return playbackState; }
|
||||||
|
+ std::shared_ptr<cspot::Context> getContext() { return ctx; }
|
||||||
|
|
||||||
|
void setEventHandler(EventHandler handler);
|
||||||
|
|
||||||
@@ -0,0 +1,563 @@
|
|||||||
|
#include "spotify.h"
|
||||||
|
|
||||||
|
#include <atomic>
|
||||||
|
#include <cstring>
|
||||||
|
#include <exception>
|
||||||
|
#include <deque>
|
||||||
|
#include <map>
|
||||||
|
#include <memory>
|
||||||
|
#include <mutex>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
#include "BellLogger.h"
|
||||||
|
#include "CSpotContext.h"
|
||||||
|
#include "LoginBlob.h"
|
||||||
|
#include "PlaybackState.h"
|
||||||
|
#include "SpircHandler.h"
|
||||||
|
#include "TrackPlayer.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/task.h"
|
||||||
|
#include "mdns.h"
|
||||||
|
|
||||||
|
extern "C" {
|
||||||
|
#include "aes67_cfg.h"
|
||||||
|
#include "aes67_web.h"
|
||||||
|
}
|
||||||
|
|
||||||
|
#define BODY_MAX 8192
|
||||||
|
|
||||||
|
static const char *TAG = "spotify";
|
||||||
|
|
||||||
|
static std::shared_ptr<cspot::LoginBlob> s_blob; // guarded by s_mutex
|
||||||
|
static std::mutex s_mutex;
|
||||||
|
static std::string s_name; // advertised device name ("" = not advertised)
|
||||||
|
static std::atomic<bool> s_enabled{false};
|
||||||
|
static std::atomic<bool> s_want{false}; // last spotify_apply(): the player needs Spotify
|
||||||
|
static std::atomic<bool> s_stop{false}; // end the running session
|
||||||
|
static std::atomic<bool> s_got_blob{false};
|
||||||
|
static std::atomic<bool> s_in_session{false}; // session() running (its tasks may exist)
|
||||||
|
static std::atomic<int> s_volume{65535}; // player volume in Spotify units (0..65535)
|
||||||
|
static std::atomic<const char *> s_state{"disabled"};
|
||||||
|
static std::atomic<uint64_t> s_pcm_bytes{0};
|
||||||
|
static std::shared_ptr<cspot::SpircHandler> s_handler; // running session, else null
|
||||||
|
static spotify_pcm_cb_t s_pcm_cb;
|
||||||
|
static spotify_event_cb_t s_event_cb;
|
||||||
|
static spotify_pos_cb_t s_written, s_played;
|
||||||
|
|
||||||
|
// Track boundaries in the output buffer: when playback passes one, the new track is audible and
|
||||||
|
// Spotify must be told (notifyAudioReachedPlayback); without it the app's state stalls after the
|
||||||
|
// first track and it drops the device. Guarded by s_bound_mutex (data callback vs session loop).
|
||||||
|
struct Boundary {
|
||||||
|
uint32_t pos;
|
||||||
|
std::string id;
|
||||||
|
};
|
||||||
|
static std::mutex s_bound_mutex;
|
||||||
|
static std::deque<Boundary> s_bounds;
|
||||||
|
static std::string s_last_id; // track of the most recent data callback
|
||||||
|
static std::atomic<bool> s_depleted{false};
|
||||||
|
|
||||||
|
static std::mutex s_cmd_mutex;
|
||||||
|
enum { CMD_VOLUME = 100 }; // internal: push s_volume to the app
|
||||||
|
struct Command {
|
||||||
|
int cmd; // spotify_cmd_t or CMD_VOLUME
|
||||||
|
uint32_t arg;
|
||||||
|
};
|
||||||
|
static std::deque<Command> s_cmds; // from spotify_command(), run by the session loop
|
||||||
|
static uint32_t s_cmd_queued; // commands queued so far (s_cmd_mutex)
|
||||||
|
static std::atomic<uint32_t> s_cmd_done{0}; // commands run so far
|
||||||
|
|
||||||
|
static std::mutex s_track_mutex;
|
||||||
|
static cspot::TrackInfo s_track; // audible track (TRACK_INFO), guarded by s_track_mutex
|
||||||
|
|
||||||
|
static void clear_boundaries(bool new_load)
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(s_bound_mutex);
|
||||||
|
s_bounds.clear();
|
||||||
|
if (new_load) {
|
||||||
|
s_last_id.clear(); // the next data (new track) marks a boundary
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Session loop, every <= 200 ms.
|
||||||
|
static void check_playback(const std::shared_ptr<cspot::SpircHandler> &handler)
|
||||||
|
{
|
||||||
|
if (!s_written || !s_played) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
uint32_t played = s_played();
|
||||||
|
std::string reached;
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(s_bound_mutex);
|
||||||
|
while (!s_bounds.empty() && (int32_t)(played - s_bounds.front().pos) >= 0) {
|
||||||
|
reached = s_bounds.front().id; // latest boundary passed wins
|
||||||
|
s_bounds.pop_front();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!reached.empty()) {
|
||||||
|
handler->notifyAudioReachedPlayback(reached);
|
||||||
|
ESP_LOGI(TAG, "track audible, Spotify notified");
|
||||||
|
}
|
||||||
|
if (s_depleted && played == s_written()) {
|
||||||
|
s_depleted = false;
|
||||||
|
handler->notifyAudioEnded();
|
||||||
|
ESP_LOGI(TAG, "playlist ended, Spotify notified");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extern "C" void spotify_suspend(bool suspend)
|
||||||
|
{
|
||||||
|
if (!suspend) {
|
||||||
|
spotify_apply(s_want);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
s_enabled = false;
|
||||||
|
s_stop = true;
|
||||||
|
s_got_blob = false;
|
||||||
|
s_state = "suspended";
|
||||||
|
for (int i = 0; i < 30 && s_in_session; i++) { // session loop exits within 200 ms, then disconnect
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(100));
|
||||||
|
}
|
||||||
|
ESP_LOGI(TAG, "suspended%s", s_in_session ? " (session still ending)" : "");
|
||||||
|
}
|
||||||
|
|
||||||
|
extern "C" void spotify_set_volume(int pct)
|
||||||
|
{
|
||||||
|
pct = pct < 0 ? 0 : pct > 100 ? 100 : pct;
|
||||||
|
int v = pct * 65535 / 100;
|
||||||
|
if (v == s_volume) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
s_volume = v;
|
||||||
|
if (s_handler) {
|
||||||
|
std::lock_guard<std::mutex> lock(s_cmd_mutex);
|
||||||
|
s_cmds.push_back({ CMD_VOLUME, 0 });
|
||||||
|
++s_cmd_queued;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extern "C" bool spotify_command(spotify_cmd_t cmd, uint32_t arg)
|
||||||
|
{
|
||||||
|
if (!s_handler) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
uint32_t seq;
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(s_cmd_mutex);
|
||||||
|
s_cmds.push_back({ cmd, arg });
|
||||||
|
seq = ++s_cmd_queued;
|
||||||
|
}
|
||||||
|
// Wait until it has run (the loop runs every <= 200 ms), so callers can report the new state.
|
||||||
|
for (int i = 0; i < 50 && (int32_t)(s_cmd_done - seq) < 0 && s_handler; i++) {
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(20));
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Session loop: run queued commands on the task that also handles Spotify's frames.
|
||||||
|
static void run_commands(const std::shared_ptr<cspot::SpircHandler> &handler)
|
||||||
|
{
|
||||||
|
std::deque<Command> cmds;
|
||||||
|
uint32_t seq;
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(s_cmd_mutex);
|
||||||
|
cmds.swap(s_cmds);
|
||||||
|
seq = s_cmd_queued;
|
||||||
|
}
|
||||||
|
for (auto [cmd, arg] : cmds) {
|
||||||
|
switch (cmd) {
|
||||||
|
case SPOTIFY_CMD_PLAY:
|
||||||
|
case SPOTIFY_CMD_PAUSE:
|
||||||
|
handler->setPause(cmd == SPOTIFY_CMD_PAUSE); // notifies the app, sends PLAY_PAUSE
|
||||||
|
break;
|
||||||
|
case SPOTIFY_CMD_NEXT:
|
||||||
|
case SPOTIFY_CMD_PREV:
|
||||||
|
// The new track's load notifies the app and flushes our buffer (PLAYBACK_START).
|
||||||
|
if (!(cmd == SPOTIFY_CMD_NEXT ? handler->nextSong() : handler->previousSong())) {
|
||||||
|
ESP_LOGW(TAG, "no %s track", cmd == SPOTIFY_CMD_NEXT ? "next" : "previous");
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case SPOTIFY_CMD_SEEK:
|
||||||
|
// As for a seek from the app (SpircHandler::handleFrame): the buffered audio is void.
|
||||||
|
handler->getTrackPlayer()->seekMs(arg ? arg : 1); // 0 means "no seek" to TrackPlayer
|
||||||
|
handler->updatePositionMs(arg); // notifies the app
|
||||||
|
clear_boundaries(false);
|
||||||
|
s_depleted = false;
|
||||||
|
if (s_event_cb) {
|
||||||
|
s_event_cb(SPOTIFY_EV_FLUSH, 0);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case CMD_VOLUME:
|
||||||
|
handler->setRemoteVolume(s_volume); // notifies the app
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
ESP_LOGI(TAG, "command %d %lu", cmd, (unsigned long)arg);
|
||||||
|
}
|
||||||
|
s_cmd_done = seq;
|
||||||
|
}
|
||||||
|
|
||||||
|
extern "C" bool spotify_session_active(void)
|
||||||
|
{
|
||||||
|
return s_handler != nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
extern "C" bool spotify_now_playing(spotify_track_t *t)
|
||||||
|
{
|
||||||
|
auto h = s_handler;
|
||||||
|
if (!h) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(s_track_mutex);
|
||||||
|
strlcpy(t->artist, s_track.artist.c_str(), sizeof(t->artist));
|
||||||
|
strlcpy(t->title, s_track.name.c_str(), sizeof(t->title));
|
||||||
|
strlcpy(t->album, s_track.album.c_str(), sizeof(t->album));
|
||||||
|
t->duration_ms = s_track.duration;
|
||||||
|
}
|
||||||
|
// Same position the app shows: last reported position, plus the time since while playing.
|
||||||
|
const auto &st = h->getPlaybackState()->innerFrame.state;
|
||||||
|
t->paused = st.status != PlayStatus_kPlayStatusPlay;
|
||||||
|
uint64_t pos = st.position_ms;
|
||||||
|
if (!t->paused) {
|
||||||
|
pos += h->getContext()->timeProvider->getSyncedTimestamp() - st.position_measured_at;
|
||||||
|
}
|
||||||
|
t->position_ms = t->duration_ms && pos > t->duration_ms ? t->duration_ms : (uint32_t)pos;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *spotify_state(void)
|
||||||
|
{
|
||||||
|
return s_state.load();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----- cspot/bell logging -> esp_log (UART + syslog) ----- */
|
||||||
|
|
||||||
|
// cspot logs through bell::bellGlobalLogger; without one, CSPOT_LOG dereferences NULL.
|
||||||
|
class EspLogger : public bell::AbstractLogger {
|
||||||
|
static void out(esp_log_level_t lvl, const std::string &file, int line, const std::string &sub,
|
||||||
|
const char *fmt, va_list ap)
|
||||||
|
{
|
||||||
|
char msg[256];
|
||||||
|
vsnprintf(msg, sizeof(msg), fmt, ap);
|
||||||
|
// CDN URLs carry signed tokens: keep them out of the log (syslog may leave the box).
|
||||||
|
char *q = strstr(msg, "?__token__=");
|
||||||
|
if (q) {
|
||||||
|
strcpy(q, "?__token__=...");
|
||||||
|
}
|
||||||
|
size_t slash = file.find_last_of('/');
|
||||||
|
const char *base = file.c_str() + (slash == std::string::npos ? 0 : slash + 1);
|
||||||
|
ESP_LOG_LEVEL(lvl, sub.empty() ? "cspot" : sub.c_str(), "%s:%d: %s", base, line, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
public:
|
||||||
|
void debug(std::string file, int line, std::string sub, const char *fmt, ...) override
|
||||||
|
{
|
||||||
|
va_list ap;
|
||||||
|
va_start(ap, fmt);
|
||||||
|
out(ESP_LOG_DEBUG, file, line, sub, fmt, ap);
|
||||||
|
va_end(ap);
|
||||||
|
}
|
||||||
|
void info(std::string file, int line, std::string sub, const char *fmt, ...) override
|
||||||
|
{
|
||||||
|
va_list ap;
|
||||||
|
va_start(ap, fmt);
|
||||||
|
out(ESP_LOG_INFO, file, line, sub, fmt, ap);
|
||||||
|
va_end(ap);
|
||||||
|
}
|
||||||
|
void error(std::string file, int line, std::string sub, const char *fmt, ...) override
|
||||||
|
{
|
||||||
|
va_list ap;
|
||||||
|
va_start(ap, fmt);
|
||||||
|
out(ESP_LOG_ERROR, file, line, sub, fmt, ap);
|
||||||
|
va_end(ap);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/* ----- zeroconf (Spotify Connect discovery) on our httpd ----- */
|
||||||
|
|
||||||
|
static std::shared_ptr<cspot::LoginBlob> blob()
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(s_mutex);
|
||||||
|
return s_blob;
|
||||||
|
}
|
||||||
|
|
||||||
|
static esp_err_t info_get(httpd_req_t *req)
|
||||||
|
{
|
||||||
|
auto b = blob();
|
||||||
|
if (!s_enabled || !b) {
|
||||||
|
return httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "Spotify Connect is disabled");
|
||||||
|
}
|
||||||
|
std::string json = b->buildZeroconfInfo();
|
||||||
|
httpd_resp_set_type(req, "application/json");
|
||||||
|
return httpd_resp_send(req, json.data(), json.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::string url_decode(const char *s, size_t n)
|
||||||
|
{
|
||||||
|
std::string out;
|
||||||
|
for (size_t i = 0; i < n; i++) {
|
||||||
|
if (s[i] == '+') {
|
||||||
|
out += ' ';
|
||||||
|
} else if (s[i] == '%' && i + 2 < n && isxdigit((unsigned char)s[i + 1]) && isxdigit((unsigned char)s[i + 2])) {
|
||||||
|
char hex[3] = { s[i + 1], s[i + 2], 0 };
|
||||||
|
out += (char)strtol(hex, nullptr, 16);
|
||||||
|
i += 2;
|
||||||
|
} else {
|
||||||
|
out += s[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The Spotify app posts its login blob (action=addUser&userName=...&blob=...&clientKey=...).
|
||||||
|
static esp_err_t info_post(httpd_req_t *req)
|
||||||
|
{
|
||||||
|
auto b = blob();
|
||||||
|
if (!s_enabled || !b) {
|
||||||
|
return httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "Spotify Connect is disabled");
|
||||||
|
}
|
||||||
|
if (req->content_len == 0 || req->content_len > BODY_MAX) {
|
||||||
|
return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "bad body");
|
||||||
|
}
|
||||||
|
std::string body(req->content_len, '\0');
|
||||||
|
size_t got = 0;
|
||||||
|
while (got < body.size()) {
|
||||||
|
int r = httpd_req_recv(req, body.data() + got, body.size() - got);
|
||||||
|
if (r <= 0) {
|
||||||
|
return ESP_FAIL;
|
||||||
|
}
|
||||||
|
got += r;
|
||||||
|
}
|
||||||
|
std::map<std::string, std::string> query;
|
||||||
|
size_t pos = 0;
|
||||||
|
while (pos < body.size()) {
|
||||||
|
size_t amp = body.find('&', pos), end = amp == std::string::npos ? body.size() : amp;
|
||||||
|
size_t eq = body.find('=', pos);
|
||||||
|
if (eq != std::string::npos && eq < end) {
|
||||||
|
query[url_decode(&body[pos], eq - pos)] = url_decode(&body[eq + 1], end - eq - 1);
|
||||||
|
}
|
||||||
|
pos = end + 1;
|
||||||
|
}
|
||||||
|
ESP_LOGI(TAG, "zeroconf %s from \"%s\"", query["action"].c_str(), query["userName"].c_str());
|
||||||
|
b->loadZeroconfQuery(query);
|
||||||
|
s_got_blob = true;
|
||||||
|
static const char ok[] = "{\"status\":101,\"spotifyError\":0,\"statusString\":\"ERROR-OK\"}";
|
||||||
|
httpd_resp_set_type(req, "application/json");
|
||||||
|
return httpd_resp_send(req, ok, sizeof(ok) - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----- session ----- */
|
||||||
|
|
||||||
|
static const char *event_name(cspot::SpircHandler::EventType t)
|
||||||
|
{
|
||||||
|
using E = cspot::SpircHandler::EventType;
|
||||||
|
switch (t) {
|
||||||
|
case E::PLAY_PAUSE: return "PLAY_PAUSE";
|
||||||
|
case E::VOLUME: return "VOLUME";
|
||||||
|
case E::TRACK_INFO: return "TRACK_INFO";
|
||||||
|
case E::DISC: return "DISC";
|
||||||
|
case E::NEXT: return "NEXT";
|
||||||
|
case E::PREV: return "PREV";
|
||||||
|
case E::SEEK: return "SEEK";
|
||||||
|
case E::DEPLETED: return "DEPLETED";
|
||||||
|
case E::FLUSH: return "FLUSH";
|
||||||
|
case E::PLAYBACK_START: return "PLAYBACK_START";
|
||||||
|
}
|
||||||
|
return "?";
|
||||||
|
}
|
||||||
|
|
||||||
|
static void session(void)
|
||||||
|
{
|
||||||
|
cJSON *src = cfg_get("source");
|
||||||
|
std::string client_id = cJSON_GetObjectItemCaseSensitive(src, "spotify_client_id")->valuestring;
|
||||||
|
std::string client_secret = cJSON_GetObjectItemCaseSensitive(src, "spotify_client_secret")->valuestring;
|
||||||
|
int bitrate = (int)cJSON_GetObjectItemCaseSensitive(src, "spotify_bitrate")->valuedouble;
|
||||||
|
cJSON_Delete(src);
|
||||||
|
|
||||||
|
auto login = blob();
|
||||||
|
auto ctx = cspot::Context::createFromBlob(login);
|
||||||
|
ctx->config.clientId = client_id;
|
||||||
|
ctx->config.clientSecret = client_secret;
|
||||||
|
ctx->config.audioFormat = bitrate >= 320 ? AudioFormat_OGG_VORBIS_320
|
||||||
|
: bitrate >= 160 ? AudioFormat_OGG_VORBIS_160 : AudioFormat_OGG_VORBIS_96;
|
||||||
|
// createFromBlob() starts at volume 0, which the app would show; report what we actually play.
|
||||||
|
ctx->config.volume = s_volume;
|
||||||
|
s_state = "connecting";
|
||||||
|
ctx->session->connectWithRandomAp();
|
||||||
|
auto token = ctx->session->authenticate(login);
|
||||||
|
if (token.empty()) {
|
||||||
|
s_state = "login failed";
|
||||||
|
ESP_LOGE(TAG, "login failed (check the client ID/secret and that the account is Premium)");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ctx->session->startTask();
|
||||||
|
auto handler = std::make_shared<cspot::SpircHandler>(ctx);
|
||||||
|
handler->subscribeToMercury();
|
||||||
|
// PCM (44.1 kHz stereo s16) to the player; returning fewer bytes makes cspot retry the rest,
|
||||||
|
// so the player's blocking write paces decoding to playback speed.
|
||||||
|
handler->getTrackPlayer()->setDataCallback([](uint8_t *data, size_t len, std::string_view id) -> size_t {
|
||||||
|
if (s_written) {
|
||||||
|
// First data of a new track: it becomes audible when playback reaches this position.
|
||||||
|
std::lock_guard<std::mutex> lock(s_bound_mutex);
|
||||||
|
if (id != s_last_id) {
|
||||||
|
s_last_id = std::string(id);
|
||||||
|
s_bounds.push_back({ s_written(), s_last_id });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
size_t frames = len / 4;
|
||||||
|
size_t taken = s_pcm_cb ? s_pcm_cb(reinterpret_cast<const int16_t *>(data), frames) : frames;
|
||||||
|
s_pcm_bytes += taken * 4;
|
||||||
|
return taken * 4;
|
||||||
|
});
|
||||||
|
handler->setEventHandler([](std::unique_ptr<cspot::SpircHandler::Event> ev) {
|
||||||
|
using E = cspot::SpircHandler::EventType;
|
||||||
|
switch (ev->eventType) {
|
||||||
|
case E::TRACK_INFO: {
|
||||||
|
auto &ti = std::get<cspot::TrackInfo>(ev->data);
|
||||||
|
ESP_LOGI(TAG, "track: %s - %s (%lu ms)", ti.artist.c_str(), ti.name.c_str(), (unsigned long)ti.duration);
|
||||||
|
std::lock_guard<std::mutex> lock(s_track_mutex);
|
||||||
|
s_track = ti;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case E::PLAY_PAUSE:
|
||||||
|
if (s_event_cb) {
|
||||||
|
s_event_cb(std::get<bool>(ev->data) ? SPOTIFY_EV_PAUSE : SPOTIFY_EV_PLAY, 0);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case E::FLUSH:
|
||||||
|
case E::SEEK:
|
||||||
|
case E::PLAYBACK_START:
|
||||||
|
// The output buffer is dropped: pending boundaries are void. A new load (PLAYBACK_START)
|
||||||
|
// gets a new boundary with its first data; a seek stays within the same track.
|
||||||
|
clear_boundaries(ev->eventType == E::PLAYBACK_START);
|
||||||
|
s_depleted = false;
|
||||||
|
if (s_event_cb) {
|
||||||
|
s_event_cb(SPOTIFY_EV_FLUSH, 0);
|
||||||
|
if (ev->eventType == E::PLAYBACK_START) {
|
||||||
|
s_event_cb(SPOTIFY_EV_PLAY, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case E::VOLUME:
|
||||||
|
s_volume = std::get<int>(ev->data); // exact value from the app, no echo back
|
||||||
|
if (s_event_cb) {
|
||||||
|
s_event_cb(SPOTIFY_EV_VOLUME, std::get<int>(ev->data));
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case E::DEPLETED:
|
||||||
|
s_depleted = true; // queue done: tell Spotify once the buffer has played out
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
ESP_LOGI(TAG, "event %s", event_name(ev->eventType));
|
||||||
|
});
|
||||||
|
s_handler = handler;
|
||||||
|
s_state = "connected";
|
||||||
|
ESP_LOGI(TAG, "connected as %s", ctx->config.username.c_str());
|
||||||
|
clear_boundaries(true);
|
||||||
|
s_depleted = false;
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(s_cmd_mutex);
|
||||||
|
s_cmds.clear();
|
||||||
|
s_cmd_done = s_cmd_queued;
|
||||||
|
}
|
||||||
|
while (!s_stop) {
|
||||||
|
ctx->session->handlePacket(); // waits at most 200 ms
|
||||||
|
run_commands(handler);
|
||||||
|
check_playback(handler);
|
||||||
|
}
|
||||||
|
// Stops the queue and player tasks (waits for them), then closes the connection.
|
||||||
|
s_handler.reset();
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(s_track_mutex);
|
||||||
|
s_track = {};
|
||||||
|
}
|
||||||
|
handler->disconnect();
|
||||||
|
ESP_LOGI(TAG, "session ended");
|
||||||
|
}
|
||||||
|
|
||||||
|
static void spotify_task(void *arg)
|
||||||
|
{
|
||||||
|
while (true) {
|
||||||
|
while (!s_enabled || !s_got_blob) {
|
||||||
|
if (s_enabled) {
|
||||||
|
s_state = "waiting for Spotify app";
|
||||||
|
}
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(500));
|
||||||
|
}
|
||||||
|
s_got_blob = false;
|
||||||
|
s_stop = false;
|
||||||
|
s_in_session = true;
|
||||||
|
try {
|
||||||
|
session();
|
||||||
|
} catch (const std::exception &e) {
|
||||||
|
s_state = "error";
|
||||||
|
ESP_LOGE(TAG, "session ended: %s", e.what());
|
||||||
|
}
|
||||||
|
s_handler.reset();
|
||||||
|
s_in_session = false;
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(2000));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extern "C" void spotify_apply(bool enable)
|
||||||
|
{
|
||||||
|
s_want = enable;
|
||||||
|
cJSON *src = cfg_get("source");
|
||||||
|
std::string name = cJSON_GetObjectItemCaseSensitive(src, "spotify_name")->valuestring;
|
||||||
|
bool creds = cJSON_GetObjectItemCaseSensitive(src, "spotify_client_id")->valuestring[0] &&
|
||||||
|
cJSON_GetObjectItemCaseSensitive(src, "spotify_client_secret")->valuestring[0];
|
||||||
|
cJSON_Delete(src);
|
||||||
|
bool want = enable && creds;
|
||||||
|
|
||||||
|
if (!want || name != s_name) {
|
||||||
|
// Disable, or re-advertise under a new name: end any session, drop the old entry.
|
||||||
|
s_enabled = false;
|
||||||
|
s_stop = true;
|
||||||
|
s_got_blob = false;
|
||||||
|
if (!s_name.empty()) {
|
||||||
|
mdns_service_remove("_spotify-connect", "_tcp");
|
||||||
|
ESP_LOGI(TAG, "Spotify Connect \"%s\" withdrawn", s_name.c_str());
|
||||||
|
s_name.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!want) {
|
||||||
|
s_state = !creds ? "no client credentials" : "disabled (source mode)";
|
||||||
|
if (!creds && enable) {
|
||||||
|
ESP_LOGW(TAG, "not started: set the Spotify client ID and secret (web UI, Source)");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (s_name.empty()) {
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(s_mutex);
|
||||||
|
s_blob = std::make_shared<cspot::LoginBlob>(name);
|
||||||
|
}
|
||||||
|
mdns_txt_item_t txt[] = { { "VERSION", "1.0" }, { "CPath", "/spotify_info" }, { "Stack", "SP" } };
|
||||||
|
esp_err_t err = mdns_service_add(name.c_str(), "_spotify-connect", "_tcp", 80, txt, 3);
|
||||||
|
s_name = name;
|
||||||
|
ESP_LOGI(TAG, "Spotify Connect \"%s\" advertised (%s)", name.c_str(), esp_err_to_name(err));
|
||||||
|
}
|
||||||
|
s_enabled = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
extern "C" esp_err_t spotify_init(spotify_pcm_cb_t pcm, spotify_event_cb_t event, spotify_pos_cb_t written,
|
||||||
|
spotify_pos_cb_t played)
|
||||||
|
{
|
||||||
|
s_pcm_cb = pcm;
|
||||||
|
s_event_cb = event;
|
||||||
|
s_written = written;
|
||||||
|
s_played = played;
|
||||||
|
if (!bell::bellGlobalLogger) {
|
||||||
|
bell::bellGlobalLogger = new EspLogger();
|
||||||
|
}
|
||||||
|
static const httpd_uri_t get = { .uri = "/spotify_info", .method = HTTP_GET, .handler = info_get, .user_ctx = nullptr };
|
||||||
|
static const httpd_uri_t post = { .uri = "/spotify_info", .method = HTTP_POST, .handler = info_post, .user_ctx = nullptr };
|
||||||
|
web_register_uri(&get);
|
||||||
|
web_register_uri(&post);
|
||||||
|
if (xTaskCreate(spotify_task, "spotify", 32 * 1024, nullptr, 5, nullptr) != pdPASS) {
|
||||||
|
return ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
|
return ESP_OK; // the player enables it (spotify_apply)
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
dependencies:
|
||||||
|
espressif/esp_audio_codec:
|
||||||
|
component_hash: 16e2880dbdd5a72264051f750f33a6e5a38fd25621c83e3a32a85a152d2d2643
|
||||||
|
dependencies:
|
||||||
|
- name: idf
|
||||||
|
require: private
|
||||||
|
version: '>=4.4'
|
||||||
|
source:
|
||||||
|
registry_url: https://components.espressif.com/
|
||||||
|
type: service
|
||||||
|
version: 2.5.0
|
||||||
|
espressif/esp_audio_effects:
|
||||||
|
component_hash: 6ad72ee106e25b07c9ae5b8ec77b566ef8d697473095f1c982e13247005b9ba6
|
||||||
|
dependencies:
|
||||||
|
- name: espressif/gmf_fft
|
||||||
|
registry_url: https://components.espressif.com
|
||||||
|
require: private
|
||||||
|
version: ~1.0
|
||||||
|
source:
|
||||||
|
registry_url: https://components.espressif.com/
|
||||||
|
type: service
|
||||||
|
version: 1.3.0~1
|
||||||
|
espressif/gmf_fft:
|
||||||
|
component_hash: b59451ef2f96d22b80c27a162515b21f1b85954dda434c0b092172164028779d
|
||||||
|
dependencies: []
|
||||||
|
source:
|
||||||
|
registry_url: https://components.espressif.com
|
||||||
|
type: service
|
||||||
|
version: 1.0.0
|
||||||
|
espressif/mdns:
|
||||||
|
component_hash: b679eafd0acae2066e2645bd91d073e33ca5be515e2545cd3c4e55a3e3bce3cb
|
||||||
|
dependencies:
|
||||||
|
- name: idf
|
||||||
|
require: private
|
||||||
|
version: '>=5.0'
|
||||||
|
source:
|
||||||
|
registry_url: https://components.espressif.com/
|
||||||
|
type: service
|
||||||
|
version: 1.13.1
|
||||||
|
idf:
|
||||||
|
source:
|
||||||
|
type: idf
|
||||||
|
version: 5.5.5
|
||||||
|
direct_dependencies:
|
||||||
|
- espressif/esp_audio_codec
|
||||||
|
- espressif/esp_audio_effects
|
||||||
|
- espressif/mdns
|
||||||
|
manifest_hash: 95404bd3492778da35a8aeee53935ee8ad13b09c56ae5fcbe77a4e921dafbb23
|
||||||
|
target: esp32p4
|
||||||
|
version: 2.0.0
|
||||||
+40
-17
@@ -6,33 +6,37 @@ Reference devices for UI and defaults: Riedel Bolero (PTP status), Riedel Direct
|
|||||||
|
|
||||||
## Web UI (web/index.html)
|
## Web UI (web/index.html)
|
||||||
- Single file, no dependencies, minimal CSS. Embed in firmware (EMBED_TXTFILES, gzip optional).
|
- Single file, no dependencies, minimal CSS. Embed in firmware (EMBED_TXTFILES, gzip optional).
|
||||||
|
- Theme: dark by default; a toggle (top right) switches to light, remembered per browser (localStorage).
|
||||||
- CORE sections: Status (incl. temperatures), PTP status (Riedel-style + Details), PTP, AES67 output, Network (+VLAN), Logging, SDP, Firmware.
|
- CORE sections: Status (incl. temperatures), PTP status (Riedel-style + Details), PTP, AES67 output, Network (+VLAN), Logging, SDP, Firmware.
|
||||||
- PROJECT blocks are marked `PROJECT START/END` in the HTML (live controls and config fieldsets) and in the script (`PROJECT` object: `title`, `def` defaults merged over core defaults, `toggle(f)`, `statusRows(st)`, `poll()`).
|
- PROJECT blocks are marked `PROJECT START/END` in the HTML (live controls and config fieldsets) and in the script (`PROJECT` object: `title`, `def` defaults merged over core defaults, `toggle(f)`, `statusRows(st)`, `poll()`).
|
||||||
- Binding: every `<input|select name="group.key">` maps to `cfg[group][key]`. Adding a setting means adding an input and a default; no other JS needed. Number inputs and numeric selects are sent as JSON numbers.
|
- Binding: every `<input|select name="group.key">` maps to `cfg[group][key]`. Adding a setting means adding an input and a default; no other JS needed. Number inputs and numeric selects are sent as JSON numbers.
|
||||||
- Status table values can be text or {cls: ok|warn|bad, text} for colour.
|
- Status table values can be text or {cls: ok|warn|bad, text} for colour.
|
||||||
- Device config is merged over defaults on load, so older firmware missing keys still renders.
|
- Device config is merged over defaults on load, so older firmware missing keys still renders.
|
||||||
- Save bumps `aes67.session_ver` (SDP o= version). Save is blocked while any field is invalid (e.g. multicast out of range).
|
- Save bumps `aes67.session_ver` (SDP o= version). Save is blocked while any field is invalid (e.g. multicast out of range).
|
||||||
- UI uses IEEE 1588-2019 terms (TimeTransmitter / TimeReceiver), like Riedel. Config/API values stay master/slave/auto.
|
- UI uses IEEE 1588-2019 terms (TimeTransmitter / TimeReceiver), like Riedel. Config/API values stay slave/auto.
|
||||||
- AES67 fields carry Riedel Director-style "Default / Range" hints.
|
- AES67 fields carry Riedel Director-style "Default / Range" hints.
|
||||||
- PTP preset buttons: "Riedel SIC defaults" and "AES67 media profile defaults" fill the form (Save to apply).
|
- PTP preset buttons: "Riedel PTP defaults" and "AES67 Media PTP defaults" fill the form (Save to apply).
|
||||||
|
|
||||||
## Config schema (core groups)
|
## Config schema (core groups)
|
||||||
- ptp: {mode: multicast|hybrid, role: slave|auto|master, domain, priority1, priority2, log_sync, log_announce, announce_timeout, log_delay_req, dscp, hw_ts}
|
- ptp: {mode: multicast|hybrid, role: slave|auto, domain, priority1, priority2, log_sync, log_announce, announce_timeout, log_delay_req, dscp} (hardware timestamps always; not configurable)
|
||||||
- aes67: {name, enabled, discovery: manual|sap, mcast, port, ttl, dscp, channels, mono_sum, encoding: L16|L24, rate, ptime, pt, ssrc, clk_offset, session_id, session_ver}
|
- aes67: {name, enabled, discovery: manual|sap, mcast, port, ttl, dscp, channels, mono_sum, encoding: L16|L24, rate: 48000 only (all sources are 48 kHz), ptime, pt, ssrc, clk_offset, session_id, session_ver}
|
||||||
- net: {hostname, vlan, web_on: both|inet|aes67, dhcp, ip, mask, gw, dns} (AES67 / untagged interface)
|
- net: {hostname, vlan, web_on: both|inet|aes67, dhcp, ip, mask, gw, dns} (AES67 / untagged interface)
|
||||||
- inet: {vlan_id, pcp, dhcp, ip, mask, gw, dns} (internet / tagged, only if net.vlan)
|
- inet: {vlan_id, pcp, dhcp, ip, mask, gw, dns} (internet / tagged, only if net.vlan)
|
||||||
- log: {syslog, host, port, level: error|warn|info|debug, facility, format: rfc5424|rfc3164}
|
- log: {syslog, host, port, level: error|warn|info|debug, facility, format: rfc5424|rfc3164}
|
||||||
|
|
||||||
## Core API
|
## Core API
|
||||||
- GET/POST /api/config (full JSON; POST validates, stores to NVS, applies live where possible, returns 4xx with message on bad values)
|
- GET/POST /api/config (full JSON; POST validates, stores to NVS, applies live where possible, returns 4xx with message on bad values)
|
||||||
- GET /api/status -> {model?, fw?, power?, ip, aes67_ip, inet_ip, inet_vlan, mac, link, tx_packets, underruns, uptime_s, heap_free, psram_free, temps:[…], ptp:{…}, …project fields}
|
- Write-only keys (`cfg_mark_secret`, e.g. passwords/client secrets): GET returns "" for them; a POST with "" keeps the stored value, null clears it. Stored in NVS in plain text (NVS encryption is not enabled).
|
||||||
|
- GET /api/status -> {model?, fw?, power?, ip, aes67_ip, mask, gw, dns, inet_ip, inet_vlan, mac, link, tx_packets, underruns, uptime_s, heap_free, psram_free, temps:[…], ptp:{…}, …project fields}
|
||||||
- model, fw, power are optional; rows only appear when present (power e.g. "PoE" / "USB" if the board can detect it).
|
- model, fw, power are optional; rows only appear when present (power e.g. "PoE" / "USB" if the board can detect it).
|
||||||
- GET /stream.sdp, POST /api/reboot, POST /api/log/test
|
- GET /stream.sdp, POST /api/reboot, POST /api/log/test
|
||||||
- Firmware: GET /api/ota, POST /api/ota, POST /api/ota/confirm, POST /api/ota/rollback (see Firmware update)
|
- Firmware: GET /api/ota, POST /api/ota, POST /api/ota/confirm, POST /api/ota/rollback (see Firmware update)
|
||||||
|
|
||||||
## Temperatures
|
## Temperatures
|
||||||
|
- `status.ip/mask/gw/dns` = the addresses in use (from DHCP or static; "" when none). With DHCP on, the UI shows them in the greyed-out static fields; unticking DHCP keeps them there as the starting point for a static setup.
|
||||||
- `status.temps` = array of {name, c, min_c, max_c, warn_c}; min/max since boot, warn_c optional. Any number of sensors; the UI renders one row per sensor and marks HIGH (red) at or above warn_c.
|
- `status.temps` = array of {name, c, min_c, max_c, warn_c}; min/max since boot, warn_c optional. Any number of sensors; the UI renders one row per sensor and marks HIGH (red) at or above warn_c.
|
||||||
- ESP32-P4: on-die sensor via the `temperature_sensor` driver (driver/temperature_sensor.h). Pick the measurement range to suit (e.g. -10..80 °C), sample every ~2 s in the health task, and report it as "SoC". It measures the die, not ambient: expect it to read well above room temperature.
|
- ESP32-P4: on-die sensor via the `temperature_sensor` driver (driver/temperature_sensor.h). Pick the measurement range to suit (e.g. -10..80 °C), sample every ~2 s in the health task, and report it as "SoC". It measures the die, not ambient: expect it to read well above room temperature.
|
||||||
|
- Implemented with range 20..100 °C (±2 °C; the warning level must lie inside the range), warn_c 85 °C. On the test board the die reads ~27 °C at idle in a cool room.
|
||||||
- Boards may add external sensors (e.g. I2C) by appending to the same array; the project or board component registers them.
|
- Boards may add external sensors (e.g. I2C) by appending to the same array; the project or board component registers them.
|
||||||
- Log a warning (goes to syslog) when crossing warn_c, with hysteresis (e.g. clear at warn_c - 5).
|
- Log a warning (goes to syslog) when crossing warn_c, with hysteresis (e.g. clear at warn_c - 5).
|
||||||
|
|
||||||
@@ -48,12 +52,23 @@ Reference devices for UI and defaults: Riedel Bolero (PTP status), Riedel Direct
|
|||||||
- Roles / BMCA dataset:
|
- Roles / BMCA dataset:
|
||||||
- slave (TimeReceiver only): clockClass 255, never transmits time.
|
- slave (TimeReceiver only): clockClass 255, never transmits time.
|
||||||
- auto (default): clockClass 248, priority1 250, priority2 250. Loses to any real GM (Riedel default 128); takes over only if none.
|
- auto (default): clockClass 248, priority1 250, priority2 250. Loses to any real GM (Riedel default 128); takes over only if none.
|
||||||
- master (preferred TimeTransmitter): clockClass 248, priority1 100 (UI suggestion, editable).
|
- To prefer this device as TimeTransmitter, use auto with a lower priority1 (e.g. 100). (A separate "master" role was dropped: it behaved like auto; a stored "master" is converted to auto at boot.)
|
||||||
- clockAccuracy 0xFE (unknown), offsetScaledLogVariance 0xFFFF, timeSource 0xA0 (internal oscillator).
|
- clockAccuracy 0xFE (unknown), offsetScaledLogVariance 0xFFFF, timeSource 0xA0 (internal oscillator).
|
||||||
- clockIdentity = EUI-64 from MAC (xx-xx-xx-FF-FE-xx-xx-xx).
|
- clockIdentity = EUI-64 from MAC (xx-xx-xx-FF-FE-xx-xx-xx).
|
||||||
- Note: Riedel Bolero reports its own clock class as 228.
|
- Note: Riedel Bolero reports its own clock class as 228.
|
||||||
- When the GM changes (including this device becoming GM): update SDP ts-refclk, bump session_ver, send SAP immediately.
|
- When the GM changes (including this device becoming GM): update SDP ts-refclk, bump session_ver, send SAP immediately.
|
||||||
- Hardware timestamping preferred (ESP32-P4 EMAC has IEEE 1588 support); software fallback flagged in status.
|
- Hardware timestamping preferred (ESP32-P4 EMAC has IEEE 1588 support); software fallback flagged in status.
|
||||||
|
- ESP32-P4 implementation (aes67_ptp):
|
||||||
|
- IDF's `examples/ethernet/ptp` (ptpd) is Layer 2 only, so it is not used. IDF's EMAC clock is used: `ETH_MAC_ESP_CMD_PTP_ENABLE`, then the IPv4/UDP snapshot bit (`emac_ll_ts_ptp_ip4_enable`), which IDF leaves off.
|
||||||
|
- RX timestamps: a hook on the driver's info input path (`esp_eth_update_input_path_info`) records port-319 event timestamps and forwards every frame to lwIP. TX: Delay_Req is a raw Eth/IPv4/UDP frame sent with `esp_eth_transmit_ctrl_vargs` for its HW timestamp. Needs `CONFIG_ETH_TRANSMIT_MUTEX`.
|
||||||
|
- Servo: step on the first Sync from a new GM (frequency seeded from the measured rate), then linuxptp-style PI (kp 0.7 / ki 0.3 at 1 Sync/s, scaled by the interval); re-step above 1 ms. Locked: 8 Syncs below 1 µs; unlocked after 3 above. GM loss keeps the frequency (holdover).
|
||||||
|
- Path delay is corrected for offset drift between t2 and t3 until the clock is syntonised; delay statistics start at lock.
|
||||||
|
- TimeTransmitter/BMCA (step 6): own dataset from the role; a foreign GM is followed only if better; LISTENING -> MASTER after the announce receipt timeout. Two-step Sync (raw frame, HW TX time in Follow_Up), Announce with the PTP timescale flag, Delay_Resp with HW RX time. Hybrid: as TimeReceiver, Delay_Req unicast to the GM (IP from Announce, MAC from its Sync) with the unicastFlag; as TimeTransmitter, a unicast Delay_Req gets a unicast Delay_Resp.
|
||||||
|
- The EMAC's PTP filter only timestamps multicast PTP; unicast Delay_Req got none. The EMAC now timestamps every received frame (`emac_ll_ts_all_enable`); the RX hook picks the port-319 PTP event messages.
|
||||||
|
- A unicast Delay_Resp carries logMessageInterval 0x7F; then ptp.log_delay_req is used.
|
||||||
|
- As GM without an earlier lock the clock starts at 0 (1970): no RTC/NTP. Media timing is unaffected; NTP seeding could follow with the internet interface (phase 2).
|
||||||
|
- Sync send times jitter by ~10 ms (FreeRTOS 100 Hz tick); accuracy is unaffected (two-step).
|
||||||
|
- Measured vs ptp4l (Intel i210 GM, non-PTP switch): lock in ~35 s cold, ~22 s after GM loss; offset within a few hundred ns; board crystal -39.8 ppm. Link asymmetry (1G GM / 100M board through a store-and-forward switch) adds a constant offset error of a few µs that no receiver can see.
|
||||||
|
|
||||||
### PTP status (`status.ptp`) — main panel modelled on Riedel Bolero "PTP Status"
|
### PTP status (`status.ptp`) — main panel modelled on Riedel Bolero "PTP Status"
|
||||||
| UI row | field(s) | notes |
|
| UI row | field(s) | notes |
|
||||||
@@ -61,15 +76,11 @@ Reference devices for UI and defaults: Riedel Bolero (PTP status), Riedel Direct
|
|||||||
| PTP State | state | INITIALIZING/LISTENING/UNCALIBRATED/SLAVE/MASTER/PASSIVE/FAULTY/DISABLED, shown as TimeReceiver/TimeTransmitter/… |
|
| PTP State | state | INITIALIZING/LISTENING/UNCALIBRATED/SLAVE/MASTER/PASSIVE/FAULTY/DISABLED, shown as TimeReceiver/TimeTransmitter/… |
|
||||||
| Lock State | locked | servo converged (e.g. \|offset\| < 1 µs for N consecutive syncs) |
|
| Lock State | locked | servo converged (e.g. \|offset\| < 1 µs for N consecutive syncs) |
|
||||||
| TimeTransmitter | gm_id | shown as MAC + "(FFFE)" when EUI-64 from MAC |
|
| TimeTransmitter | gm_id | shown as MAC + "(FFFE)" when EUI-64 from MAC |
|
||||||
| Time Offset | offset_ns | Bolero brackets in ns: <100 (green), 100-500 (green), 500-1000 (amber), 1000-10000 (red), >10000 (red); exact value in brackets |
|
| Time Offset (2 min avg) | offset_avg_ns | mean \|offset\| over the last 2 min (reset on a clock step); Bolero brackets in ns: <100 (green), 100-500 (green), 500-1000 (amber), 1000-10000 (red), >10000 (red). The current offset_ns is in Details |
|
||||||
| Frequency Deviation | freq_ppb | servo frequency correction; buckets <100 ppb, 100-500 ppb, 500 ppb-1 ppm, 1-10 ppm, 10-50 ppm, >50 ppm |
|
| Frequency Deviation | freq_ppb | servo frequency correction; buckets <100 ppb, 100-500 ppb, 500 ppb-1 ppm, 1-10 ppm, 10-50 ppm, >50 ppm |
|
||||||
| Network Delay | path_delay_ns ± path_delay_sd_ns | mean path delay ± std dev over the rolling window |
|
| Network Delay | path_delay_ns ± path_delay_sd_ns | mean path delay ± std dev over the rolling window |
|
||||||
| Hops | steps_removed | |
|
|
||||||
| Time/Frequency Traceable | gm_time_traceable, gm_freq_traceable | Announce flagField bits |
|
|
||||||
| Version | version | 2 |
|
|
||||||
| Own Clock Class | own_class | 255 / 248 per role |
|
|
||||||
|
|
||||||
Details (collapsed): clock_id, gm_class, gm_accuracy, gm_p1, gm_p2, sync_avg_ms/min/max + sync_jitter_us (measured Sync interval over the last `window` = 64 messages; RX as receiver, TX as transmitter), announce_avg_ms, delay_req/delay_resp counters, hw_ts.
|
Details (collapsed): clock_id, current offset_ns, gm_class, gm_accuracy, gm_p1, gm_p2, hops (steps_removed), time/frequency traceable (gm_time_traceable, gm_freq_traceable: Announce flagField bits), version (2), own clock class (own_class: 255 / 248 per role), sync_avg_ms/min/max + sync_jitter_us (measured Sync interval over the last `window` = 64 messages; RX as receiver, TX as transmitter), announce_avg_ms, delay_req/delay_resp counters, hw_ts.
|
||||||
When this device is the GM, offset/frequency/delay show "–".
|
When this device is the GM, offset/frequency/delay show "–".
|
||||||
|
|
||||||
## AES67 TX
|
## AES67 TX
|
||||||
@@ -81,6 +92,8 @@ When this device is the GM, offset/frequency/delay show "–".
|
|||||||
- Discovery: manual (SDP export only) or SAP. NMOS IS-04/05 is a possible future option (Riedel SIC cards have an NMOS tab).
|
- Discovery: manual (SDP export only) or SAP. NMOS IS-04/05 is a possible future option (Riedel SIC cards have an NMOS tab).
|
||||||
- SDP: v, o (aes67 IP, session_id, session_ver), s, c=mcast/ttl, t=0 0, a=clock-domain:PTPv2 <dom>, m=audio port RTP/AVP pt, a=rtpmap, a=recvonly, a=ptime, a=ts-refclk:ptp=IEEE1588-2008:<gm>:<dom>, a=mediaclk:direct.
|
- SDP: v, o (aes67 IP, session_id, session_ver), s, c=mcast/ttl, t=0 0, a=clock-domain:PTPv2 <dom>, m=audio port RTP/AVP pt, a=rtpmap, a=recvonly, a=ptime, a=ts-refclk:ptp=IEEE1588-2008:<gm>:<dom>, a=mediaclk:direct.
|
||||||
- SAP to 239.255.255.255:9875 every 30 s, plus immediately on change; deletion packet on disable or shutdown.
|
- SAP to 239.255.255.255:9875 every 30 s, plus immediately on change; deletion packet on disable or shutdown.
|
||||||
|
- Implemented (aes67_sdp_sap): SAPv1, payload type `application/sdp`, msg id hash = 16-bit hash of the SDP, TTL = aes67.ttl. The SDP is checked once a second; on a change the old hash is deleted before the new one is announced. Nothing is announced until a PTP GM is known (else ts-refclk would be all zeros). Shutdown deletion via `esp_register_shutdown_handler` (covers reboot and OTA).
|
||||||
|
- GM change: aes67.session_ver is bumped (stored via `cfg_set_number`, without re-applying the aes67 group so the stream keeps running) and SAP re-announces within 1 s. The first GM after boot is not counted as a change.
|
||||||
- Media 2 (ST 2022-7 redundancy): not possible on single-port boards like the ESP32-P4-ETH. Keep the schema open for a `mcast2`/`port2` pair on dual-NIC hardware (Riedel applies one PTP config to both Media 1 and Media 2).
|
- Media 2 (ST 2022-7 redundancy): not possible on single-port boards like the ESP32-P4-ETH. Keep the schema open for a `mcast2`/`port2` pair on dual-NIC hardware (Riedel applies one PTP config to both Media 1 and Media 2).
|
||||||
|
|
||||||
## AES67 RX (future, for receiver projects) — Riedel Director 4-wire input defaults
|
## AES67 RX (future, for receiver projects) — Riedel Director 4-wire input defaults
|
||||||
@@ -89,24 +102,34 @@ When this device is the GM, offset/frequency/delay show "–".
|
|||||||
- Channel selection: which channel of the stream feeds a mono output.
|
- Channel selection: which channel of the stream feeds a mono output.
|
||||||
|
|
||||||
## Network
|
## Network
|
||||||
- Default: one untagged interface. VLAN split option: AES67 untagged + internet tagged (inet.vlan_id/pcp) using the ESP-IDF vlan_support approach (examples/network/vlan_support, ESP32-P4 supported). AES67 side has no gateway; default route and DNS are on inet.
|
- Default: one untagged interface. VLAN split (phase 2, not implemented yet) option: AES67 untagged + internet tagged (inet.vlan_id/pcp) using the ESP-IDF vlan_support approach (examples/network/vlan_support, ESP32-P4 supported). AES67 side has no gateway; default route and DNS are on inet.
|
||||||
- PTP, RTP, SAP and IGMP bind to the AES67 netif. HTTP server filters on `web_on`.
|
- PTP, RTP, SAP and IGMP bind to the AES67 netif. HTTP server filters on `web_on`.
|
||||||
|
- DHCP sends net.hostname (option 12), so the router's lease list / local DNS shows it; after a rename it applies at the next lease renewal.
|
||||||
|
- mDNS (espressif/mdns): `<net.hostname>.local` plus the web UI as `_http._tcp` port 80. A hostname change applies live (the new name answers after ~1 s of RFC 6762 probing).
|
||||||
|
- LLDP (IEEE 802.1AB), transmit only, own code (not in IDF/lwIP): every 30 s, TTL 120 s, plus immediately on a new IP or hostname. TLVs: chassis ID and port ID = MAC, port description "eth0", system name = net.hostname, system description = project + firmware version, capabilities station-only, management address = IPv4. With the VLAN split, send it on the AES67 (untagged) side; the 802.1 port VLAN ID TLV can be added then.
|
||||||
- Switch port: AES67 as native/untagged VLAN, internet tagged, PoE on. IGMP snooping + querier on the AES67 VLAN.
|
- Switch port: AES67 as native/untagged VLAN, internet tagged, PoE on. IGMP snooping + querier on the AES67 VLAN.
|
||||||
|
|
||||||
|
## Time / NTP (phase 2, not implemented yet)
|
||||||
|
- SNTP client for wall-clock time. Servers configurable as hostnames or IPs (e.g. `pool.ntp.org`, `0.pool.ntp.org`, a local server); several allowed, tried in order; names resolved via DNS and re-resolved when a server stops answering.
|
||||||
|
- Uses: set the EMAC PTP clock to real time (TAI = UTC + 37 s) before this device becomes GM when it has not learned time from another GM (without NTP it starts at 1970); RFC 5424/3164 syslog timestamps.
|
||||||
|
- Never step the PTP clock from NTP while locked to a GM or while GM with receivers locked; only seed it before becoming GM.
|
||||||
|
- Planned config group: time: {ntp, servers[] or a comma-separated string, sync_interval_s}; the UI needs matching fields.
|
||||||
|
|
||||||
## Syslog
|
## Syslog
|
||||||
- esp_log vprintf hook (chains to UART) -> queue -> low-priority UDP task. Non-blocking, drop and count on overflow, no recursion. RFC 5424 or 3164, PRI = facility*8 + severity (E3 W4 I6 D7 V7). Strip ANSI colour codes. HOSTNAME = net.hostname, APP-NAME = log tag.
|
- esp_log vprintf hook (chains to UART) -> queue -> low-priority UDP task. Non-blocking, drop and count on overflow, no recursion. RFC 5424 or 3164, PRI = facility*8 + severity (E3 W4 I6 D7 V7). Strip ANSI colour codes. HOSTNAME = net.hostname, APP-NAME = log tag.
|
||||||
- Buffer early boot logs in the queue until the netif has an IP. POST /api/log/test sends one info-level message.
|
- Buffer early boot logs in the queue until the netif has an IP. POST /api/log/test sends one info-level message.
|
||||||
|
|
||||||
## Firmware update (OTA)
|
## Firmware update (OTA)
|
||||||
- Partition table: nvs, otadata, phy_init, ota_0, ota_1 (no factory app). Size the slots from flash_id; e.g. on 16 MB, 2 × 6 MB leaves room for growth (cspot + TLS + codecs). Keep NVS outside the app slots so config survives updates.
|
- Partition table: nvs, otadata, phy_init, ota_0, ota_1 (no factory app). Size the slots from flash_id; e.g. on 16 MB, 2 × 6 MB leaves room for growth (cspot + TLS + codecs). Keep NVS outside the app slots so config survives updates.
|
||||||
- Version: `PROJECT_VER` from `git describe --tags --dirty`, read at runtime from `esp_app_get_description()`; also reported as `status.fw`.
|
- Version: `PROJECT_VER` = `<version.txt>-<git short hash>` (e.g. `0.0.1-1d613b1`; the first part set by hand), read at runtime from `esp_app_get_description()`; also reported as `status.fw`.
|
||||||
- API:
|
- API:
|
||||||
- GET /api/ota -> {version, project, build_date, idf, running, previous, previous_version, pending_verify, can_rollback}
|
- GET /api/ota -> {version, project, build_date, idf, running, previous, previous_version, pending_verify, can_rollback}
|
||||||
- POST /api/ota: raw .bin as `application/octet-stream`, streamed with esp_ota_begin/write/end into the inactive slot (never buffered whole in RAM). 200 then reboot; 4xx with a message if rejected.
|
- POST /api/ota: raw .bin as `application/octet-stream`, streamed with esp_ota_begin/write/end into the inactive slot (never buffered whole in RAM). 200 then reboot; 4xx with a message if rejected.
|
||||||
- Upload only, by design: the device never pulls firmware from a URL or git server (no esp_https_ota, no update checks).
|
- Upload only, by design: the device never pulls firmware from a URL or git server (no esp_https_ota, no update checks).
|
||||||
- POST /api/ota/confirm: mark the running app valid. POST /api/ota/rollback: boot the previous slot.
|
- POST /api/ota/confirm: mark the running app valid. POST /api/ota/rollback: boot the previous slot.
|
||||||
- Reject before writing: wrong `project_name` in the image's app description (stops flashing another project's .bin), and an image whose chip revision range doesn't match this chip (matters on the rev < 3 boards; esp_ota_end / image verify checks the header). Reject downgrades only if a flag is set (off by default).
|
- Reject before writing (checked on the first chunk): image magic, chip ID, wrong `project_name` in the image's app description (stops flashing another project's .bin), and a chip revision outside the image's min/max range (matters on the rev < 3 boards). esp_ota_end then verifies the whole image. Reject downgrades only if a flag is set (off by default; the flag doesn't exist yet).
|
||||||
- Rollback: enable `CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE`. New firmware boots in "pending verify". Self-test after boot: Ethernet has an IP and the web server answers (optionally PTP locked within N seconds). Pass: `esp_ota_mark_app_valid_cancel_rollback()` automatically. Fail or crash before that: reboot, and the bootloader rolls back to the previous slot. The UI also offers manual confirm/rollback while pending.
|
- `previous`/`previous_version` are only reported when that slot is bootable (`esp_ota_check_rollback_is_possible()`), so a half-written upload or a rolled-back image is never offered.
|
||||||
|
- Rollback: enable `CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE`. New firmware boots in "pending verify". Self-test after boot (60 s limit): Ethernet has an IP and the web server answers (an HTTP GET of its own /api/status returns 200; optionally PTP locked within N seconds later). Test-only `CONFIG_AES67_OTA_SELFTEST_FORCE_FAIL` (sdkconfig.selftest_fail) forces a failure to test rollback. Pass: `esp_ota_mark_app_valid_cancel_rollback()` automatically. Fail or crash before that: reboot, and the bootloader rolls back to the previous slot. The UI also offers manual confirm/rollback while pending.
|
||||||
- Keep AES67 TX running during the upload if possible (OTA writes are slow flash erases; run them at lower priority than PTP/TX). Expect short audio glitches; the reboot drops the stream for a few seconds.
|
- Keep AES67 TX running during the upload if possible (OTA writes are slow flash erases; run them at lower priority than PTP/TX). Expect short audio glitches; the reboot drops the stream for a few seconds.
|
||||||
- Security: no auth yet (LAN only), like the rest of the API. Add a bearer token and optionally signed images (secure boot v2 / signed OTA) before exposing the device on an untrusted network.
|
- Security: no auth yet (LAN only), like the rest of the API. Add a bearer token and optionally signed images (secure boot v2 / signed OTA) before exposing the device on an untrusted network.
|
||||||
- UI: Firmware section: upload with progress bar, waits for the reboot and reports the new version (or that it rolled back), confirm/rollback buttons while pending.
|
- UI: Firmware section: upload with progress bar, waits for the reboot and reports the new version (or that it rolled back), confirm/rollback buttons while pending.
|
||||||
@@ -117,7 +140,7 @@ components/
|
|||||||
aes67_board/ board pin profiles (waveshare_esp32p4_eth.h, …), eth init
|
aes67_board/ board pin profiles (waveshare_esp32p4_eth.h, …), eth init
|
||||||
aes67_net/ netif setup, optional VLAN split, DSCP/PCP helpers
|
aes67_net/ netif setup, optional VLAN split, DSCP/PCP helpers
|
||||||
aes67_ptp/ PTPv2 ordinary clock: BMCA, servo, master, multicast/hybrid, EMAC HW timestamps, stats
|
aes67_ptp/ PTPv2 ordinary clock: BMCA, servo, master, multicast/hybrid, EMAC HW timestamps, stats
|
||||||
aes67_tx/ RTP sender task, PTP-paced, pull callback: size_t (*read)(int32_t *buf, size_t frames); optional mono sum
|
aes67_tx/ RTP sender task, PTP-paced, pull callback: size_t (*read)(int32_t *buf, size_t frames), always stereo (AES67_TX_SRC_CHANNELS); TX maps it to the stream (mono: L, or (L+R)/2 with mono_sum); built-in test signals: 1 kHz tone at -18 dBFS phase-locked to PTP (source NULL), pink noise at -18 dBFS RMS (aes67_tx_pink_noise)
|
||||||
aes67_sdp_sap/ SDP builder/parser + SAP announcer
|
aes67_sdp_sap/ SDP builder/parser + SAP announcer
|
||||||
aes67_syslog/ remote syslog
|
aes67_syslog/ remote syslog
|
||||||
aes67_health/ uptime, heap/PSRAM, temperature sensors (temps[] with min/max/warn)
|
aes67_health/ uptime, heap/PSRAM, temperature sensors (temps[] with min/max/warn)
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
Core AES67 parts (PTP, TX, SDP/SAP, network/VLAN, syslog, web UI base, config schema, component layout) are in **aes67-core-base.md**. This file covers the board and the project-specific parts.
|
Core AES67 parts (PTP, TX, SDP/SAP, network/VLAN, syslog, web UI base, config schema, component layout) are in **aes67-core-base.md**. This file covers the board and the project-specific parts.
|
||||||
|
|
||||||
## Board: Waveshare ESP32-P4-ETH (bought as ESP32-P4-POE-ETH, i.e. with PoE add-on module)
|
## Board: Waveshare ESP32-P4-ETH (bought as ESP32-P4-POE-ETH, i.e. with PoE add-on module)
|
||||||
- ESP32-P4, dual-core RISC-V HP @ 360 MHz + LP core, 32 MB in-package PSRAM, NOR flash (Waveshare wiki says 32 MB, ESPHome says 16 MB — check with `esptool.py flash_id`)
|
- ESP32-P4, dual-core RISC-V HP @ 360 MHz + LP core, 32 MB in-package PSRAM, 32 MB NOR flash (confirmed with `esptool.py flash_id`)
|
||||||
- **No Wi-Fi/BT** on this variant (the -WIFI6- variant adds an ESP32-C6). Ethernet only.
|
- **No Wi-Fi/BT** on this variant (the -WIFI6- variant adds an ESP32-C6). Ethernet only.
|
||||||
- Ethernet: IP101GRI PHY, RMII, 100 Mb, 50 MHz ref clock from PHY (25 MHz xtal), PHY addr 1
|
- Ethernet: IP101GRI PHY, RMII, 100 Mb, 50 MHz ref clock from PHY (25 MHz xtal), PHY addr 1
|
||||||
- REF_CLK 50 (EMAC_CLK_EXT_IN), TX_EN 49, TXD0 34, TXD1 35, CRS_DV 28, RXD0 29, RXD1 30, MDC 31, MDIO 52, PHY_RST/power 51
|
- REF_CLK 50 (EMAC_CLK_EXT_IN), TX_EN 49, TXD0 34, TXD1 35, CRS_DV 28, RXD0 29, RXD1 30, MDC 31, MDIO 52, PHY_RST/power 51
|
||||||
@@ -17,7 +17,8 @@ Core AES67 parts (PTP, TX, SDP/SAP, network/VLAN, syslog, web UI base, config sc
|
|||||||
- Sources: Waveshare wiki (waveshare.com/wiki/ESP32-P4-ETH), ESPHome device page (devices.esphome.io/devices/waveshare-esp32-p4-eth), espp board docs (esp-cpp.github.io/espp/dev_boards/waveshare/esp32_p4_eth.html).
|
- Sources: Waveshare wiki (waveshare.com/wiki/ESP32-P4-ETH), ESPHome device page (devices.esphome.io/devices/waveshare-esp32-p4-eth), espp board docs (esp-cpp.github.io/espp/dev_boards/waveshare/esp32_p4_eth.html).
|
||||||
|
|
||||||
## Project pipeline
|
## Project pipeline
|
||||||
source (cspot Spotify Connect | HLS player) -> decode (Vorbis/AAC/MP3) -> SRC 44.1k->48k -> volume/gain -> PSRAM ring buffer -> aes67_tx pull callback
|
source (cspot Spotify Connect | HLS player) -> decode (Vorbis/AAC/MP3) -> SRC 44.1k->48k -> PSRAM ring buffer -> volume/gain -> aes67_tx pull callback
|
||||||
|
- Volume is applied after the ring (in the pull callback) so a change is heard at once, not one ring length (4 s) later; ramped over one packet to avoid zipper noise. Curve: amplitude = (volume/100)^3 (about -18 dB at 50 %, 0 = mute). The built-in test signals (modes "tone", "pink") are not affected.
|
||||||
- Spotify Connect: cspot (feelfreelinux/cspot), needs Premium, zeroconf via mDNS (on the internet interface when VLAN split). Spotify occasionally changes auth for 3rd-party clients — expect breakage risk.
|
- Spotify Connect: cspot (feelfreelinux/cspot), needs Premium, zeroconf via mDNS (on the internet interface when VLAN split). Spotify occasionally changes auth for 3rd-party clients — expect breakage risk.
|
||||||
- HLS: HTTPS (mbedTLS), m3u8 parse (master->media playlist), segment fetch, TS demux or fMP4/ADTS, AAC decode (esp_audio_codec / esp-gmf).
|
- HLS: HTTPS (mbedTLS), m3u8 parse (master->media playlist), segment fetch, TS demux or fMP4/ADTS, AAC decode (esp_audio_codec / esp-gmf).
|
||||||
- Stereo L24/48k at 1 ms is about 3 Mbit/s on the wire; 100 Mb has plenty of headroom.
|
- Stereo L24/48k at 1 ms is about 3 Mbit/s on the wire; 100 Mb has plenty of headroom.
|
||||||
@@ -30,8 +31,10 @@ source (cspot Spotify Connect | HLS player) -> decode (Vorbis/AAC/MP3) -> SRC 44
|
|||||||
- Firmware needs Spotify events: cspot connect, disconnect, play, pause.
|
- Firmware needs Spotify events: cspot connect, disconnect, play, pause.
|
||||||
|
|
||||||
## Project config group
|
## Project config group
|
||||||
- source: {mode: spotify|hls|auto|off, spotify_name, spotify_bitrate, hls_url, autoplay, gain_db, failover_delay_s, failover_on_pause}
|
- source: {mode: spotify|hls|auto|tone|pink|off, spotify_name, spotify_bitrate, hls_url, autoplay, gain_db, failover_delay_s, failover_on_pause, spotify_client_id, spotify_client_secret}
|
||||||
|
- spotify_client_id / spotify_client_secret: each user's own Spotify developer app (developer.spotify.com, Premium account), needed by the maintained cspot fork (philippe44/cspot) since Spotify's 2025 API restrictions. The secret is write-only (never returned by GET /api/config). spotify_state reports "no client credentials" while either is missing.
|
||||||
- Project status fields: active_source, source_state, spotify_state, buffer_ms
|
- Project status fields: active_source, source_state, spotify_state, buffer_ms
|
||||||
|
- mode "tone": the core's 1 kHz / -18 dBFS test tone, phase-locked to PTP (commissioning, e.g. Riedel import tests). "pink": the core's pink noise, -18 dBFS RMS (peaks about -6 dBFS), same on L and R (level/EQ checks). Neither is affected by volume or gain. "off": silence.
|
||||||
|
|
||||||
## Player control API (project routes)
|
## Player control API (project routes)
|
||||||
- GET /api/player -> {source, forced, state(playing|paused|stopped|buffering|idle), artist, title, album, position_ms, duration_ms, volume(0-100), can:{pause,next,prev,seek}}
|
- GET /api/player -> {source, forced, state(playing|paused|stopped|buffering|idle), artist, title, album, position_ms, duration_ms, volume(0-100), can:{pause,next,prev,seek}}
|
||||||
@@ -39,6 +42,6 @@ source (cspot Spotify Connect | HLS player) -> decode (Vorbis/AAC/MP3) -> SRC 44
|
|||||||
- POST /api/player/seek {ms}; POST /api/player/volume {value} or {delta}
|
- POST /api/player/seek {ms}; POST /api/player/volume {value} or {delta}
|
||||||
- POST /api/player/source {source: spotify|hls|off|config}: runtime override, not saved; "config" returns to the configured mode
|
- POST /api/player/source {source: spotify|hls|off|config}: runtime override, not saved; "config" returns to the configured mode
|
||||||
- POST /api/player/url {url}: play an m3u8 now (runtime, not saved)
|
- POST /api/player/url {url}: play an m3u8 now (runtime, not saved)
|
||||||
- On Spotify, commands go to cspot (the Spotify app stays in sync, including volume). On HLS (live): pause = stop fetching, resume = rejoin at live edge; next/prev/seek return 409 and `can` reflects that.
|
- On Spotify, commands go to cspot (the Spotify app stays in sync, including volume). stop = pause (the session stays). prev restarts the track after its first 3 s (cspot, like the apps). After next/prev the response can still show the old track; the new one follows within ~1 s. On HLS (live): pause/stop = stop fetching, resume = rejoin at live edge (a pause lasts until the next source switch); next/prev/seek return 409 and `can` reflects that. Tone/off, or Spotify without a session: transport returns 409.
|
||||||
- Volume = runtime player volume; source.gain_db is a fixed trim on top.
|
- Volume = runtime player volume; source.gain_db is a fixed trim on top.
|
||||||
- No auth yet: LAN only.
|
- No auth yet: LAN only.
|
||||||
|
|||||||
@@ -0,0 +1,230 @@
|
|||||||
|
# P4 AES67 Streamer: user guide
|
||||||
|
|
||||||
|
The P4 AES67 Streamer turns Spotify Connect or an internet radio stream (HLS / m3u8) into an **AES67 multicast stream**, locked to your PTP clock. Any AES67 receiver on the network can play it: a Riedel Artist 4-wire port, a Dante device in AES67 mode, a DAW, and so on.
|
||||||
|
|
||||||
|
It runs on a **Waveshare ESP32-P4-ETH** board, powered over PoE, and is set up entirely from a web page.
|
||||||
|
|
||||||
|
Contents: [Getting started](#getting-started) · [The web page](#the-web-page) · [Sources](#sources) · [Spotify](#spotify) · [AES67 output](#aes67-output) · [PTP](#ptp) · [Network](#network) · [Logging](#logging) · [Firmware updates](#firmware-updates) · [Player API](#player-api) · [Troubleshooting](#troubleshooting) · [Limitations](#limitations)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Getting started
|
||||||
|
|
||||||
|
1. **Connect** the board's Ethernet port to a PoE switch port, or to a normal port and power it over USB-C. Use the same network (or VLAN) as your AES67 devices and your PTP grandmaster.
|
||||||
|
2. **Wait about 20 seconds.** The board gets an address by DHCP and locks to PTP.
|
||||||
|
3. **Open the web page** at **http://p4-aes67.local/**. Alternatively, look up the board's IP in your router's DHCP list (the name is `p4-aes67`) and open `http://<IP>/`.
|
||||||
|
4. **Pick a source** under *Source* and click **Save** (see [Sources](#sources)).
|
||||||
|
5. **On the receiver**, either find the stream via SAP, or copy the SDP from the page's *SDP* section (see [AES67 output](#aes67-output)).
|
||||||
|
|
||||||
|
Out of the box the board streams **2-channel, 24-bit, 48 kHz audio with 1 ms packets to 239.69.1.10:5004** and announces it by SAP under the name "P4 AES67".
|
||||||
|
|
||||||
|
> **More than one board?** Each board needs its own hostname, stream name and multicast address, or they clash. Change them under *Network* and *AES67 output*, or let `tools/flash_board.py` ask for them when you flash a new board.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## The web page
|
||||||
|
|
||||||
|
The page is split into sections, from top to bottom:
|
||||||
|
|
||||||
|
| Section | What it's for |
|
||||||
|
|---|---|
|
||||||
|
| **Status** | Firmware version, IP / MAC, link speed, active source, Spotify state, buffer, packets sent, underruns, uptime, memory, chip temperature. |
|
||||||
|
| **PTP status** | Whether the clock is locked, which grandmaster it follows, the time offset (bracket of the 2-minute average) and path delay. *Details* shows the current offset, hops and more. |
|
||||||
|
| **Player** | What's playing now, transport buttons, progress bar (drag to seek), volume. |
|
||||||
|
| **Source**, **PTP**, **AES67 output**, **Network**, **Logging** | Settings. They take effect only when you click **Save**. |
|
||||||
|
| **SDP** | The stream description, to copy or download for receivers. |
|
||||||
|
| **Firmware** | Update the firmware (see [Firmware updates](#firmware-updates)). |
|
||||||
|
|
||||||
|
**Saving:** *Save*, *Revert* (throw away unsaved edits) and *Reboot* stay at the bottom of the window while you scroll through the settings. Messages such as "Saved." or error texts appear next to them. Invalid values are rejected with the reason, and nothing is saved.
|
||||||
|
|
||||||
|
**Light / dark:** the page is dark by default. The **◐** button at the top right switches to light, and your browser remembers the choice.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Sources
|
||||||
|
|
||||||
|
Choose the source under **Source → Source**:
|
||||||
|
|
||||||
|
| Source | What it plays |
|
||||||
|
|---|---|
|
||||||
|
| **Spotify Connect** | The board appears as a speaker in the Spotify app (default). Needs your own Spotify app credentials; see [Spotify](#spotify). |
|
||||||
|
| **HLS / M3U8 URL** | An internet radio stream, e.g. `https://…/playlist.m3u8`. Enter it under *Stream URL*. |
|
||||||
|
| **Spotify, fail over to HLS** | Spotify when someone plays to it, otherwise the stream (see below). |
|
||||||
|
| **Test tone** | 1 kHz sine at −18 dBFS, locked to PTP. For line-up and receiver tests. |
|
||||||
|
| **Pink noise** | Pink noise at −18 dBFS RMS (peaks around −6 dBFS), the same signal on both channels. For level and EQ checks. |
|
||||||
|
| **Off** | Silence. The stream keeps running. |
|
||||||
|
|
||||||
|
### Failover (Spotify, fail over to HLS)
|
||||||
|
|
||||||
|
- **Spotify playing:** the board plays Spotify, switching over within about a second of pressing play.
|
||||||
|
- **No Spotify connection:** after *Failover delay* seconds (default 5), the board switches to the HLS stream.
|
||||||
|
- **Paused:** with **Also fail over when paused** ticked, a paused Spotify counts as "not playing" and the stream takes over after the delay. Unticked (default), a pause gives silence and the board stays on Spotify.
|
||||||
|
- **Fades:** switches fade out and in over 30 ms, so there are no clicks.
|
||||||
|
- **Resuming:** Spotify is held while the stream plays. When you press play again, the song continues where you paused.
|
||||||
|
|
||||||
|
### Volume and gain
|
||||||
|
|
||||||
|
- **Volume (Player section):** the everyday volume. With Spotify it follows the app's volume slider, and the other way round.
|
||||||
|
- **Output gain (dB):** a fixed trim on top of the volume, −60 to +12 dB. Above 0 dB, loud passages can clip at full scale.
|
||||||
|
- **Neither affects** the test tone or pink noise. Those always come out at their calibrated level.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Spotify
|
||||||
|
|
||||||
|
Since 2025, Spotify requires every Spotify Connect device to use a **developer app registered to your own account**. You need **Spotify Premium**. Setup takes about five minutes:
|
||||||
|
|
||||||
|
1. Go to **https://developer.spotify.com/dashboard** and log in.
|
||||||
|
2. **Create app**:
|
||||||
|
- Name and description: anything, e.g. "P4 AES67".
|
||||||
|
- Redirect URI: `http://127.0.0.1:8888/callback`. Spotify requires one, but this device never uses it.
|
||||||
|
- API: tick **Web API**, then save.
|
||||||
|
3. Open the app's **Settings**. Copy the **Client ID**, and click *View client secret* to copy the **Client secret**.
|
||||||
|
4. On the board's page under **Source**, paste them into **Spotify client ID** and **Spotify client secret**, then **Save**.
|
||||||
|
|
||||||
|
The secret is write-only: after saving, the field shows empty. Leave it empty to keep the stored secret, or type a new one to replace it.
|
||||||
|
|
||||||
|
**Connecting:** make sure your phone or computer is on the **same network** as the board. In the Spotify app, open the device list and pick **P4 AES67** (or the name you set under *Spotify device name*). Play, pause, skip, seek and volume all work from the app. The web page shows the track and position and can control playback too.
|
||||||
|
|
||||||
|
- **Spotify bitrate:** 96, 160 or 320 kbit/s (default 320).
|
||||||
|
- **Spotify device name:** the name shown in the app. Changing it disconnects a running session.
|
||||||
|
- **Status → Spotify** shows the state: e.g. *waiting for Spotify app*, *connected*, *no client credentials*, *login failed*.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## AES67 output
|
||||||
|
|
||||||
|
| Setting | Default | Notes |
|
||||||
|
|---|---|---|
|
||||||
|
| Stream name (s=) | P4 AES67 | The name receivers show. |
|
||||||
|
| Enabled | on | Off stops sending. |
|
||||||
|
| Discovery | SAP | **SAP**: announced every 30 s on 239.255.255.255:9875, so receivers that support SAP find it by themselves. **Manual**: no announcements; use the SDP. |
|
||||||
|
| RTP multicast IP / port | 239.69.1.10 : 5004 | Must be unique per stream on your network. |
|
||||||
|
| TTL | 32 | |
|
||||||
|
| DSCP (media) | 34 (AF41) | QoS marking for the audio packets. |
|
||||||
|
| Channels | 2 | 1 or 2. |
|
||||||
|
| Mono sum | off | Sends (left + right) / 2 as a 1-channel stream. Forces *Channels* to 1; it can't clip. |
|
||||||
|
| Bit depth | L24 | L24 or L16. |
|
||||||
|
| Sample rate | 48000 | Fixed; all sources are 48 kHz. |
|
||||||
|
| Packet time | 1 ms | 0.125, 0.25, 0.333, 1 or 4 ms. 1 ms is the AES67 default and works with nearly all receivers. |
|
||||||
|
| Payload type / SSRC / time stamp offset | 96 / 0 / 0 | Only change these if a receiver needs it. |
|
||||||
|
|
||||||
|
**Getting the SDP to a receiver:**
|
||||||
|
- **SAP:** receivers that listen for SAP (Riedel, many AES67 devices) list the stream by its name.
|
||||||
|
- **By hand:** in the *SDP* section, **Copy** or **Download .sdp** and import it on the receiver. The board also serves it at `http://p4-aes67.local/stream.sdp`.
|
||||||
|
- **When the SDP changes:** after a setting that changes the stream, the SDP gets a new version number. Re-import it on receivers that were set up by hand.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## PTP
|
||||||
|
|
||||||
|
The board locks its media clock to the PTP grandmaster on the network (IEEE 1588-2008, UDP/IPv4, E2E, always with hardware timestamps). *PTP status* shows the lock state and the grandmaster.
|
||||||
|
|
||||||
|
| Setting | Default | Notes |
|
||||||
|
|---|---|---|
|
||||||
|
| Mode | multicast | **hybrid** sends the delay requests unicast (fewer multicast packets). |
|
||||||
|
| Role | Auto | **TimeReceiver only**: never becomes grandmaster. **Auto**: becomes grandmaster only if there is none (fallback). To make this board the preferred grandmaster, keep *Auto* and set a low *Priority 1* (e.g. 100). |
|
||||||
|
| Domain | 0 | Must match your grandmaster. |
|
||||||
|
| Priority 1 / 2 | 250 / 250 | Lower wins the grandmaster election. |
|
||||||
|
| Intervals, timeout, DSCP (46) | | Presets below set them. |
|
||||||
|
|
||||||
|
**Presets:**
|
||||||
|
- **Riedel PTP defaults:** TimeReceiver only, priorities 128/126, Riedel's intervals. Use this when a Riedel system provides the clock.
|
||||||
|
- **AES67 Media PTP defaults:** the faster intervals of the AES67 profile.
|
||||||
|
|
||||||
|
A preset only fills in the fields; click **Save** to apply them.
|
||||||
|
|
||||||
|
Audio starts only when PTP is locked, usually about 20 s after power-up. When the board is itself the grandmaster (no other clock on the network), its clock starts at 1 January 1970. That's fine for AES67, but it isn't real time.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Network
|
||||||
|
|
||||||
|
- **Hostname:** the name in DHCP, mDNS (`<hostname>.local`) and LLDP (the switch's neighbour list). Changing it applies at once.
|
||||||
|
- **DHCP (default):** with DHCP on, the greyed-out IP, netmask, gateway and DNS fields show the addresses DHCP handed out.
|
||||||
|
- **Static IP:** untick **DHCP**. The current addresses stay in the fields as a starting point; edit them and **Save**. The board **reboots** to apply them, and the page switches to the new address after 20 s. The page checks that the netmask is valid, that the IP isn't the subnet's network or broadcast address, and that the gateway is in the subnet.
|
||||||
|
- **A wrong static address makes the board unreachable** over the network. Double-check before saving; see [Troubleshooting](#troubleshooting) for recovery.
|
||||||
|
- With a static IP, your router's DNS name for the board can go stale. `http://<hostname>.local/` keeps working.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Logging
|
||||||
|
|
||||||
|
The board can send its log to a syslog server (UDP):
|
||||||
|
- Tick **Send to syslog** and enter the server (hostname or IP) and port (default 514).
|
||||||
|
- **Minimum level:** Error, Warning, Info or Debug.
|
||||||
|
- **Facility and format:** RFC 5424 or RFC 3164 (BSD).
|
||||||
|
- **Send test message** checks the path.
|
||||||
|
|
||||||
|
The log shows PTP lock/unlock, source switches, stream errors and firmware updates, which makes it useful for troubleshooting.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Firmware updates
|
||||||
|
|
||||||
|
**Over the network (normal way):** in the **Firmware** section, choose the new `aes67_p4.bin` and click **Upload & install**. The board installs it to its second firmware slot and reboots into it.
|
||||||
|
- The new firmware must **prove itself** within 60 s: network up and web page answering. Only then is it kept. If it fails or crashes, the board automatically goes back to the previous firmware.
|
||||||
|
- While the new firmware is on trial, the page offers **Keep this firmware** and **Roll back to previous**.
|
||||||
|
- During the upload the Spotify session ends and the stream pauses. Reconnect from the app afterwards.
|
||||||
|
- From a computer: `curl -f --data-binary @aes67_p4.bin -H 'Content-Type: application/octet-stream' http://p4-aes67.local/api/ota`
|
||||||
|
|
||||||
|
**Over USB (new board, or recovery):** `tools/flash_board.py` (needs ESP-IDF or `pip install esptool`, plus a build). It:
|
||||||
|
- checks the board (chip revision, 32 MB flash),
|
||||||
|
- optionally erases it (this clears all settings),
|
||||||
|
- flashes the firmware and finds the board's IP,
|
||||||
|
- asks for a hostname, stream name and multicast address.
|
||||||
|
|
||||||
|
**Making an update file:**
|
||||||
|
1. Set the version in **`version.txt`** (first line, e.g. `0.0.2`) and commit your changes.
|
||||||
|
2. Build: `idf.py build`. The firmware version becomes `<version>-<commit>`, e.g. `0.0.2-1d613b1`, as shown under *Firmware* and *Status*.
|
||||||
|
3. The update file is **`build/aes67_p4.bin`**. Upload it in the *Firmware* section, or with the `curl` command above.
|
||||||
|
|
||||||
|
The .bin is for ESP32-P4 chips of **revision v1.x** (the current Waveshare boards). A board with a v3 chip needs a build for that revision; the flash script refuses it with a hint.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Player API
|
||||||
|
|
||||||
|
Everything the Player section does is also available over HTTP, e.g. for a control panel or Companion. Every command returns the current player state as JSON.
|
||||||
|
|
||||||
|
```
|
||||||
|
GET /api/player state, source, track, position, volume
|
||||||
|
POST /api/player/play | pause | toggle | stop | next | prev
|
||||||
|
POST /api/player/seek {"ms": 90000}
|
||||||
|
POST /api/player/volume {"value": 0-100} or {"delta": -5}
|
||||||
|
POST /api/player/source {"source": "spotify" | "hls" | "off" | "config"}
|
||||||
|
POST /api/player/url {"url": "https://…/playlist.m3u8"}
|
||||||
|
```
|
||||||
|
|
||||||
|
Example: `curl -X POST http://p4-aes67.local/api/player/next`
|
||||||
|
|
||||||
|
- **With Spotify:** the app follows every command. *stop* equals *pause*. *prev* restarts the song if it has played more than 3 s, like the Spotify apps.
|
||||||
|
- **With HLS (live radio):** *pause* stops downloading, and *play* rejoins the live stream. *next*, *prev* and *seek* return an error (409).
|
||||||
|
- **`source` and `url`:** temporary overrides; they're not saved, and a reboot or `"source": "config"` returns to the saved setting. `url` plays a stream right away.
|
||||||
|
- **Security:** there is no password. Keep the device on a trusted network.
|
||||||
|
|
||||||
|
The full device API (status, config, SDP, firmware) is described in `docs/aes67-core-base.md`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
| Problem | What to try |
|
||||||
|
|---|---|
|
||||||
|
| **Can't find the page** | Try `http://p4-aes67.local/`, or the IP from your router's DHCP list. If the board has a static IP you no longer know, use `tools/flash_board.py` over USB with erase (resets all settings). |
|
||||||
|
| **Board doesn't appear in the Spotify app** | Phone or computer on the same network? *Status → Spotify* should say *waiting for Spotify app*. *no client credentials*: enter ID and secret. *login failed*: check them, and check that the account is Premium. |
|
||||||
|
| **"Can't connect" in Spotify on the first try** | Try again; a second attempt usually works. |
|
||||||
|
| **Spotify controls do nothing** after a long idle session | Quit and reopen the Spotify app, then connect again. |
|
||||||
|
| **No audio at the receiver** | *PTP status* locked? *Status → AES67 TX* counting packets? The receiver on the same grandmaster and domain? After changing stream settings, re-import the SDP. |
|
||||||
|
| **Stutter or dropouts** | *Status → underruns* rising? With HLS, check the internet connection. During a firmware upload short stutters are normal. |
|
||||||
|
| **HLS stream doesn't start** | Check the URL in a browser. *Status → Source* shows *buffering* while it loads, usually for a few seconds. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Limitations
|
||||||
|
|
||||||
|
These are known limitations in the current firmware:
|
||||||
|
- **Autoplay stream on boot:** the checkbox has no effect yet. HLS always starts on boot.
|
||||||
|
- **VLAN split** (separate VLANs for AES67 and internet) isn't available yet.
|
||||||
|
- **No password** on the web page or API.
|
||||||
|
- **HLS clock drift:** the radio station's clock and PTP drift slightly apart. Over many hours of continuous playback, the stream can skip ahead to catch up with the live edge.
|
||||||
+1
Submodule external/cspot added at 3010349b46
@@ -0,0 +1,5 @@
|
|||||||
|
idf_component_register(SRCS "main.c" "project_cfg.c" "player.c" "audio_ring.c" "hls.c" "decoder.c" "audio_out.c"
|
||||||
|
INCLUDE_DIRS "."
|
||||||
|
REQUIRES esp_app_format esp_hw_support heap esp_http_client mbedtls esp_timer
|
||||||
|
aes67_board aes67_health aes67_net aes67_ota aes67_ptp aes67_sdp_sap
|
||||||
|
aes67_syslog aes67_tx aes67_web spotify)
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
#include "audio_out.h"
|
||||||
|
|
||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
|
#include "esp_ae_rate_cvt.h"
|
||||||
|
#include "esp_heap_caps.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
|
||||||
|
#define OUT_RATE 48000
|
||||||
|
#define CONV_FRAMES 4096 // per rate converter call
|
||||||
|
|
||||||
|
static const char *TAG = "audio_out";
|
||||||
|
|
||||||
|
struct audio_conv {
|
||||||
|
player_src_t src;
|
||||||
|
const char *name;
|
||||||
|
esp_ae_rate_cvt_handle_t cvt; // NULL: no conversion (source is 48 kHz)
|
||||||
|
uint32_t rate; // input rate the converter was opened for
|
||||||
|
int32_t *in32, *out32; // stereo int32 work buffers (PSRAM)
|
||||||
|
};
|
||||||
|
|
||||||
|
audio_conv_t *audio_conv_create(player_src_t src, const char *name)
|
||||||
|
{
|
||||||
|
audio_conv_t *c = calloc(1, sizeof(*c));
|
||||||
|
if (!c) {
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
c->src = src;
|
||||||
|
c->name = name;
|
||||||
|
c->in32 = heap_caps_malloc(CONV_FRAMES * 2 * sizeof(int32_t), MALLOC_CAP_SPIRAM);
|
||||||
|
c->out32 = heap_caps_malloc(CONV_FRAMES * 2 * 2 * sizeof(int32_t), MALLOC_CAP_SPIRAM);
|
||||||
|
if (!c->in32 || !c->out32) {
|
||||||
|
free(c->in32);
|
||||||
|
free(c->out32);
|
||||||
|
free(c);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void set_rate(audio_conv_t *c, uint32_t rate)
|
||||||
|
{
|
||||||
|
if (c->cvt) {
|
||||||
|
esp_ae_rate_cvt_close(c->cvt);
|
||||||
|
c->cvt = NULL;
|
||||||
|
}
|
||||||
|
c->rate = rate;
|
||||||
|
if (rate == OUT_RATE) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
esp_ae_rate_cvt_cfg_t cfg = {
|
||||||
|
.src_rate = rate, .dest_rate = OUT_RATE, .channel = 2, .bits_per_sample = 32,
|
||||||
|
.complexity = 3, .perf_type = ESP_AE_RATE_CVT_PERF_TYPE_SPEED,
|
||||||
|
};
|
||||||
|
if (esp_ae_rate_cvt_open(&cfg, &c->cvt) != ESP_AE_ERR_OK) {
|
||||||
|
ESP_LOGE(TAG, "%s: rate converter %lu -> %d Hz: open failed", c->name, (unsigned long)rate, OUT_RATE);
|
||||||
|
} else {
|
||||||
|
ESP_LOGI(TAG, "%s: rate converter %lu -> %d Hz", c->name, (unsigned long)rate, OUT_RATE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t audio_conv_write(audio_conv_t *c, const int16_t *pcm, uint32_t frames, int ch, uint32_t rate)
|
||||||
|
{
|
||||||
|
if (rate != c->rate) {
|
||||||
|
set_rate(c, rate);
|
||||||
|
}
|
||||||
|
size_t produced = 0;
|
||||||
|
while (frames) {
|
||||||
|
uint32_t n = frames < CONV_FRAMES ? frames : CONV_FRAMES;
|
||||||
|
for (uint32_t i = 0; i < n; i++) { // to stereo int32 (full scale = INT32_MAX)
|
||||||
|
int32_t l = (int32_t)pcm[i * ch] << 16;
|
||||||
|
c->in32[i * 2] = l;
|
||||||
|
c->in32[i * 2 + 1] = ch > 1 ? (int32_t)pcm[i * ch + 1] << 16 : l;
|
||||||
|
}
|
||||||
|
const int32_t *out = c->in32;
|
||||||
|
uint32_t out_n = n;
|
||||||
|
if (c->cvt) {
|
||||||
|
out_n = CONV_FRAMES * 2;
|
||||||
|
if (esp_ae_rate_cvt_process(c->cvt, c->in32, n, c->out32, &out_n) != ESP_AE_ERR_OK) {
|
||||||
|
ESP_LOGW(TAG, "%s: rate conversion failed", c->name);
|
||||||
|
return produced;
|
||||||
|
}
|
||||||
|
out = c->out32;
|
||||||
|
}
|
||||||
|
produced += player_write(c->src, out, out_n);
|
||||||
|
pcm += n * ch;
|
||||||
|
frames -= n;
|
||||||
|
}
|
||||||
|
return produced;
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
// PCM from a source (s16, any rate/channels) -> 48 kHz stereo int32 -> player ring.
|
||||||
|
// One converter per source: each keeps its own resampler state.
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <stddef.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
#include "player.h"
|
||||||
|
|
||||||
|
typedef struct audio_conv audio_conv_t;
|
||||||
|
|
||||||
|
audio_conv_t *audio_conv_create(player_src_t src, const char *name);
|
||||||
|
// Blocks while the ring is full; dropped when src is not the active source.
|
||||||
|
// Returns the 48 kHz frames produced.
|
||||||
|
size_t audio_conv_write(audio_conv_t *c, const int16_t *pcm, uint32_t frames, int channels, uint32_t rate);
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
#include "audio_ring.h"
|
||||||
|
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "esp_heap_caps.h"
|
||||||
|
|
||||||
|
static int32_t *s_buf;
|
||||||
|
static size_t s_cap; // frames
|
||||||
|
static int s_ch;
|
||||||
|
// Monotonic frame counters; level = wr - rd. Written by one side each (acquire/release).
|
||||||
|
static uint32_t s_wr, s_rd;
|
||||||
|
|
||||||
|
esp_err_t audio_ring_init(size_t capacity_frames, int channels)
|
||||||
|
{
|
||||||
|
s_buf = heap_caps_malloc(capacity_frames * channels * sizeof(int32_t), MALLOC_CAP_SPIRAM);
|
||||||
|
if (!s_buf) {
|
||||||
|
return ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
|
s_cap = capacity_frames;
|
||||||
|
s_ch = channels;
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t audio_ring_level(void)
|
||||||
|
{
|
||||||
|
return __atomic_load_n(&s_wr, __ATOMIC_ACQUIRE) - __atomic_load_n(&s_rd, __ATOMIC_ACQUIRE);
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t audio_ring_space(void)
|
||||||
|
{
|
||||||
|
return s_cap - audio_ring_level();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Copy n frames between the ring (starting at frame index pos) and a linear buffer.
|
||||||
|
static void copy(int32_t *ring_to_lin, const int32_t *lin_to_ring, uint32_t pos, size_t n)
|
||||||
|
{
|
||||||
|
size_t start = pos % s_cap;
|
||||||
|
size_t first = n < s_cap - start ? n : s_cap - start;
|
||||||
|
size_t fb = first * s_ch * sizeof(int32_t), rb = (n - first) * s_ch * sizeof(int32_t);
|
||||||
|
if (ring_to_lin) {
|
||||||
|
memcpy(ring_to_lin, s_buf + start * s_ch, fb);
|
||||||
|
memcpy(ring_to_lin + first * s_ch, s_buf, rb);
|
||||||
|
} else {
|
||||||
|
memcpy(s_buf + start * s_ch, lin_to_ring, fb);
|
||||||
|
memcpy(s_buf, lin_to_ring + first * s_ch, rb);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t audio_ring_write(const int32_t *frames, size_t n)
|
||||||
|
{
|
||||||
|
uint32_t wr = __atomic_load_n(&s_wr, __ATOMIC_RELAXED);
|
||||||
|
size_t space = s_cap - (wr - __atomic_load_n(&s_rd, __ATOMIC_ACQUIRE));
|
||||||
|
n = n < space ? n : space;
|
||||||
|
if (n) {
|
||||||
|
copy(NULL, frames, wr, n);
|
||||||
|
__atomic_store_n(&s_wr, wr + n, __ATOMIC_RELEASE);
|
||||||
|
}
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t audio_ring_read(int32_t *frames, size_t n)
|
||||||
|
{
|
||||||
|
uint32_t rd = __atomic_load_n(&s_rd, __ATOMIC_RELAXED);
|
||||||
|
size_t level = __atomic_load_n(&s_wr, __ATOMIC_ACQUIRE) - rd;
|
||||||
|
n = n < level ? n : level;
|
||||||
|
if (n) {
|
||||||
|
copy(frames, NULL, rd, n);
|
||||||
|
__atomic_store_n(&s_rd, rd + n, __ATOMIC_RELEASE);
|
||||||
|
}
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t audio_ring_written(void)
|
||||||
|
{
|
||||||
|
return __atomic_load_n(&s_wr, __ATOMIC_ACQUIRE);
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t audio_ring_read_pos(void)
|
||||||
|
{
|
||||||
|
return __atomic_load_n(&s_rd, __ATOMIC_ACQUIRE);
|
||||||
|
}
|
||||||
|
|
||||||
|
void audio_ring_flush(void)
|
||||||
|
{
|
||||||
|
__atomic_store_n(&s_rd, __atomic_load_n(&s_wr, __ATOMIC_ACQUIRE), __ATOMIC_RELEASE);
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
// Single-producer / single-consumer ring of interleaved int32 frames in PSRAM.
|
||||||
|
// The producer is a source task, the consumer the AES67 TX pull callback (must never block).
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <stddef.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
#include "esp_err.h"
|
||||||
|
|
||||||
|
esp_err_t audio_ring_init(size_t capacity_frames, int channels);
|
||||||
|
size_t audio_ring_level(void); // frames available to read
|
||||||
|
size_t audio_ring_space(void); // frames that can be written
|
||||||
|
size_t audio_ring_write(const int32_t *frames, size_t n); // producer; returns frames written
|
||||||
|
size_t audio_ring_read(int32_t *frames, size_t n); // consumer; returns frames read
|
||||||
|
void audio_ring_flush(void); // consumer side: drop everything buffered
|
||||||
|
// Monotonic frame counters (wrap at 2^32): frames written so far / read (played) so far.
|
||||||
|
uint32_t audio_ring_written(void);
|
||||||
|
uint32_t audio_ring_read_pos(void);
|
||||||
+185
@@ -0,0 +1,185 @@
|
|||||||
|
#include "decoder.h"
|
||||||
|
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "esp_audio_dec_default.h"
|
||||||
|
#include "esp_audio_simple_dec.h"
|
||||||
|
#include "esp_audio_simple_dec_default.h"
|
||||||
|
#include "audio_out.h"
|
||||||
|
#include "esp_heap_caps.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
|
||||||
|
static const char *TAG = "decoder";
|
||||||
|
|
||||||
|
#define OUT_RATE 48000
|
||||||
|
|
||||||
|
static audio_conv_t *s_conv; // HLS: s16 -> 48 kHz -> ring
|
||||||
|
static uint64_t s_seg_out; // 48 kHz frames written this segment
|
||||||
|
|
||||||
|
static esp_audio_simple_dec_handle_t s_dec;
|
||||||
|
static uint8_t *s_pcm;
|
||||||
|
static uint32_t s_pcm_size = 8192;
|
||||||
|
static esp_audio_simple_dec_info_t s_info;
|
||||||
|
static uint64_t s_seg_frames, s_seg_count, s_seg_es;
|
||||||
|
|
||||||
|
// MPEG-TS demux state: packets reassembled across HTTP chunks, PAT -> PMT -> ADTS-AAC PID.
|
||||||
|
static uint8_t s_pkt[188];
|
||||||
|
static size_t s_pkt_len;
|
||||||
|
static int s_pmt_pid = -1, s_audio_pid = -1;
|
||||||
|
|
||||||
|
static void report_segment(void)
|
||||||
|
{
|
||||||
|
if (s_seg_count && s_info.sample_rate) {
|
||||||
|
ESP_LOGI(TAG, "segment: %llu ES bytes -> %llu frames at %lu Hz = %.3f s -> %llu frames at 48 kHz = %.3f s",
|
||||||
|
s_seg_es, s_seg_frames, (unsigned long)s_info.sample_rate,
|
||||||
|
(double)s_seg_frames / s_info.sample_rate, s_seg_out, (double)s_seg_out / OUT_RATE);
|
||||||
|
}
|
||||||
|
s_seg_frames = 0;
|
||||||
|
s_seg_es = 0;
|
||||||
|
s_seg_out = 0;
|
||||||
|
s_seg_count++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Feed ADTS-AAC elementary stream bytes to the decoder.
|
||||||
|
static void decode_es(const uint8_t *data, size_t len)
|
||||||
|
{
|
||||||
|
s_seg_es += len;
|
||||||
|
esp_audio_simple_dec_raw_t raw = { .buffer = (uint8_t *)data, .len = len };
|
||||||
|
while (raw.len) {
|
||||||
|
esp_audio_simple_dec_out_t out = { .buffer = s_pcm, .len = s_pcm_size };
|
||||||
|
esp_audio_err_t err = esp_audio_simple_dec_process(s_dec, &raw, &out);
|
||||||
|
if (err == ESP_AUDIO_ERR_BUFF_NOT_ENOUGH) {
|
||||||
|
uint8_t *p = heap_caps_realloc(s_pcm, out.needed_size, MALLOC_CAP_SPIRAM);
|
||||||
|
if (!p) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
s_pcm = p;
|
||||||
|
s_pcm_size = out.needed_size;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (err != ESP_AUDIO_ERR_OK) {
|
||||||
|
ESP_LOGW(TAG, "decode error %d, resetting decoder", err);
|
||||||
|
esp_audio_simple_dec_reset(s_dec);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (out.decoded_size) {
|
||||||
|
if (!s_info.sample_rate) {
|
||||||
|
esp_audio_simple_dec_get_info(s_dec, &s_info);
|
||||||
|
ESP_LOGI(TAG, "stream: %lu Hz, %u ch, %u bit, %lu bit/s", (unsigned long)s_info.sample_rate,
|
||||||
|
s_info.channel, s_info.bits_per_sample, (unsigned long)s_info.bitrate);
|
||||||
|
}
|
||||||
|
uint32_t n = out.decoded_size / (s_info.channel * s_info.bits_per_sample / 8);
|
||||||
|
s_seg_frames += n;
|
||||||
|
if (s_info.bits_per_sample == 16) {
|
||||||
|
s_seg_out += audio_conv_write(s_conv, (const int16_t *)out.buffer, n, s_info.channel,
|
||||||
|
s_info.sample_rate);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
raw.buffer += raw.consumed;
|
||||||
|
raw.len -= raw.consumed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void ts_packet(const uint8_t *p)
|
||||||
|
{
|
||||||
|
if (p[0] != 0x47) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
bool pusi = p[1] & 0x40;
|
||||||
|
int pid = ((p[1] & 0x1f) << 8) | p[2];
|
||||||
|
int afc = (p[3] >> 4) & 3;
|
||||||
|
if (!(afc & 1)) {
|
||||||
|
return; // no payload
|
||||||
|
}
|
||||||
|
size_t off = 4 + ((afc & 2) ? 1 + p[4] : 0);
|
||||||
|
if (off >= 188) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const uint8_t *pl = p + off;
|
||||||
|
size_t len = 188 - off;
|
||||||
|
|
||||||
|
if (pid == 0 && pusi) { // PAT: first program's PMT PID
|
||||||
|
const uint8_t *sec = pl + 1 + pl[0];
|
||||||
|
s_pmt_pid = ((sec[10] & 0x1f) << 8) | sec[11];
|
||||||
|
} else if (pid == s_pmt_pid && pusi && s_audio_pid < 0) { // PMT: first ADTS-AAC stream
|
||||||
|
const uint8_t *sec = pl + 1 + pl[0];
|
||||||
|
int slen = ((sec[1] & 0x0f) << 8) | sec[2];
|
||||||
|
int i = 12 + (((sec[10] & 0x0f) << 8) | sec[11]);
|
||||||
|
while (i + 5 <= 3 + slen - 4 && sec + i + 5 <= p + 188) {
|
||||||
|
int type = sec[i], epid = ((sec[i + 1] & 0x1f) << 8) | sec[i + 2];
|
||||||
|
if (type == 0x0F) {
|
||||||
|
s_audio_pid = epid;
|
||||||
|
ESP_LOGI(TAG, "TS: PMT PID 0x%x, ADTS-AAC on PID 0x%x", s_pmt_pid, epid);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
i += 5 + (((sec[i + 3] & 0x0f) << 8) | sec[i + 4]);
|
||||||
|
}
|
||||||
|
} else if (pid == s_audio_pid) {
|
||||||
|
if (pusi) { // strip the PES header
|
||||||
|
if (len < 9 || pl[0] || pl[1] || pl[2] != 1 || 9u + pl[8] > len) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
size_t h = 9 + pl[8];
|
||||||
|
pl += h;
|
||||||
|
len -= h;
|
||||||
|
}
|
||||||
|
decode_es(pl, len);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// hls_sink_t: MPEG-TS bytes in any chunking.
|
||||||
|
bool decoder_feed(const uint8_t *data, size_t len, bool segment_start)
|
||||||
|
{
|
||||||
|
if (segment_start) {
|
||||||
|
report_segment();
|
||||||
|
s_pkt_len = 0; // segments start on a packet boundary
|
||||||
|
}
|
||||||
|
while (len) {
|
||||||
|
if (!s_pkt_len) {
|
||||||
|
// resync on 0x47 if needed, then take whole packets straight from the input
|
||||||
|
while (len && data[0] != 0x47) {
|
||||||
|
data++;
|
||||||
|
len--;
|
||||||
|
}
|
||||||
|
while (len >= 188 && data[0] == 0x47) {
|
||||||
|
ts_packet(data);
|
||||||
|
data += 188;
|
||||||
|
len -= 188;
|
||||||
|
}
|
||||||
|
if (len && data[0] != 0x47) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
size_t n = 188 - s_pkt_len < len ? 188 - s_pkt_len : len;
|
||||||
|
memcpy(s_pkt + s_pkt_len, data, n);
|
||||||
|
s_pkt_len += n;
|
||||||
|
data += n;
|
||||||
|
len -= n;
|
||||||
|
if (s_pkt_len == 188) {
|
||||||
|
ts_packet(s_pkt);
|
||||||
|
s_pkt_len = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t decoder_init(void)
|
||||||
|
{
|
||||||
|
esp_audio_dec_register_default();
|
||||||
|
esp_audio_simple_dec_register_default();
|
||||||
|
// Own TS demux (the library's TS decoder lost ~8% of the frames); AAC with ADTS headers,
|
||||||
|
// AAC-Plus on so HE-AAC v1/v2 variants work too.
|
||||||
|
esp_aac_dec_cfg_t aac_cfg = ESP_AAC_DEC_CONFIG_DEFAULT();
|
||||||
|
aac_cfg.aac_plus_enable = true;
|
||||||
|
esp_audio_simple_dec_cfg_t cfg = {
|
||||||
|
.dec_type = ESP_AUDIO_SIMPLE_DEC_TYPE_AAC, .dec_cfg = &aac_cfg, .cfg_size = sizeof(aac_cfg),
|
||||||
|
};
|
||||||
|
if (esp_audio_simple_dec_open(&cfg, &s_dec) != ESP_AUDIO_ERR_OK) {
|
||||||
|
ESP_LOGE(TAG, "AAC decoder open failed");
|
||||||
|
return ESP_FAIL;
|
||||||
|
}
|
||||||
|
s_pcm = heap_caps_malloc(s_pcm_size, MALLOC_CAP_SPIRAM);
|
||||||
|
s_conv = audio_conv_create(PLAYER_SRC_HLS, "hls");
|
||||||
|
return s_pcm && s_conv ? ESP_OK : ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
// Decoder for HLS segments (MPEG-TS with AAC-LC / HE-AAC), fed by the HLS client's sink.
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <stdbool.h>
|
||||||
|
#include <stddef.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
#include "esp_err.h"
|
||||||
|
|
||||||
|
esp_err_t decoder_init(void);
|
||||||
|
// hls_sink_t: segment bytes in; PCM out (7.3: counted and logged).
|
||||||
|
bool decoder_feed(const uint8_t *data, size_t len, bool segment_start);
|
||||||
+322
@@ -0,0 +1,322 @@
|
|||||||
|
#include "hls.h"
|
||||||
|
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "esp_crt_bundle.h"
|
||||||
|
#include "esp_heap_caps.h"
|
||||||
|
#include "esp_http_client.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_timer.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/task.h"
|
||||||
|
|
||||||
|
#define URL_MAX HLS_URL_MAX
|
||||||
|
#define PLAYLIST_MAX (64 * 1024)
|
||||||
|
#define MAX_SEGMENTS 64
|
||||||
|
#define LIVE_BACK 3 // start this many segments behind the live edge
|
||||||
|
#define CHUNK 4096
|
||||||
|
#define MAX_REDIRECTS 5
|
||||||
|
#define SEG_MAX (4 * 1024 * 1024) // largest segment we accept (PSRAM)
|
||||||
|
|
||||||
|
static const char *TAG = "hls";
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
int target_s;
|
||||||
|
long long media_seq;
|
||||||
|
int count;
|
||||||
|
char uri[MAX_SEGMENTS][URL_MAX];
|
||||||
|
} media_pl_t;
|
||||||
|
|
||||||
|
static hls_sink_t s_sink;
|
||||||
|
static char *s_text; // playlist buffer (PSRAM)
|
||||||
|
static media_pl_t *s_pl; // parsed media playlist (PSRAM)
|
||||||
|
static char s_url[URL_MAX]; // URL being played
|
||||||
|
static char s_want_url[URL_MAX]; // from hls_set_url(), guarded by s_url_lock
|
||||||
|
static portMUX_TYPE s_url_lock = portMUX_INITIALIZER_UNLOCKED;
|
||||||
|
static char s_media_url[URL_MAX];
|
||||||
|
static uint8_t *s_seg; // current segment (PSRAM)
|
||||||
|
static volatile unsigned s_suspended; // HLS_SUSPEND_* bits
|
||||||
|
|
||||||
|
void hls_suspend(unsigned reason, bool suspend)
|
||||||
|
{
|
||||||
|
if (suspend) {
|
||||||
|
__atomic_or_fetch(&s_suspended, reason, __ATOMIC_SEQ_CST);
|
||||||
|
} else {
|
||||||
|
__atomic_and_fetch(&s_suspended, ~reason, __ATOMIC_SEQ_CST);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void hls_set_url(const char *url)
|
||||||
|
{
|
||||||
|
taskENTER_CRITICAL(&s_url_lock);
|
||||||
|
strlcpy(s_want_url, url, sizeof(s_want_url));
|
||||||
|
taskEXIT_CRITICAL(&s_url_lock);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void wanted_url(char *out, size_t n)
|
||||||
|
{
|
||||||
|
taskENTER_CRITICAL(&s_url_lock);
|
||||||
|
strlcpy(out, s_want_url, n);
|
||||||
|
taskEXIT_CRITICAL(&s_url_lock);
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool still_wanted(void)
|
||||||
|
{
|
||||||
|
if (s_suspended) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
char u[URL_MAX];
|
||||||
|
wanted_url(u, sizeof(u));
|
||||||
|
return strcmp(u, s_url) == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----- HTTP ----- */
|
||||||
|
|
||||||
|
// Open a GET and follow redirects. Returns the client with headers read, or NULL.
|
||||||
|
static esp_http_client_handle_t http_open(const char *url)
|
||||||
|
{
|
||||||
|
esp_http_client_config_t cfg = {
|
||||||
|
.url = url, .crt_bundle_attach = esp_crt_bundle_attach, .timeout_ms = 10000,
|
||||||
|
.buffer_size = CHUNK, .buffer_size_tx = 1024, .user_agent = "p4-aes67",
|
||||||
|
.disable_auto_redirect = true, .keep_alive_enable = true,
|
||||||
|
};
|
||||||
|
esp_http_client_handle_t c = esp_http_client_init(&cfg);
|
||||||
|
if (!c) {
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
for (int i = 0; i <= MAX_REDIRECTS; i++) {
|
||||||
|
esp_err_t err = esp_http_client_open(c, 0);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
ESP_LOGW(TAG, "open %s: %s", url, esp_err_to_name(err));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
esp_http_client_fetch_headers(c);
|
||||||
|
int st = esp_http_client_get_status_code(c);
|
||||||
|
if (st == 301 || st == 302 || st == 303 || st == 307 || st == 308) {
|
||||||
|
esp_http_client_flush_response(c, NULL);
|
||||||
|
esp_http_client_set_redirection(c);
|
||||||
|
esp_http_client_close(c);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (st == 200) {
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
ESP_LOGW(TAG, "GET %s: HTTP %d", url, st);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
esp_http_client_cleanup(c);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
// GET into s_text (NUL-terminated). Returns length or -1.
|
||||||
|
static int http_get_text(const char *url)
|
||||||
|
{
|
||||||
|
esp_http_client_handle_t c = http_open(url);
|
||||||
|
if (!c) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
int n = 0, r;
|
||||||
|
while (n < PLAYLIST_MAX - 1 && (r = esp_http_client_read(c, s_text + n, PLAYLIST_MAX - 1 - n)) > 0) {
|
||||||
|
n += r;
|
||||||
|
}
|
||||||
|
s_text[n] = 0;
|
||||||
|
esp_http_client_close(c);
|
||||||
|
esp_http_client_cleanup(c);
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----- playlists ----- */
|
||||||
|
|
||||||
|
// Absolute, host-relative ("/x") or path-relative ("x") reference against base.
|
||||||
|
static void resolve(char *out, size_t n, const char *base, const char *ref)
|
||||||
|
{
|
||||||
|
if (strstr(ref, "://")) {
|
||||||
|
strlcpy(out, ref, n);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
char b[URL_MAX];
|
||||||
|
strlcpy(b, base, sizeof(b));
|
||||||
|
char *q = strchr(b, '?');
|
||||||
|
if (q) {
|
||||||
|
*q = 0;
|
||||||
|
}
|
||||||
|
if (ref[0] == '/') {
|
||||||
|
char *host_end = strchr(strstr(b, "://") + 3, '/');
|
||||||
|
if (host_end) {
|
||||||
|
*host_end = 0;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
char *slash = strrchr(b, '/');
|
||||||
|
if (slash) {
|
||||||
|
slash[1] = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
snprintf(out, n, "%s%s", b, ref);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Next line of s_text (CRLF tolerant); NULL at the end.
|
||||||
|
static char *next_line(char **p)
|
||||||
|
{
|
||||||
|
if (!*p || !**p) {
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
char *line = *p, *e = strchr(line, '\n');
|
||||||
|
*p = e ? e + 1 : NULL;
|
||||||
|
if (e) {
|
||||||
|
*e = 0;
|
||||||
|
}
|
||||||
|
size_t l = strlen(line);
|
||||||
|
while (l && (line[l - 1] == '\r' || line[l - 1] == ' ')) {
|
||||||
|
line[--l] = 0;
|
||||||
|
}
|
||||||
|
return line;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Master playlist: pick the variant with the highest BANDWIDTH. false if s_text is a media playlist.
|
||||||
|
static bool pick_variant(const char *base, char *out, size_t n)
|
||||||
|
{
|
||||||
|
if (!strstr(s_text, "#EXT-X-STREAM-INF")) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
long best = -1, bw = -1;
|
||||||
|
char *p = s_text, *line;
|
||||||
|
while ((line = next_line(&p))) {
|
||||||
|
if (!strncmp(line, "#EXT-X-STREAM-INF:", 18)) {
|
||||||
|
const char *b = strstr(line, "BANDWIDTH=");
|
||||||
|
bw = b ? atol(b + 10) : 0;
|
||||||
|
} else if (line[0] && line[0] != '#' && bw >= 0) {
|
||||||
|
if (bw > best) {
|
||||||
|
best = bw;
|
||||||
|
resolve(out, n, base, line);
|
||||||
|
}
|
||||||
|
bw = -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ESP_LOGI(TAG, "variant %ld bit/s: %s", best, out);
|
||||||
|
return best >= 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool parse_media(const char *base)
|
||||||
|
{
|
||||||
|
s_pl->target_s = 10;
|
||||||
|
s_pl->media_seq = 0;
|
||||||
|
s_pl->count = 0;
|
||||||
|
char *p = s_text, *line;
|
||||||
|
bool is_m3u = false;
|
||||||
|
while ((line = next_line(&p))) {
|
||||||
|
if (!strcmp(line, "#EXTM3U")) {
|
||||||
|
is_m3u = true;
|
||||||
|
} else if (!strncmp(line, "#EXT-X-TARGETDURATION:", 22)) {
|
||||||
|
s_pl->target_s = atoi(line + 22);
|
||||||
|
} else if (!strncmp(line, "#EXT-X-MEDIA-SEQUENCE:", 22)) {
|
||||||
|
s_pl->media_seq = atoll(line + 22);
|
||||||
|
} else if (line[0] && line[0] != '#' && s_pl->count < MAX_SEGMENTS) {
|
||||||
|
resolve(s_pl->uri[s_pl->count++], URL_MAX, base, line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return is_m3u && s_pl->count > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----- segments ----- */
|
||||||
|
|
||||||
|
static bool fetch_segment(long long seq, const char *url)
|
||||||
|
{
|
||||||
|
int64_t t0 = esp_timer_get_time();
|
||||||
|
esp_http_client_handle_t c = http_open(url);
|
||||||
|
if (!c) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// Download completely first, then decode: the connection is not held open while the
|
||||||
|
// decoder waits for space in the ring (a stalled TCP stream for ~10 s may get cut by the CDN).
|
||||||
|
size_t total = 0;
|
||||||
|
int r = 0;
|
||||||
|
bool ok = true;
|
||||||
|
while (total < SEG_MAX && (r = esp_http_client_read(c, (char *)s_seg + total, SEG_MAX - total)) > 0) {
|
||||||
|
total += r;
|
||||||
|
}
|
||||||
|
if (r < 0 || total == SEG_MAX) {
|
||||||
|
ok = false;
|
||||||
|
}
|
||||||
|
esp_http_client_close(c);
|
||||||
|
esp_http_client_cleanup(c);
|
||||||
|
int64_t us = esp_timer_get_time() - t0;
|
||||||
|
ESP_LOGD(TAG, "segment %lld: %u bytes in %.2f s (%.1f Mbit/s)%s", seq, (unsigned)total, us / 1e6,
|
||||||
|
us ? total * 8.0 / us : 0.0, ok ? "" : ", failed");
|
||||||
|
if (ok && s_sink) {
|
||||||
|
ok = s_sink(s_seg, total, true); // blocks at playback speed while the ring is full
|
||||||
|
}
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void hls_task(void *arg)
|
||||||
|
{
|
||||||
|
while (1) {
|
||||||
|
wanted_url(s_url, sizeof(s_url));
|
||||||
|
if (!s_url[0] || s_suspended) {
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(1000));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
ESP_LOGI(TAG, "start: %s", s_url);
|
||||||
|
// Master -> media playlist
|
||||||
|
if (http_get_text(s_url) < 0) {
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(5000));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!pick_variant(s_url, s_media_url, sizeof(s_media_url))) {
|
||||||
|
strlcpy(s_media_url, s_url, sizeof(s_media_url));
|
||||||
|
}
|
||||||
|
long long next = -1;
|
||||||
|
int errors = 0;
|
||||||
|
while (still_wanted() && errors < 5) {
|
||||||
|
int64_t t0 = esp_timer_get_time();
|
||||||
|
if (http_get_text(s_media_url) < 0 || !parse_media(s_media_url)) {
|
||||||
|
errors++;
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(2000));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
long long first = s_pl->media_seq, last = first + s_pl->count - 1;
|
||||||
|
if (next < 0) {
|
||||||
|
next = last - LIVE_BACK + 1 > first ? last - LIVE_BACK + 1 : first;
|
||||||
|
ESP_LOGI(TAG, "live playlist: seq %lld..%lld, target %d s, starting at %lld",
|
||||||
|
first, last, s_pl->target_s, next);
|
||||||
|
} else if (next < first) {
|
||||||
|
ESP_LOGW(TAG, "fell behind the live window (%lld < %lld), skipping ahead", next, first);
|
||||||
|
next = first;
|
||||||
|
}
|
||||||
|
bool got_new = false;
|
||||||
|
for (; next <= last && still_wanted(); next++) {
|
||||||
|
if (!fetch_segment(next, s_pl->uri[next - first])) {
|
||||||
|
errors++;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
errors = 0;
|
||||||
|
got_new = true;
|
||||||
|
}
|
||||||
|
// No new segment: wait half the target duration before reloading (RFC 8216 6.3.4).
|
||||||
|
if (!got_new) {
|
||||||
|
int64_t wait = s_pl->target_s * 500000LL - (esp_timer_get_time() - t0);
|
||||||
|
if (wait > 0) {
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(wait / 1000));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (errors >= 5) {
|
||||||
|
ESP_LOGW(TAG, "too many errors, restarting from the playlist in 5 s");
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(5000));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t hls_start(hls_sink_t sink)
|
||||||
|
{
|
||||||
|
s_sink = sink;
|
||||||
|
s_text = heap_caps_malloc(PLAYLIST_MAX, MALLOC_CAP_SPIRAM);
|
||||||
|
s_pl = heap_caps_malloc(sizeof(media_pl_t), MALLOC_CAP_SPIRAM);
|
||||||
|
s_seg = heap_caps_malloc(SEG_MAX, MALLOC_CAP_SPIRAM);
|
||||||
|
if (!s_text || !s_pl || !s_seg) {
|
||||||
|
return ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
|
return xTaskCreate(hls_task, "hls", 10240, NULL, 4, NULL) == pdPASS ? ESP_OK : ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
+23
@@ -0,0 +1,23 @@
|
|||||||
|
// HLS client: playlists, variant choice, live segment loop. Segment bytes go to a sink callback.
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <stdbool.h>
|
||||||
|
#include <stddef.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
#include "esp_err.h"
|
||||||
|
|
||||||
|
// Receives segment data in chunks (MPEG-TS etc.). Return false to abort the segment.
|
||||||
|
typedef bool (*hls_sink_t)(const uint8_t *data, size_t len, bool segment_start);
|
||||||
|
|
||||||
|
#define HLS_URL_MAX 384
|
||||||
|
|
||||||
|
esp_err_t hls_start(hls_sink_t sink);
|
||||||
|
// The playlist URL to play ("" = none). A different URL restarts fetching with it.
|
||||||
|
void hls_set_url(const char *url);
|
||||||
|
// Stop fetching (current download is abandoned) until resumed. Reasons are independent:
|
||||||
|
// fetching runs only when no reason holds it.
|
||||||
|
#define HLS_SUSPEND_OTA (1 << 0)
|
||||||
|
#define HLS_SUSPEND_FAILOVER (1 << 1)
|
||||||
|
#define HLS_SUSPEND_USER (1 << 2) // paused via the player API
|
||||||
|
void hls_suspend(unsigned reason, bool suspend);
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
dependencies:
|
||||||
|
# Newer versions use P4 assembly that needs chip rev >= 3.0; this board is rev 1.3 (see CLAUDE.md).
|
||||||
|
espressif/esp_audio_codec: "~2.5.0"
|
||||||
|
espressif/esp_audio_effects: "~1.3.0"
|
||||||
+46
@@ -0,0 +1,46 @@
|
|||||||
|
#include "aes67_board.h"
|
||||||
|
#include "aes67_health.h"
|
||||||
|
#include "aes67_net.h"
|
||||||
|
#include "aes67_ota.h"
|
||||||
|
#include "aes67_ptp.h"
|
||||||
|
#include "aes67_sdp_sap.h"
|
||||||
|
#include "aes67_syslog.h"
|
||||||
|
#include "aes67_tx.h"
|
||||||
|
#include "aes67_web.h"
|
||||||
|
#include "esp_app_desc.h"
|
||||||
|
#include "esp_chip_info.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "player.h"
|
||||||
|
#include "project_cfg.h"
|
||||||
|
|
||||||
|
static const char *TAG = "main";
|
||||||
|
|
||||||
|
void app_main(void)
|
||||||
|
{
|
||||||
|
const esp_app_desc_t *app = esp_app_get_description();
|
||||||
|
esp_chip_info_t chip;
|
||||||
|
esp_chip_info(&chip);
|
||||||
|
|
||||||
|
ESP_LOGI(TAG, "%s %s (IDF %s, built %s %s)",
|
||||||
|
app->project_name, app->version, app->idf_ver, app->date, app->time);
|
||||||
|
ESP_LOGI(TAG, "chip rev v%d.%d, %d cores",
|
||||||
|
chip.revision / 100, chip.revision % 100, chip.cores);
|
||||||
|
|
||||||
|
project_cfg_defaults();
|
||||||
|
// First, so boot messages are queued for syslog until the interface has an IP.
|
||||||
|
ESP_ERROR_CHECK(aes67_syslog_init());
|
||||||
|
|
||||||
|
esp_eth_handle_t eth;
|
||||||
|
ESP_ERROR_CHECK(aes67_board_eth_init(ð));
|
||||||
|
ESP_ERROR_CHECK(aes67_net_init(eth));
|
||||||
|
ESP_ERROR_CHECK(aes67_health_init());
|
||||||
|
ESP_ERROR_CHECK(aes67_ptp_init());
|
||||||
|
ESP_ERROR_CHECK(aes67_ptp_start(eth));
|
||||||
|
ESP_ERROR_CHECK(aes67_tx_init());
|
||||||
|
project_cfg_register();
|
||||||
|
ESP_ERROR_CHECK(aes67_ota_init());
|
||||||
|
ESP_ERROR_CHECK(aes67_sdp_sap_init());
|
||||||
|
ESP_ERROR_CHECK(player_init());
|
||||||
|
ESP_ERROR_CHECK(aes67_tx_start());
|
||||||
|
ESP_ERROR_CHECK(aes67_web_start());
|
||||||
|
}
|
||||||
+641
@@ -0,0 +1,641 @@
|
|||||||
|
#include "player.h"
|
||||||
|
|
||||||
|
#include <math.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "aes67_cfg.h"
|
||||||
|
#include "aes67_ota.h"
|
||||||
|
#include "aes67_tx.h"
|
||||||
|
#include "aes67_web.h"
|
||||||
|
#include "audio_out.h"
|
||||||
|
#include "audio_ring.h"
|
||||||
|
#include "decoder.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_timer.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/task.h"
|
||||||
|
#include "hls.h"
|
||||||
|
#include "spotify.h"
|
||||||
|
|
||||||
|
#define RATE 48000
|
||||||
|
#define CHANNELS AES67_TX_SRC_CHANNELS // the ring holds what TX pulls: stereo
|
||||||
|
#define RING_FRAMES (4 * RATE) // 4 s in PSRAM
|
||||||
|
#define PREFILL_FRAMES (RATE) // 1 s before (re)starting output
|
||||||
|
#define FADE_FRAMES (RATE * 30 / 1000) // 30 ms ramp at a source switch
|
||||||
|
#define SPOTIFY_WAIT_MS 100 // longest the Spotify data callback may wait (cspot holds a lock)
|
||||||
|
#define CONTROL_MS 250
|
||||||
|
|
||||||
|
static const char *TAG = "player";
|
||||||
|
|
||||||
|
typedef enum { MODE_TONE, MODE_OFF, MODE_HLS, MODE_SPOTIFY, MODE_AUTO, MODE_PINK } mode_t_;
|
||||||
|
static const char *const SRC_NAME[] = { "tone", "off", "hls", "spotify", "pink" };
|
||||||
|
static const char *const MODE_NAME[] = { "tone", "off", "hls", "spotify", "auto", "pink" };
|
||||||
|
|
||||||
|
static volatile mode_t_ s_mode = MODE_OFF;
|
||||||
|
static volatile player_src_t s_src = PLAYER_SRC_OFF; // what is playing now
|
||||||
|
static volatile player_src_t s_target = PLAYER_SRC_OFF; // switch to this (TX task, with fades)
|
||||||
|
static volatile bool s_playing; // ring output running (after prefill)
|
||||||
|
static volatile bool s_flush; // consumer drops buffered audio on the next read
|
||||||
|
static volatile bool s_paused; // Spotify paused: silence, buffer kept, no underrun
|
||||||
|
static volatile bool s_sp_playing; // Spotify has started playback and is not paused
|
||||||
|
static volatile bool s_hls_paused; // HLS paused via the API: not fetching, silence
|
||||||
|
static audio_conv_t *s_spotify_conv;
|
||||||
|
|
||||||
|
// Effective mode: the config's, or a runtime override from the API (not saved). Web server task.
|
||||||
|
static mode_t_ s_cfg_mode = MODE_OFF;
|
||||||
|
static char s_cfg_url[HLS_URL_MAX];
|
||||||
|
static int s_forced = -1; // mode forced via /api/player/source|url, -1 = none
|
||||||
|
static char s_forced_url[HLS_URL_MAX]; // from /api/player/url; "" = the config's URL
|
||||||
|
|
||||||
|
// Failover (mode auto)
|
||||||
|
static volatile int s_failover_delay_s = 5;
|
||||||
|
static volatile bool s_failover_on_pause;
|
||||||
|
|
||||||
|
// TX task only
|
||||||
|
static int s_fade_out; // frames left in the fade-out before a switch
|
||||||
|
static int s_fade_in; // frames left in the fade-in after a switch
|
||||||
|
|
||||||
|
// Player volume and the fixed output trim (source.gain_db), applied after the ring so a change is
|
||||||
|
// heard at once (not a ring length later).
|
||||||
|
static volatile float s_target_gain = 1.0f;
|
||||||
|
static float s_gain = 1.0f; // TX task only; ramps to s_target_gain
|
||||||
|
static volatile int s_volume_pct = 100;
|
||||||
|
static volatile float s_trim = 1.0f; // source.gain_db as amplitude
|
||||||
|
|
||||||
|
// 0..100 % -> amplitude: cubic curve (about -18 dB at 50 %, 0 % = mute), times the trim.
|
||||||
|
static void set_volume(int pct)
|
||||||
|
{
|
||||||
|
pct = pct < 0 ? 0 : pct > 100 ? 100 : pct;
|
||||||
|
float r = pct / 100.0f;
|
||||||
|
s_volume_pct = pct;
|
||||||
|
s_target_gain = r * r * r * s_trim;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scale one sample, clipping at full scale (the trim can boost up to +12 dB).
|
||||||
|
static inline int32_t scale(int32_t x, float g)
|
||||||
|
{
|
||||||
|
float v = x * g;
|
||||||
|
return v >= 2147483520.0f ? INT32_MAX : v <= -2147483648.0f ? INT32_MIN : (int32_t)v;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply the gain, ramping linearly from the previous gain over this buffer (no zipper noise).
|
||||||
|
static void apply_gain(int32_t *buf, size_t frames)
|
||||||
|
{
|
||||||
|
float target = s_target_gain;
|
||||||
|
if (s_gain == target && target == 1.0f) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
float step = (target - s_gain) / frames;
|
||||||
|
for (size_t i = 0; i < frames; i++) {
|
||||||
|
s_gain += step;
|
||||||
|
buf[i * 2] = scale(buf[i * 2], s_gain);
|
||||||
|
buf[i * 2 + 1] = scale(buf[i * 2 + 1], s_gain);
|
||||||
|
}
|
||||||
|
s_gain = target;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Linear ramp over a fade: position counts down from FADE_FRAMES; fade-in rises, fade-out falls.
|
||||||
|
static void apply_fade(int32_t *buf, size_t frames, int *left, bool in)
|
||||||
|
{
|
||||||
|
for (size_t i = 0; i < frames && *left > 0; i++, (*left)--) {
|
||||||
|
float g = (float)(*left) / FADE_FRAMES; // 1 -> 0 over the fade
|
||||||
|
if (in) {
|
||||||
|
g = 1.0f - g;
|
||||||
|
}
|
||||||
|
buf[i * 2] = (int32_t)(buf[i * 2] * g);
|
||||||
|
buf[i * 2 + 1] = (int32_t)(buf[i * 2 + 1] * g);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static mode_t_ mode_of(const char *m)
|
||||||
|
{
|
||||||
|
return !strcmp(m, "tone") ? MODE_TONE : !strcmp(m, "hls") ? MODE_HLS : !strcmp(m, "spotify") ? MODE_SPOTIFY :
|
||||||
|
!strcmp(m, "auto") ? MODE_AUTO : !strcmp(m, "pink") ? MODE_PINK : MODE_OFF;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----- output (AES67 TX pull callback, TX task, must not block) ----- */
|
||||||
|
|
||||||
|
// One buffer of the current source: ring audio, or silence while off / paused / buffering.
|
||||||
|
// Returns the frames produced (fewer = underrun).
|
||||||
|
static size_t read_current(int32_t *buf, size_t frames)
|
||||||
|
{
|
||||||
|
if (s_flush) {
|
||||||
|
audio_ring_flush();
|
||||||
|
s_flush = false;
|
||||||
|
s_playing = false;
|
||||||
|
}
|
||||||
|
if (s_src == PLAYER_SRC_OFF || (s_src == PLAYER_SRC_SPOTIFY && s_paused) ||
|
||||||
|
(s_src == PLAYER_SRC_HLS && s_hls_paused)) {
|
||||||
|
memset(buf, 0, frames * CHANNELS * sizeof(int32_t));
|
||||||
|
return frames;
|
||||||
|
}
|
||||||
|
if (!s_playing) {
|
||||||
|
if (audio_ring_level() < PREFILL_FRAMES) {
|
||||||
|
memset(buf, 0, frames * CHANNELS * sizeof(int32_t));
|
||||||
|
return frames;
|
||||||
|
}
|
||||||
|
s_playing = true;
|
||||||
|
s_fade_in = FADE_FRAMES; // (re)start without a click
|
||||||
|
}
|
||||||
|
size_t got = audio_ring_read(buf, frames);
|
||||||
|
if (got < frames) {
|
||||||
|
s_playing = false; // ran dry: underrun (counted by TX), prefill again
|
||||||
|
}
|
||||||
|
return got;
|
||||||
|
}
|
||||||
|
|
||||||
|
static size_t player_read(int32_t *buf, size_t frames)
|
||||||
|
{
|
||||||
|
// A switch is due: fade the current source out, then switch (ring flushed, new source prefills).
|
||||||
|
if (s_target != s_src && s_fade_out == 0) {
|
||||||
|
s_fade_out = FADE_FRAMES;
|
||||||
|
}
|
||||||
|
size_t got = read_current(buf, frames);
|
||||||
|
if (s_fade_in > 0) {
|
||||||
|
apply_fade(buf, got, &s_fade_in, true);
|
||||||
|
}
|
||||||
|
if (s_fade_out > 0) {
|
||||||
|
apply_fade(buf, got, &s_fade_out, false);
|
||||||
|
if (s_fade_out == 0 || got < frames) {
|
||||||
|
s_fade_out = 0;
|
||||||
|
audio_ring_flush(); // before s_src changes: writers only write for the active source
|
||||||
|
s_playing = false;
|
||||||
|
s_flush = false;
|
||||||
|
s_src = s_target;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
apply_gain(buf, got);
|
||||||
|
return got;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test signals: straight from the core to TX, not through the ring, volume or gain.
|
||||||
|
static bool is_test_signal(player_src_t src)
|
||||||
|
{
|
||||||
|
return src == PLAYER_SRC_TONE || src == PLAYER_SRC_PINK;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set the source to play. Test signals come from the core (the tone phase-locked to PTP), so
|
||||||
|
// switches from/to them are immediate; everything else fades through player_read.
|
||||||
|
static void select_source(player_src_t src)
|
||||||
|
{
|
||||||
|
if (src == s_target) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ESP_LOGI(TAG, "source: %s -> %s", SRC_NAME[s_src], SRC_NAME[src]);
|
||||||
|
if (s_hls_paused) { // an API pause of HLS lasts until the next switch
|
||||||
|
s_hls_paused = false;
|
||||||
|
hls_suspend(HLS_SUSPEND_USER, false);
|
||||||
|
}
|
||||||
|
if (is_test_signal(src) || is_test_signal(s_src)) {
|
||||||
|
s_target = s_src = src;
|
||||||
|
s_flush = true;
|
||||||
|
aes67_tx_set_source(src == PLAYER_SRC_TONE ? NULL : src == PLAYER_SRC_PINK ? aes67_tx_pink_noise :
|
||||||
|
player_read);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
s_target = src; // player_read fades out and switches
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply the effective mode: Spotify on/off, the HLS URL, and the source to play.
|
||||||
|
static void apply_mode(void)
|
||||||
|
{
|
||||||
|
static char applied_url[HLS_URL_MAX];
|
||||||
|
mode_t_ mode = s_forced >= 0 ? (mode_t_)s_forced : s_cfg_mode;
|
||||||
|
if (s_spotify_conv) { // after spotify_init: follows mode / name / credentials live
|
||||||
|
spotify_apply(mode == MODE_SPOTIFY || mode == MODE_AUTO);
|
||||||
|
}
|
||||||
|
const char *url = mode != MODE_HLS && mode != MODE_AUTO ? "" : s_forced_url[0] ? s_forced_url : s_cfg_url;
|
||||||
|
if (strcmp(url, applied_url)) {
|
||||||
|
strlcpy(applied_url, url, sizeof(applied_url));
|
||||||
|
hls_set_url(url);
|
||||||
|
if (s_src == PLAYER_SRC_HLS) {
|
||||||
|
s_flush = true; // another stream: don't finish the old one's buffer
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (mode == s_mode) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
s_mode = mode;
|
||||||
|
// HLS fetches only in hls mode, or in auto while it is the active source (control task).
|
||||||
|
hls_suspend(HLS_SUSPEND_FAILOVER, mode == MODE_AUTO);
|
||||||
|
switch (mode) {
|
||||||
|
case MODE_TONE: select_source(PLAYER_SRC_TONE); break;
|
||||||
|
case MODE_PINK: select_source(PLAYER_SRC_PINK); break;
|
||||||
|
case MODE_HLS: select_source(PLAYER_SRC_HLS); break;
|
||||||
|
case MODE_SPOTIFY: select_source(PLAYER_SRC_SPOTIFY); break;
|
||||||
|
case MODE_AUTO: select_source(PLAYER_SRC_SPOTIFY); break; // Spotify inactive: HLS after the delay
|
||||||
|
default: select_source(PLAYER_SRC_OFF); break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void player_apply(const cJSON *source)
|
||||||
|
{
|
||||||
|
s_failover_delay_s = (int)cJSON_GetObjectItemCaseSensitive(source, "failover_delay_s")->valuedouble;
|
||||||
|
s_failover_on_pause = cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(source, "failover_on_pause"));
|
||||||
|
s_trim = powf(10.0f, (float)cJSON_GetObjectItemCaseSensitive(source, "gain_db")->valuedouble / 20.0f);
|
||||||
|
set_volume(s_volume_pct);
|
||||||
|
s_cfg_mode = mode_of(cJSON_GetObjectItemCaseSensitive(source, "mode")->valuestring);
|
||||||
|
strlcpy(s_cfg_url, cJSON_GetObjectItemCaseSensitive(source, "hls_url")->valuestring, sizeof(s_cfg_url));
|
||||||
|
apply_mode();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----- source side ----- */
|
||||||
|
|
||||||
|
// Write converted 48 kHz frames, waiting for space at playback speed. Frames of a source that is
|
||||||
|
// neither playing nor about to play are dropped (returns n).
|
||||||
|
size_t player_write(player_src_t src, const int32_t *frames, size_t n)
|
||||||
|
{
|
||||||
|
size_t done = 0;
|
||||||
|
while (done < n) {
|
||||||
|
if (src == PLAYER_SRC_HLS && s_hls_paused) {
|
||||||
|
return n; // paused: let the decoder finish the segment it is on
|
||||||
|
}
|
||||||
|
if (s_src != src) {
|
||||||
|
if (s_target != src) {
|
||||||
|
return n; // not this source's turn: drop
|
||||||
|
}
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(5)); // switch in progress (fade-out, ~30 ms)
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
size_t w = audio_ring_write(frames + done * CHANNELS, n - done);
|
||||||
|
if (!w) {
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(20));
|
||||||
|
}
|
||||||
|
done += w;
|
||||||
|
}
|
||||||
|
return done;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----- Spotify ----- */
|
||||||
|
|
||||||
|
// cspot calls this holding a lock that stopping the session also needs: never wait long. Take only
|
||||||
|
// what fits in the ring; return 0 after SPOTIFY_WAIT_MS and cspot retries (it can stop in between).
|
||||||
|
// When it isn't Spotify's turn, hold cspot back the same way: it doesn't stop decoding on pause, so
|
||||||
|
// dropping frames would let it race through the queue at full speed (CPU and network), starving HLS.
|
||||||
|
static size_t spotify_pcm(const int16_t *pcm, size_t frames)
|
||||||
|
{
|
||||||
|
int64_t until = esp_timer_get_time() + SPOTIFY_WAIT_MS * 1000LL;
|
||||||
|
while (true) {
|
||||||
|
if (s_src == PLAYER_SRC_SPOTIFY) {
|
||||||
|
// 44.1 kHz in -> about 1.09x as many 48 kHz frames out; keep a margin
|
||||||
|
size_t fit = audio_ring_space() * 44100 / 48000;
|
||||||
|
fit = fit > 64 ? fit - 64 : 0;
|
||||||
|
size_t n = frames < fit ? frames : fit;
|
||||||
|
if (n) {
|
||||||
|
audio_conv_write(s_spotify_conv, pcm, n, 2, 44100);
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (esp_timer_get_time() >= until) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(10));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void spotify_event(spotify_event_t ev, int value)
|
||||||
|
{
|
||||||
|
switch (ev) {
|
||||||
|
case SPOTIFY_EV_PLAY:
|
||||||
|
s_paused = false;
|
||||||
|
s_sp_playing = true;
|
||||||
|
break;
|
||||||
|
case SPOTIFY_EV_PAUSE:
|
||||||
|
s_paused = true;
|
||||||
|
s_sp_playing = false;
|
||||||
|
break;
|
||||||
|
case SPOTIFY_EV_FLUSH:
|
||||||
|
if (s_src == PLAYER_SRC_SPOTIFY) {
|
||||||
|
s_flush = true; // skip/seek: don't play out the old buffer
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case SPOTIFY_EV_VOLUME: {
|
||||||
|
// Spotify sends 0..65535; the app's slider stays the master of the player volume.
|
||||||
|
int pct = (value * 100 + 32767) / 65535;
|
||||||
|
set_volume(pct);
|
||||||
|
float g = s_target_gain;
|
||||||
|
ESP_LOGI(TAG, "volume %d%% (%.1f dB)", pct, g > 0 ? 20.0f * log10f(g) : -INFINITY);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----- failover (mode auto) ----- */
|
||||||
|
|
||||||
|
// Spotify stays advertised; HLS plays whenever Spotify is inactive for failover_delay_s, and Spotify
|
||||||
|
// takes over as soon as it plays. HLS is stopped while Spotify plays (no bandwidth/CPU).
|
||||||
|
static void control_task(void *arg)
|
||||||
|
{
|
||||||
|
int64_t inactive_since = esp_timer_get_time();
|
||||||
|
while (true) {
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(CONTROL_MS));
|
||||||
|
if (s_mode != MODE_AUTO) {
|
||||||
|
inactive_since = esp_timer_get_time();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
bool session = spotify_session_active();
|
||||||
|
if (!session) {
|
||||||
|
s_sp_playing = false; // session ended (app left, error, disabled)
|
||||||
|
}
|
||||||
|
bool playing = session && s_sp_playing;
|
||||||
|
// Inactive: no session; with failover_on_pause also a connected but paused/stopped one.
|
||||||
|
bool inactive = !session || (s_failover_on_pause && !playing);
|
||||||
|
int64_t now = esp_timer_get_time();
|
||||||
|
if (!inactive) {
|
||||||
|
inactive_since = now;
|
||||||
|
}
|
||||||
|
if (playing && s_target != PLAYER_SRC_SPOTIFY) {
|
||||||
|
ESP_LOGI(TAG, "auto: Spotify is playing, switching to it");
|
||||||
|
hls_suspend(HLS_SUSPEND_FAILOVER, true);
|
||||||
|
select_source(PLAYER_SRC_SPOTIFY);
|
||||||
|
} else if (inactive && s_target == PLAYER_SRC_SPOTIFY &&
|
||||||
|
now - inactive_since >= (int64_t)s_failover_delay_s * 1000000) {
|
||||||
|
ESP_LOGI(TAG, "auto: Spotify inactive for %d s, failing over to HLS", s_failover_delay_s);
|
||||||
|
hls_suspend(HLS_SUSPEND_FAILOVER, false);
|
||||||
|
select_source(PLAYER_SRC_HLS);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Firmware upload: flash writes stall tasks for > 20 ms at a time; with a Spotify session running,
|
||||||
|
// uploads crawled and sometimes ended in a reset (pausing was not enough). End the session (its
|
||||||
|
// tasks and connections are gone before the first write) and stop HLS fetching meanwhile. The
|
||||||
|
// device reboots after a good upload anyway; after a failed one the sources come back (Spotify
|
||||||
|
// waits for the app to reconnect).
|
||||||
|
static void on_ota(bool starting)
|
||||||
|
{
|
||||||
|
if (starting) {
|
||||||
|
spotify_suspend(true);
|
||||||
|
hls_suspend(HLS_SUSPEND_OTA, true);
|
||||||
|
ESP_LOGI(TAG, "firmware update: Spotify session ended, HLS suspended");
|
||||||
|
} else {
|
||||||
|
hls_suspend(HLS_SUSPEND_OTA, false);
|
||||||
|
spotify_suspend(false);
|
||||||
|
ESP_LOGI(TAG, "firmware update failed: sources resumed");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static const char *source_state(player_src_t src)
|
||||||
|
{
|
||||||
|
return is_test_signal(src) ? "playing" : src == PLAYER_SRC_OFF ? "idle" :
|
||||||
|
src == PLAYER_SRC_SPOTIFY && !spotify_session_active() ? "idle" :
|
||||||
|
src == PLAYER_SRC_SPOTIFY && s_paused ? "paused" :
|
||||||
|
src == PLAYER_SRC_HLS && s_hls_paused ? "paused" : s_playing ? "playing" : "buffering";
|
||||||
|
}
|
||||||
|
|
||||||
|
static void player_status(cJSON *st)
|
||||||
|
{
|
||||||
|
player_src_t src = s_src;
|
||||||
|
const char *state = source_state(src);
|
||||||
|
cJSON_AddStringToObject(st, "active_source", SRC_NAME[src]);
|
||||||
|
cJSON_AddStringToObject(st, "source_state", state);
|
||||||
|
cJSON_AddStringToObject(st, "spotify_state", spotify_state());
|
||||||
|
cJSON_AddNumberToObject(st, "buffer_ms", (double)(audio_ring_level() * 1000 / RATE));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ----- Player API ----- */
|
||||||
|
|
||||||
|
static void add_str_or_null(cJSON *o, const char *key, const char *s)
|
||||||
|
{
|
||||||
|
if (s && s[0]) {
|
||||||
|
cJSON_AddStringToObject(o, key, s);
|
||||||
|
} else {
|
||||||
|
cJSON_AddNullToObject(o, key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Same JSON for GET /api/player and every POST.
|
||||||
|
static esp_err_t send_player(httpd_req_t *req)
|
||||||
|
{
|
||||||
|
player_src_t src = s_src;
|
||||||
|
spotify_track_t t;
|
||||||
|
bool sp = src == PLAYER_SRC_SPOTIFY && spotify_now_playing(&t);
|
||||||
|
cJSON *o = cJSON_CreateObject();
|
||||||
|
cJSON_AddStringToObject(o, "source", SRC_NAME[src]);
|
||||||
|
add_str_or_null(o, "forced", s_forced >= 0 ? MODE_NAME[s_forced] : NULL);
|
||||||
|
cJSON_AddStringToObject(o, "state", src == PLAYER_SRC_OFF ? "stopped" : source_state(src));
|
||||||
|
add_str_or_null(o, "artist", sp ? t.artist : NULL);
|
||||||
|
add_str_or_null(o, "title", sp ? t.title : NULL);
|
||||||
|
add_str_or_null(o, "album", sp ? t.album : NULL);
|
||||||
|
if (sp && t.duration_ms) {
|
||||||
|
cJSON_AddNumberToObject(o, "position_ms", t.position_ms);
|
||||||
|
cJSON_AddNumberToObject(o, "duration_ms", t.duration_ms);
|
||||||
|
} else {
|
||||||
|
cJSON_AddNullToObject(o, "position_ms");
|
||||||
|
cJSON_AddNullToObject(o, "duration_ms");
|
||||||
|
}
|
||||||
|
cJSON_AddNumberToObject(o, "volume", s_volume_pct);
|
||||||
|
cJSON *can = cJSON_AddObjectToObject(o, "can");
|
||||||
|
cJSON_AddBoolToObject(can, "pause", sp || src == PLAYER_SRC_HLS);
|
||||||
|
cJSON_AddBoolToObject(can, "next", sp);
|
||||||
|
cJSON_AddBoolToObject(can, "prev", sp);
|
||||||
|
cJSON_AddBoolToObject(can, "seek", sp);
|
||||||
|
esp_err_t err = web_send_json(req, o);
|
||||||
|
cJSON_Delete(o);
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
static esp_err_t player_get(httpd_req_t *req)
|
||||||
|
{
|
||||||
|
return send_player(req);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void hls_pause(bool pause)
|
||||||
|
{
|
||||||
|
if (pause == s_hls_paused) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
s_hls_paused = pause;
|
||||||
|
hls_suspend(HLS_SUSPEND_USER, pause);
|
||||||
|
s_flush = true; // live: resume rejoins at the live edge, never plays the old buffer
|
||||||
|
ESP_LOGI(TAG, "hls %s", pause ? "paused" : "resumed");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Transport on the active source. Returns NULL, or the reason it can't be done (409).
|
||||||
|
static const char *transport(const char *cmd)
|
||||||
|
{
|
||||||
|
player_src_t src = s_src;
|
||||||
|
bool pause = !strcmp(cmd, "pause") || !strcmp(cmd, "stop");
|
||||||
|
bool play = !strcmp(cmd, "play");
|
||||||
|
bool next = !strcmp(cmd, "next"), prev = !strcmp(cmd, "prev");
|
||||||
|
if (!strcmp(cmd, "toggle")) {
|
||||||
|
bool paused = src == PLAYER_SRC_SPOTIFY ? s_paused : s_hls_paused;
|
||||||
|
pause = !paused;
|
||||||
|
play = paused;
|
||||||
|
}
|
||||||
|
if (src == PLAYER_SRC_SPOTIFY) {
|
||||||
|
spotify_cmd_t c = pause ? SPOTIFY_CMD_PAUSE : play ? SPOTIFY_CMD_PLAY :
|
||||||
|
next ? SPOTIFY_CMD_NEXT : SPOTIFY_CMD_PREV;
|
||||||
|
return spotify_command(c, 0) ? NULL : "no Spotify session";
|
||||||
|
}
|
||||||
|
if (src == PLAYER_SRC_HLS) {
|
||||||
|
if (next || prev) {
|
||||||
|
return "live stream: no next/previous";
|
||||||
|
}
|
||||||
|
hls_pause(pause);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
return "no player source active";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Small JSON body of a POST; NULL if missing or invalid.
|
||||||
|
static cJSON *read_body(httpd_req_t *req)
|
||||||
|
{
|
||||||
|
char buf[HLS_URL_MAX + 128]; // fits {"url": ...}
|
||||||
|
if (req->content_len == 0 || req->content_len >= sizeof(buf)) {
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
size_t got = 0;
|
||||||
|
while (got < req->content_len) {
|
||||||
|
int r = httpd_req_recv(req, buf + got, req->content_len - got);
|
||||||
|
if (r == HTTPD_SOCK_ERR_TIMEOUT) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (r <= 0) {
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
got += r;
|
||||||
|
}
|
||||||
|
buf[got] = '\0';
|
||||||
|
return cJSON_Parse(buf);
|
||||||
|
}
|
||||||
|
|
||||||
|
static esp_err_t send_409(httpd_req_t *req, const char *msg)
|
||||||
|
{
|
||||||
|
httpd_resp_set_status(req, "409 Conflict");
|
||||||
|
return httpd_resp_sendstr(req, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST /api/player/seek {ms}, /api/player/volume {value} or {delta}
|
||||||
|
static esp_err_t seek_or_volume(httpd_req_t *req, bool seek)
|
||||||
|
{
|
||||||
|
cJSON *body = read_body(req);
|
||||||
|
const cJSON *v = cJSON_GetObjectItemCaseSensitive(body, seek ? "ms" : "value");
|
||||||
|
const cJSON *d = seek ? NULL : cJSON_GetObjectItemCaseSensitive(body, "delta");
|
||||||
|
double val = cJSON_IsNumber(v) ? v->valuedouble : cJSON_IsNumber(d) ? s_volume_pct + d->valuedouble : -1;
|
||||||
|
cJSON_Delete(body);
|
||||||
|
if (val < 0 && !(cJSON_IsNumber(d) && !seek)) {
|
||||||
|
return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, seek ? "expected {\"ms\": n}" :
|
||||||
|
"expected {\"value\": 0-100} or {\"delta\": n}");
|
||||||
|
}
|
||||||
|
if (seek) {
|
||||||
|
if (s_src != PLAYER_SRC_SPOTIFY) {
|
||||||
|
return send_409(req, "source can't seek");
|
||||||
|
}
|
||||||
|
if (!spotify_command(SPOTIFY_CMD_SEEK, (uint32_t)val)) {
|
||||||
|
return send_409(req, "no Spotify session");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
int pct = val < 0 ? 0 : val > 100 ? 100 : (int)(val + 0.5);
|
||||||
|
set_volume(pct);
|
||||||
|
spotify_set_volume(pct); // the app follows (if a session runs)
|
||||||
|
}
|
||||||
|
return send_player(req);
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST /api/player/source {source: spotify|hls|off|config}, /api/player/url {url}: runtime override
|
||||||
|
static esp_err_t force_source(httpd_req_t *req, bool url)
|
||||||
|
{
|
||||||
|
cJSON *body = read_body(req);
|
||||||
|
const cJSON *v = cJSON_GetObjectItemCaseSensitive(body, url ? "url" : "source");
|
||||||
|
const char *s = cJSON_IsString(v) ? v->valuestring : "";
|
||||||
|
const char *err = NULL;
|
||||||
|
if (url) {
|
||||||
|
if (strncmp(s, "http://", 7) && strncmp(s, "https://", 8)) {
|
||||||
|
err = "expected {\"url\": \"http(s)://...m3u8\"}";
|
||||||
|
} else if (strlen(s) >= sizeof(s_forced_url)) {
|
||||||
|
err = "url too long";
|
||||||
|
} else {
|
||||||
|
s_forced = MODE_HLS;
|
||||||
|
strlcpy(s_forced_url, s, sizeof(s_forced_url));
|
||||||
|
if (s_hls_paused && s_src == PLAYER_SRC_HLS) {
|
||||||
|
hls_pause(false); // a new stream starts playing
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (!strcmp(s, "config")) {
|
||||||
|
s_forced = -1;
|
||||||
|
s_forced_url[0] = '\0';
|
||||||
|
} else if (!strcmp(s, "spotify") || !strcmp(s, "hls") || !strcmp(s, "off")) {
|
||||||
|
s_forced = mode_of(s);
|
||||||
|
s_forced_url[0] = '\0';
|
||||||
|
} else {
|
||||||
|
err = "expected {\"source\": \"spotify|hls|off|config\"}";
|
||||||
|
}
|
||||||
|
if (!err) {
|
||||||
|
ESP_LOGI(TAG, "override: %s%s%s", s_forced >= 0 ? MODE_NAME[s_forced] : "none (config)",
|
||||||
|
s_forced_url[0] ? " " : "", s_forced_url);
|
||||||
|
apply_mode();
|
||||||
|
}
|
||||||
|
cJSON_Delete(body);
|
||||||
|
return err ? httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, err) : send_player(req);
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST /api/player/<cmd>
|
||||||
|
static esp_err_t player_post(httpd_req_t *req)
|
||||||
|
{
|
||||||
|
static const char *const TRANSPORT[] = { "play", "pause", "toggle", "stop", "next", "prev" };
|
||||||
|
const char *cmd = req->uri + strlen("/api/player/");
|
||||||
|
char name[16];
|
||||||
|
size_t len = strcspn(cmd, "?");
|
||||||
|
if (len >= sizeof(name)) {
|
||||||
|
return httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "unknown player command");
|
||||||
|
}
|
||||||
|
memcpy(name, cmd, len);
|
||||||
|
name[len] = '\0';
|
||||||
|
for (int i = 0; i < sizeof(TRANSPORT) / sizeof(TRANSPORT[0]); i++) {
|
||||||
|
if (!strcmp(name, TRANSPORT[i])) {
|
||||||
|
const char *err = transport(name);
|
||||||
|
return err ? send_409(req, err) : send_player(req);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!strcmp(name, "seek") || !strcmp(name, "volume")) {
|
||||||
|
return seek_or_volume(req, name[0] == 's');
|
||||||
|
}
|
||||||
|
if (!strcmp(name, "source") || !strcmp(name, "url")) {
|
||||||
|
return force_source(req, name[0] == 'u');
|
||||||
|
}
|
||||||
|
return httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "unknown player command");
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t player_init(void)
|
||||||
|
{
|
||||||
|
esp_err_t err = audio_ring_init(RING_FRAMES, CHANNELS);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
ESP_LOGE(TAG, "ring buffer: %s", esp_err_to_name(err));
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
aes67_tx_set_source(player_read);
|
||||||
|
cJSON *src = cfg_get("source");
|
||||||
|
s_mode = (mode_t_)-1;
|
||||||
|
player_apply(src);
|
||||||
|
cJSON_Delete(src);
|
||||||
|
err = decoder_init();
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
s_spotify_conv = audio_conv_create(PLAYER_SRC_SPOTIFY, "spotify");
|
||||||
|
if (!s_spotify_conv) {
|
||||||
|
return ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
|
spotify_init(spotify_pcm, spotify_event, audio_ring_written, audio_ring_read_pos);
|
||||||
|
apply_mode(); // now with Spotify
|
||||||
|
aes67_ota_on_update(on_ota);
|
||||||
|
err = hls_start(decoder_feed);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
if (xTaskCreate(control_task, "player_ctl", 3072, NULL, 4, NULL) != pdPASS) {
|
||||||
|
return ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
|
static const httpd_uri_t uris[] = {
|
||||||
|
{ .uri = "/api/player", .method = HTTP_GET, .handler = player_get },
|
||||||
|
{ .uri = "/api/player/*", .method = HTTP_POST, .handler = player_post },
|
||||||
|
};
|
||||||
|
for (int i = 0; i < sizeof(uris) / sizeof(uris[0]); i++) {
|
||||||
|
err = web_register_uri(&uris[i]);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return status_register(player_status);
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
// Project player: picks the audio source for AES67 TX (test tone, pink noise, silence, HLS, Spotify).
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <stddef.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
#include "cJSON.h"
|
||||||
|
#include "esp_err.h"
|
||||||
|
|
||||||
|
typedef enum { PLAYER_SRC_TONE, PLAYER_SRC_OFF, PLAYER_SRC_HLS, PLAYER_SRC_SPOTIFY, PLAYER_SRC_PINK } player_src_t;
|
||||||
|
|
||||||
|
esp_err_t player_init(void);
|
||||||
|
// Apply the "source" config group (mode etc.).
|
||||||
|
void player_apply(const cJSON *source);
|
||||||
|
// Source side: write 48 kHz stereo int32 frames, blocking while the ring is full.
|
||||||
|
// Frames from a source that is not the active one are dropped (returns n).
|
||||||
|
size_t player_write(player_src_t src, const int32_t *frames, size_t n);
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
// Project config: defaults over the core groups and the "source" group.
|
||||||
|
#include "project_cfg.h"
|
||||||
|
|
||||||
|
#include "aes67_cfg.h"
|
||||||
|
#include "esp_err.h"
|
||||||
|
#include "player.h"
|
||||||
|
|
||||||
|
static const char SOURCE_DEFAULTS[] =
|
||||||
|
"{\"mode\":\"spotify\",\"spotify_name\":\"P4 AES67\",\"spotify_bitrate\":320,\"hls_url\":\"\","
|
||||||
|
"\"autoplay\":false,\"gain_db\":0,\"failover_delay_s\":5,\"failover_on_pause\":false,"
|
||||||
|
"\"spotify_client_id\":\"\",\"spotify_client_secret\":\"\"}";
|
||||||
|
|
||||||
|
static bool source_validate(const cJSON *g, char *err, size_t n)
|
||||||
|
{
|
||||||
|
static const char *const modes[] = { "spotify", "hls", "auto", "tone", "pink", "off", NULL };
|
||||||
|
static const double bitrates[] = { 96, 160, 320 };
|
||||||
|
return cfg_check_enum(g, "mode", modes, err, n) &&
|
||||||
|
cfg_check_str(g, "spotify_name", 1, 63, err, n) &&
|
||||||
|
cfg_check_num_in(g, "spotify_bitrate", bitrates, 3, err, n) &&
|
||||||
|
cfg_check_str(g, "hls_url", 0, 255, err, n) &&
|
||||||
|
cfg_check_str(g, "spotify_client_id", 0, 64, err, n) &&
|
||||||
|
cfg_check_str(g, "spotify_client_secret", 0, 64, err, n) &&
|
||||||
|
cfg_check_num(g, "gain_db", -60, 12, err, n) &&
|
||||||
|
cfg_check_int(g, "failover_delay_s", 0, 3600, err, n);
|
||||||
|
}
|
||||||
|
|
||||||
|
void project_cfg_defaults(void)
|
||||||
|
{
|
||||||
|
// Same as PROJECT.def in web/index.html.
|
||||||
|
ESP_ERROR_CHECK(cfg_override_defaults("aes67", "{\"name\":\"P4 AES67\"}"));
|
||||||
|
ESP_ERROR_CHECK(cfg_override_defaults("net", "{\"hostname\":\"p4-aes67\"}"));
|
||||||
|
}
|
||||||
|
|
||||||
|
void project_cfg_register(void)
|
||||||
|
{
|
||||||
|
ESP_ERROR_CHECK(cfg_register("source", SOURCE_DEFAULTS, source_validate, player_apply));
|
||||||
|
// Each user's own Spotify developer app (developer.spotify.com); the secret is write-only.
|
||||||
|
ESP_ERROR_CHECK(cfg_mark_secret("source", "spotify_client_secret"));
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
// Call before the core components register their groups.
|
||||||
|
void project_cfg_defaults(void);
|
||||||
|
// Registers the project's own config groups.
|
||||||
|
void project_cfg_register(void);
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# OTA layout: two app slots, no factory app. Fixed from step 0 on; do not change later.
|
||||||
|
# 32 MB flash, but app slots must stay below 16 MB (no cache mapping above it). 16-32 MB is free for data.
|
||||||
|
# Partition table at 0x10000 (not 0x8000) leaves the bootloader room to grow (0x2000-0x10000).
|
||||||
|
# NVS sits outside the app slots so config survives updates.
|
||||||
|
# Name, Type, SubType, Offset, Size
|
||||||
|
nvs, data, nvs, 0x11000, 0x6000
|
||||||
|
otadata, data, ota, 0x17000, 0x2000
|
||||||
|
phy_init, data, phy, 0x19000, 0x1000
|
||||||
|
ota_0, app, ota_0, 0x20000, 0x600000
|
||||||
|
ota_1, app, ota_1, 0x620000, 0x600000
|
||||||
|
coredump, data, coredump, 0xc20000, 0x10000
|
||||||
|
@@ -0,0 +1,38 @@
|
|||||||
|
CONFIG_IDF_TARGET="esp32p4"
|
||||||
|
|
||||||
|
# OTA layout (partitions.csv): two app slots, no factory
|
||||||
|
CONFIG_PARTITION_TABLE_CUSTOM=y
|
||||||
|
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
|
||||||
|
# Bootloader had only 6% free below 0x8000; moved so it can grow (e.g. secure boot) without a relayout
|
||||||
|
CONFIG_PARTITION_TABLE_OFFSET=0x10000
|
||||||
|
|
||||||
|
# Rollback lives in the bootloader, which is only ever flashed over USB: enable it from the start
|
||||||
|
CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y
|
||||||
|
|
||||||
|
# Board has engineering silicon v1.3 (esptool chip_id). Rev <3 binaries don't run on rev 3 and vice versa.
|
||||||
|
CONFIG_ESP32P4_SELECTS_REV_LESS_V3=y
|
||||||
|
CONFIG_ESP32P4_REV_MIN_100=y
|
||||||
|
|
||||||
|
# 32 MB flash (esptool flash_id: GigaDevice c8/4019). App slots stay below 16 MB;
|
||||||
|
# cache mapping above 16 MB is experimental in IDF.
|
||||||
|
CONFIG_ESPTOOLPY_FLASHSIZE_32MB=y
|
||||||
|
|
||||||
|
# LLDP and PTP send raw frames from their own tasks next to lwIP: serialise EMAC transmits
|
||||||
|
CONFIG_ETH_TRANSMIT_MUTEX=y
|
||||||
|
|
||||||
|
# lwIP default is 10 sockets; PTP (2), AES67 TX, SAP, syslog and httpd's listen/control sockets
|
||||||
|
# use 7, leaving ~3 for web clients (httpd allows 7): a browser's keep-alive connections then
|
||||||
|
# starve new requests. 16 = 7 others + 7 web clients + OTA self-test client + 1 spare.
|
||||||
|
CONFIG_LWIP_MAX_SOCKETS=16
|
||||||
|
|
||||||
|
# 32 MB PSRAM in the P4 package (hex mode, 200 MHz; 250 MHz needs rev >= 3). Needed for step 7:
|
||||||
|
# HLS segment buffers, cspot, decoders. malloc() puts blocks >16 KB in PSRAM; DMA buffers stay internal.
|
||||||
|
CONFIG_SPIRAM=y
|
||||||
|
|
||||||
|
# cspot (Spotify Connect, step 7.5) needs C++ exceptions.
|
||||||
|
CONFIG_COMPILER_CXX_EXCEPTIONS=y
|
||||||
|
|
||||||
|
# esp_audio_codec's Vorbis decoder exports the same symbols (vorbis_info_init, ...) as cspot's
|
||||||
|
# Tremor (bell): keep it out of the link. HLS only needs AAC.
|
||||||
|
# CONFIG_AUDIO_DECODER_VORBIS_SUPPORT is not set
|
||||||
|
# CONFIG_AUDIO_SIMPLE_DEC_OGG_SUPPORT is not set
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
# Rollback test build only (step 2b). Build in its own directory, e.g.:
|
||||||
|
# idf.py -B build-selftest-fail -DSDKCONFIG=build-selftest-fail/sdkconfig \
|
||||||
|
# -DSDKCONFIG_DEFAULTS="sdkconfig.defaults;sdkconfig.selftest_fail" build
|
||||||
|
CONFIG_AES67_OTA_SELFTEST_FORCE_FAIL=y
|
||||||
Executable
+222
@@ -0,0 +1,222 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Flash this firmware onto another ESP32-P4 board over USB, then give it its own identity.
|
||||||
|
|
||||||
|
Steps: pick the port, check the chip (ESP32-P4, revision the image supports, flash size),
|
||||||
|
optionally erase, write bootloader + partition table + app, wait for the board's IP in its boot
|
||||||
|
log, then set hostname / stream name / multicast address over the web API so it doesn't clash
|
||||||
|
with other boards on the network.
|
||||||
|
|
||||||
|
Needs esptool (in the ESP-IDF Python env, or `pip install esptool`) and a build (`idf.py build`).
|
||||||
|
Every question can also be answered with an option, e.g.:
|
||||||
|
tools/flash_board.py --port /dev/ttyACM0 --erase --hostname p4-aes67-2 --name "P4 AES67 2" \\
|
||||||
|
--mcast 239.69.1.11
|
||||||
|
Boards already running this firmware and on the network update over the web (OTA) instead.
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import struct
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
MIN_FLASH_MB = 32 # the bootloader header says 32 MB (sdkconfig); smaller chips aren't supported
|
||||||
|
|
||||||
|
|
||||||
|
def die(msg):
|
||||||
|
print(f"\nERROR: {msg}")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
|
||||||
|
def ask(prompt, default=None):
|
||||||
|
s = input(f"{prompt}{f' [{default}]' if default is not None else ''}: ").strip()
|
||||||
|
return s or (default if default is not None else "")
|
||||||
|
|
||||||
|
|
||||||
|
def yes(prompt, default):
|
||||||
|
s = input(f"{prompt} [{'Y/n' if default else 'y/N'}]: ").strip().lower()
|
||||||
|
return default if not s else s.startswith("y")
|
||||||
|
|
||||||
|
|
||||||
|
def esptool(port, *args, capture=True):
|
||||||
|
cmd = [sys.executable, "-m", "esptool", "--chip", "esp32p4", "--port", port, *args]
|
||||||
|
if not capture:
|
||||||
|
if subprocess.call(cmd) != 0:
|
||||||
|
die("esptool failed (see above)")
|
||||||
|
return ""
|
||||||
|
r = subprocess.run(cmd, capture_output=True, text=True)
|
||||||
|
if r.returncode != 0:
|
||||||
|
die(f"esptool {' '.join(args)} failed:\n{r.stdout}{r.stderr}")
|
||||||
|
return r.stdout
|
||||||
|
|
||||||
|
|
||||||
|
def pick_port(given):
|
||||||
|
if given:
|
||||||
|
return given
|
||||||
|
try:
|
||||||
|
from serial.tools import list_ports
|
||||||
|
except ImportError:
|
||||||
|
die("pyserial missing: run inside the ESP-IDF environment or `pip install esptool`")
|
||||||
|
ports = [p for p in list_ports.comports() if "ACM" in p.device or "USB" in p.device]
|
||||||
|
if not ports:
|
||||||
|
die("no USB serial port found: connect the board's USB-C port (not the PoE/Ethernet side)")
|
||||||
|
for i, p in enumerate(ports, 1):
|
||||||
|
print(f" {i}) {p.device} {p.description}")
|
||||||
|
if len(ports) == 1:
|
||||||
|
return ports[0].device if yes(f"Use {ports[0].device}?", True) else die("no port chosen")
|
||||||
|
n = ask("Port number", "1")
|
||||||
|
return ports[int(n) - 1].device
|
||||||
|
|
||||||
|
|
||||||
|
def load_images(build):
|
||||||
|
"""(offset, path) pairs and flash options from build/flash_args."""
|
||||||
|
fa = os.path.join(build, "flash_args")
|
||||||
|
if not os.path.exists(fa):
|
||||||
|
die(f"{fa} not found: build first (idf.py build)")
|
||||||
|
lines = open(fa).read().split("\n")
|
||||||
|
opts = lines[0].split()
|
||||||
|
images = []
|
||||||
|
for line in lines[1:]:
|
||||||
|
if line.strip():
|
||||||
|
off, path = line.split()
|
||||||
|
images.append((off, os.path.join(build, path)))
|
||||||
|
return opts, images
|
||||||
|
|
||||||
|
|
||||||
|
def image_rev_range(app):
|
||||||
|
"""Chip revision range from the app image header (esp_image_header_t), as (min, max) * 100."""
|
||||||
|
h = open(app, "rb").read(24)
|
||||||
|
if h[0] != 0xE9:
|
||||||
|
die(f"{app} is not an ESP app image")
|
||||||
|
min_full, max_full = struct.unpack_from("<HH", h, 15)
|
||||||
|
return min_full, max_full
|
||||||
|
|
||||||
|
|
||||||
|
def app_version(app):
|
||||||
|
# esp_app_desc_t after the image header (24 B) and first segment header (8 B): version at +16.
|
||||||
|
d = open(app, "rb").read(24 + 8 + 256)[32:]
|
||||||
|
return d[16:48].split(b"\0")[0].decode(errors="replace")
|
||||||
|
|
||||||
|
|
||||||
|
def check_chip(port, app):
|
||||||
|
out = esptool(port, "flash_id")
|
||||||
|
m = re.search(r"ESP32-P4 \(revision v(\d+)\.(\d+)\)", out)
|
||||||
|
if not m:
|
||||||
|
die(f"not an ESP32-P4?\n{out}")
|
||||||
|
rev = int(m.group(1)) * 100 + int(m.group(2))
|
||||||
|
lo, hi = image_rev_range(app)
|
||||||
|
print(f" chip: ESP32-P4 revision v{rev // 100}.{rev % 100}")
|
||||||
|
if not lo <= rev <= hi:
|
||||||
|
die(f"this build supports chip revisions v{lo // 100}.{lo % 100} to v{hi // 100}.{hi % 100}; "
|
||||||
|
f"the board is v{rev // 100}.{rev % 100}. Build with the matching "
|
||||||
|
"CONFIG_ESP32P4_SELECTS_REV_LESS_V3 setting (see CLAUDE.md).")
|
||||||
|
m = re.search(r"Detected flash size: (\d+)MB", out)
|
||||||
|
if not m:
|
||||||
|
die(f"could not read the flash size:\n{out}")
|
||||||
|
mb = int(m.group(1))
|
||||||
|
print(f" flash: {mb} MB")
|
||||||
|
if mb < MIN_FLASH_MB:
|
||||||
|
die(f"{mb} MB flash; this build needs {MIN_FLASH_MB} MB")
|
||||||
|
|
||||||
|
|
||||||
|
def wait_for_ip(port, timeout=90):
|
||||||
|
"""Read the boot log until the board reports its IP (the port open may reset it: fine here)."""
|
||||||
|
import serial
|
||||||
|
print(f" waiting for the board's IP (boot log on {port}, up to {timeout} s; Ethernet plugged in?)")
|
||||||
|
end = time.time() + timeout
|
||||||
|
with serial.Serial(port, 115200, timeout=1) as s:
|
||||||
|
buf = b""
|
||||||
|
while time.time() < end:
|
||||||
|
buf += s.read(4096)
|
||||||
|
m = re.search(rb"got IP (\d+\.\d+\.\d+\.\d+)", buf)
|
||||||
|
if m:
|
||||||
|
return m.group(1).decode()
|
||||||
|
buf = buf[-4096:]
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def api(ip, method, path, body=None):
|
||||||
|
req = urllib.request.Request(f"http://{ip}{path}", method=method,
|
||||||
|
data=json.dumps(body).encode() if body is not None else None,
|
||||||
|
headers={"Content-Type": "application/json"})
|
||||||
|
with urllib.request.urlopen(req, timeout=10) as r:
|
||||||
|
t = r.read()
|
||||||
|
return json.loads(t) if t else {}
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||||
|
ap.add_argument("--port")
|
||||||
|
ap.add_argument("--build", default=os.path.join(REPO, "build"), help="build directory (default: build/)")
|
||||||
|
ap.add_argument("--erase", action=argparse.BooleanOptionalAction,
|
||||||
|
help="erase the whole flash first (clears any stored config)")
|
||||||
|
ap.add_argument("--hostname")
|
||||||
|
ap.add_argument("--name", help="stream / Spotify device name")
|
||||||
|
ap.add_argument("--mcast", help="AES67 multicast address")
|
||||||
|
ap.add_argument("--no-config", action="store_true", help="flash only, keep the default identity")
|
||||||
|
a = ap.parse_args()
|
||||||
|
|
||||||
|
opts, images = load_images(a.build)
|
||||||
|
app = next(p for off, p in images if p.endswith("aes67_p4.bin"))
|
||||||
|
print(f"Firmware: {app_version(app)} ({app})\n")
|
||||||
|
|
||||||
|
print("1) Port")
|
||||||
|
port = pick_port(a.port)
|
||||||
|
|
||||||
|
print("\n2) Checking the board")
|
||||||
|
check_chip(port, app)
|
||||||
|
|
||||||
|
print("\n3) Flashing")
|
||||||
|
erase = a.erase if a.erase is not None else yes(
|
||||||
|
" Erase the whole flash first? (yes for a new board or to clear an old config)", True)
|
||||||
|
if erase:
|
||||||
|
esptool(port, "erase_flash", capture=False)
|
||||||
|
args = ["write_flash", *opts]
|
||||||
|
for off, path in images:
|
||||||
|
args += [off, path]
|
||||||
|
esptool(port, *args, capture=False)
|
||||||
|
|
||||||
|
if a.no_config:
|
||||||
|
print("\nDone (default identity: hostname p4-aes67, multicast 239.69.1.10).")
|
||||||
|
return
|
||||||
|
|
||||||
|
print("\n4) Finding the board on the network")
|
||||||
|
ip = wait_for_ip(port)
|
||||||
|
if not ip:
|
||||||
|
die("no IP seen in the boot log. Check the Ethernet cable/DHCP; the board is flashed, set the "
|
||||||
|
"identity later in the web UI.")
|
||||||
|
print(f" board is at {ip}")
|
||||||
|
for _ in range(30): # web server comes up right after the IP
|
||||||
|
try:
|
||||||
|
cfg = api(ip, "GET", "/api/config")
|
||||||
|
break
|
||||||
|
except OSError:
|
||||||
|
time.sleep(1)
|
||||||
|
else:
|
||||||
|
die(f"web UI at http://{ip}/ does not answer")
|
||||||
|
|
||||||
|
print("\n5) Identity (must differ from every other board on this network)")
|
||||||
|
host = a.hostname or ask(" Hostname", "p4-aes67-2")
|
||||||
|
name = a.name or ask(" Stream / Spotify device name", "P4 AES67 2")
|
||||||
|
mcast = a.mcast or ask(" AES67 multicast address", "239.69.1.11")
|
||||||
|
cfg["net"]["hostname"] = host
|
||||||
|
cfg["aes67"]["name"] = name
|
||||||
|
cfg["aes67"]["mcast"] = mcast
|
||||||
|
cfg["source"]["spotify_name"] = name
|
||||||
|
try:
|
||||||
|
api(ip, "POST", "/api/config", cfg)
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
die(f"config rejected: {e.read().decode()}")
|
||||||
|
print(f"\nDone. Web UI: http://{ip}/ or http://{host}.local/")
|
||||||
|
print("Still to set in the web UI if needed: Spotify client ID/secret, source mode, PTP role.")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
try:
|
||||||
|
main()
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print("\naborted")
|
||||||
|
sys.exit(1)
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
0.0.1
|
||||||
+21
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 Ben Nicholson
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
+93
-29
@@ -5,13 +5,18 @@
|
|||||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
<title>AES67 device</title>
|
<title>AES67 device</title>
|
||||||
<!--
|
<!--
|
||||||
|
SPDX-License-Identifier: MIT (see web/LICENSE)
|
||||||
AES67 device web UI – reusable base.
|
AES67 device web UI – reusable base.
|
||||||
CORE : status, PTP, AES67 output, network/VLAN, logging, SDP. Keep identical across projects.
|
CORE : status, PTP, AES67 output, network/VLAN, logging, SDP. Keep identical across projects.
|
||||||
PROJECT: blocks between "PROJECT START/END" markers (HTML and the PROJECT object in the script).
|
PROJECT: blocks between "PROJECT START/END" markers (HTML and the PROJECT object in the script).
|
||||||
Form fields bind to config JSON by name="group.key". Add a field = add an input; no JS needed.
|
Form fields bind to config JSON by name="group.key". Add a field = add an input; no JS needed.
|
||||||
-->
|
-->
|
||||||
<style>
|
<style>
|
||||||
:root{color-scheme:light dark}
|
/* Dark by default; the toggle (top right) switches to light and is remembered in this browser. */
|
||||||
|
:root{color-scheme:dark}
|
||||||
|
:root.light{color-scheme:light}
|
||||||
|
#theme{position:fixed;top:8px;right:8px;font-size:18px;line-height:1;padding:4px 8px;cursor:pointer}
|
||||||
|
[hidden]{display:none!important} /* else label{display:block} overrides it */
|
||||||
body{font:14px/1.4 system-ui,sans-serif;max-width:720px;margin:0 auto;padding:0 16px 32px}
|
body{font:14px/1.4 system-ui,sans-serif;max-width:720px;margin:0 auto;padding:0 16px 32px}
|
||||||
fieldset{margin:12px 0}
|
fieldset{margin:12px 0}
|
||||||
label{display:block;margin:4px 0}
|
label{display:block;margin:4px 0}
|
||||||
@@ -20,13 +25,23 @@ input:not([type=checkbox]),select{width:14em;max-width:100%}
|
|||||||
textarea{width:100%;height:14em;font:12px monospace}
|
textarea{width:100%;height:14em;font:12px monospace}
|
||||||
table td:first-child{padding-right:1em;opacity:.7}
|
table td:first-child{padding-right:1em;opacity:.7}
|
||||||
pre{overflow-x:auto}
|
pre{overflow-x:auto}
|
||||||
#msg{min-height:1.4em}
|
#msg{margin-left:1em}
|
||||||
|
/* Save bar: stays at the bottom of the window while the settings form is in view */
|
||||||
|
.bar{position:sticky;bottom:0;background:Canvas;padding:8px 0;border-top:1px solid color-mix(in srgb,CanvasText 20%,transparent)}
|
||||||
.ok{color:#2a2}.warn{color:#d80}.bad{color:#e33}
|
.ok{color:#2a2}.warn{color:#d80}.bad{color:#e33}
|
||||||
</style>
|
</style>
|
||||||
|
<script>
|
||||||
|
// Before the page is drawn, so a light choice doesn't flash dark first (and vice versa).
|
||||||
|
try { if (localStorage.getItem('theme') === 'light') document.documentElement.classList.add('light'); } catch {}
|
||||||
|
function toggleTheme() {
|
||||||
|
const light = document.documentElement.classList.toggle('light');
|
||||||
|
try { localStorage.setItem('theme', light ? 'light' : 'dark'); } catch {}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
<button id="theme" type="button" onclick="toggleTheme()" title="Light / dark">◐</button>
|
||||||
<h2 id="title">AES67 device</h2>
|
<h2 id="title">AES67 device</h2>
|
||||||
<p id="msg"></p>
|
|
||||||
|
|
||||||
<fieldset><legend>Status</legend><table id="status"></table></fieldset>
|
<fieldset><legend>Status</legend><table id="status"></table></fieldset>
|
||||||
<fieldset><legend>PTP status</legend><table id="ptpstat"></table>
|
<fieldset><legend>PTP status</legend><table id="ptpstat"></table>
|
||||||
@@ -39,11 +54,11 @@ pre{overflow-x:auto}
|
|||||||
<button onclick="ctl('toggle')">⏯</button>
|
<button onclick="ctl('toggle')">⏯</button>
|
||||||
<button onclick="ctl('next')">⏭</button>
|
<button onclick="ctl('next')">⏭</button>
|
||||||
<button onclick="ctl('stop')">⏹</button>
|
<button onclick="ctl('stop')">⏹</button>
|
||||||
|
<label><span>Position</span><input id="pos" type="range" min="0" max="0" value="0" step="1000" disabled
|
||||||
|
oninput="seekDrag=true; showPos()" onchange="seekDrag=false; ctl('seek',{ms:+this.value})">
|
||||||
|
<small id="postime"></small></label>
|
||||||
<label><span>Volume</span><input id="vol" type="range" min="0" max="100"
|
<label><span>Volume</span><input id="vol" type="range" min="0" max="100"
|
||||||
onchange="ctl('volume',{value:+this.value})"></label>
|
onchange="ctl('volume',{value:+this.value})"></label>
|
||||||
<label><span>Force source</span><select id="force" onchange="ctl('source',{source:this.value})">
|
|
||||||
<option value="config">As configured</option><option value="spotify">Spotify</option>
|
|
||||||
<option value="hls">HLS</option><option value="off">Off</option></select></label>
|
|
||||||
<details><summary>API</summary><pre>
|
<details><summary>API</summary><pre>
|
||||||
GET /api/player state, track, position, volume
|
GET /api/player state, track, position, volume
|
||||||
POST /api/player/play|pause|toggle|stop|next|prev
|
POST /api/player/play|pause|toggle|stop|next|prev
|
||||||
@@ -64,12 +79,19 @@ e.g. curl -X POST http://p4-aes67.local/api/player/next
|
|||||||
<option value="spotify">Spotify Connect</option>
|
<option value="spotify">Spotify Connect</option>
|
||||||
<option value="hls">HLS / M3U8 URL</option>
|
<option value="hls">HLS / M3U8 URL</option>
|
||||||
<option value="auto">Spotify, fail over to HLS</option>
|
<option value="auto">Spotify, fail over to HLS</option>
|
||||||
|
<option value="tone">Test tone (1 kHz, -18 dBFS)</option>
|
||||||
|
<option value="pink">Pink noise (-18 dBFS RMS)</option>
|
||||||
<option value="off">Off (silence)</option></select></label>
|
<option value="off">Off (silence)</option></select></label>
|
||||||
<label><span>Failover delay (s)</span><input name="source.failover_delay_s" type="number" min="0" max="3600"></label>
|
<label><span>Failover delay (s)</span><input name="source.failover_delay_s" type="number" min="0" max="3600"></label>
|
||||||
<label><span>Also fail over when paused</span><input name="source.failover_on_pause" type="checkbox"></label>
|
<label><span>Also fail over when paused</span><input name="source.failover_on_pause" type="checkbox"></label>
|
||||||
<label><span>Spotify device name</span><input name="source.spotify_name"></label>
|
<label><span>Spotify device name</span><input name="source.spotify_name"></label>
|
||||||
<label><span>Spotify bitrate</span><select name="source.spotify_bitrate">
|
<label><span>Spotify bitrate</span><select name="source.spotify_bitrate">
|
||||||
<option>96</option><option>160</option><option>320</option></select></label>
|
<option>96</option><option>160</option><option>320</option></select></label>
|
||||||
|
<label><span>Spotify client ID</span><input name="source.spotify_client_id" autocomplete="off"></label>
|
||||||
|
<label><span>Spotify client secret</span><input name="source.spotify_client_secret" type="password"
|
||||||
|
autocomplete="new-password" placeholder="stored; leave empty to keep"></label>
|
||||||
|
<small>Your own app from <a href="https://developer.spotify.com/dashboard" target="_blank">developer.spotify.com</a>
|
||||||
|
(Premium account). The secret is never shown again once saved.</small>
|
||||||
<label><span>Stream URL</span><input name="source.hls_url" type="url" placeholder="https://…/playlist.m3u8"></label>
|
<label><span>Stream URL</span><input name="source.hls_url" type="url" placeholder="https://…/playlist.m3u8"></label>
|
||||||
<label><span>Autoplay stream on boot</span><input name="source.autoplay" type="checkbox"></label>
|
<label><span>Autoplay stream on boot</span><input name="source.autoplay" type="checkbox"></label>
|
||||||
<label><span>Output gain (dB)</span><input name="source.gain_db" type="number" min="-60" max="12" step="0.5"></label>
|
<label><span>Output gain (dB)</span><input name="source.gain_db" type="number" min="-60" max="12" step="0.5"></label>
|
||||||
@@ -77,15 +99,14 @@ e.g. curl -X POST http://p4-aes67.local/api/player/next
|
|||||||
<!-- ===== PROJECT END ===== -->
|
<!-- ===== PROJECT END ===== -->
|
||||||
|
|
||||||
<fieldset><legend>PTP</legend>
|
<fieldset><legend>PTP</legend>
|
||||||
<button type="button" onclick="ptpPreset('riedel')">Riedel SIC defaults</button>
|
<button type="button" onclick="ptpPreset('riedel')">Riedel PTP defaults</button>
|
||||||
<button type="button" onclick="ptpPreset('aes67')">AES67 media profile defaults</button>
|
<button type="button" onclick="ptpPreset('aes67')">AES67 Media PTP defaults</button>
|
||||||
<label><span>Mode</span><select name="ptp.mode">
|
<label><span>Mode</span><select name="ptp.mode">
|
||||||
<option value="multicast">multicast</option><option value="hybrid">hybrid</option></select>
|
<option value="multicast">multicast</option><option value="hybrid">hybrid</option></select>
|
||||||
<small>hybrid: Delay_Req/Resp unicast</small></label>
|
<small>hybrid: Delay_Req/Resp unicast</small></label>
|
||||||
<label><span>Role</span><select name="ptp.role">
|
<label><span>Role</span><select name="ptp.role">
|
||||||
<option value="slave">TimeReceiver only</option>
|
<option value="slave">TimeReceiver only</option>
|
||||||
<option value="auto">Auto (TimeTransmitter if none)</option>
|
<option value="auto">Auto (TimeTransmitter if none)</option></select></label>
|
||||||
<option value="master">Preferred TimeTransmitter</option></select></label>
|
|
||||||
<label><span>Domain</span><input name="ptp.domain" type="number" min="0" max="127"></label>
|
<label><span>Domain</span><input name="ptp.domain" type="number" min="0" max="127"></label>
|
||||||
<label><span>Priority 1</span><input name="ptp.priority1" type="number" min="0" max="255"></label>
|
<label><span>Priority 1</span><input name="ptp.priority1" type="number" min="0" max="255"></label>
|
||||||
<label><span>Priority 2</span><input name="ptp.priority2" type="number" min="0" max="255"></label>
|
<label><span>Priority 2</span><input name="ptp.priority2" type="number" min="0" max="255"></label>
|
||||||
@@ -101,7 +122,6 @@ e.g. curl -X POST http://p4-aes67.local/api/player/next
|
|||||||
<option value="-4">-4 (16/s)</option><option value="-3">-3 (8/s)</option><option value="-2">-2 (4/s)</option>
|
<option value="-4">-4 (16/s)</option><option value="-3">-3 (8/s)</option><option value="-2">-2 (4/s)</option>
|
||||||
<option value="-1">-1 (2/s)</option><option value="0">0 (1/s)</option><option value="1">1 (every 2 s)</option></select></label>
|
<option value="-1">-1 (2/s)</option><option value="0">0 (1/s)</option><option value="1">1 (every 2 s)</option></select></label>
|
||||||
<label><span>DSCP (PTP)</span><input name="ptp.dscp" type="number" min="0" max="63"></label>
|
<label><span>DSCP (PTP)</span><input name="ptp.dscp" type="number" min="0" max="63"></label>
|
||||||
<label><span>HW timestamping</span><input name="ptp.hw_ts" type="checkbox"></label>
|
|
||||||
<small>Transport UDP/IPv4 224.0.1.129 (ports 319/320), delay mechanism E2E.</small>
|
<small>Transport UDP/IPv4 224.0.1.129 (ports 319/320), delay mechanism E2E.</small>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
|
|
||||||
@@ -124,7 +144,7 @@ e.g. curl -X POST http://p4-aes67.local/api/player/next
|
|||||||
<small>(Ch 1 + Ch 2) / 2 → 1-channel stream</small></label>
|
<small>(Ch 1 + Ch 2) / 2 → 1-channel stream</small></label>
|
||||||
<label><span>Bit depth</span><select name="aes67.encoding"><option>L24</option><option>L16</option></select>
|
<label><span>Bit depth</span><select name="aes67.encoding"><option>L24</option><option>L16</option></select>
|
||||||
<small>Default L24</small></label>
|
<small>Default L24</small></label>
|
||||||
<label><span>Sample rate</span><select name="aes67.rate"><option>48000</option><option>96000</option></select></label>
|
<label><span>Sample rate</span><select name="aes67.rate"><option>48000</option></select></label>
|
||||||
<label><span>Packet time</span><select name="aes67.ptime">
|
<label><span>Packet time</span><select name="aes67.ptime">
|
||||||
<option value="0.125">0.125 ms</option><option value="0.25">0.250 ms</option><option value="0.333">0.333 ms</option>
|
<option value="0.125">0.125 ms</option><option value="0.25">0.250 ms</option><option value="0.333">0.333 ms</option>
|
||||||
<option value="1">1.000 ms</option><option value="4">4.000 ms</option></select>
|
<option value="1">1.000 ms</option><option value="4">4.000 ms</option></select>
|
||||||
@@ -139,7 +159,8 @@ e.g. curl -X POST http://p4-aes67.local/api/player/next
|
|||||||
|
|
||||||
<fieldset><legend>Network</legend>
|
<fieldset><legend>Network</legend>
|
||||||
<label><span>Hostname</span><input name="net.hostname"></label>
|
<label><span>Hostname</span><input name="net.hostname"></label>
|
||||||
<label><span>VLAN split</span><input name="net.vlan" type="checkbox">
|
<!-- VLAN split: not implemented yet (phase 2); hidden until the firmware applies it. -->
|
||||||
|
<label hidden><span>VLAN split</span><input name="net.vlan" type="checkbox">
|
||||||
<small>off: one untagged interface for everything</small></label>
|
<small>off: one untagged interface for everything</small></label>
|
||||||
<p id="netlbl" hidden><b>AES67 interface (untagged)</b></p>
|
<p id="netlbl" hidden><b>AES67 interface (untagged)</b></p>
|
||||||
<label><span>DHCP</span><input name="net.dhcp" type="checkbox"></label>
|
<label><span>DHCP</span><input name="net.dhcp" type="checkbox"></label>
|
||||||
@@ -179,9 +200,12 @@ e.g. curl -X POST http://p4-aes67.local/api/player/next
|
|||||||
<button type="button" onclick="api('POST','/api/log/test').then(()=>msg.textContent='Test message sent.',()=>{})">Send test message</button>
|
<button type="button" onclick="api('POST','/api/log/test').then(()=>msg.textContent='Test message sent.',()=>{})">Send test message</button>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
|
|
||||||
|
<div class="bar">
|
||||||
<button>Save</button>
|
<button>Save</button>
|
||||||
<button type="button" onclick="load()">Revert</button>
|
<button type="button" onclick="load()">Revert</button>
|
||||||
<button type="button" onclick="confirm('Reboot device?')&&api('POST','/api/reboot')">Reboot</button>
|
<button type="button" onclick="confirm('Reboot device?')&&api('POST','/api/reboot')">Reboot</button>
|
||||||
|
<span id="msg"></span>
|
||||||
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<fieldset><legend>SDP</legend>
|
<fieldset><legend>SDP</legend>
|
||||||
@@ -207,7 +231,7 @@ const PROJECT = {
|
|||||||
title: 'P4 AES67 Streamer',
|
title: 'P4 AES67 Streamer',
|
||||||
def: {
|
def: {
|
||||||
source:{mode:'spotify',spotify_name:'P4 AES67',spotify_bitrate:'320',hls_url:'',autoplay:false,gain_db:0,
|
source:{mode:'spotify',spotify_name:'P4 AES67',spotify_bitrate:'320',hls_url:'',autoplay:false,gain_db:0,
|
||||||
failover_delay_s:5,failover_on_pause:false},
|
failover_delay_s:5,failover_on_pause:false,spotify_client_id:'',spotify_client_secret:''},
|
||||||
aes67:{name:'P4 AES67'},
|
aes67:{name:'P4 AES67'},
|
||||||
net:{hostname:'p4-aes67'}
|
net:{hostname:'p4-aes67'}
|
||||||
},
|
},
|
||||||
@@ -215,6 +239,7 @@ const PROJECT = {
|
|||||||
const m = f['source.mode'].value;
|
const m = f['source.mode'].value;
|
||||||
const sp = m === 'spotify' || m === 'auto', hl = m === 'hls' || m === 'auto';
|
const sp = m === 'spotify' || m === 'auto', hl = m === 'hls' || m === 'auto';
|
||||||
f['source.spotify_name'].disabled = f['source.spotify_bitrate'].disabled = !sp;
|
f['source.spotify_name'].disabled = f['source.spotify_bitrate'].disabled = !sp;
|
||||||
|
f['source.spotify_client_id'].disabled = f['source.spotify_client_secret'].disabled = !sp;
|
||||||
f['source.hls_url'].disabled = !hl;
|
f['source.hls_url'].disabled = !hl;
|
||||||
f['source.autoplay'].disabled = m !== 'hls';
|
f['source.autoplay'].disabled = m !== 'hls';
|
||||||
f['source.failover_delay_s'].disabled = f['source.failover_on_pause'].disabled = m !== 'auto';
|
f['source.failover_delay_s'].disabled = f['source.failover_on_pause'].disabled = m !== 'auto';
|
||||||
@@ -230,15 +255,27 @@ const PROJECT = {
|
|||||||
async function ctl(cmd, body) {
|
async function ctl(cmd, body) {
|
||||||
try { showPlayer(await api('POST', '/api/player/' + cmd, body)); } catch {}
|
try { showPlayer(await api('POST', '/api/player/' + cmd, body)); } catch {}
|
||||||
}
|
}
|
||||||
|
// Progress bar: follows the polled position, moves on locally while playing, seeks on release.
|
||||||
|
let np = null, npAt = 0, seekDrag = false;
|
||||||
|
const mmss = ms => `${Math.floor(ms/60000)}:${String(Math.floor(ms/1000)%60).padStart(2,'0')}`;
|
||||||
|
function showPos() {
|
||||||
|
const pos = document.getElementById('pos'), dur = np?.duration_ms;
|
||||||
|
pos.disabled = !(dur && np.can?.seek);
|
||||||
|
if (!seekDrag) {
|
||||||
|
const at = !dur ? 0 : np.state === 'playing' ? Math.min(np.position_ms + Date.now() - npAt, dur) : np.position_ms;
|
||||||
|
pos.max = dur || 0;
|
||||||
|
pos.value = at;
|
||||||
|
}
|
||||||
|
document.getElementById('postime').textContent = dur ? `${mmss(+pos.value)} / ${mmss(dur)}` : '';
|
||||||
|
}
|
||||||
|
setInterval(showPos, 500);
|
||||||
function showPlayer(p) {
|
function showPlayer(p) {
|
||||||
if (!p || !p.state) return;
|
if (!p || !p.state) return;
|
||||||
const t = s => s == null ? '' : `${Math.floor(s/60000)}:${String(Math.floor(s/1000)%60).padStart(2,'0')}`;
|
np = p; npAt = Date.now(); showPos();
|
||||||
document.getElementById('np').textContent =
|
document.getElementById('np').textContent =
|
||||||
`[${p.source}] ${p.state}: ${[p.artist, p.title].filter(Boolean).join(' – ') || '–'}` +
|
`[${p.source}] ${p.state}: ${[p.artist, p.title].filter(Boolean).join(' – ') || '–'}`;
|
||||||
(p.duration_ms ? ` ${t(p.position_ms)} / ${t(p.duration_ms)}` : '');
|
|
||||||
const v = document.getElementById('vol');
|
const v = document.getElementById('vol');
|
||||||
if (document.activeElement !== v) v.value = p.volume;
|
if (document.activeElement !== v) v.value = p.volume;
|
||||||
document.getElementById('force').value = p.forced || 'config';
|
|
||||||
}
|
}
|
||||||
/* ===== PROJECT END ===== */
|
/* ===== PROJECT END ===== */
|
||||||
|
|
||||||
@@ -246,7 +283,7 @@ function showPlayer(p) {
|
|||||||
const CORE_DEF = {
|
const CORE_DEF = {
|
||||||
// Intervals follow Riedel SIC AES67 defaults; role/priorities are the "fallback TimeTransmitter" setup.
|
// Intervals follow Riedel SIC AES67 defaults; role/priorities are the "fallback TimeTransmitter" setup.
|
||||||
ptp:{mode:'multicast',role:'auto',domain:0,priority1:250,priority2:250,log_sync:0,log_announce:1,
|
ptp:{mode:'multicast',role:'auto',domain:0,priority1:250,priority2:250,log_sync:0,log_announce:1,
|
||||||
announce_timeout:3,log_delay_req:0,dscp:46,hw_ts:true},
|
announce_timeout:3,log_delay_req:0,dscp:46},
|
||||||
aes67:{name:'AES67',enabled:true,mcast:'239.69.1.10',port:5004,ttl:32,dscp:34,pt:96,encoding:'L24',
|
aes67:{name:'AES67',enabled:true,mcast:'239.69.1.10',port:5004,ttl:32,dscp:34,pt:96,encoding:'L24',
|
||||||
rate:'48000',channels:'2',ptime:'1',ssrc:0,clk_offset:0,mono_sum:false,discovery:'sap',session_id:1,session_ver:1},
|
rate:'48000',channels:'2',ptime:'1',ssrc:0,clk_offset:0,mono_sum:false,discovery:'sap',session_id:1,session_ver:1},
|
||||||
net:{hostname:'aes67',vlan:false,web_on:'both',dhcp:true,ip:'',mask:'',gw:'',dns:''},
|
net:{hostname:'aes67',vlan:false,web_on:'both',dhcp:true,ip:'',mask:'',gw:'',dns:''},
|
||||||
@@ -254,7 +291,7 @@ const CORE_DEF = {
|
|||||||
log:{syslog:false,host:'',port:514,level:'info',facility:'16',format:'rfc5424'}
|
log:{syslog:false,host:'',port:514,level:'info',facility:'16',format:'rfc5424'}
|
||||||
};
|
};
|
||||||
// Priority1 suggested when the role is changed in the UI (user can still edit it).
|
// Priority1 suggested when the role is changed in the UI (user can still edit it).
|
||||||
const ROLE_P1 = {auto:250, master:100};
|
const ROLE_P1 = {auto:250};
|
||||||
// PTP presets. riedel = Riedel Director defaults for a SIC AES67 card.
|
// PTP presets. riedel = Riedel Director defaults for a SIC AES67 card.
|
||||||
const PTP_PRESETS = {
|
const PTP_PRESETS = {
|
||||||
riedel: {mode:'multicast', role:'slave', domain:0, priority1:128, priority2:126,
|
riedel: {mode:'multicast', role:'slave', domain:0, priority1:128, priority2:126,
|
||||||
@@ -265,7 +302,7 @@ function ptpPreset(name) {
|
|||||||
for (const [k, v] of Object.entries(PTP_PRESETS[name])) f['ptp.' + k].value = v;
|
for (const [k, v] of Object.entries(PTP_PRESETS[name])) f['ptp.' + k].value = v;
|
||||||
toggle(); sdp(); msg.textContent = `Loaded ${name} PTP defaults – Save to apply.`;
|
toggle(); sdp(); msg.textContent = `Loaded ${name} PTP defaults – Save to apply.`;
|
||||||
}
|
}
|
||||||
const CLOCK_CLASS = {slave:255, auto:248, master:248};
|
const CLOCK_CLASS = {slave:255, auto:248};
|
||||||
|
|
||||||
const $ = id => document.getElementById(id);
|
const $ = id => document.getElementById(id);
|
||||||
const f = $('f'), sdpEl = $('sdp'), msg = $('msg');
|
const f = $('f'), sdpEl = $('sdp'), msg = $('msg');
|
||||||
@@ -317,6 +354,13 @@ function read() {
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// With DHCP on, the greyed-out static fields show what DHCP gave us. Unticking DHCP leaves the values
|
||||||
|
// there (a starting point for static addressing) until they are edited.
|
||||||
|
function netLive() {
|
||||||
|
if (!f['net.dhcp'].checked || !st.ip) return;
|
||||||
|
for (const k of ['ip','mask','gw','dns']) f['net.' + k].value = st[k] ?? '';
|
||||||
|
}
|
||||||
|
|
||||||
function toggle() {
|
function toggle() {
|
||||||
PROJECT.toggle?.(f);
|
PROJECT.toggle?.(f);
|
||||||
const role = f['ptp.role'].value;
|
const role = f['ptp.role'].value;
|
||||||
@@ -330,6 +374,7 @@ function toggle() {
|
|||||||
}
|
}
|
||||||
// VLAN split: default route lives on the internet VLAN, so the AES67 side gets no gateway/DNS.
|
// VLAN split: default route lives on the internet VLAN, so the AES67 side gets no gateway/DNS.
|
||||||
if (vlan) f['net.gw'].disabled = f['net.dns'].disabled = true;
|
if (vlan) f['net.gw'].disabled = f['net.dns'].disabled = true;
|
||||||
|
netLive();
|
||||||
// RTP multicast must be 224.0.2.0 – 239.255.255.255 (same range Riedel Director enforces).
|
// RTP multicast must be 224.0.2.0 – 239.255.255.255 (same range Riedel Director enforces).
|
||||||
const m = f['aes67.mcast'], o = m.value.split('.').map(Number);
|
const m = f['aes67.mcast'], o = m.value.split('.').map(Number);
|
||||||
const ok = o.length === 4 && o.every(x => Number.isInteger(x) && x >= 0 && x <= 255) &&
|
const ok = o.length === 4 && o.every(x => Number.isInteger(x) && x >= 0 && x <= 255) &&
|
||||||
@@ -385,7 +430,15 @@ async function save(e) {
|
|||||||
const c = read();
|
const c = read();
|
||||||
c.aes67.session_ver = (Number(cfg.aes67?.session_ver) || 0) + 1; // SDP version bump per RFC 4566
|
c.aes67.session_ver = (Number(cfg.aes67?.session_ver) || 0) + 1; // SDP version bump per RFC 4566
|
||||||
await api('POST', '/api/config', c);
|
await api('POST', '/api/config', c);
|
||||||
|
// A changed IP setup reboots the device: follow it to the new address.
|
||||||
|
const addr = n => n.dhcp ? 'dhcp' : [n.ip, n.mask, n.gw, n.dns].join('/');
|
||||||
|
const moved = addr(cfg.net || {}) !== addr(c.net);
|
||||||
cfg = c; fill(); msg.textContent = 'Saved.';
|
cfg = c; fill(); msg.textContent = 'Saved.';
|
||||||
|
if (moved) {
|
||||||
|
const to = c.net.dhcp ? location.host : c.net.ip;
|
||||||
|
msg.textContent = `Rebooting with the new IP setup. Opening http://${to}/ in 20 s.`;
|
||||||
|
setTimeout(() => location.href = `http://${to}/`, 20000);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// PTP display follows the Riedel (Bolero/Artist) status layout, IEEE 1588-2019 terms.
|
// PTP display follows the Riedel (Bolero/Artist) status layout, IEEE 1588-2019 terms.
|
||||||
@@ -406,7 +459,7 @@ function offsetBucket(ns) {
|
|||||||
// Same brackets and colours as Riedel Bolero.
|
// Same brackets and colours as Riedel Bolero.
|
||||||
const [t, cls] = a < 100 ? ['< 100 ns','ok'] : a < 500 ? ['100-500 ns','ok'] : a < 1e3 ? ['500-1000 ns','warn']
|
const [t, cls] = a < 100 ? ['< 100 ns','ok'] : a < 500 ? ['100-500 ns','ok'] : a < 1e3 ? ['500-1000 ns','warn']
|
||||||
: a < 1e4 ? ['1000-10000 ns','bad'] : ['> 10000 ns','bad'];
|
: a < 1e4 ? ['1000-10000 ns','bad'] : ['> 10000 ns','bad'];
|
||||||
return {cls, text: `${t} (${n(ns)} ns)`};
|
return {cls, text: t};
|
||||||
}
|
}
|
||||||
function freqBucket(ppb) {
|
function freqBucket(ppb) {
|
||||||
if (ppb == null) return '–';
|
if (ppb == null) return '–';
|
||||||
@@ -416,6 +469,13 @@ function freqBucket(ppb) {
|
|||||||
return `${t} (${n(ppb)} ppb)`;
|
return `${t} (${n(ppb)} ppb)`;
|
||||||
}
|
}
|
||||||
const yn = v => v == null ? '–' : v ? 'Yes' : 'No';
|
const yn = v => v == null ? '–' : v ? 'Yes' : 'No';
|
||||||
|
// 93784 -> "1d 2h 3m 4s"; leading zero units left out.
|
||||||
|
function uptime(s) {
|
||||||
|
if (s == null) return '–';
|
||||||
|
const parts = [[Math.floor(s / 86400), 'd'], [Math.floor(s / 3600) % 24, 'h'], [Math.floor(s / 60) % 60, 'm'], [s % 60, 's']];
|
||||||
|
const i = parts.findIndex(([v]) => v > 0);
|
||||||
|
return parts.slice(i < 0 ? 3 : i).map(([v, u]) => v + u).join(' ');
|
||||||
|
}
|
||||||
|
|
||||||
function showPtp(p) {
|
function showPtp(p) {
|
||||||
if (!p) { table($('ptpmore'), {}); return table($('ptpstat'), {'PTP': 'no data'}); }
|
if (!p) { table($('ptpmore'), {}); return table($('ptpstat'), {'PTP': 'no data'}); }
|
||||||
@@ -424,18 +484,21 @@ function showPtp(p) {
|
|||||||
'PTP State': PTP_STATE[p.state] || p.state,
|
'PTP State': PTP_STATE[p.state] || p.state,
|
||||||
'Lock State': p.locked ? {cls:'ok', text:'Locked'} : {cls:'bad', text:'Unlocked'},
|
'Lock State': p.locked ? {cls:'ok', text:'Locked'} : {cls:'bad', text:'Unlocked'},
|
||||||
'TimeTransmitter': clockId(p.gm_id) + (gmSelf ? ' (this device)' : ''),
|
'TimeTransmitter': clockId(p.gm_id) + (gmSelf ? ' (this device)' : ''),
|
||||||
'Time Offset': gmSelf ? '–' : offsetBucket(p.offset_ns),
|
// Bracket from the mean |offset| over the last 2 min; the current value is in Details.
|
||||||
|
'Time Offset (2 min avg)': gmSelf ? '–' : offsetBucket(p.offset_avg_ns),
|
||||||
'Frequency Deviation': gmSelf ? '–' : freqBucket(p.freq_ppb),
|
'Frequency Deviation': gmSelf ? '–' : freqBucket(p.freq_ppb),
|
||||||
'Network Delay': gmSelf ? '–' : `${n(p.path_delay_ns)} ± ${n(p.path_delay_sd_ns)} ns`,
|
'Network Delay': gmSelf ? '–' : `${n(p.path_delay_ns)} ± ${n(p.path_delay_sd_ns)} ns`,
|
||||||
'Hops': p.steps_removed,
|
|
||||||
'Time/Frequency Traceable': `${yn(p.gm_time_traceable)} / ${yn(p.gm_freq_traceable)}`,
|
|
||||||
'Version': p.version ?? 2,
|
|
||||||
'Own Clock Class': p.own_class
|
|
||||||
});
|
});
|
||||||
table($('ptpmore'), {
|
table($('ptpmore'), {
|
||||||
'This clock': clockId(p.clock_id),
|
'This clock': clockId(p.clock_id),
|
||||||
|
// Same colours as the average's brackets, for the current value.
|
||||||
|
'Time offset now': gmSelf || p.offset_ns == null ? '–' : {cls: offsetBucket(p.offset_ns).cls, text: `${n(p.offset_ns)} ns`},
|
||||||
'TT class / accuracy': `${p.gm_class ?? '–'} / 0x${(p.gm_accuracy ?? 0).toString(16).toUpperCase()}`,
|
'TT class / accuracy': `${p.gm_class ?? '–'} / 0x${(p.gm_accuracy ?? 0).toString(16).toUpperCase()}`,
|
||||||
'TT priority 1 / 2': `${p.gm_p1 ?? '–'} / ${p.gm_p2 ?? '–'}`,
|
'TT priority 1 / 2': `${p.gm_p1 ?? '–'} / ${p.gm_p2 ?? '–'}`,
|
||||||
|
'Hops': p.steps_removed ?? '–',
|
||||||
|
'Time/Frequency Traceable': `${yn(p.gm_time_traceable)} / ${yn(p.gm_freq_traceable)}`,
|
||||||
|
'Version': p.version ?? 2,
|
||||||
|
'Own Clock Class': p.own_class ?? '–',
|
||||||
// Measured over the last p.window Sync messages (RX as receiver, TX as transmitter).
|
// Measured over the last p.window Sync messages (RX as receiver, TX as transmitter).
|
||||||
'Sync interval avg': `${n(p.sync_avg_ms, 3)} ms (min ${n(p.sync_min_ms, 3)} / max ${n(p.sync_max_ms, 3)}, jitter ${n(p.sync_jitter_us, 1)} µs)`,
|
'Sync interval avg': `${n(p.sync_avg_ms, 3)} ms (min ${n(p.sync_min_ms, 3)} / max ${n(p.sync_max_ms, 3)}, jitter ${n(p.sync_jitter_us, 1)} µs)`,
|
||||||
'Announce interval avg': n(p.announce_avg_ms, 1) + ' ms',
|
'Announce interval avg': n(p.announce_avg_ms, 1) + ' ms',
|
||||||
@@ -469,10 +532,11 @@ async function poll() {
|
|||||||
...(st.power ? {'Power source': st.power} : {}),
|
...(st.power ? {'Power source': st.power} : {}),
|
||||||
...PROJECT.statusRows?.(st),
|
...PROJECT.statusRows?.(st),
|
||||||
'AES67 TX': `${st.tx_packets} pkts, ${st.underruns} underruns`,
|
'AES67 TX': `${st.tx_packets} pkts, ${st.underruns} underruns`,
|
||||||
'Uptime': st.uptime_s + ' s', 'Heap / PSRAM free': `${st.heap_free} / ${st.psram_free}`,
|
'Uptime': uptime(st.uptime_s), 'Heap / PSRAM free': `${st.heap_free} / ${st.psram_free}`,
|
||||||
...temps(st.temps)
|
...temps(st.temps)
|
||||||
});
|
});
|
||||||
showPtp(st.ptp);
|
showPtp(st.ptp);
|
||||||
|
netLive();
|
||||||
sdp();
|
sdp();
|
||||||
} catch { table($('status'), {'Device': 'offline'}); showPtp(null); }
|
} catch { table($('status'), {'Device': 'offline'}); showPtp(null); }
|
||||||
}
|
}
|
||||||
@@ -489,7 +553,7 @@ async function otaInfo() {
|
|||||||
try {
|
try {
|
||||||
const o = await api('GET', '/api/ota');
|
const o = await api('GET', '/api/ota');
|
||||||
table($('fwinfo'), {
|
table($('fwinfo'), {
|
||||||
'Version': o.version, 'Project': o.project, 'Built': o.build_date, 'ESP-IDF': o.idf,
|
'Version': o.version,
|
||||||
'Running slot': o.running, 'Previous slot': o.previous ? `${o.previous} (${o.previous_version ?? '?'})` : '–',
|
'Running slot': o.running, 'Previous slot': o.previous ? `${o.previous} (${o.previous_version ?? '?'})` : '–',
|
||||||
'State': o.pending_verify ? {cls:'warn', text:'New firmware on trial – confirm or roll back'} : 'Confirmed'
|
'State': o.pending_verify ? {cls:'warn', text:'New firmware on trial – confirm or roll back'} : 'Confirmed'
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user