Add internet radio streaming with runtime API, modernize web UI, remove auto-tune/beep at boot
Streaming (main feature this session): - New WebRadioConfig/WebRadioJson core types, ISecureStore-backed persistence - New webradio::WebRadioService (thread-safe live config) + GET/POST /api/streaming - web_radio_stream task now runtime-toggleable (no reboot), no hardcoded URL - Content-Type diagnostic: warns clearly when a URL is a webpage, not an audio stream Boot cleanup: - Removed boot-time auto FM/DAB tune, auto-beep, and the (now-concluded) Si4684 crystal IBIAS/CTUN empirical sweep from main.cpp — tuning/beep are on-demand via the existing REST API only Web UI: - Modernized styling (cards, gradients, toggle switches, light/dark theme) - New Stream tab wired to /api/streaming Fixes found via real idf.py build (not just clangd): - Restored wrongly-removed si4684/Si4684Tuner.hpp include in main.cpp - Fixed MP3Decode() argument types in web_radio_stream.cpp (unsigned char**/int*) Quality-gate fixes: - Host-test stub headers (esp_log.h, freertos/*) so TunerService.cpp's scanForStation logging/pacing compiles for station_service_test / integration_service_test instead of running stale binaries - Added WifiScanner and WebRadioService manual sections; filled in missing Doxygen docs on BluetoothService, i2s_sdata_probe, test_firmware, Bt1035At - Ignore clangd's .cache/ index directory Also includes prior uncommitted work carried in the tree: Wi-Fi/Bluetooth device scan REST API and UI (WifiScanner, BT scan), SigmaStudio TCP bridge, and the current ADAU1701 SigmaStudio DSP program export. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -130,6 +130,20 @@ public:
|
||||
[[nodiscard]] std::expected<void, core::StoreError> setMasterVolume(
|
||||
core::GainDb left, core::GainDb right, bool persist);
|
||||
|
||||
/**
|
||||
* @brief applyRadioFirstMix — route Si4684 to output, mute ESP32 path.
|
||||
*
|
||||
* @dname applyRadioFirstMix
|
||||
* @param persist When true and store is set, write NVS.
|
||||
* @return Ok on success, or StoreError.
|
||||
* @pubstate updates profile_.mixer and master; safeloads ADAU1701.
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-08-05
|
||||
*/
|
||||
[[nodiscard]] std::expected<void, core::StoreError> applyRadioFirstMix(
|
||||
bool persist);
|
||||
|
||||
/**
|
||||
* @brief setEqBand — update one PEQ band and apply live.
|
||||
*
|
||||
@@ -179,6 +193,21 @@ public:
|
||||
[[nodiscard]] std::expected<void, core::StoreError> setBassEnhance(
|
||||
core::EnhanceLevel level, bool persist);
|
||||
|
||||
/**
|
||||
* @brief setBeepEnabled — toggle the ADAU1701 Beep1 tone generator.
|
||||
*
|
||||
* @dname setBeepEnabled
|
||||
* @param enabled true unmutes Beep1, false mutes it.
|
||||
* @return Ok on success, or DspError.
|
||||
* @pubstate live-only: not part of AudioProfile, never persisted, does
|
||||
* not touch profile_.
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-08-07
|
||||
*/
|
||||
[[nodiscard]] std::expected<void, core::DspError> setBeepEnabled(
|
||||
bool enabled);
|
||||
|
||||
private:
|
||||
[[nodiscard]] std::expected<void, core::StoreError> persistProfile() const;
|
||||
|
||||
|
||||
@@ -134,6 +134,25 @@ std::expected<void, core::StoreError> AudioService::setMasterVolume(
|
||||
return {};
|
||||
}
|
||||
|
||||
std::expected<void, core::StoreError> AudioService::applyRadioFirstMix(
|
||||
bool persist)
|
||||
{
|
||||
const core::GainDb unity = core::GainDb::zero();
|
||||
profile_.mixer = core::MixerState::radioFirst();
|
||||
profile_.masterLeft = unity;
|
||||
profile_.masterRight = unity;
|
||||
if (auto applied = dsp_.applyMixer(profile_.mixer); !applied) {
|
||||
return std::unexpected(core::StoreError::IoFailed);
|
||||
}
|
||||
if (auto master = dsp_.setMasterVolume(unity, unity); !master) {
|
||||
return std::unexpected(core::StoreError::IoFailed);
|
||||
}
|
||||
if (persist) {
|
||||
return persistProfile();
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
std::expected<void, core::StoreError> AudioService::setEqBand(
|
||||
core::EqBandIndex band, core::GainDb gain, core::FrequencyHz center, float q,
|
||||
bool persist)
|
||||
@@ -160,4 +179,9 @@ std::expected<void, core::StoreError> AudioService::setBassEnhance(
|
||||
return applyEffectiveEq(persist);
|
||||
}
|
||||
|
||||
std::expected<void, core::DspError> AudioService::setBeepEnabled(bool enabled)
|
||||
{
|
||||
return dsp_.setBeepEnabled(enabled);
|
||||
}
|
||||
|
||||
} // namespace audio
|
||||
|
||||
@@ -2,7 +2,7 @@ idf_component_register(
|
||||
SRCS
|
||||
"src/BluetoothService.cpp"
|
||||
INCLUDE_DIRS "include"
|
||||
REQUIRES core bt1035
|
||||
REQUIRES core bt1035 freertos
|
||||
)
|
||||
|
||||
target_compile_features(${COMPONENT_LIB} PUBLIC cxx_std_23)
|
||||
|
||||
@@ -15,6 +15,9 @@
|
||||
#include "bt1035/Bt1035Driver.hpp"
|
||||
#include "bt1035/Bt1035Error.hpp"
|
||||
#include "core/BluetoothJson.hpp"
|
||||
#include "core/BtSpeakerTarget.hpp"
|
||||
#include "core/ISecureStore.hpp"
|
||||
#include "core/StoreError.hpp"
|
||||
|
||||
#include <expected>
|
||||
#include <vector>
|
||||
@@ -22,12 +25,11 @@
|
||||
namespace bluetooth {
|
||||
|
||||
/**
|
||||
* @brief BluetoothService — pairing and A2DP status for the web API.
|
||||
* @brief BluetoothService — pairing, scan, and saved-speaker reconnect.
|
||||
*
|
||||
* @dname BluetoothService
|
||||
* @return n/a (type)
|
||||
* @pubstate Borrows bt1035::Bt1035Driver for the process lifetime. Tracks
|
||||
* whether discoverable mode was requested via startPairing().
|
||||
* @pubstate Borrows bt1035::Bt1035Driver and core::ISecureStore for life.
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-07-06
|
||||
@@ -35,96 +37,173 @@ namespace bluetooth {
|
||||
class BluetoothService {
|
||||
public:
|
||||
/**
|
||||
* @brief BluetoothService — bind to the BT1035 driver.
|
||||
* @brief BluetoothService — bind driver and store for the process life.
|
||||
*
|
||||
* @dname BluetoothService
|
||||
* @param driver Booted BT1035 driver (must outlive this service).
|
||||
* @pubstate stores driver reference; pairing inactive initially.
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-07-06
|
||||
* @param driver BT1035 driver (must outlive this service).
|
||||
* @param store Secure store for the saved default speaker.
|
||||
* @pubstate initialises pairingActive_ to false.
|
||||
*/
|
||||
explicit BluetoothService(bt1035::Bt1035Driver& driver);
|
||||
explicit BluetoothService(bt1035::Bt1035Driver& driver,
|
||||
core::ISecureStore& store);
|
||||
|
||||
/**
|
||||
* @brief refreshStatus — read module boot, pairing, and A2DP state.
|
||||
* @brief refreshStatus — read boot/pairing/name/reconnect/A2DP state.
|
||||
*
|
||||
* @dname refreshStatus
|
||||
* @return BluetoothStatus on success, or Bt1035Error from the driver.
|
||||
* @pubstate queries driver for A2DP state when booted.
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-07-06
|
||||
* @return BluetoothStatus (booted=false if the module never booted),
|
||||
* or a Bt1035Error from the first failing query.
|
||||
* @pubstate queries driver_; reads pairingActive_.
|
||||
*/
|
||||
[[nodiscard]] std::expected<core::BluetoothStatus, bt1035::Bt1035Error>
|
||||
refreshStatus();
|
||||
|
||||
/**
|
||||
* @brief startPairing — enter discoverable mode (AT+PAIR=1).
|
||||
* @brief startPairing — enter BT1035 discoverable mode.
|
||||
*
|
||||
* @dname startPairing
|
||||
* @return Ok on success, or Bt1035Error.
|
||||
* @pubstate sets pairingActive_ on success.
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-07-06
|
||||
* @return Ok on success, or a Bt1035Error.
|
||||
* @pubstate sets pairingActive_ true on success.
|
||||
*/
|
||||
[[nodiscard]] std::expected<void, bt1035::Bt1035Error> startPairing();
|
||||
|
||||
/**
|
||||
* @brief stopPairing — leave discoverable mode (AT+PAIR=0).
|
||||
* @brief stopPairing — leave BT1035 discoverable mode.
|
||||
*
|
||||
* @dname stopPairing
|
||||
* @return Ok on success, or Bt1035Error.
|
||||
* @pubstate clears pairingActive_ on success.
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-07-06
|
||||
* @return Ok on success, or a Bt1035Error.
|
||||
* @pubstate sets pairingActive_ false on success.
|
||||
*/
|
||||
[[nodiscard]] std::expected<void, bt1035::Bt1035Error> stopPairing();
|
||||
|
||||
/**
|
||||
* @brief disconnect — release the active A2DP link (AT+A2DPDISC).
|
||||
* @brief disconnect — tear down the current A2DP link.
|
||||
*
|
||||
* @dname disconnect
|
||||
* @return Ok on success, or Bt1035Error.
|
||||
* @pubstate delegates to driver.
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-07-06
|
||||
* @return Ok on success, or a Bt1035Error.
|
||||
* @pubstate none
|
||||
*/
|
||||
[[nodiscard]] std::expected<void, bt1035::Bt1035Error> disconnect();
|
||||
|
||||
/**
|
||||
* @brief listPaired — read paired remotes from the module.
|
||||
* @brief listPaired — read the BT1035's paired-device list.
|
||||
*
|
||||
* @dname listPaired
|
||||
* @return Device list on success, or Bt1035Error.
|
||||
* @pubstate queries AT+PLIST via the driver.
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-07-07
|
||||
* @return Paired devices, or a Bt1035Error.
|
||||
* @pubstate none
|
||||
*/
|
||||
[[nodiscard]] std::expected<std::vector<core::Bt1035PairedDevice>,
|
||||
bt1035::Bt1035Error>
|
||||
listPaired();
|
||||
|
||||
/**
|
||||
* @brief setAutoReconnect — configure power-on reconnect attempts.
|
||||
* @brief setAutoReconnect — set the module's auto-reconnect attempts.
|
||||
*
|
||||
* @dname setAutoReconnect
|
||||
* @param times 0 off, 1–15 per Feasycom manual.
|
||||
* @return Ok on success, or Bt1035Error.
|
||||
* @pubstate writes AT+AUTOCONN via the driver.
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-07-07
|
||||
* @param times Retry count passed to the BT1035 firmware.
|
||||
* @return Ok on success, or a Bt1035Error.
|
||||
* @pubstate none
|
||||
*/
|
||||
[[nodiscard]] std::expected<void, bt1035::Bt1035Error> setAutoReconnect(
|
||||
std::uint8_t times);
|
||||
|
||||
/**
|
||||
* @brief scanNearby — classic BT/EDR discovery, cancelling pairing.
|
||||
*
|
||||
* @dname scanNearby
|
||||
* @param scanSeconds Scan duration in seconds.
|
||||
* @return Discovered devices, or a Bt1035Error.
|
||||
* @pubstate leaves pairing mode and stops any active scan first; sets
|
||||
* pairingActive_ false.
|
||||
*/
|
||||
[[nodiscard]] std::expected<std::vector<core::Bt1035ScannedDevice>,
|
||||
bt1035::Bt1035Error>
|
||||
scanNearby(std::uint8_t scanSeconds = 20U);
|
||||
|
||||
/**
|
||||
* @brief connectTo — direct A2DPCONN to a MAC, wait for streaming.
|
||||
*
|
||||
* @dname connectTo
|
||||
* @param mac Target BT1035 MAC (12 hex chars, no separators).
|
||||
* @return Ok once A2DP reaches Streaming, or a Bt1035Error.
|
||||
* @pubstate sets pairingActive_ false; blocks up to the connect and
|
||||
* stream settle timeouts.
|
||||
*/
|
||||
[[nodiscard]] std::expected<void, bt1035::Bt1035Error> connectTo(
|
||||
std::string_view mac);
|
||||
|
||||
/**
|
||||
* @brief connectTo — connect by request, optionally saving the target.
|
||||
*
|
||||
* @dname connectTo
|
||||
* @param request Validated MAC/name plus a save flag.
|
||||
* @return Ok once A2DP reaches Streaming, or a Bt1035Error
|
||||
* (UnexpectedResponse for an invalid MAC).
|
||||
* @pubstate sets pairingActive_ false; persists via saveSpeaker() when
|
||||
* request.save is true (a failed save does not fail connect).
|
||||
*/
|
||||
[[nodiscard]] std::expected<void, bt1035::Bt1035Error> connectTo(
|
||||
const core::BluetoothConnectRequest& request);
|
||||
|
||||
/**
|
||||
* @brief hasSavedSpeaker — check whether a default speaker is stored.
|
||||
*
|
||||
* @dname hasSavedSpeaker
|
||||
* @return true when loadSavedSpeaker() would succeed.
|
||||
* @pubstate reads store_.
|
||||
*/
|
||||
[[nodiscard]] bool hasSavedSpeaker() const;
|
||||
|
||||
/**
|
||||
* @brief loadSavedSpeaker — read the stored default speaker.
|
||||
*
|
||||
* @dname loadSavedSpeaker
|
||||
* @return BtSpeakerTarget on success, or a StoreError.
|
||||
* @pubstate reads store_.
|
||||
*/
|
||||
[[nodiscard]] std::expected<core::BtSpeakerTarget, core::StoreError>
|
||||
loadSavedSpeaker() const;
|
||||
|
||||
/**
|
||||
* @brief saveSpeaker — persist the default A2DP speaker target.
|
||||
*
|
||||
* @dname saveSpeaker
|
||||
* @param target MAC and optional display name.
|
||||
* @return Ok on success, or a StoreError.
|
||||
* @pubstate writes store_.
|
||||
*/
|
||||
[[nodiscard]] std::expected<void, core::StoreError> saveSpeaker(
|
||||
const core::BtSpeakerTarget& target);
|
||||
|
||||
/**
|
||||
* @brief clearSavedSpeaker — erase the stored default speaker.
|
||||
*
|
||||
* @dname clearSavedSpeaker
|
||||
* @return Ok on success, or a StoreError.
|
||||
* @pubstate writes store_.
|
||||
*/
|
||||
[[nodiscard]] std::expected<void, core::StoreError> clearSavedSpeaker();
|
||||
|
||||
/** @brief Launch background task: A2DPCONN saved MAC, scan fallback. */
|
||||
void startupReconnect();
|
||||
|
||||
/**
|
||||
* @brief reconnectSavedSpeaker — direct MAC connect, optional scan retry.
|
||||
*
|
||||
* @dname reconnectSavedSpeaker
|
||||
* @param scanFallback Run AT+SCAN when direct connect fails.
|
||||
* @return Ok when A2DP reaches Connected, or Bt1035Error.
|
||||
* @pubstate may block tens of seconds when scanFallback is true.
|
||||
*/
|
||||
[[nodiscard]] std::expected<void, bt1035::Bt1035Error> reconnectSavedSpeaker(
|
||||
bool scanFallback);
|
||||
|
||||
private:
|
||||
[[nodiscard]] std::expected<void, bt1035::Bt1035Error> connectDirect(
|
||||
std::string_view mac);
|
||||
|
||||
bt1035::Bt1035Driver& driver_;
|
||||
core::ISecureStore& store_;
|
||||
bool pairingActive_;
|
||||
};
|
||||
|
||||
|
||||
@@ -13,10 +13,67 @@
|
||||
|
||||
#include "bluetooth/BluetoothService.hpp"
|
||||
|
||||
#include "esp_log.h"
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
|
||||
namespace bluetooth {
|
||||
|
||||
BluetoothService::BluetoothService(bt1035::Bt1035Driver& driver)
|
||||
namespace {
|
||||
constexpr char kTag[] = "BluetoothSvc";
|
||||
constexpr int kConnectSettleMs = 30000;
|
||||
constexpr int kStreamSettleMs = 20000;
|
||||
constexpr int kAutoReconnectWaitMs = 45000;
|
||||
|
||||
[[nodiscard]] bool isA2dpLinked(core::Bt1035A2dpState state) noexcept
|
||||
{
|
||||
using core::Bt1035A2dpState;
|
||||
return state == Bt1035A2dpState::Connected
|
||||
|| state == Bt1035A2dpState::Streaming
|
||||
|| state == Bt1035A2dpState::Paused;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool isA2dpLinked(bt1035::Bt1035Driver& driver)
|
||||
{
|
||||
if (auto state = driver.queryA2dpState(); state) {
|
||||
return isA2dpLinked(*state);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool ensureA2dpStreaming(bt1035::Bt1035Driver& driver)
|
||||
{
|
||||
if (auto state = driver.queryA2dpState(); state
|
||||
&& *state == core::Bt1035A2dpState::Streaming) {
|
||||
ESP_LOGI(kTag, "A2DP already streaming");
|
||||
return true;
|
||||
}
|
||||
if (!driver.waitForA2dpStreaming(kStreamSettleMs)) {
|
||||
ESP_LOGW(kTag, "A2DP not streaming within %d ms", kStreamSettleMs);
|
||||
return false;
|
||||
}
|
||||
ESP_LOGI(kTag, "A2DP streaming OK");
|
||||
return true;
|
||||
}
|
||||
|
||||
void savedSpeakerReconnectTask(void* arg)
|
||||
{
|
||||
auto* service = static_cast<BluetoothService*>(arg);
|
||||
ESP_LOGI(kTag, "boot reconnect task started");
|
||||
if (auto result = service->reconnectSavedSpeaker(true); !result) {
|
||||
ESP_LOGW(kTag, "boot reconnect failed (%d)",
|
||||
static_cast<int>(result.error()));
|
||||
} else {
|
||||
ESP_LOGI(kTag, "boot reconnect OK");
|
||||
}
|
||||
vTaskDelete(nullptr);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
BluetoothService::BluetoothService(bt1035::Bt1035Driver& driver,
|
||||
core::ISecureStore& store)
|
||||
: driver_(driver)
|
||||
, store_(store)
|
||||
, pairingActive_(false)
|
||||
{
|
||||
}
|
||||
@@ -91,4 +148,152 @@ std::expected<void, bt1035::Bt1035Error> BluetoothService::setAutoReconnect(
|
||||
return driver_.setAutoReconnect(times);
|
||||
}
|
||||
|
||||
std::expected<std::vector<core::Bt1035ScannedDevice>, bt1035::Bt1035Error>
|
||||
BluetoothService::scanNearby(std::uint8_t scanSeconds)
|
||||
{
|
||||
pairingActive_ = false;
|
||||
(void)driver_.leavePairingMode();
|
||||
(void)driver_.stopScan();
|
||||
return driver_.scanNearbyBrEdr(scanSeconds);
|
||||
}
|
||||
|
||||
std::expected<void, bt1035::Bt1035Error> BluetoothService::connectDirect(
|
||||
std::string_view mac)
|
||||
{
|
||||
if (auto sent = driver_.connectA2dp(mac); !sent) {
|
||||
return sent;
|
||||
}
|
||||
if (!driver_.waitForA2dpConnected(kConnectSettleMs)) {
|
||||
ESP_LOGW(kTag, "A2DP connect sent but link not up in %d ms",
|
||||
kConnectSettleMs);
|
||||
return std::unexpected(bt1035::Bt1035Error::AtTimeout);
|
||||
}
|
||||
if (!ensureA2dpStreaming(driver_)) {
|
||||
return std::unexpected(bt1035::Bt1035Error::AtTimeout);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
std::expected<void, bt1035::Bt1035Error> BluetoothService::connectTo(
|
||||
std::string_view mac)
|
||||
{
|
||||
pairingActive_ = false;
|
||||
return connectDirect(mac);
|
||||
}
|
||||
|
||||
std::expected<void, bt1035::Bt1035Error> BluetoothService::connectTo(
|
||||
const core::BluetoothConnectRequest& request)
|
||||
{
|
||||
if (request.mac.empty() || !core::isValidBt1035Mac(request.mac)) {
|
||||
return std::unexpected(bt1035::Bt1035Error::UnexpectedResponse);
|
||||
}
|
||||
pairingActive_ = false;
|
||||
if (auto connected = connectDirect(request.mac); !connected) {
|
||||
return connected;
|
||||
}
|
||||
if (request.save) {
|
||||
core::BtSpeakerTarget target{
|
||||
.mac = request.mac,
|
||||
.name = request.name,
|
||||
};
|
||||
if (auto saved = saveSpeaker(target); !saved) {
|
||||
ESP_LOGW(kTag, "connect OK but save speaker failed");
|
||||
}
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
bool BluetoothService::hasSavedSpeaker() const
|
||||
{
|
||||
return store_.hasBtSpeakerTarget();
|
||||
}
|
||||
|
||||
std::expected<core::BtSpeakerTarget, core::StoreError>
|
||||
BluetoothService::loadSavedSpeaker() const
|
||||
{
|
||||
return store_.loadBtSpeakerTarget();
|
||||
}
|
||||
|
||||
std::expected<void, core::StoreError> BluetoothService::saveSpeaker(
|
||||
const core::BtSpeakerTarget& target)
|
||||
{
|
||||
return store_.saveBtSpeakerTarget(target);
|
||||
}
|
||||
|
||||
std::expected<void, core::StoreError> BluetoothService::clearSavedSpeaker()
|
||||
{
|
||||
return store_.clearBtSpeakerTarget();
|
||||
}
|
||||
|
||||
void BluetoothService::startupReconnect()
|
||||
{
|
||||
if (!hasSavedSpeaker()) {
|
||||
ESP_LOGI(kTag, "no saved BT speaker — skip boot reconnect");
|
||||
return;
|
||||
}
|
||||
if (xTaskCreate(savedSpeakerReconnectTask, "bt_reconn", 8192, this, 4,
|
||||
nullptr)
|
||||
!= pdPASS) {
|
||||
ESP_LOGW(kTag, "boot reconnect task create failed");
|
||||
}
|
||||
}
|
||||
|
||||
std::expected<void, bt1035::Bt1035Error> BluetoothService::reconnectSavedSpeaker(
|
||||
bool scanFallback)
|
||||
{
|
||||
const auto target = loadSavedSpeaker();
|
||||
if (!target) {
|
||||
return {};
|
||||
}
|
||||
|
||||
ESP_LOGI(kTag, "reconnect saved speaker %s (%s)", target->mac.c_str(),
|
||||
target->name.empty() ? "(no name)" : target->name.c_str());
|
||||
|
||||
if (isA2dpLinked(driver_)) {
|
||||
ESP_LOGI(kTag, "A2DP already linked — ensure streaming");
|
||||
if (!ensureA2dpStreaming(driver_)) {
|
||||
return std::unexpected(bt1035::Bt1035Error::AtTimeout);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
if (auto connected = connectDirect(target->mac); connected) {
|
||||
return connected;
|
||||
}
|
||||
|
||||
if (isA2dpLinked(driver_)) {
|
||||
ESP_LOGI(kTag, "A2DP linked after connect attempt");
|
||||
if (!ensureA2dpStreaming(driver_)) {
|
||||
return std::unexpected(bt1035::Bt1035Error::AtTimeout);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
ESP_LOGI(kTag, "waiting for module auto-reconnect (%d ms)",
|
||||
kAutoReconnectWaitMs);
|
||||
if (driver_.waitForA2dpConnected(kAutoReconnectWaitMs)) {
|
||||
ESP_LOGI(kTag, "A2DP auto-reconnect linked");
|
||||
if (!ensureA2dpStreaming(driver_)) {
|
||||
return std::unexpected(bt1035::Bt1035Error::AtTimeout);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
if (!scanFallback) {
|
||||
return std::unexpected(bt1035::Bt1035Error::AtTimeout);
|
||||
}
|
||||
|
||||
ESP_LOGW(kTag, "direct A2DPCONN failed — retry connect (no scan)");
|
||||
if (auto retry = connectDirect(target->mac); retry) {
|
||||
return retry;
|
||||
}
|
||||
if (isA2dpLinked(driver_)) {
|
||||
if (!ensureA2dpStreaming(driver_)) {
|
||||
return std::unexpected(bt1035::Bt1035Error::AtTimeout);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
return std::unexpected(bt1035::Bt1035Error::AtTimeout);
|
||||
}
|
||||
|
||||
} // namespace bluetooth
|
||||
|
||||
@@ -2,7 +2,7 @@ idf_component_register(
|
||||
SRCS
|
||||
"src/TunerService.cpp"
|
||||
INCLUDE_DIRS "include"
|
||||
REQUIRES core
|
||||
REQUIRES core freertos
|
||||
)
|
||||
|
||||
target_compile_features(${COMPONENT_LIB} PUBLIC cxx_std_23)
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
#include "core/ITuner.hpp"
|
||||
#include "core/SeekDirection.hpp"
|
||||
#include "core/TunerError.hpp"
|
||||
#include "core/TunerJson.hpp"
|
||||
#include "core/TunerStatus.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
@@ -109,6 +110,20 @@ public:
|
||||
[[nodiscard]] std::expected<core::FrequencyKHz, core::TunerError> seekFm(
|
||||
core::SeekDirection direction);
|
||||
|
||||
/**
|
||||
* @brief scanForStation — FM seek or DAB ensemble search with optional name.
|
||||
*
|
||||
* @dname scanForStation
|
||||
* @param request Band, step limit, and optional label substring.
|
||||
* @return Scan outcome; TunerError only on driver failure.
|
||||
* @pubstate tunes/plays first matching station; updates last tune caches.
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-08-05
|
||||
*/
|
||||
[[nodiscard]] std::expected<core::TunerScanResult, core::TunerError>
|
||||
scanForStation(const core::TunerScanRequest& request);
|
||||
|
||||
/**
|
||||
* @brief listDabServices — programmes available on the current ensemble.
|
||||
*
|
||||
|
||||
@@ -13,15 +13,124 @@
|
||||
|
||||
#include "tuner/TunerService.hpp"
|
||||
|
||||
#include "esp_log.h"
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <string>
|
||||
|
||||
namespace tuner {
|
||||
|
||||
namespace {
|
||||
constexpr char kTag[] = "TunerSvc";
|
||||
constexpr int kDabTuneSettleMs = 600;
|
||||
/** FM scan step size (100 kHz spacing). */
|
||||
constexpr std::uint32_t kFmScanStepKhz = 100U;
|
||||
constexpr int kFmTuneSettleMs = 120;
|
||||
constexpr int kFmNamePollMs = 250;
|
||||
constexpr int kFmNamePollAttempts = 6;
|
||||
constexpr std::int8_t kMinFmScanRssiDbuV = 5;
|
||||
constexpr std::int8_t kMinFmScanSnrDb = 10;
|
||||
/** Max |READFREQ − commanded| for scan hit without RDS lock (kHz). */
|
||||
constexpr std::uint32_t kFmScanChipFreqSlackKhz = 150U;
|
||||
constexpr std::uint8_t kMinDabFicQuality = 35U;
|
||||
/** European FM band top used for scan/seek wrap (107.9 MHz). */
|
||||
constexpr std::uint32_t kFmScanMaxKhz = 107900U;
|
||||
/** European FM band bottom used for full-band scan (87.5 MHz). */
|
||||
constexpr std::uint32_t kFmScanMinKhz = 87500U;
|
||||
|
||||
[[nodiscard]] core::FrequencyKHz fmScanStartFrequency(
|
||||
core::FrequencyKHz current,
|
||||
std::string_view nameFilter)
|
||||
{
|
||||
if (!nameFilter.empty()) {
|
||||
return current;
|
||||
}
|
||||
const std::uint32_t khz = current.value();
|
||||
if (khz > kFmScanMaxKhz || khz < kFmScanMinKhz) {
|
||||
return *core::FrequencyKHz::tryFromKhz(kFmScanMinKhz);
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
[[nodiscard]] core::FrequencyKHz defaultFmFrequency()
|
||||
{
|
||||
return *core::FrequencyKHz::tryFromKhz(101500U);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string toLowerAscii(std::string_view text)
|
||||
{
|
||||
std::string lowered;
|
||||
lowered.reserve(text.size());
|
||||
for (const char ch : text) {
|
||||
lowered.push_back(static_cast<char>(std::tolower(
|
||||
static_cast<unsigned char>(ch))));
|
||||
}
|
||||
return lowered;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool nameMatchesFilter(const std::optional<core::BroadcastLabel>& label,
|
||||
std::string_view filterLower)
|
||||
{
|
||||
if (filterLower.empty()) {
|
||||
return true;
|
||||
}
|
||||
if (!label) {
|
||||
return false;
|
||||
}
|
||||
const std::string haystack = toLowerAscii(label->value());
|
||||
return haystack.find(filterLower) != std::string::npos;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool nameMatchesFilter(std::string_view label,
|
||||
std::string_view filterLower)
|
||||
{
|
||||
if (filterLower.empty()) {
|
||||
return true;
|
||||
}
|
||||
const std::string haystack = toLowerAscii(label);
|
||||
return haystack.find(filterLower) != std::string::npos;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool fmStatusUsableForScan(const core::TunerStatus& status,
|
||||
std::uint32_t commandedKhz,
|
||||
bool requireLocked)
|
||||
{
|
||||
if (!status.fmRssiDbuV || *status.fmRssiDbuV < kMinFmScanRssiDbuV) {
|
||||
return false;
|
||||
}
|
||||
if (requireLocked) {
|
||||
return status.locked;
|
||||
}
|
||||
if (!status.fmSnrDb || *status.fmSnrDb < kMinFmScanSnrDb) {
|
||||
return false;
|
||||
}
|
||||
if (status.fmChipReadFrequency) {
|
||||
const std::uint32_t chipKhz = status.fmChipReadFrequency->value();
|
||||
const std::uint32_t diff =
|
||||
chipKhz > commandedKhz ? chipKhz - commandedKhz
|
||||
: commandedKhz - chipKhz;
|
||||
if (diff > kFmScanChipFreqSlackKhz) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] core::TunerScanResult makeScanResult(
|
||||
const core::TunerScanRequest& request,
|
||||
std::uint16_t steps,
|
||||
bool found)
|
||||
{
|
||||
core::TunerScanResult result = {};
|
||||
result.found = found;
|
||||
result.band = request.band;
|
||||
result.stepsTried = steps;
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TunerService::TunerService(core::ITuner& tuner)
|
||||
@@ -77,6 +186,160 @@ std::expected<core::FrequencyKHz, core::TunerError> TunerService::seekFm(
|
||||
return result;
|
||||
}
|
||||
|
||||
std::expected<core::TunerScanResult, core::TunerError>
|
||||
TunerService::scanForStation(const core::TunerScanRequest& request)
|
||||
{
|
||||
const std::string_view nameFilter = request.nameFilter;
|
||||
|
||||
if (request.band == core::TunerBand::Fm) {
|
||||
const core::FrequencyKHz scanStart =
|
||||
fmScanStartFrequency(lastFmFrequency_, nameFilter);
|
||||
if (auto tuned = tuneFm(scanStart); !tuned) {
|
||||
return std::unexpected(tuned.error());
|
||||
}
|
||||
|
||||
const std::uint32_t startFreq = lastFmFrequency_.value();
|
||||
const bool requireLocked = !nameFilter.empty();
|
||||
std::uint32_t freqKhz = startFreq;
|
||||
|
||||
ESP_LOGI(kTag, "FM scan start from %u kHz (max %u steps, name='%.*s')",
|
||||
static_cast<unsigned>(startFreq), static_cast<unsigned>(request.maxSteps),
|
||||
static_cast<int>(nameFilter.size()), nameFilter.data());
|
||||
|
||||
for (std::uint16_t step = 1U; step <= request.maxSteps; ++step) {
|
||||
freqKhz += kFmScanStepKhz;
|
||||
if (freqKhz > kFmScanMaxKhz) {
|
||||
freqKhz = kFmScanMinKhz;
|
||||
}
|
||||
if (freqKhz == startFreq) {
|
||||
ESP_LOGI(kTag, "FM scan wrapped to start frequency");
|
||||
break;
|
||||
}
|
||||
|
||||
const auto next = core::FrequencyKHz::tryFromKhz(freqKhz);
|
||||
if (!next) {
|
||||
return std::unexpected(core::TunerError::TuneFailed);
|
||||
}
|
||||
if (auto tuned = tuneFm(*next); !tuned) {
|
||||
ESP_LOGW(kTag, "FM scan step %u tune failed at %u kHz (err=%d)",
|
||||
static_cast<unsigned>(step), static_cast<unsigned>(freqKhz),
|
||||
static_cast<int>(tuned.error()));
|
||||
return std::unexpected(tuned.error());
|
||||
}
|
||||
vTaskDelay(pdMS_TO_TICKS(kFmTuneSettleMs));
|
||||
|
||||
std::optional<core::BroadcastLabel> stationName;
|
||||
bool usable = false;
|
||||
for (int attempt = 0; attempt < kFmNamePollAttempts; ++attempt) {
|
||||
auto status = refreshStatus();
|
||||
if (!status) {
|
||||
return std::unexpected(status.error());
|
||||
}
|
||||
if (attempt == 0) {
|
||||
ESP_LOGI(kTag,
|
||||
"FM scan step %u at %u kHz: valid=%d rssi=%d dBuV "
|
||||
"snr=%d dB",
|
||||
static_cast<unsigned>(step),
|
||||
static_cast<unsigned>(lastFmFrequency_.value()),
|
||||
static_cast<int>(status->locked),
|
||||
status->fmRssiDbuV ? *status->fmRssiDbuV : -128,
|
||||
status->fmSnrDb ? *status->fmSnrDb : -128);
|
||||
}
|
||||
if (!fmStatusUsableForScan(*status, freqKhz, requireLocked)) {
|
||||
break;
|
||||
}
|
||||
usable = true;
|
||||
stationName = status->fmStationName;
|
||||
if (nameFilter.empty()
|
||||
|| nameMatchesFilter(stationName, nameFilter)) {
|
||||
break;
|
||||
}
|
||||
if (attempt + 1 < kFmNamePollAttempts) {
|
||||
vTaskDelay(pdMS_TO_TICKS(kFmNamePollMs));
|
||||
}
|
||||
}
|
||||
|
||||
if (!usable) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (nameFilter.empty() || nameMatchesFilter(stationName, nameFilter)) {
|
||||
auto status = refreshStatus();
|
||||
if (!status) {
|
||||
return std::unexpected(status.error());
|
||||
}
|
||||
|
||||
core::TunerScanResult result = makeScanResult(request, step, true);
|
||||
result.fmFrequency = status->fmFrequency;
|
||||
result.stationName = status->fmStationName;
|
||||
ESP_LOGI(kTag, "FM scan found %u kHz after %u steps",
|
||||
static_cast<unsigned>(result.fmFrequency ? result.fmFrequency->value() : 0U),
|
||||
static_cast<unsigned>(step));
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
ESP_LOGW(kTag, "FM scan: no station found");
|
||||
return makeScanResult(request, request.maxSteps, false);
|
||||
}
|
||||
|
||||
ESP_LOGI(kTag, "DAB scan start (max %u ensembles, name='%.*s')",
|
||||
static_cast<unsigned>(request.maxSteps),
|
||||
static_cast<int>(nameFilter.size()), nameFilter.data());
|
||||
|
||||
for (std::uint16_t step = 0U; step < request.maxSteps; ++step) {
|
||||
const std::uint8_t freqIndex = static_cast<std::uint8_t>(step);
|
||||
if (auto tuned = tuneDab(freqIndex); !tuned) {
|
||||
return std::unexpected(tuned.error());
|
||||
}
|
||||
vTaskDelay(pdMS_TO_TICKS(kDabTuneSettleMs));
|
||||
|
||||
auto status = refreshStatus();
|
||||
if (!status) {
|
||||
return std::unexpected(status.error());
|
||||
}
|
||||
if (!status->locked || !status->dabFicQuality
|
||||
|| *status->dabFicQuality < kMinDabFicQuality) {
|
||||
continue;
|
||||
}
|
||||
|
||||
auto services = listDabServices();
|
||||
if (!services || services->empty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const core::TunerServiceEntry& service : *services) {
|
||||
const std::string_view label(service.label.data());
|
||||
if (!nameMatchesFilter(label, nameFilter)) {
|
||||
continue;
|
||||
}
|
||||
if (auto played =
|
||||
playDabService(service.serviceId, service.componentId);
|
||||
!played) {
|
||||
continue;
|
||||
}
|
||||
|
||||
core::TunerScanResult result =
|
||||
makeScanResult(request, static_cast<std::uint16_t>(step + 1U), true);
|
||||
result.dabFreqIndex = freqIndex;
|
||||
result.dabServiceId = service.serviceId;
|
||||
result.dabComponentId = service.componentId;
|
||||
if (auto parsed = core::BroadcastLabel::tryFromChipBytes(label);
|
||||
parsed) {
|
||||
result.stationName = std::move(*parsed);
|
||||
}
|
||||
ESP_LOGI(kTag, "DAB scan found idx=%u svc=%u after %u steps",
|
||||
static_cast<unsigned>(freqIndex),
|
||||
static_cast<unsigned>(service.serviceId),
|
||||
static_cast<unsigned>(step + 1U));
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
ESP_LOGW(kTag, "DAB scan: no station found");
|
||||
return makeScanResult(request, request.maxSteps, false);
|
||||
}
|
||||
|
||||
std::expected<std::vector<core::TunerServiceEntry>, core::TunerError>
|
||||
TunerService::listDabServices()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
idf_component_register(
|
||||
SRCS
|
||||
"src/WebRadioService.cpp"
|
||||
INCLUDE_DIRS "include"
|
||||
REQUIRES core freertos
|
||||
)
|
||||
|
||||
target_compile_features(${COMPONENT_LIB} PUBLIC cxx_std_23)
|
||||
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* @file WebRadioService.hpp
|
||||
* @brief Live, persisted config for the internet radio streaming task.
|
||||
*
|
||||
* DigiRadio firmware — https://github.com/manvalan/DigiRadio
|
||||
*
|
||||
* Copyright 2026 Michele Bigi
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-08-08
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include "core/ISecureStore.hpp"
|
||||
#include "core/StoreError.hpp"
|
||||
#include "core/WebRadioConfig.hpp"
|
||||
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/semphr.h"
|
||||
|
||||
#include <expected>
|
||||
|
||||
namespace webradio {
|
||||
|
||||
/**
|
||||
* @brief WebRadioService — thread-safe streaming config for HTTP + task.
|
||||
*
|
||||
* @dname WebRadioService
|
||||
* @return n/a (type)
|
||||
* @pubstate Borrows core::ISecureStore for life. Owns a FreeRTOS mutex
|
||||
* guarding an in-RAM copy of the config; the streaming task in
|
||||
* main/web_radio_stream.cpp polls config() to react to changes
|
||||
* without a reboot.
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-08-08
|
||||
*/
|
||||
class WebRadioService {
|
||||
public:
|
||||
/**
|
||||
* @brief WebRadioService — load persisted config or factory default.
|
||||
*
|
||||
* @dname WebRadioService
|
||||
* @param store Secure store for persistence (must outlive this).
|
||||
* @pubstate reads store via loadWebRadioConfigJson(); creates mutex_.
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-08-08
|
||||
*/
|
||||
explicit WebRadioService(core::ISecureStore& store);
|
||||
|
||||
~WebRadioService();
|
||||
|
||||
WebRadioService(const WebRadioService&) = delete;
|
||||
WebRadioService& operator=(const WebRadioService&) = delete;
|
||||
|
||||
/**
|
||||
* @brief config — read a thread-safe snapshot of the current config.
|
||||
*
|
||||
* @dname config
|
||||
* @return Copy of the live WebRadioConfig.
|
||||
* @pubstate locks mutex_ for the copy.
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-08-08
|
||||
*/
|
||||
[[nodiscard]] core::WebRadioConfig config() const;
|
||||
|
||||
/**
|
||||
* @brief setConfig — persist and apply a new streaming config.
|
||||
*
|
||||
* @dname setConfig
|
||||
* @param config Validated config from the HTTP layer.
|
||||
* @return Ok on success, or a StoreError.
|
||||
* @pubstate persists via store_ first, then updates the live copy under
|
||||
* mutex_ so a failed save never desyncs the running task.
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-08-08
|
||||
*/
|
||||
[[nodiscard]] std::expected<void, core::StoreError> setConfig(
|
||||
const core::WebRadioConfig& config);
|
||||
|
||||
private:
|
||||
core::ISecureStore& store_;
|
||||
SemaphoreHandle_t mutex_;
|
||||
core::WebRadioConfig config_;
|
||||
};
|
||||
|
||||
} // namespace webradio
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* @file WebRadioService.cpp
|
||||
* @brief WebRadioService implementation.
|
||||
*
|
||||
* DigiRadio firmware — https://github.com/manvalan/DigiRadio
|
||||
*
|
||||
* Copyright 2026 Michele Bigi
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-08-08
|
||||
*/
|
||||
|
||||
#include "webradio/WebRadioService.hpp"
|
||||
|
||||
#include "core/WebRadioJson.hpp"
|
||||
|
||||
namespace webradio {
|
||||
|
||||
namespace {
|
||||
|
||||
[[nodiscard]] core::WebRadioConfig loadInitialConfig(core::ISecureStore& store)
|
||||
{
|
||||
if (store.hasWebRadioConfig()) {
|
||||
auto json = store.loadWebRadioConfigJson();
|
||||
if (json) {
|
||||
auto parsed = core::parseWebRadioConfigJson(*json);
|
||||
if (parsed) {
|
||||
return *parsed;
|
||||
}
|
||||
}
|
||||
}
|
||||
return core::WebRadioConfig::factoryDefault();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
WebRadioService::WebRadioService(core::ISecureStore& store)
|
||||
: store_(store)
|
||||
, mutex_(xSemaphoreCreateMutex())
|
||||
, config_(loadInitialConfig(store))
|
||||
{
|
||||
}
|
||||
|
||||
WebRadioService::~WebRadioService()
|
||||
{
|
||||
vSemaphoreDelete(mutex_);
|
||||
}
|
||||
|
||||
core::WebRadioConfig WebRadioService::config() const
|
||||
{
|
||||
xSemaphoreTake(mutex_, portMAX_DELAY);
|
||||
const core::WebRadioConfig snapshot = config_;
|
||||
xSemaphoreGive(mutex_);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
std::expected<void, core::StoreError> WebRadioService::setConfig(
|
||||
const core::WebRadioConfig& config)
|
||||
{
|
||||
const std::string json = core::serializeWebRadioConfigJson(config);
|
||||
if (auto saved = store_.saveWebRadioConfigJson(json); !saved) {
|
||||
return saved;
|
||||
}
|
||||
|
||||
xSemaphoreTake(mutex_, portMAX_DELAY);
|
||||
config_ = config;
|
||||
xSemaphoreGive(mutex_);
|
||||
return {};
|
||||
}
|
||||
|
||||
} // namespace webradio
|
||||
Reference in New Issue
Block a user