Add DAB ANTCAP calibration and fix BT1035 boot banner timing
Extend the FM-only ANTCAP antenna-varactor override to DAB, mirroring the existing mechanism end to end (driver, tuner, service, EEPROM storage, HTTP API). Live sweep on real hardware found no ANTCAP value beating auto-tune on the ensembles tested, so DAB stays on auto-tune by default. Also fix BT1035 boot: the module's real boot banner doesn't appear until ~18-24s after RESET# releases, not the 3.5s previously waited; add a 2-attempt retry and a baud-rate probe fallback for diagnostics. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -86,6 +86,10 @@ public:
|
||||
*
|
||||
* @dname tuneDab
|
||||
* @param freqIndex Ensemble index 0–37.
|
||||
* @param antCap Front-end antenna varactor override (0-128).
|
||||
* 0 = automatic; other values force a specific
|
||||
* varactor setting, for antenna calibration
|
||||
* sweeps. See tuneFm's antCap doc for details.
|
||||
* @return Ok on success, or WrongBand / TuneFailed / NotBooted.
|
||||
* @pubstate writes last tune target in the adapter.
|
||||
*
|
||||
@@ -93,13 +97,21 @@ public:
|
||||
* @date 2026-07-06
|
||||
*/
|
||||
[[nodiscard]] virtual std::expected<void, TunerError> tuneDab(
|
||||
std::uint8_t freqIndex) = 0;
|
||||
std::uint8_t freqIndex, std::uint8_t antCap = 0U) = 0;
|
||||
|
||||
/**
|
||||
* @brief tuneFm — tune to an FM centre frequency.
|
||||
*
|
||||
* @dname tuneFm
|
||||
* @param frequency Validated FM centre frequency.
|
||||
* @param antCap Front-end antenna varactor override (0-128).
|
||||
* 0 = automatic (chip's own FE_VARM/VARB-derived
|
||||
* tuning); other values force a specific varactor
|
||||
* setting, for antenna calibration sweeps. Chip-
|
||||
* specific concept (AN851 Appendix A on the
|
||||
* Si4684), exposed here only because ANTCAP has no
|
||||
* other reasonable home without duplicating the
|
||||
* whole tune path per driver.
|
||||
* @return Ok on success, or WrongBand / TuneFailed / NotBooted.
|
||||
* @pubstate writes last tune target in the adapter.
|
||||
*
|
||||
@@ -107,7 +119,7 @@ public:
|
||||
* @date 2026-07-06
|
||||
*/
|
||||
[[nodiscard]] virtual std::expected<void, TunerError> tuneFm(
|
||||
FrequencyKHz frequency) = 0;
|
||||
FrequencyKHz frequency, std::uint8_t antCap = 0U) = 0;
|
||||
|
||||
/**
|
||||
* @brief seekFm — seek to the next valid FM station.
|
||||
|
||||
@@ -41,6 +41,9 @@ struct TunerTuneRequest {
|
||||
TunerBand band; ///< Target band (Dab or Fm).
|
||||
std::uint8_t dabFreqIndex; ///< Band III ensemble index (0–37) when band is Dab.
|
||||
std::optional<FrequencyKHz> fmFrequency; ///< FM centre frequency when band is Fm.
|
||||
std::optional<std::uint8_t> antCap; ///< Antenna varactor override (0–128),
|
||||
///< for calibration sweeps; applies to
|
||||
///< whichever band is being tuned.
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -239,4 +242,38 @@ struct TunerFmScannedStation {
|
||||
[[nodiscard]] std::string serializeTunerFmBandScanJson(
|
||||
const std::vector<TunerFmScannedStation>& stations);
|
||||
|
||||
/**
|
||||
* @brief AntennaCalibrationRequest — parsed POST
|
||||
* /api/tuner/calibrate-antenna body.
|
||||
*
|
||||
* @dname AntennaCalibrationRequest
|
||||
* @return n/a (type)
|
||||
* @pubstate Plain DTO filled by parseAntennaCalibrationJson at the HTTP
|
||||
* boundary.
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-08-20
|
||||
*/
|
||||
struct AntennaCalibrationRequest {
|
||||
TunerBand band; ///< Which band's ANTCAP default this saves.
|
||||
std::uint8_t antCap; ///< Value to persist (0-128).
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief parseAntennaCalibrationJson — validate POST
|
||||
* /api/tuner/calibrate-antenna body.
|
||||
*
|
||||
* @dname parseAntennaCalibrationJson
|
||||
* @param json Untrusted request body from the HTTP handler.
|
||||
* @return Band + ANTCAP value (0-128) on success, or a ParseError.
|
||||
* `band` defaults to Fm when the field is omitted, preserving
|
||||
* the original FM-only request shape.
|
||||
* @pubstate none
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-08-19
|
||||
*/
|
||||
[[nodiscard]] std::expected<AntennaCalibrationRequest, ParseError>
|
||||
parseAntennaCalibrationJson(std::string_view json);
|
||||
|
||||
} // namespace core
|
||||
|
||||
@@ -203,6 +203,10 @@ std::expected<TunerTuneRequest, ParseError> parseTunerTuneJson(
|
||||
} else {
|
||||
return std::unexpected(ParseError::InvalidJson);
|
||||
}
|
||||
unsigned long antCap = 0U;
|
||||
if (extractJsonUint(json, "antcap", antCap) && antCap <= 128U) {
|
||||
req.antCap = static_cast<std::uint8_t>(antCap);
|
||||
}
|
||||
return req;
|
||||
}
|
||||
|
||||
@@ -336,4 +340,28 @@ std::string serializeTunerFmBandScanJson(
|
||||
return out.str();
|
||||
}
|
||||
|
||||
std::expected<AntennaCalibrationRequest, ParseError>
|
||||
parseAntennaCalibrationJson(std::string_view json)
|
||||
{
|
||||
if (json.find('{') == std::string_view::npos) {
|
||||
return std::unexpected(ParseError::InvalidJson);
|
||||
}
|
||||
unsigned long antCap = 0U;
|
||||
if (!extractJsonUint(json, "antcap", antCap) || antCap > 128U) {
|
||||
return std::unexpected(ParseError::MissingField);
|
||||
}
|
||||
|
||||
AntennaCalibrationRequest req = {};
|
||||
req.antCap = static_cast<std::uint8_t>(antCap);
|
||||
const std::string_view band = extractJsonString(json, "band");
|
||||
if (band == "dab") {
|
||||
req.band = TunerBand::Dab;
|
||||
} else if (band.empty() || band == "fm") {
|
||||
req.band = TunerBand::Fm;
|
||||
} else {
|
||||
return std::unexpected(ParseError::InvalidJson);
|
||||
}
|
||||
return req;
|
||||
}
|
||||
|
||||
} // namespace core
|
||||
|
||||
@@ -94,6 +94,10 @@ add_executable(dsp_param_json_test dsp_param_json_test.cpp)
|
||||
target_link_libraries(dsp_param_json_test PRIVATE digiradio_core)
|
||||
add_test(NAME dsp_param_json_test COMMAND dsp_param_json_test)
|
||||
|
||||
add_executable(bluetooth_json_test bluetooth_json_test.cpp)
|
||||
target_link_libraries(bluetooth_json_test PRIVATE digiradio_core)
|
||||
add_test(NAME bluetooth_json_test COMMAND bluetooth_json_test)
|
||||
|
||||
add_executable(frequency_khz_test frequency_khz_test.cpp)
|
||||
target_link_libraries(frequency_khz_test PRIVATE digiradio_core)
|
||||
add_test(NAME frequency_khz_test COMMAND frequency_khz_test)
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
/**
|
||||
* @file bluetooth_json_test.cpp
|
||||
* @brief Host tests for Bluetooth JSON parse/serialise.
|
||||
*
|
||||
* DigiRadio firmware — https://github.com/manvalan/DigiRadio
|
||||
*
|
||||
* Copyright 2026 Michele Bigi
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-08-19
|
||||
*/
|
||||
|
||||
#include "core/BluetoothJson.hpp"
|
||||
#include "core/ParseError.hpp"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
namespace {
|
||||
|
||||
[[nodiscard]] bool expectEqual(const std::string& actual,
|
||||
const std::string& expected)
|
||||
{
|
||||
if (actual == expected) {
|
||||
return true;
|
||||
}
|
||||
std::cerr << "expected: " << expected << "\nactual: " << actual << '\n';
|
||||
return false;
|
||||
}
|
||||
|
||||
[[nodiscard]] int runStatusSerialiseTest()
|
||||
{
|
||||
const core::BluetoothStatus status{
|
||||
.booted = true,
|
||||
.pairing = false,
|
||||
.a2dpState = core::Bt1035A2dpState::Streaming,
|
||||
.deviceName = "DigiRadio-CC4DB4",
|
||||
.autoReconnect = 3U,
|
||||
};
|
||||
const std::string json = core::serializeBluetoothStatusJson(status);
|
||||
if (!expectEqual(json,
|
||||
R"({"booted":true,"pairing":false,"a2dp":"streaming",)"
|
||||
R"("device_name":"DigiRadio-CC4DB4","auto_reconnect":3})")) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
[[nodiscard]] int runScanSerialiseTest()
|
||||
{
|
||||
const std::vector<core::Bt1035ScannedDevice> devices{
|
||||
core::Bt1035ScannedDevice{
|
||||
.index = 1U,
|
||||
.addressType = 2U,
|
||||
.mac = "001122334455",
|
||||
.rssiDbm = -58,
|
||||
.name = "Bose SoundLink",
|
||||
.deviceClass = "240404",
|
||||
},
|
||||
};
|
||||
const std::string json = core::serializeBluetoothScanJson(devices);
|
||||
if (!expectEqual(json,
|
||||
R"({"devices":[{"index":1,"mac":"001122334455",)"
|
||||
R"("name":"Bose SoundLink","rssi_dbm":-58}]})")) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
[[nodiscard]] int runPairedSerialiseTest()
|
||||
{
|
||||
const std::vector<core::Bt1035PairedDevice> devices{
|
||||
core::Bt1035PairedDevice{.index = 1U, .mac = "AABBCCDDEEFF", .name = "Phone"},
|
||||
};
|
||||
const std::string json = core::serializeBluetoothPairedJson(devices);
|
||||
if (!expectEqual(json,
|
||||
R"({"devices":[{"index":1,"mac":"AABBCCDDEEFF","name":"Phone"}]})")) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
[[nodiscard]] int runAutoReconnectParseTest()
|
||||
{
|
||||
const auto ok = core::parseBluetoothAutoReconnectJson(R"({"times":5})");
|
||||
if (!ok || *ok != 5U) {
|
||||
std::cerr << "auto-reconnect valid parse failed\n";
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
const auto tooHigh = core::parseBluetoothAutoReconnectJson(R"({"times":16})");
|
||||
if (tooHigh) {
|
||||
std::cerr << "auto-reconnect out-of-range accepted\n";
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
const auto missing = core::parseBluetoothAutoReconnectJson(R"({})");
|
||||
if (missing || missing.error() != core::ParseError::MissingField) {
|
||||
std::cerr << "auto-reconnect missing field mis-reported\n";
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
[[nodiscard]] int runConnectJsonParseTest()
|
||||
{
|
||||
const auto ok =
|
||||
core::parseBluetoothConnectJson(R"({"mac":"001122334455"})");
|
||||
if (!ok || *ok != "001122334455") {
|
||||
std::cerr << "connect mac parse failed\n";
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
// Normalises to uppercase.
|
||||
const auto lower =
|
||||
core::parseBluetoothConnectJson(R"({"mac":"aabbccddeeff"})");
|
||||
if (!lower || *lower != "AABBCCDDEEFF") {
|
||||
std::cerr << "connect mac uppercasing failed\n";
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
const auto invalid = core::parseBluetoothConnectJson(R"({"mac":"not-a-mac"})");
|
||||
if (invalid) {
|
||||
std::cerr << "connect invalid mac accepted\n";
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
[[nodiscard]] int runConnectRequestParseTest()
|
||||
{
|
||||
const auto request = core::parseBluetoothConnectRequest(
|
||||
R"({"mac":"001122334455","name":"Bose SoundLink","save":true})");
|
||||
if (request.mac != "001122334455" || request.name != "Bose SoundLink"
|
||||
|| !request.save) {
|
||||
std::cerr << "connect request full parse failed\n";
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
const auto minimal =
|
||||
core::parseBluetoothConnectRequest(R"({"mac":"001122334455"})");
|
||||
if (minimal.mac != "001122334455" || !minimal.name.empty()
|
||||
|| minimal.save) {
|
||||
std::cerr << "connect request minimal parse failed\n";
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
const auto badMac = core::parseBluetoothConnectRequest(R"({})");
|
||||
if (!badMac.mac.empty()) {
|
||||
std::cerr << "connect request missing mac should stay empty\n";
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
[[nodiscard]] int runSpeakerRoundTripTest()
|
||||
{
|
||||
const core::BtSpeakerTarget target{.mac = "001122334455",
|
||||
.name = "Bose SoundLink"};
|
||||
const std::string json = core::serializeBluetoothSpeakerJson(&target);
|
||||
if (!expectEqual(json,
|
||||
R"({"configured":true,"mac":"001122334455",)"
|
||||
R"("name":"Bose SoundLink"})")) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
const std::string unset = core::serializeBluetoothSpeakerJson(nullptr);
|
||||
if (!expectEqual(unset, R"({"configured":false})")) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
|
||||
const auto parsed = core::parseBluetoothSpeakerJson(
|
||||
R"({"mac":"001122334455","name":"Bose SoundLink"})");
|
||||
if (!parsed || parsed->mac != "001122334455"
|
||||
|| parsed->name != "Bose SoundLink") {
|
||||
std::cerr << "speaker parse round-trip failed\n";
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
const auto invalid = core::parseBluetoothSpeakerJson(R"({"mac":"bad"})");
|
||||
if (invalid) {
|
||||
std::cerr << "speaker parse invalid mac accepted\n";
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
[[nodiscard]] int runErrorSerialiseTest()
|
||||
{
|
||||
const std::string json = core::serializeBluetoothErrorJson("scan_failed");
|
||||
if (!expectEqual(json, R"({"status":"error","reason":"scan_failed"})")) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
if (runStatusSerialiseTest() != EXIT_SUCCESS) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
if (runScanSerialiseTest() != EXIT_SUCCESS) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
if (runPairedSerialiseTest() != EXIT_SUCCESS) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
if (runAutoReconnectParseTest() != EXIT_SUCCESS) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
if (runConnectJsonParseTest() != EXIT_SUCCESS) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
if (runConnectRequestParseTest() != EXIT_SUCCESS) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
if (runSpeakerRoundTripTest() != EXIT_SUCCESS) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
if (runErrorSerialiseTest() != EXIT_SUCCESS) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
@@ -111,13 +111,13 @@ public:
|
||||
}
|
||||
|
||||
[[nodiscard]] std::expected<void, core::TunerError> tuneDab(
|
||||
std::uint8_t) override
|
||||
std::uint8_t, std::uint8_t) override
|
||||
{
|
||||
return {};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::expected<void, core::TunerError> tuneFm(
|
||||
core::FrequencyKHz) override
|
||||
core::FrequencyKHz, std::uint8_t) override
|
||||
{
|
||||
tunedFm = true;
|
||||
return {};
|
||||
|
||||
@@ -53,13 +53,13 @@ public:
|
||||
}
|
||||
|
||||
[[nodiscard]] std::expected<void, core::TunerError> tuneDab(
|
||||
std::uint8_t) override
|
||||
std::uint8_t, std::uint8_t) override
|
||||
{
|
||||
return {};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::expected<void, core::TunerError> tuneFm(
|
||||
core::FrequencyKHz) override
|
||||
core::FrequencyKHz, std::uint8_t) override
|
||||
{
|
||||
return {};
|
||||
}
|
||||
|
||||
@@ -343,6 +343,7 @@ public:
|
||||
private:
|
||||
[[nodiscard]] std::expected<void, Bt1035Error> ensureBooted() const;
|
||||
[[nodiscard]] std::expected<void, Bt1035Error> runInitSequence();
|
||||
[[nodiscard]] std::expected<void, Bt1035Error> resetAndInitOnce();
|
||||
[[nodiscard]] std::expected<std::string, Bt1035Error> transmitAndCollect(
|
||||
std::string_view commandLine, int timeoutMs = kResponseTimeoutMs);
|
||||
[[nodiscard]] std::expected<std::string, Bt1035Error> transmitAndCollectUntil(
|
||||
|
||||
@@ -38,6 +38,23 @@ constexpr int kUartTxBuffer = 256;
|
||||
constexpr int kResponseTimeoutMs = 2000;
|
||||
constexpr int kPostResetMs = 500;
|
||||
constexpr int kPostUartMs = 100;
|
||||
/** Feasycom BT1035 programming user guide §2.2 (pin 34 SYS_CTRL): "Delay
|
||||
* 100ms, pull high". */
|
||||
constexpr int kSysCtlLeadInMs = 100;
|
||||
/** Margin beyond the datasheet's own >20ms SYS_CTRL-assertion-to-power-up
|
||||
* minimum (§4.7), for regulator/crystal settling before RESET releases. */
|
||||
constexpr int kSysCtlSettleMs = 50;
|
||||
/** Measured live (2026-08-20, power/wiring confirmed sound with a
|
||||
* multimeter — VBAT_IN/SYS_CTRL/1.8V_OUT/VDD_IO all correct, TX/RX pins
|
||||
* verified via continuity): the module's spontaneous boot banner
|
||||
* (+VER=FSC-BT1035,..., +DEVSTAT=1) doesn't appear until ~18.5s after
|
||||
* RESET# releases — full BT stack init, not just the internal regulator.
|
||||
* The previous 3500ms wait here was never enough for the module to say
|
||||
* anything, so every prior boot attempt cut power and restarted before
|
||||
* the module could finish booting even once. See kBootAttempts below. */
|
||||
constexpr int kBootBannerWaitMs = 25000;
|
||||
constexpr int kBootAttempts = 2;
|
||||
constexpr int kBootRetryDelayMs = 300;
|
||||
|
||||
void flushUartRx(int uartPort) noexcept
|
||||
{
|
||||
@@ -49,15 +66,53 @@ void flushUartRx(int uartPort) noexcept
|
||||
}
|
||||
}
|
||||
|
||||
// Diagnostic only: some BT1035 firmware prints an unsolicited boot banner on
|
||||
// UART right after the hardware RESET# pulse. Capturing it (or its absence)
|
||||
// tells us whether the UART link is electrically alive independent of the
|
||||
// AT command layer.
|
||||
// Diagnostic only, run once if all kBootAttempts fail at 115200 (the
|
||||
// datasheet's own default). AT+BAUD persists across RESET#/SYS_CTRL power
|
||||
// cycles (programming guide §5.1.3), so a stray manual AT+BAUD or
|
||||
// AT+RESTORE sent during earlier interactive testing could have left the
|
||||
// module listening at a different rate than our fixed assumption — this
|
||||
// sweep tells us if that's what's happening instead of guessing.
|
||||
constexpr std::array<int, 8> kBaudProbeCandidates = {
|
||||
9600, 19200, 38400, 57600, 115200, 230400, 460800, 921600};
|
||||
|
||||
void probeBaudRates(int uartPort) noexcept
|
||||
{
|
||||
ESP_LOGW(kTag, "115200 unresponsive after %d attempts — sweeping baud rates",
|
||||
kBootAttempts);
|
||||
for (const int baud : kBaudProbeCandidates) {
|
||||
if (uart_set_baudrate(static_cast<uart_port_t>(uartPort), baud)
|
||||
!= ESP_OK) {
|
||||
continue;
|
||||
}
|
||||
flushUartRx(uartPort);
|
||||
uart_write_bytes(static_cast<uart_port_t>(uartPort), "AT\r\n", 4);
|
||||
|
||||
std::array<char, 64> buf{};
|
||||
const int n = uart_read_bytes(static_cast<uart_port_t>(uartPort),
|
||||
buf.data(), buf.size(),
|
||||
pdMS_TO_TICKS(500));
|
||||
if (n > 0) {
|
||||
ESP_LOGW(kTag, "baud probe: module responded at %d baud (%d bytes)",
|
||||
baud, n);
|
||||
ESP_LOG_BUFFER_HEX(kTag, buf.data(), static_cast<std::size_t>(n));
|
||||
} else {
|
||||
ESP_LOGI(kTag, "baud probe: silent at %d baud", baud);
|
||||
}
|
||||
}
|
||||
uart_set_baudrate(static_cast<uart_port_t>(uartPort), kBaudRate);
|
||||
flushUartRx(uartPort);
|
||||
}
|
||||
|
||||
// The BT1035 prints an unsolicited boot banner (+VER=..., +DEVSTAT=1, ...)
|
||||
// once its full Bluetooth stack finishes initialising — this blocks for up
|
||||
// to kBootBannerWaitMs waiting for it, since that's the real boot-complete
|
||||
// signal (the module is otherwise silent and won't answer AT commands
|
||||
// until this appears).
|
||||
void logRawUartBoot(int uartPort) noexcept
|
||||
{
|
||||
std::array<std::uint8_t, 128> buf{};
|
||||
const int n = uart_read_bytes(static_cast<uart_port_t>(uartPort), buf.data(),
|
||||
buf.size(), pdMS_TO_TICKS(3500));
|
||||
buf.size(), pdMS_TO_TICKS(kBootBannerWaitMs));
|
||||
if (n <= 0) {
|
||||
ESP_LOGW("Bt1035", "no spontaneous UART bytes after hardware reset");
|
||||
return;
|
||||
@@ -904,32 +959,68 @@ std::expected<void, Bt1035Error> Bt1035Driver::runInitSequence()
|
||||
return {};
|
||||
}
|
||||
|
||||
std::expected<void, Bt1035Error> Bt1035Driver::resetAndInitOnce()
|
||||
{
|
||||
// Feasycom BT1035 programming user guide §2.2, pin 34 SYS_CTRL:
|
||||
// "Delay 100ms, pull high" — the datasheet's own OFF-state timing spec
|
||||
// (§4.7) says SYS_CTRL must be asserted >20ms before the internal
|
||||
// regulators start powering up at all, so pulling it high with no
|
||||
// lead-in delay (the previous sequence here) races the chip's own
|
||||
// power-on requirement. Held low with RESET already asserted, then a
|
||||
// 100ms lead-in exactly matching the guide, then SYS_CTRL high, then
|
||||
// extra settle time before releasing RESET into a chip that's had a
|
||||
// chance to actually power up first.
|
||||
const auto sysCtlPin = static_cast<gpio_num_t>(pins_.sysCtlGpio);
|
||||
const auto resetPin = static_cast<gpio_num_t>(pins_.resetGpio);
|
||||
|
||||
gpio_set_level(sysCtlPin, 0);
|
||||
gpio_set_level(resetPin, 0);
|
||||
vTaskDelay(pdMS_TO_TICKS(kSysCtlLeadInMs));
|
||||
ESP_LOGI(kTag, "pre-power: SYS_CTRL=%d RESET=%d (want 0,0)",
|
||||
gpio_get_level(sysCtlPin), gpio_get_level(resetPin));
|
||||
|
||||
gpio_set_level(sysCtlPin, 1);
|
||||
vTaskDelay(pdMS_TO_TICKS(kSysCtlSettleMs));
|
||||
ESP_LOGI(kTag, "post-syscl: SYS_CTRL=%d RESET=%d (want 1,0)",
|
||||
gpio_get_level(sysCtlPin), gpio_get_level(resetPin));
|
||||
|
||||
gpio_set_level(resetPin, 1);
|
||||
vTaskDelay(pdMS_TO_TICKS(kPostResetMs));
|
||||
ESP_LOGI(kTag, "post-reset: SYS_CTRL=%d RESET=%d (want 1,1)",
|
||||
gpio_get_level(sysCtlPin), gpio_get_level(resetPin));
|
||||
|
||||
logRawUartBoot(uartPort_);
|
||||
uart_flush_input(static_cast<uart_port_t>(uartPort_));
|
||||
vTaskDelay(pdMS_TO_TICKS(kPostUartMs));
|
||||
|
||||
return runInitSequence();
|
||||
}
|
||||
|
||||
std::expected<void, Bt1035Error> Bt1035Driver::boot()
|
||||
{
|
||||
if (booted_) {
|
||||
return {};
|
||||
}
|
||||
|
||||
// GPIO_MODE_INPUT_OUTPUT (not plain GPIO_MODE_OUTPUT): gpio_config()
|
||||
// only enables the pad's input buffer when the INPUT bit is set, so a
|
||||
// pure-output config leaves gpio_get_level() reading a stale/always-0
|
||||
// register instead of the real driven level — needed for the readback
|
||||
// diagnostic below to be meaningful.
|
||||
gpio_config_t resetCfg = {};
|
||||
resetCfg.pin_bit_mask = 1ULL << pins_.resetGpio;
|
||||
resetCfg.mode = GPIO_MODE_OUTPUT;
|
||||
resetCfg.mode = GPIO_MODE_INPUT_OUTPUT;
|
||||
if (gpio_config(&resetCfg) != ESP_OK) {
|
||||
return std::unexpected(Bt1035Error::ResetFailed);
|
||||
}
|
||||
|
||||
gpio_config_t sysCfg = {};
|
||||
sysCfg.pin_bit_mask = 1ULL << pins_.sysCtlGpio;
|
||||
sysCfg.mode = GPIO_MODE_OUTPUT;
|
||||
sysCfg.mode = GPIO_MODE_INPUT_OUTPUT;
|
||||
if (gpio_config(&sysCfg) != ESP_OK) {
|
||||
return std::unexpected(Bt1035Error::ResetFailed);
|
||||
}
|
||||
|
||||
gpio_set_level(static_cast<gpio_num_t>(pins_.sysCtlGpio), 1);
|
||||
gpio_set_level(static_cast<gpio_num_t>(pins_.resetGpio), 0);
|
||||
vTaskDelay(pdMS_TO_TICKS(100));
|
||||
gpio_set_level(static_cast<gpio_num_t>(pins_.resetGpio), 1);
|
||||
vTaskDelay(pdMS_TO_TICKS(kPostResetMs));
|
||||
|
||||
if (!uartInstalled_) {
|
||||
const uart_config_t uartCfg = {
|
||||
.baud_rate = kBaudRate,
|
||||
@@ -961,12 +1052,20 @@ std::expected<void, Bt1035Error> Bt1035Driver::boot()
|
||||
uartInstalled_ = true;
|
||||
}
|
||||
|
||||
logRawUartBoot(uartPort_);
|
||||
uart_flush_input(static_cast<uart_port_t>(uartPort_));
|
||||
vTaskDelay(pdMS_TO_TICKS(kPostUartMs));
|
||||
|
||||
if (auto init = runInitSequence(); !init) {
|
||||
ESP_LOGE(kTag, "AT init failed");
|
||||
std::expected<void, Bt1035Error> init = std::unexpected(Bt1035Error::UnexpectedResponse);
|
||||
for (int attempt = 1; attempt <= kBootAttempts; ++attempt) {
|
||||
init = resetAndInitOnce();
|
||||
if (init) {
|
||||
break;
|
||||
}
|
||||
ESP_LOGW(kTag, "boot attempt %d/%d failed", attempt, kBootAttempts);
|
||||
if (attempt < kBootAttempts) {
|
||||
vTaskDelay(pdMS_TO_TICKS(kBootRetryDelayMs));
|
||||
}
|
||||
}
|
||||
if (!init) {
|
||||
ESP_LOGE(kTag, "AT init failed after %d attempts", kBootAttempts);
|
||||
probeBaudRates(uartPort_);
|
||||
return init;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
idf_component_register(
|
||||
SRCS "src/Eeprom24aa.cpp"
|
||||
INCLUDE_DIRS "include"
|
||||
REQUIRES core driver esp_driver_i2c
|
||||
REQUIRES core driver esp_driver_i2c freertos
|
||||
)
|
||||
|
||||
target_compile_features(${COMPONENT_LIB} PUBLIC cxx_std_23)
|
||||
|
||||
@@ -13,27 +13,44 @@
|
||||
#pragma once
|
||||
|
||||
#include "core/IDeviceIdentitySource.hpp"
|
||||
#include "core/IdentityError.hpp"
|
||||
|
||||
#include "driver/i2c_master.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <optional>
|
||||
|
||||
namespace eeprom24aa {
|
||||
|
||||
/**
|
||||
* @brief Eeprom24aa — reads the factory EUI-48 from Microchip 24AA025E48.
|
||||
* @brief Eeprom24aa — reads the factory EUI-48 from Microchip 24AA025E48;
|
||||
* also stores one board-specific calibration byte in the chip's
|
||||
* user-writable region.
|
||||
*
|
||||
* @dname Eeprom24aa
|
||||
* @return n/a (type)
|
||||
* @pubstate Borrows an existing I2C master bus (shared with ADAU1701). The
|
||||
* EUI-48 lives at word address 0xFA..0xFF per the 24AA025E48
|
||||
* datasheet (DS20001191).
|
||||
* EUI-48 lives at word address 0xFA..0xFF (read-only, factory
|
||||
* programmed) per the 24AA025E48 datasheet (DS20001191); the FM
|
||||
* ANTCAP calibration byte lives at word address 0x00, and the
|
||||
* DAB ANTCAP calibration byte at word address 0x01, both in the
|
||||
* remaining user-writable 250 bytes.
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-07-07
|
||||
*/
|
||||
class Eeprom24aa : public core::IDeviceIdentitySource {
|
||||
public:
|
||||
/** Valid ANTCAP calibration values (FM or DAB) are 0-128 (AN649/AN851);
|
||||
* any stored byte above this, including the EEPROM's blank/erased
|
||||
* 0xFF, reads back as "never calibrated" — no separate sentinel write
|
||||
* needed for a fresh chip. */
|
||||
static constexpr std::uint8_t kFmAntCapMax = 128U;
|
||||
/** Same range as kFmAntCapMax; kept as a separate name for the DAB
|
||||
* calibration byte's own doc comments below. */
|
||||
static constexpr std::uint8_t kDabAntCapMax = 128U;
|
||||
|
||||
/**
|
||||
* @brief Eeprom24aa — bind to a running I2C master bus and 7-bit addr.
|
||||
*
|
||||
@@ -60,6 +77,69 @@ public:
|
||||
[[nodiscard]] std::expected<core::DeviceIdentity, core::IdentityError>
|
||||
readDeviceIdentity() override;
|
||||
|
||||
/**
|
||||
* @brief readFmAntCap — read the stored FM antenna calibration byte.
|
||||
*
|
||||
* @dname readFmAntCap
|
||||
* @return Calibrated ANTCAP (0-kFmAntCapMax) if one was ever saved via
|
||||
* writeFmAntCap(), nullopt if the byte is blank/out of range,
|
||||
* or IdentityError on an I2C failure.
|
||||
* @pubstate performs one I2C read of one byte at word address 0x00.
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-08-19
|
||||
*/
|
||||
[[nodiscard]] std::expected<std::optional<std::uint8_t>, core::IdentityError>
|
||||
readFmAntCap();
|
||||
|
||||
/**
|
||||
* @brief writeFmAntCap — persist an FM antenna calibration value.
|
||||
*
|
||||
* @dname writeFmAntCap
|
||||
* @param value ANTCAP to store, 0-kFmAntCapMax (AN851 Appendix A
|
||||
* calibration procedure; found via a sweep, not
|
||||
* computed).
|
||||
* @return Ok on success, or IdentityError::I2cFailed.
|
||||
* @pubstate performs one I2C byte write at word address 0x00, then
|
||||
* blocks for the chip's write-cycle time before returning.
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-08-19
|
||||
*/
|
||||
[[nodiscard]] std::expected<void, core::IdentityError>
|
||||
writeFmAntCap(std::uint8_t value);
|
||||
|
||||
/**
|
||||
* @brief readDabAntCap — read the stored DAB antenna calibration byte.
|
||||
*
|
||||
* @dname readDabAntCap
|
||||
* @return Calibrated ANTCAP (0-kDabAntCapMax) if one was ever saved via
|
||||
* writeDabAntCap(), nullopt if the byte is blank/out of range,
|
||||
* or IdentityError on an I2C failure.
|
||||
* @pubstate performs one I2C read of one byte at word address 0x01.
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-08-20
|
||||
*/
|
||||
[[nodiscard]] std::expected<std::optional<std::uint8_t>, core::IdentityError>
|
||||
readDabAntCap();
|
||||
|
||||
/**
|
||||
* @brief writeDabAntCap — persist a DAB antenna calibration value.
|
||||
*
|
||||
* @dname writeDabAntCap
|
||||
* @param value ANTCAP to store, 0-kDabAntCapMax (AN649 Command
|
||||
* 0xB0 ARG4; found via a sweep, not computed).
|
||||
* @return Ok on success, or IdentityError::I2cFailed.
|
||||
* @pubstate performs one I2C byte write at word address 0x01, then
|
||||
* blocks for the chip's write-cycle time before returning.
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-08-20
|
||||
*/
|
||||
[[nodiscard]] std::expected<void, core::IdentityError>
|
||||
writeDabAntCap(std::uint8_t value);
|
||||
|
||||
private:
|
||||
i2c_master_bus_handle_t bus_;
|
||||
std::uint8_t addr7_;
|
||||
|
||||
@@ -15,6 +15,8 @@
|
||||
|
||||
#include "driver/i2c_master.h"
|
||||
#include "esp_log.h"
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
|
||||
#include <array>
|
||||
|
||||
@@ -25,7 +27,15 @@ namespace {
|
||||
constexpr char kTag[] = "Eeprom24aa";
|
||||
/** EUI-48 word address per Microchip 24AA025E48 datasheet (DS20001191). */
|
||||
constexpr std::uint8_t kEui48WordAddress = 0xFAU;
|
||||
/** FM ANTCAP calibration byte, in the chip's user-writable region (anywhere
|
||||
* below the factory-locked 0xFA-0xFF EUI-48 block). */
|
||||
constexpr std::uint8_t kFmAntCapWordAddress = 0x00U;
|
||||
/** DAB ANTCAP calibration byte, next word address after the FM byte. */
|
||||
constexpr std::uint8_t kDabAntCapWordAddress = 0x01U;
|
||||
constexpr int kI2cTimeoutMs = 100;
|
||||
/** DS20001191 §"Page Write"/"Byte Write": max write cycle time after STOP
|
||||
* before the chip acknowledges further I2C traffic. */
|
||||
constexpr int kI2cWriteCycleMs = 5;
|
||||
|
||||
} // namespace
|
||||
|
||||
@@ -69,4 +79,146 @@ Eeprom24aa::readDeviceIdentity()
|
||||
return core::DeviceIdentity::fromEui48(core::Eui48::fromBytes(payload));
|
||||
}
|
||||
|
||||
std::expected<std::optional<std::uint8_t>, core::IdentityError>
|
||||
Eeprom24aa::readFmAntCap()
|
||||
{
|
||||
if (bus_ == nullptr) {
|
||||
return std::unexpected(core::IdentityError::I2cFailed);
|
||||
}
|
||||
|
||||
i2c_device_config_t devCfg = {};
|
||||
devCfg.dev_addr_length = I2C_ADDR_BIT_LEN_7;
|
||||
devCfg.device_address = addr7_;
|
||||
devCfg.scl_speed_hz = 100000;
|
||||
|
||||
i2c_master_dev_handle_t dev = nullptr;
|
||||
if (i2c_master_bus_add_device(bus_, &devCfg, &dev) != ESP_OK) {
|
||||
ESP_LOGW(kTag, "i2c_master_bus_add_device failed");
|
||||
return std::unexpected(core::IdentityError::I2cFailed);
|
||||
}
|
||||
|
||||
const std::uint8_t wordAddress = kFmAntCapWordAddress;
|
||||
std::uint8_t value = 0xFFU;
|
||||
const esp_err_t err = i2c_master_transmit_receive(
|
||||
dev, &wordAddress, 1U, &value, 1U, kI2cTimeoutMs);
|
||||
|
||||
i2c_master_bus_rm_device(dev);
|
||||
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGW(kTag, "FM ANTCAP read failed (err=0x%x)",
|
||||
static_cast<unsigned>(err));
|
||||
return std::unexpected(core::IdentityError::ReadFailed);
|
||||
}
|
||||
|
||||
if (value > kFmAntCapMax) {
|
||||
return std::optional<std::uint8_t>{};
|
||||
}
|
||||
return std::optional<std::uint8_t>{value};
|
||||
}
|
||||
|
||||
std::expected<void, core::IdentityError>
|
||||
Eeprom24aa::writeFmAntCap(std::uint8_t value)
|
||||
{
|
||||
if (bus_ == nullptr) {
|
||||
return std::unexpected(core::IdentityError::I2cFailed);
|
||||
}
|
||||
|
||||
i2c_device_config_t devCfg = {};
|
||||
devCfg.dev_addr_length = I2C_ADDR_BIT_LEN_7;
|
||||
devCfg.device_address = addr7_;
|
||||
devCfg.scl_speed_hz = 100000;
|
||||
|
||||
i2c_master_dev_handle_t dev = nullptr;
|
||||
if (i2c_master_bus_add_device(bus_, &devCfg, &dev) != ESP_OK) {
|
||||
ESP_LOGW(kTag, "i2c_master_bus_add_device failed");
|
||||
return std::unexpected(core::IdentityError::I2cFailed);
|
||||
}
|
||||
|
||||
const std::array<std::uint8_t, 2> payload = {kFmAntCapWordAddress, value};
|
||||
const esp_err_t err =
|
||||
i2c_master_transmit(dev, payload.data(), payload.size(), kI2cTimeoutMs);
|
||||
|
||||
i2c_master_bus_rm_device(dev);
|
||||
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGW(kTag, "FM ANTCAP write failed (err=0x%x)",
|
||||
static_cast<unsigned>(err));
|
||||
return std::unexpected(core::IdentityError::I2cFailed);
|
||||
}
|
||||
|
||||
vTaskDelay(pdMS_TO_TICKS(kI2cWriteCycleMs));
|
||||
return {};
|
||||
}
|
||||
|
||||
std::expected<std::optional<std::uint8_t>, core::IdentityError>
|
||||
Eeprom24aa::readDabAntCap()
|
||||
{
|
||||
if (bus_ == nullptr) {
|
||||
return std::unexpected(core::IdentityError::I2cFailed);
|
||||
}
|
||||
|
||||
i2c_device_config_t devCfg = {};
|
||||
devCfg.dev_addr_length = I2C_ADDR_BIT_LEN_7;
|
||||
devCfg.device_address = addr7_;
|
||||
devCfg.scl_speed_hz = 100000;
|
||||
|
||||
i2c_master_dev_handle_t dev = nullptr;
|
||||
if (i2c_master_bus_add_device(bus_, &devCfg, &dev) != ESP_OK) {
|
||||
ESP_LOGW(kTag, "i2c_master_bus_add_device failed");
|
||||
return std::unexpected(core::IdentityError::I2cFailed);
|
||||
}
|
||||
|
||||
const std::uint8_t wordAddress = kDabAntCapWordAddress;
|
||||
std::uint8_t value = 0xFFU;
|
||||
const esp_err_t err = i2c_master_transmit_receive(
|
||||
dev, &wordAddress, 1U, &value, 1U, kI2cTimeoutMs);
|
||||
|
||||
i2c_master_bus_rm_device(dev);
|
||||
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGW(kTag, "DAB ANTCAP read failed (err=0x%x)",
|
||||
static_cast<unsigned>(err));
|
||||
return std::unexpected(core::IdentityError::ReadFailed);
|
||||
}
|
||||
|
||||
if (value > kDabAntCapMax) {
|
||||
return std::optional<std::uint8_t>{};
|
||||
}
|
||||
return std::optional<std::uint8_t>{value};
|
||||
}
|
||||
|
||||
std::expected<void, core::IdentityError>
|
||||
Eeprom24aa::writeDabAntCap(std::uint8_t value)
|
||||
{
|
||||
if (bus_ == nullptr) {
|
||||
return std::unexpected(core::IdentityError::I2cFailed);
|
||||
}
|
||||
|
||||
i2c_device_config_t devCfg = {};
|
||||
devCfg.dev_addr_length = I2C_ADDR_BIT_LEN_7;
|
||||
devCfg.device_address = addr7_;
|
||||
devCfg.scl_speed_hz = 100000;
|
||||
|
||||
i2c_master_dev_handle_t dev = nullptr;
|
||||
if (i2c_master_bus_add_device(bus_, &devCfg, &dev) != ESP_OK) {
|
||||
ESP_LOGW(kTag, "i2c_master_bus_add_device failed");
|
||||
return std::unexpected(core::IdentityError::I2cFailed);
|
||||
}
|
||||
|
||||
const std::array<std::uint8_t, 2> payload = {kDabAntCapWordAddress, value};
|
||||
const esp_err_t err =
|
||||
i2c_master_transmit(dev, payload.data(), payload.size(), kI2cTimeoutMs);
|
||||
|
||||
i2c_master_bus_rm_device(dev);
|
||||
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGW(kTag, "DAB ANTCAP write failed (err=0x%x)",
|
||||
static_cast<unsigned>(err));
|
||||
return std::unexpected(core::IdentityError::I2cFailed);
|
||||
}
|
||||
|
||||
vTaskDelay(pdMS_TO_TICKS(kI2cWriteCycleMs));
|
||||
return {};
|
||||
}
|
||||
|
||||
} // namespace eeprom24aa
|
||||
|
||||
@@ -288,13 +288,18 @@ public:
|
||||
*
|
||||
* @dname tuneDab
|
||||
* @param freqIndex Ensemble index 0–37.
|
||||
* @param antCap ANTCAP[7:0] override (0-128, AN649 Command 0xB0
|
||||
* ARG4). 0 = automatic front-end tuning; other
|
||||
* values force a specific varactor setting, for
|
||||
* antenna calibration sweeps (mirrors tuneFm).
|
||||
* @return Ok on success, or Si4684Error.
|
||||
* @pubstate sends DAB_TUNE_FREQ and waits for STC.
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-07-06
|
||||
*/
|
||||
[[nodiscard]] std::expected<void, Si4684Error> tuneDab(std::uint8_t freqIndex);
|
||||
[[nodiscard]] std::expected<void, Si4684Error> tuneDab(
|
||||
std::uint8_t freqIndex, std::uint8_t antCap = 0U);
|
||||
|
||||
/**
|
||||
* @brief readDabDigRadStatus — read ensemble lock metrics.
|
||||
|
||||
@@ -96,6 +96,7 @@ public:
|
||||
*
|
||||
* @dname tuneDab
|
||||
* @param freqIndex Ensemble index 0–37.
|
||||
* @param antCap Forwarded to Si4684Driver::tuneDab (0 = auto).
|
||||
* @return Ok on success, or a mapped TunerError.
|
||||
* @pubstate writes dabIndex_ on success.
|
||||
*
|
||||
@@ -103,13 +104,14 @@ public:
|
||||
* @date 2026-07-06
|
||||
*/
|
||||
[[nodiscard]] std::expected<void, core::TunerError> tuneDab(
|
||||
std::uint8_t freqIndex) override;
|
||||
std::uint8_t freqIndex, std::uint8_t antCap = 0U) override;
|
||||
|
||||
/**
|
||||
* @brief tuneFm — tune to an FM centre frequency in kHz.
|
||||
*
|
||||
* @dname tuneFm
|
||||
* @param frequency Validated FM centre frequency.
|
||||
* @param antCap Forwarded to Si4684Driver::tuneFm (0 = auto).
|
||||
* @return Ok on success, or a mapped TunerError.
|
||||
* @pubstate writes fmFrequency_ on success.
|
||||
*
|
||||
@@ -117,7 +119,7 @@ public:
|
||||
* @date 2026-07-06
|
||||
*/
|
||||
[[nodiscard]] std::expected<void, core::TunerError> tuneFm(
|
||||
core::FrequencyKHz frequency) override;
|
||||
core::FrequencyKHz frequency, std::uint8_t antCap = 0U) override;
|
||||
|
||||
/**
|
||||
* @brief seekFm — seek FM with band wrap.
|
||||
|
||||
@@ -85,6 +85,7 @@ constexpr std::uint16_t kPropDabTuneFeCfg = 0x1712U;
|
||||
constexpr std::uint16_t kPropFmTuneFeCfg = 0x1712U;
|
||||
constexpr std::uint16_t kPropDabXpadEnable = 0xB400U;
|
||||
constexpr std::uint16_t kPropDigitalServiceIntSource = 0x8100U;
|
||||
constexpr std::uint16_t kPropDabEventIntSource = 0xB300U;
|
||||
/** AN649 INT_CTL_ENABLE / INT_CTL_REPEAT — route STC to INTB until STCACK. */
|
||||
constexpr std::uint16_t kPropIntCtlEnable = 0x0000U;
|
||||
constexpr std::uint16_t kPropIntCtlRepeat = 0x0001U;
|
||||
@@ -504,6 +505,15 @@ std::expected<void, Si4684Error> Si4684Driver::configureAfterBoot(
|
||||
ESP_LOGW(kTag, "DIGITAL_SERVICE_INT_SOURCE (0x8100) failed");
|
||||
return dsrv;
|
||||
}
|
||||
// AN649 Property 0xB300 DAB_EVENT_INTERRUPT_SOURCE, bit0=SRVLIST_INTEN
|
||||
// (default 0x0000 = disabled at power-on). Without this, nothing in
|
||||
// this driver ever enables the service-list-ready event, so
|
||||
// fetchDabServiceList() can stay gated behind an eternally-false
|
||||
// serviceListReady even on a clean, well-locked ensemble.
|
||||
if (auto evt = setProperty(kPropDabEventIntSource, 0x0001U); !evt) {
|
||||
ESP_LOGW(kTag, "DAB_EVENT_INTERRUPT_SOURCE (0xB300) failed");
|
||||
return evt;
|
||||
}
|
||||
} else {
|
||||
// FM varactor cal per hitech95/uGreen DTS (not DAB PE5PVB values).
|
||||
static constexpr std::uint16_t kFmFeProps[][2] = {
|
||||
@@ -1027,7 +1037,8 @@ std::expected<void, Si4684Error> Si4684Driver::installDefaultDabFrequencyPlan()
|
||||
return sendCommand(cmd);
|
||||
}
|
||||
|
||||
std::expected<void, Si4684Error> Si4684Driver::tuneDab(std::uint8_t freqIndex)
|
||||
std::expected<void, Si4684Error> Si4684Driver::tuneDab(
|
||||
std::uint8_t freqIndex, std::uint8_t antCap)
|
||||
{
|
||||
if (auto band = ensureBand(Si4684Band::Dab); !band) {
|
||||
return band;
|
||||
@@ -1037,8 +1048,9 @@ std::expected<void, Si4684Error> Si4684Driver::tuneDab(std::uint8_t freqIndex)
|
||||
}
|
||||
// writeCommand() always prepends a fixed ARG1=0x00 (INJECTION=0), so
|
||||
// this array starts at ARG2 (AN649 Command 0xB0 table: ARG2=FREQ_INDEX,
|
||||
// ARG3=0x00 fixed, ARG4=ANTCAP[7:0], ARG5=ANTCAP[15:8]).
|
||||
const std::uint8_t args[] = {freqIndex, 0x00U, 0x00U, 0x00U};
|
||||
// ARG3=0x00 fixed, ARG4=ANTCAP[7:0], ARG5=ANTCAP[15:8] -- high byte
|
||||
// always 0, range is 0-128, same as tuneFm's ANTCAP).
|
||||
const std::uint8_t args[] = {freqIndex, 0x00U, antCap, 0x00U};
|
||||
if (auto cmd = writeCommand(Command::DabTuneFreq, args, sizeof(args));
|
||||
!cmd) {
|
||||
return std::unexpected(Si4684Error::TuneFailed);
|
||||
@@ -1121,26 +1133,37 @@ Si4684Driver::fetchDabServiceList()
|
||||
}
|
||||
|
||||
// raw[5]=RESP4=SIZE[7:0], raw[6]=RESP5=SIZE[15:8] (see readFmRds()).
|
||||
// AN649 only documents SIZE/DATA_0/DATA_N generically for this command
|
||||
// and defers the DAB payload layout to a supplemental "Digital
|
||||
// Services User's Guide" we don't have; the exact field layout below
|
||||
// is cross-checked against hitech95/si468x_dab_receiver's
|
||||
// si468x_core_cmd_dab_get_service_list() (drivers/mfd/si468x-cmd.c),
|
||||
// a real working Linux driver for the same command. That driver also
|
||||
// establishes that the payload actually carried after SIZE is
|
||||
// SIZE-2 bytes, not SIZE bytes.
|
||||
const std::uint16_t payloadSize = readLe16(header.data() + 5);
|
||||
if (payloadSize == 0U || payloadSize + 7U > kSpiBufferSize) {
|
||||
if (payloadSize <= 2U || payloadSize + 5U > kSpiBufferSize) {
|
||||
return std::unexpected(Si4684Error::ReplyTooShort);
|
||||
}
|
||||
|
||||
// DATA_0 (first byte of the AN649 Table 14 "DAB/DMB Digital Service
|
||||
// List" structure) is RESP6 = body[7]: lead-in(1) + STATUS0-3(4) +
|
||||
// SIZE(2) = 7 header bytes before it.
|
||||
std::vector<std::uint8_t> body(payloadSize + 7U, 0U);
|
||||
// DATA_0 (first byte of the payload) is RESP6 = body[7]: lead-in(1) +
|
||||
// STATUS0-3(4) + SIZE(2) = 7 header bytes before it. Total frame is
|
||||
// lead-in(1) + STATUS0-3(4) + SIZE(2) + payload(SIZE-2) = SIZE+5.
|
||||
std::vector<std::uint8_t> body(payloadSize + 5U, 0U);
|
||||
if (auto rd = readRaw(body); !rd) {
|
||||
return std::unexpected(rd.error());
|
||||
}
|
||||
|
||||
// Table 14: List Size(2) + Version(2) + NumServices(1) + AlignPad(3) =
|
||||
// 8 bytes, then Service 1 begins.
|
||||
const std::uint8_t serviceCount = body[11];
|
||||
// From DATA_0 (body[7]): Version(2) + NumServices/flags(1) +
|
||||
// AlignPad(3) = 6 bytes, then Service 1 begins at body[13]. (The
|
||||
// previous version of this code double-counted the already-consumed
|
||||
// SIZE field here, offsetting every read by 2 bytes — that is why the
|
||||
// service list always came back empty.)
|
||||
const std::uint8_t serviceCount = body[9] & 0x1FU; // max 32 services
|
||||
std::vector<Si4684DabService> services;
|
||||
services.reserve(serviceCount);
|
||||
|
||||
std::size_t offset = 15U;
|
||||
std::size_t offset = 13U;
|
||||
for (std::uint8_t i = 0; i < serviceCount; ++i) {
|
||||
// Fixed per-service part: ServiceID(4) + ServiceInfo1-3(3) +
|
||||
// AlignPad(1) + Label(16) = 24 bytes.
|
||||
@@ -1155,11 +1178,13 @@ Si4684Driver::fetchDabServiceList()
|
||||
entry.label[16] = '\0';
|
||||
offset += 24U;
|
||||
|
||||
// Component ID is 2 bytes (AN649 Table 14); only the first
|
||||
// Component ID is 2 bytes (hitech95's si468x-cmd.c packs tm_id/
|
||||
// sub_ch_id/fidc_id/sc_id into this same field; only the raw
|
||||
// 16-bit value is exposed on this DTO). Only the first
|
||||
// component's ID is exposed on this DTO. Every component (M =
|
||||
// componentCount) must still be skipped to keep the next service
|
||||
// entry aligned, each one ComponentID(2) + ComponentInfo(1) +
|
||||
// ValidFlags(1) = 4 bytes.
|
||||
// entry aligned, each one 2 bytes packed field + ServiceType/
|
||||
// flags(1) + ValidFlags(1) = 4 bytes.
|
||||
if (componentCount > 0U && offset + 2U <= body.size()) {
|
||||
entry.componentId = readLe16(body.data() + offset);
|
||||
}
|
||||
|
||||
@@ -209,12 +209,12 @@ std::expected<core::TunerStatus, core::TunerError> Si4684Tuner::readStatus()
|
||||
}
|
||||
|
||||
std::expected<void, core::TunerError> Si4684Tuner::tuneDab(
|
||||
std::uint8_t freqIndex)
|
||||
std::uint8_t freqIndex, std::uint8_t antCap)
|
||||
{
|
||||
if (auto ready = ensureBandLoaded(core::TunerBand::Dab); !ready) {
|
||||
return ready;
|
||||
}
|
||||
if (auto result = driver_.tuneDab(freqIndex); !result) {
|
||||
if (auto result = driver_.tuneDab(freqIndex, antCap); !result) {
|
||||
return std::unexpected(mapError(result.error()));
|
||||
}
|
||||
dabIndex_ = freqIndex;
|
||||
@@ -225,12 +225,12 @@ std::expected<void, core::TunerError> Si4684Tuner::tuneDab(
|
||||
}
|
||||
|
||||
std::expected<void, core::TunerError> Si4684Tuner::tuneFm(
|
||||
core::FrequencyKHz frequency)
|
||||
core::FrequencyKHz frequency, std::uint8_t antCap)
|
||||
{
|
||||
if (auto ready = ensureBandLoaded(core::TunerBand::Fm); !ready) {
|
||||
return ready;
|
||||
}
|
||||
if (auto result = driver_.tuneFm(frequency); !result) {
|
||||
if (auto result = driver_.tuneFm(frequency, antCap); !result) {
|
||||
return std::unexpected(mapError(result.error()));
|
||||
}
|
||||
fmFrequency_ = frequency;
|
||||
|
||||
@@ -31,15 +31,19 @@ namespace net::ble_provisioning {
|
||||
* @dname start
|
||||
* @param store Secure store the received credentials are saved
|
||||
* to (same store POST /api/wifi writes to).
|
||||
* @param deviceIdentity Supplies the BLE advertising name (softApSsid)
|
||||
* and the proof-of-possession string (serialNumber).
|
||||
* @param deviceIdentity Supplies the BLE advertising name (softApSsid).
|
||||
* @return Ok once provisioning is advertising, or NetError::BleProvisioningFailed.
|
||||
* @pubstate Starts the onboard ESP32-S3 BLE radio (independent of the BT1035
|
||||
* UART module) and a process-lifetime wifi_provisioning manager
|
||||
* singleton. On a successful join, saves credentials to store and
|
||||
* reboots, mirroring wifiPostHandler's POST /api/wifi behaviour.
|
||||
* Runs alongside the existing SoftAP + HTTP provisioning route,
|
||||
* not instead of it — either path can complete setup.
|
||||
* not instead of it — either path can complete setup. Uses
|
||||
* protocomm Security0 (no proof-of-possession, no encryption):
|
||||
* a PoP derived from the BLE advertising name would be visible to
|
||||
* anyone scanning anyway, so it added app/firmware coupling
|
||||
* without adding real secrecy — same trust level as the open
|
||||
* SoftAP setup path this runs alongside.
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-08-18
|
||||
|
||||
@@ -87,6 +87,8 @@ public:
|
||||
* @param ota Firmware OTA service for POST /api/system/ota.
|
||||
* @param webRadio Streaming config for GET/POST /api/streaming.
|
||||
* @param phoneStream I2S write-through for PUT /api/stream/phone.
|
||||
* @param antennaCalibration EEPROM write-through for
|
||||
* POST /api/tuner/calibrate-antenna.
|
||||
* @param companionChips Boot flags exposed on GET /api/health.
|
||||
* @param deviceIdentity EEPROM-derived SSID, hostname, and serial.
|
||||
* @return NetBootstrap on success, or a NetError.
|
||||
@@ -103,6 +105,7 @@ public:
|
||||
ota::OtaService& ota,
|
||||
webradio::WebRadioService& webRadio,
|
||||
PhoneStreamSink& phoneStream,
|
||||
AntennaCalibration& antennaCalibration,
|
||||
core::CompanionChipStatus companionChips,
|
||||
const core::DeviceIdentity& deviceIdentity);
|
||||
|
||||
|
||||
@@ -85,6 +85,28 @@ struct PhoneStreamSink {
|
||||
std::size_t frameCount);
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief AntennaCalibration — plain function pointers over EEPROM-backed
|
||||
* FM and DAB ANTCAP storage, so net/ never includes eeprom24aa
|
||||
* headers directly; main/ supplies it (HardwareBootstrap owns the
|
||||
* I2C bus and EEPROM handle).
|
||||
*
|
||||
* @dname AntennaCalibration
|
||||
* @return n/a (type)
|
||||
* @pubstate Free functions with process lifetime; no per-instance state.
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-08-19
|
||||
*/
|
||||
struct AntennaCalibration {
|
||||
/** Persist a new FM ANTCAP calibration value to EEPROM.
|
||||
* @return false on an I2C failure. */
|
||||
bool (*save)(std::uint8_t antCap);
|
||||
/** Persist a new DAB ANTCAP calibration value to EEPROM.
|
||||
* @return false on an I2C failure. */
|
||||
bool (*saveDab)(std::uint8_t antCap);
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief HttpRouteContext — dependencies injected into HTTP handlers.
|
||||
*
|
||||
@@ -106,6 +128,7 @@ struct HttpRouteContext {
|
||||
ota::OtaService* ota; ///< Firmware OTA streaming.
|
||||
webradio::WebRadioService* webRadio; ///< Streaming config REST routes.
|
||||
PhoneStreamSink* phoneStream; ///< PUT /api/stream/phone I2S write-through.
|
||||
AntennaCalibration* antennaCalibration; ///< POST /api/tuner/calibrate-antenna.
|
||||
core::CompanionChipStatus companionChips; ///< Boot flags for /api/health.
|
||||
core::DeviceIdentity deviceIdentity; ///< EEPROM-derived unit identity.
|
||||
};
|
||||
@@ -187,6 +210,8 @@ public:
|
||||
* @param ota Firmware OTA service for POST /api/system/ota.
|
||||
* @param webRadio Streaming config for GET/POST /api/streaming.
|
||||
* @param phoneStream I2S write-through for PUT /api/stream/phone.
|
||||
* @param antennaCalibration EEPROM write-through for
|
||||
* POST /api/tuner/calibrate-antenna.
|
||||
* @param companionChips Boot flags for GET /api/health.
|
||||
* @param deviceIdentity Unit identity for /api/health serialNumber.
|
||||
* @return Ok on success, or NetError::HttpServerStartFailed.
|
||||
@@ -204,6 +229,7 @@ public:
|
||||
ota::OtaService& ota,
|
||||
webradio::WebRadioService& webRadio,
|
||||
PhoneStreamSink& phoneStream,
|
||||
AntennaCalibration& antennaCalibration,
|
||||
core::CompanionChipStatus companionChips,
|
||||
const core::DeviceIdentity& deviceIdentity);
|
||||
|
||||
|
||||
@@ -125,10 +125,9 @@ start(core::ISecureStore& store, const core::DeviceIdentity& deviceIdentity)
|
||||
gStore = &store;
|
||||
gPendingCreds.reset();
|
||||
|
||||
// Copies kept for the lifetime of provisioning: wifi_prov_mgr_start_
|
||||
// provisioning only borrows these pointers, it does not take ownership.
|
||||
// Copy kept for the lifetime of provisioning: wifi_prov_mgr_start_
|
||||
// provisioning only borrows this pointer, it does not take ownership.
|
||||
static const std::string serviceName(deviceIdentity.softApSsid());
|
||||
static const std::string pop(deviceIdentity.serialNumber());
|
||||
|
||||
const wifi_prov_mgr_config_t config{
|
||||
.scheme = wifi_prov_scheme_ble,
|
||||
@@ -141,7 +140,7 @@ start(core::ISecureStore& store, const core::DeviceIdentity& deviceIdentity)
|
||||
return std::unexpected(NetError::BleProvisioningFailed);
|
||||
}
|
||||
|
||||
if (wifi_prov_mgr_start_provisioning(WIFI_PROV_SECURITY_1, pop.c_str(),
|
||||
if (wifi_prov_mgr_start_provisioning(WIFI_PROV_SECURITY_0, nullptr,
|
||||
serviceName.c_str(),
|
||||
nullptr) != ESP_OK) {
|
||||
ESP_LOGE(kTag, "wifi_prov_mgr_start_provisioning failed");
|
||||
@@ -149,9 +148,8 @@ start(core::ISecureStore& store, const core::DeviceIdentity& deviceIdentity)
|
||||
return std::unexpected(NetError::BleProvisioningFailed);
|
||||
}
|
||||
|
||||
ESP_LOGI(kTag,
|
||||
"BLE provisioning advertising as %s (proof-of-possession: "
|
||||
"device serial number)",
|
||||
ESP_LOGI(kTag, "BLE provisioning advertising as %s (no PoP, same trust "
|
||||
"level as the open SoftAP)",
|
||||
serviceName.c_str());
|
||||
return {};
|
||||
}
|
||||
|
||||
@@ -106,6 +106,7 @@ startSetupMode(core::ISecureStore& store, tuner::TunerService& tuner,
|
||||
ota::OtaService& ota,
|
||||
webradio::WebRadioService& webRadio,
|
||||
PhoneStreamSink& phoneStream,
|
||||
AntennaCalibration& antennaCalibration,
|
||||
core::CompanionChipStatus companionChips,
|
||||
const core::DeviceIdentity& deviceIdentity)
|
||||
{
|
||||
@@ -121,7 +122,8 @@ startSetupMode(core::ISecureStore& store, tuner::TunerService& tuner,
|
||||
if (auto webResult =
|
||||
webServer.start(store, NetState::SoftApSetup, tuner, audio,
|
||||
bluetooth, stations, integration, ota, webRadio,
|
||||
phoneStream, companionChips, deviceIdentity);
|
||||
phoneStream, antennaCalibration, companionChips,
|
||||
deviceIdentity);
|
||||
!webResult) {
|
||||
return std::unexpected(webResult.error());
|
||||
}
|
||||
@@ -168,6 +170,7 @@ startStaMode(core::ISecureStore& store, tuner::TunerService& tuner,
|
||||
ota::OtaService& ota,
|
||||
webradio::WebRadioService& webRadio,
|
||||
PhoneStreamSink& phoneStream,
|
||||
AntennaCalibration& antennaCalibration,
|
||||
core::CompanionChipStatus companionChips,
|
||||
const core::DeviceIdentity& deviceIdentity)
|
||||
{
|
||||
@@ -198,7 +201,8 @@ startStaMode(core::ISecureStore& store, tuner::TunerService& tuner,
|
||||
if (auto webResult =
|
||||
webServer.start(store, NetState::StaConnected, tuner, audio,
|
||||
bluetooth, stations, integration, ota, webRadio,
|
||||
phoneStream, companionChips, deviceIdentity);
|
||||
phoneStream, antennaCalibration, companionChips,
|
||||
deviceIdentity);
|
||||
!webResult) {
|
||||
return std::unexpected(webResult.error());
|
||||
}
|
||||
@@ -227,6 +231,7 @@ NetBootstrap::start(core::ISecureStore& store, tuner::TunerService& tuner,
|
||||
ota::OtaService& ota,
|
||||
webradio::WebRadioService& webRadio,
|
||||
PhoneStreamSink& phoneStream,
|
||||
AntennaCalibration& antennaCalibration,
|
||||
core::CompanionChipStatus companionChips,
|
||||
const core::DeviceIdentity& deviceIdentity)
|
||||
{
|
||||
@@ -241,7 +246,8 @@ NetBootstrap::start(core::ISecureStore& store, tuner::TunerService& tuner,
|
||||
if (store.hasWifiCredentials()) {
|
||||
auto staResult = startStaMode(store, tuner, audio, bluetooth, stations,
|
||||
integration, ota, webRadio, phoneStream,
|
||||
companionChips, deviceIdentity);
|
||||
antennaCalibration, companionChips,
|
||||
deviceIdentity);
|
||||
if (staResult) {
|
||||
return staResult;
|
||||
}
|
||||
@@ -253,8 +259,8 @@ NetBootstrap::start(core::ISecureStore& store, tuner::TunerService& tuner,
|
||||
}
|
||||
|
||||
return startSetupMode(store, tuner, audio, bluetooth, stations, integration,
|
||||
ota, webRadio, phoneStream, companionChips,
|
||||
deviceIdentity);
|
||||
ota, webRadio, phoneStream, antennaCalibration,
|
||||
companionChips, deviceIdentity);
|
||||
}
|
||||
|
||||
NetBootstrap::NetBootstrap(std::optional<SoftApHost> softAp,
|
||||
|
||||
@@ -68,7 +68,7 @@ namespace net {
|
||||
|
||||
namespace {
|
||||
constexpr char kTag[] = "SetupWebServer";
|
||||
constexpr char kFirmwareVersion[] = "0.8.5";
|
||||
constexpr char kFirmwareVersion[] = "0.9.0";
|
||||
constexpr unsigned kRebootDelaySec = 3;
|
||||
|
||||
extern const uint8_t index_html_gz_start[] asm(
|
||||
@@ -99,6 +99,7 @@ extern const uint8_t index_html_gz_end[] asm(
|
||||
.ota = nullptr,
|
||||
.webRadio = nullptr,
|
||||
.phoneStream = nullptr,
|
||||
.antennaCalibration = nullptr,
|
||||
.companionChips = {},
|
||||
.deviceIdentity = core::DeviceIdentity::unknown(),
|
||||
};
|
||||
@@ -429,10 +430,13 @@ esp_err_t tunerTunePostHandler(httpd_req_t* req)
|
||||
|
||||
std::expected<void, core::TunerError> result = std::unexpected(
|
||||
core::TunerError::InvalidInput);
|
||||
// Omitting antcap uses the board's saved calibration for that band (or
|
||||
// hardware auto-tune if never calibrated) — only an explicit value in
|
||||
// the request overrides it, e.g. for a calibration sweep.
|
||||
if (parsed->band == core::TunerBand::Dab) {
|
||||
result = ctx->tuner->tuneDab(parsed->dabFreqIndex);
|
||||
result = ctx->tuner->tuneDab(parsed->dabFreqIndex, parsed->antCap);
|
||||
} else if (parsed->fmFrequency) {
|
||||
result = ctx->tuner->tuneFm(*parsed->fmFrequency);
|
||||
result = ctx->tuner->tuneFm(*parsed->fmFrequency, parsed->antCap);
|
||||
}
|
||||
|
||||
if (!result) {
|
||||
@@ -635,6 +639,66 @@ esp_err_t tunerFullScanPostHandler(httpd_req_t* req)
|
||||
return httpd_resp_send(req, json.c_str(), json.size());
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief tunerCalibrateAntennaPostHandler — save the FM ANTCAP found by
|
||||
* a calibration sweep as the board's permanent default.
|
||||
*
|
||||
* @dname tunerCalibrateAntennaPostHandler
|
||||
* @param req HTTP request handle from esp_http_server.
|
||||
* @return ESP_OK on success, or an esp_err_t error code.
|
||||
* @pubstate writes the 24AA025E48 via route context antenna calibration
|
||||
* bridge, then updates the live tuner default immediately.
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-08-19
|
||||
*/
|
||||
esp_err_t tunerCalibrateAntennaPostHandler(httpd_req_t* req)
|
||||
{
|
||||
auto* ctx = routeContextFrom(req);
|
||||
if (ctx == nullptr || ctx->tuner == nullptr
|
||||
|| ctx->antennaCalibration == nullptr) {
|
||||
httpd_resp_set_status(req, "503 Service Unavailable");
|
||||
return httpd_resp_send(req, nullptr, 0);
|
||||
}
|
||||
|
||||
std::array<char, 128> body{};
|
||||
if (!readRequestBody(req, body)) {
|
||||
httpd_resp_set_status(req, "400 Bad Request");
|
||||
return httpd_resp_send(req, nullptr, 0);
|
||||
}
|
||||
|
||||
const auto parsed =
|
||||
core::parseAntennaCalibrationJson(std::string_view(body.data()));
|
||||
if (!parsed) {
|
||||
const std::string json = core::serializeTunerErrorJson("invalid_json");
|
||||
httpd_resp_set_status(req, "400 Bad Request");
|
||||
httpd_resp_set_type(req, "application/json");
|
||||
return httpd_resp_send(req, json.c_str(), json.size());
|
||||
}
|
||||
|
||||
const bool isDab = parsed->band == core::TunerBand::Dab;
|
||||
const bool saved = isDab ? ctx->antennaCalibration->saveDab(parsed->antCap)
|
||||
: ctx->antennaCalibration->save(parsed->antCap);
|
||||
if (!saved) {
|
||||
const std::string json = core::serializeTunerErrorJson("store_failed");
|
||||
httpd_resp_set_status(req, "500 Internal Server Error");
|
||||
httpd_resp_set_type(req, "application/json");
|
||||
return httpd_resp_send(req, json.c_str(), json.size());
|
||||
}
|
||||
if (isDab) {
|
||||
ctx->tuner->setDefaultDabAntCap(parsed->antCap);
|
||||
} else {
|
||||
ctx->tuner->setDefaultFmAntCap(parsed->antCap);
|
||||
}
|
||||
|
||||
const std::string json =
|
||||
std::string("{\"status\":\"saved\",\"band\":\"")
|
||||
+ (isDab ? "dab" : "fm") + "\",\"antcap\":"
|
||||
+ std::to_string(parsed->antCap) + "}";
|
||||
httpd_resp_set_type(req, "application/json");
|
||||
return httpd_resp_send(req, json.c_str(), json.size());
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief audioProfileGetHandler — serve GET /api/audio/profile JSON.
|
||||
*
|
||||
@@ -1865,6 +1929,7 @@ std::expected<void, NetError> SetupWebServer::start(
|
||||
ota::OtaService& ota,
|
||||
webradio::WebRadioService& webRadio,
|
||||
PhoneStreamSink& phoneStream,
|
||||
AntennaCalibration& antennaCalibration,
|
||||
core::CompanionChipStatus companionChips,
|
||||
const core::DeviceIdentity& deviceIdentity)
|
||||
{
|
||||
@@ -1889,13 +1954,18 @@ std::expected<void, NetError> SetupWebServer::start(
|
||||
routeContext.ota = &ota;
|
||||
routeContext.webRadio = &webRadio;
|
||||
routeContext.phoneStream = &phoneStream;
|
||||
routeContext.antennaCalibration = &antennaCalibration;
|
||||
routeContext.companionChips = companionChips;
|
||||
routeContext.deviceIdentity = deviceIdentity;
|
||||
|
||||
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
|
||||
config.stack_size = 12288;
|
||||
config.max_open_sockets = 3;
|
||||
config.max_uri_handlers = 40;
|
||||
config.max_uri_handlers = 56; // 41 routes registered below as of 2026-08-19;
|
||||
// keep headroom so a silent
|
||||
// httpd_register_uri_handler failure
|
||||
// ("no slots left") doesn't quietly drop
|
||||
// the last-registered route again.
|
||||
config.server_port = 80;
|
||||
config.lru_purge_enable = true;
|
||||
config.recv_wait_timeout = 60;
|
||||
@@ -1997,6 +2067,14 @@ std::expected<void, NetError> SetupWebServer::start(
|
||||
};
|
||||
httpd_register_uri_handler(server_, &tunerFullScanUri);
|
||||
|
||||
const httpd_uri_t tunerCalibrateAntennaUri = {
|
||||
.uri = "/api/tuner/calibrate-antenna",
|
||||
.method = HTTP_POST,
|
||||
.handler = tunerCalibrateAntennaPostHandler,
|
||||
.user_ctx = routeCtx,
|
||||
};
|
||||
httpd_register_uri_handler(server_, &tunerCalibrateAntennaUri);
|
||||
|
||||
const httpd_uri_t audioProfileGetUri = {
|
||||
.uri = "/api/audio/profile",
|
||||
.method = HTTP_GET,
|
||||
|
||||
@@ -73,6 +73,10 @@ public:
|
||||
*
|
||||
* @dname tuneDab
|
||||
* @param freqIndex Ensemble index 0–37.
|
||||
* @param antCap Front-end antenna varactor override for this one
|
||||
* tune (e.g. for a calibration sweep). Omit to use
|
||||
* defaultDabAntCap_ (the board's saved calibration,
|
||||
* or hardware auto-tune if never calibrated).
|
||||
* @return Ok on success, or a TunerError from ITuner.
|
||||
* @pubstate writes lastDabIndex_ on success; clears last-played DAB ids.
|
||||
*
|
||||
@@ -80,13 +84,32 @@ public:
|
||||
* @date 2026-07-06
|
||||
*/
|
||||
[[nodiscard]] std::expected<void, core::TunerError> tuneDab(
|
||||
std::uint8_t freqIndex);
|
||||
std::uint8_t freqIndex,
|
||||
std::optional<std::uint8_t> antCap = std::nullopt);
|
||||
|
||||
/**
|
||||
* @brief setDefaultDabAntCap — set the board's calibrated DAB ANTCAP.
|
||||
*
|
||||
* @dname setDefaultDabAntCap
|
||||
* @param antCap Value applied to every DAB tune that doesn't pass an
|
||||
* explicit override (0 = chip auto-tune, the factory
|
||||
* default before any calibration is saved).
|
||||
* @pubstate writes defaultDabAntCap_. Does not itself re-tune.
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-08-20
|
||||
*/
|
||||
void setDefaultDabAntCap(std::uint8_t antCap) noexcept;
|
||||
|
||||
/**
|
||||
* @brief tuneFm — tune to an FM centre frequency.
|
||||
*
|
||||
* @dname tuneFm
|
||||
* @param frequency Validated FM centre frequency.
|
||||
* @param antCap Front-end antenna varactor override for this one
|
||||
* tune (e.g. for a calibration sweep). Omit to use
|
||||
* defaultFmAntCap_ (the board's saved calibration,
|
||||
* or hardware auto-tune if never calibrated).
|
||||
* @return Ok on success, or a TunerError from ITuner.
|
||||
* @pubstate writes lastFmFrequency_ on success.
|
||||
*
|
||||
@@ -94,7 +117,22 @@ public:
|
||||
* @date 2026-07-06
|
||||
*/
|
||||
[[nodiscard]] std::expected<void, core::TunerError> tuneFm(
|
||||
core::FrequencyKHz frequency);
|
||||
core::FrequencyKHz frequency,
|
||||
std::optional<std::uint8_t> antCap = std::nullopt);
|
||||
|
||||
/**
|
||||
* @brief setDefaultFmAntCap — set the board's calibrated ANTCAP.
|
||||
*
|
||||
* @dname setDefaultFmAntCap
|
||||
* @param antCap Value applied to every FM tune that doesn't pass an
|
||||
* explicit override (0 = chip auto-tune, the factory
|
||||
* default before any calibration is saved).
|
||||
* @pubstate writes defaultFmAntCap_. Does not itself re-tune.
|
||||
*
|
||||
* @author Michele Bigi
|
||||
* @date 2026-08-19
|
||||
*/
|
||||
void setDefaultFmAntCap(std::uint8_t antCap) noexcept;
|
||||
|
||||
/**
|
||||
* @brief seekFm — seek FM in the given direction.
|
||||
@@ -200,6 +238,8 @@ private:
|
||||
std::uint8_t lastDabIndex_;
|
||||
core::FrequencyKHz lastFmFrequency_;
|
||||
std::uint8_t volume_;
|
||||
std::uint8_t defaultFmAntCap_;
|
||||
std::uint8_t defaultDabAntCap_;
|
||||
std::optional<std::uint32_t> lastPlayedServiceId_;
|
||||
std::optional<std::uint32_t> lastPlayedComponentId_;
|
||||
};
|
||||
|
||||
@@ -138,9 +138,21 @@ TunerService::TunerService(core::ITuner& tuner)
|
||||
, lastDabIndex_(0U)
|
||||
, lastFmFrequency_(defaultFmFrequency())
|
||||
, volume_(40U)
|
||||
, defaultFmAntCap_(0U)
|
||||
, defaultDabAntCap_(0U)
|
||||
{
|
||||
}
|
||||
|
||||
void TunerService::setDefaultFmAntCap(std::uint8_t antCap) noexcept
|
||||
{
|
||||
defaultFmAntCap_ = antCap;
|
||||
}
|
||||
|
||||
void TunerService::setDefaultDabAntCap(std::uint8_t antCap) noexcept
|
||||
{
|
||||
defaultDabAntCap_ = antCap;
|
||||
}
|
||||
|
||||
std::expected<core::TunerStatus, core::TunerError> TunerService::refreshStatus()
|
||||
{
|
||||
auto status = tuner_.readStatus();
|
||||
@@ -155,9 +167,11 @@ std::expected<core::TunerStatus, core::TunerError> TunerService::refreshStatus()
|
||||
}
|
||||
|
||||
std::expected<void, core::TunerError> TunerService::tuneDab(
|
||||
std::uint8_t freqIndex)
|
||||
std::uint8_t freqIndex, std::optional<std::uint8_t> antCap)
|
||||
{
|
||||
if (auto result = tuner_.tuneDab(freqIndex); !result) {
|
||||
if (auto result =
|
||||
tuner_.tuneDab(freqIndex, antCap.value_or(defaultDabAntCap_));
|
||||
!result) {
|
||||
return result;
|
||||
}
|
||||
lastDabIndex_ = freqIndex;
|
||||
@@ -167,9 +181,10 @@ std::expected<void, core::TunerError> TunerService::tuneDab(
|
||||
}
|
||||
|
||||
std::expected<void, core::TunerError> TunerService::tuneFm(
|
||||
core::FrequencyKHz frequency)
|
||||
core::FrequencyKHz frequency, std::optional<std::uint8_t> antCap)
|
||||
{
|
||||
if (auto result = tuner_.tuneFm(frequency); !result) {
|
||||
if (auto result = tuner_.tuneFm(frequency, antCap.value_or(defaultFmAntCap_));
|
||||
!result) {
|
||||
return result;
|
||||
}
|
||||
lastFmFrequency_ = frequency;
|
||||
|
||||
Reference in New Issue
Block a user