Add preset polish and broadcast metadata (fw 0.8.0).

Ship station reorder, DAB playing ids in presets, RDS PS/RT and DAB DLS in tuner status, Si4684 data-service read, host tests, and UI now-playing lines.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-07-07 00:01:49 +02:00
co-authored by Cursor
parent 9f76ab9e74
commit 0fc714e431
34 changed files with 1379 additions and 65 deletions
+3
View File
@@ -29,6 +29,9 @@ idf_component_register(
"src/StationList.cpp"
"src/StationListJson.cpp"
"src/BluetoothJson.cpp"
"src/BroadcastLabel.cpp"
"src/RdsMetadataAccumulator.cpp"
"src/DabDynamicLabelAccumulator.cpp"
INCLUDE_DIRS "include"
)
@@ -0,0 +1,69 @@
/**
* @file BroadcastLabel.hpp
* @brief Validated on-air label text (RDS PS/RT, DAB DLS).
*
* DigiRadio firmware — https://github.com/manvalan/DigiRadio
*
* Copyright 2026 Michele Bigi
* SPDX-License-Identifier: Apache-2.0
*
* @author Michele Bigi
* @date 2026-07-06
*/
#pragma once
#include <cstddef>
#include <optional>
#include <string>
#include <string_view>
namespace core {
/**
* @brief BroadcastLabel — trimmed UTF-8 label from chip byte buffers.
*
* @dname BroadcastLabel
* @return n/a (type)
* @pubstate Owns label_ (immutable after construction).
*
* @author Michele Bigi
* @date 2026-07-06
*/
class BroadcastLabel {
public:
/** Maximum DAB DLS length supported in status JSON. */
static constexpr std::size_t kMaxLength = 128;
/**
* @brief tryFromChipBytes — parse a NUL- or space-padded chip buffer.
*
* @dname tryFromChipBytes
* @param raw Raw bytes from RDS or DAB data service (may contain NUL).
* @return BroadcastLabel when non-empty after trim, otherwise nullopt.
* @pubstate none
*
* @author Michele Bigi
* @date 2026-07-06
*/
[[nodiscard]] static std::optional<BroadcastLabel>
tryFromChipBytes(std::string_view raw);
/**
* @brief value — read the validated label text.
*
* @dname value
* @return Trimmed label string.
* @pubstate reads label_.
*
* @author Michele Bigi
* @date 2026-07-06
*/
[[nodiscard]] std::string_view value() const noexcept;
private:
explicit BroadcastLabel(std::string label);
std::string label_;
};
} // namespace core
@@ -0,0 +1,86 @@
/**
* @file DabDynamicLabelAccumulator.hpp
* @brief Reassemble DAB DLS payloads into one dynamic label string.
*
* DigiRadio firmware — https://github.com/manvalan/DigiRadio
*
* Copyright 2026 Michele Bigi
* SPDX-License-Identifier: Apache-2.0
*
* @author Michele Bigi
* @date 2026-07-06
*/
#pragma once
#include "core/BroadcastLabel.hpp"
#include <array>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <span>
namespace core {
/**
* @brief DabDynamicLabelAccumulator — segmented DAB DLS label buffer.
*
* @dname DabDynamicLabelAccumulator
* @return n/a (type)
* @pubstate Holds partial DLS segments until the label can be read out.
*
* @author Michele Bigi
* @date 2026-07-06
*/
class DabDynamicLabelAccumulator {
public:
/**
* @brief reset — discard accumulated DLS segments.
*
* @dname reset
* @return n/a
* @pubstate clears buffer and segment flags.
*
* @author Michele Bigi
* @date 2026-07-06
*/
void reset() noexcept;
/**
* @brief applySegment — ingest one DLS payload block from the driver.
*
* @dname applySegment
* @param segmentIndex Zero-based segment index from the chip.
* @param segmentCount Total segments advertised for this label.
* @param payload Raw UTF-8 bytes for this segment.
* @return n/a
* @pubstate copies payload into buffer_ at the computed offset.
*
* @author Michele Bigi
* @date 2026-07-06
*/
void applySegment(std::uint16_t segmentIndex,
std::uint16_t segmentCount,
std::span<const std::uint8_t> payload) noexcept;
/**
* @brief label — read the assembled dynamic label when complete.
*
* @dname label
* @return Trimmed DLS text when all segments were received.
* @pubstate reads buffer_ and segmentValid_.
*
* @author Michele Bigi
* @date 2026-07-06
*/
[[nodiscard]] std::optional<BroadcastLabel> label() const;
private:
static constexpr std::size_t kMaxSegments = 32U;
std::array<char, BroadcastLabel::kMaxLength> buffer_{};
std::array<bool, kMaxSegments> segmentValid_{};
std::uint16_t expectedSegments_{0U};
};
} // namespace core
@@ -0,0 +1,102 @@
/**
* @file RdsMetadataAccumulator.hpp
* @brief Accumulate FM RDS program name and radiotext from raw groups.
*
* DigiRadio firmware — https://github.com/manvalan/DigiRadio
*
* Copyright 2026 Michele Bigi
* SPDX-License-Identifier: Apache-2.0
*
* @author Michele Bigi
* @date 2026-07-06
*/
#pragma once
#include "core/BroadcastLabel.hpp"
#include <array>
#include <cstdint>
#include <optional>
namespace core {
/**
* @brief RdsMetadataAccumulator — stateful RDS PS/RT decoder (IEC 62106).
*
* @dname RdsMetadataAccumulator
* @return n/a (type)
* @pubstate Holds partial PS and RT buffers until complete groups arrive.
*
* @author Michele Bigi
* @date 2026-07-06
*/
class RdsMetadataAccumulator {
public:
/**
* @brief reset — clear accumulated PS and radiotext.
*
* @dname reset
* @return n/a
* @pubstate clears internal buffers.
*
* @author Michele Bigi
* @date 2026-07-06
*/
void reset() noexcept;
/**
* @brief applyGroup — ingest one RDS group (blocks AD).
*
* @dname applyGroup
* @param blockA RDS block A (PI code).
* @param blockB RDS block B (group type and address).
* @param blockC RDS block C (text payload).
* @param blockD RDS block D (text payload for RT).
* @return n/a
* @pubstate updates PS/RT buffers for group types 0A and 2A.
*
* @author Michele Bigi
* @date 2026-07-06
*/
void applyGroup(std::uint16_t blockA,
std::uint16_t blockB,
std::uint16_t blockC,
std::uint16_t blockD) noexcept;
/**
* @brief programName — read the accumulated 8-character PS name.
*
* @dname programName
* @return Trimmed PS label when all four segments were received.
* @pubstate reads psBuffer_.
*
* @author Michele Bigi
* @date 2026-07-06
*/
[[nodiscard]] std::optional<BroadcastLabel> programName() const;
/**
* @brief radiotext — read the accumulated 64-character RT string.
*
* @dname radiotext
* @return Trimmed radiotext when at least one RT segment was received.
* @pubstate reads rtBuffer_.
*
* @author Michele Bigi
* @date 2026-07-06
*/
[[nodiscard]] std::optional<BroadcastLabel> radiotext() const;
private:
static constexpr std::size_t kPsSegments = 4U;
static constexpr std::size_t kRtSegments = 16U;
std::array<char, 8> psBuffer_{};
std::array<bool, kPsSegments> psSegmentValid_{};
std::array<char, 64> rtBuffer_{};
std::array<bool, kRtSegments> rtSegmentValid_{};
bool rtAbFlag_{false};
bool rtAbInitialized_{false};
};
} // namespace core
@@ -29,6 +29,7 @@ enum class StationListError {
Full,
NotFound,
SlotInUse,
PersistFailed,
};
} // namespace core
@@ -38,6 +38,21 @@ struct StationRemoveRequest {
std::size_t index; ///< Zero-based list index to delete.
};
/**
* @brief StationReorderRequest — parsed POST /api/stations/reorder body.
*
* @dname StationReorderRequest
* @return n/a (type)
* @pubstate Plain DTO filled by parseStationReorderJson.
*
* @author Michele Bigi
* @date 2026-07-06
*/
struct StationReorderRequest {
std::size_t fromIndex; ///< Current list position.
std::size_t toIndex; ///< Target list position.
};
/**
* @brief serializeStationListJson — serialise all presets for GET /api/stations.
*
@@ -93,6 +108,20 @@ parseStationListJson(std::string_view json);
[[nodiscard]] std::expected<StationRemoveRequest, ParseError>
parseStationRemoveJson(std::string_view json);
/**
* @brief parseStationReorderJson — validate POST /api/stations/reorder body.
*
* @dname parseStationReorderJson
* @param json Untrusted request body with from/to index fields.
* @return StationReorderRequest on success, or ParseError.
* @pubstate none
*
* @author Michele Bigi
* @date 2026-07-06
*/
[[nodiscard]] std::expected<StationReorderRequest, ParseError>
parseStationReorderJson(std::string_view json);
/**
* @brief serializeStationListErrorJson — serialise a station API error.
*
@@ -12,6 +12,7 @@
*/
#pragma once
#include "core/BroadcastLabel.hpp"
#include "core/FrequencyKHz.hpp"
#include "core/TunerBand.hpp"
@@ -56,10 +57,15 @@ struct TunerStatus {
std::optional<std::uint8_t> dabFreqIndex; ///< Current Band III ensemble index.
std::optional<std::uint8_t> dabFicQuality; ///< FIC quality 0100 when DAB.
std::optional<std::int8_t> dabCnrDb; ///< CNR in dB when DAB.
std::optional<std::uint32_t> dabPlayingServiceId; ///< Last played DAB service.
std::optional<std::uint32_t> dabPlayingComponentId; ///< Last played DAB component.
std::optional<FrequencyKHz> fmFrequency; ///< Tuned FM centre frequency.
std::optional<std::int8_t> fmRssiDbuV; ///< FM RSSI in dBµV.
std::optional<std::int8_t> fmSnrDb; ///< FM SNR in dB.
std::optional<bool> fmStereo; ///< FM stereo pilot detected.
std::optional<BroadcastLabel> fmStationName; ///< FM RDS program service name.
std::optional<BroadcastLabel> fmRadiotext; ///< FM RDS radiotext (RT).
std::optional<BroadcastLabel> dabDynamicLabel; ///< DAB DLS now-playing label.
};
} // namespace core
@@ -0,0 +1,58 @@
/**
* @file BroadcastLabel.cpp
* @brief BroadcastLabel implementation.
*
* DigiRadio firmware — https://github.com/manvalan/DigiRadio
*
* Copyright 2026 Michele Bigi
* SPDX-License-Identifier: Apache-2.0
*
* @author Michele Bigi
* @date 2026-07-06
*/
#include "core/BroadcastLabel.hpp"
namespace core {
namespace {
[[nodiscard]] std::string trimChipPadding(std::string_view raw)
{
std::size_t end = raw.size();
if (end > BroadcastLabel::kMaxLength) {
end = BroadcastLabel::kMaxLength;
}
while (end > 0U && (raw[end - 1U] == '\0' || raw[end - 1U] == ' ')) {
--end;
}
std::size_t start = 0U;
while (start < end && raw[start] == ' ') {
++start;
}
return std::string(raw.substr(start, end - start));
}
} // namespace
std::optional<BroadcastLabel> BroadcastLabel::tryFromChipBytes(
std::string_view raw)
{
const std::string trimmed = trimChipPadding(raw);
if (trimmed.empty()) {
return std::nullopt;
}
return BroadcastLabel(trimmed);
}
BroadcastLabel::BroadcastLabel(std::string label)
: label_(std::move(label))
{
}
std::string_view BroadcastLabel::value() const noexcept
{
return label_;
}
} // namespace core
@@ -0,0 +1,70 @@
/**
* @file DabDynamicLabelAccumulator.cpp
* @brief DabDynamicLabelAccumulator implementation.
*
* DigiRadio firmware — https://github.com/manvalan/DigiRadio
*
* Copyright 2026 Michele Bigi
* SPDX-License-Identifier: Apache-2.0
*
* @author Michele Bigi
* @date 2026-07-06
*/
#include "core/DabDynamicLabelAccumulator.hpp"
#include <algorithm>
#include <cstring>
namespace core {
void DabDynamicLabelAccumulator::reset() noexcept
{
buffer_.fill('\0');
segmentValid_.fill(false);
expectedSegments_ = 0U;
}
void DabDynamicLabelAccumulator::applySegment(
std::uint16_t segmentIndex,
std::uint16_t segmentCount,
std::span<const std::uint8_t> payload) noexcept
{
if (segmentCount == 0U || segmentCount > kMaxSegments) {
return;
}
if (segmentIndex >= segmentCount) {
return;
}
if (expectedSegments_ != segmentCount) {
reset();
expectedSegments_ = segmentCount;
}
const std::size_t offset =
static_cast<std::size_t>(segmentIndex)
* static_cast<std::size_t>(payload.size());
if (offset >= buffer_.size()) {
return;
}
const std::size_t copyLen =
std::min(payload.size(), buffer_.size() - offset);
std::memcpy(buffer_.data() + offset, payload.data(), copyLen);
segmentValid_[segmentIndex] = true;
}
std::optional<BroadcastLabel> DabDynamicLabelAccumulator::label() const
{
if (expectedSegments_ == 0U) {
return std::nullopt;
}
for (std::uint16_t i = 0U; i < expectedSegments_; ++i) {
if (!segmentValid_[i]) {
return std::nullopt;
}
}
return BroadcastLabel::tryFromChipBytes(
std::string_view(buffer_.data(), buffer_.size()));
}
} // namespace core
@@ -0,0 +1,100 @@
/**
* @file RdsMetadataAccumulator.cpp
* @brief RdsMetadataAccumulator implementation.
*
* DigiRadio firmware — https://github.com/manvalan/DigiRadio
*
* Copyright 2026 Michele Bigi
* SPDX-License-Identifier: Apache-2.0
*
* @author Michele Bigi
* @date 2026-07-06
*/
#include "core/RdsMetadataAccumulator.hpp"
namespace core {
void RdsMetadataAccumulator::reset() noexcept
{
psBuffer_.fill('\0');
psSegmentValid_.fill(false);
rtBuffer_.fill('\0');
rtSegmentValid_.fill(false);
rtAbFlag_ = false;
rtAbInitialized_ = false;
}
void RdsMetadataAccumulator::applyGroup(std::uint16_t blockA,
std::uint16_t blockB,
std::uint16_t blockC,
std::uint16_t blockD) noexcept
{
(void)blockA;
const std::uint8_t groupType =
static_cast<std::uint8_t>((blockB >> 12U) & 0x0FU);
if (groupType == 0U) {
const std::size_t index =
static_cast<std::size_t>((blockB >> 1U) & 0x03U);
if (index < kPsSegments) {
psBuffer_[index * 2U] =
static_cast<char>((blockC >> 8U) & 0xFFU);
psBuffer_[index * 2U + 1U] = static_cast<char>(blockC & 0xFFU);
psSegmentValid_[index] = true;
}
return;
}
if (groupType == 2U) {
const bool abFlag = (blockB & 0x10U) != 0U;
if (!rtAbInitialized_ || abFlag != rtAbFlag_) {
rtBuffer_.fill('\0');
rtSegmentValid_.fill(false);
rtAbFlag_ = abFlag;
rtAbInitialized_ = true;
}
const std::size_t index =
static_cast<std::size_t>(blockB & 0x0FU);
if (index < kRtSegments) {
rtBuffer_[index * 4U] =
static_cast<char>((blockC >> 8U) & 0xFFU);
rtBuffer_[index * 4U + 1U] =
static_cast<char>(blockC & 0xFFU);
rtBuffer_[index * 4U + 2U] =
static_cast<char>((blockD >> 8U) & 0xFFU);
rtBuffer_[index * 4U + 3U] =
static_cast<char>(blockD & 0xFFU);
rtSegmentValid_[index] = true;
}
}
}
std::optional<BroadcastLabel> RdsMetadataAccumulator::programName() const
{
for (bool valid : psSegmentValid_) {
if (!valid) {
return std::nullopt;
}
}
return BroadcastLabel::tryFromChipBytes(
std::string_view(psBuffer_.data(), psBuffer_.size()));
}
std::optional<BroadcastLabel> RdsMetadataAccumulator::radiotext() const
{
bool any = false;
for (bool valid : rtSegmentValid_) {
if (valid) {
any = true;
break;
}
}
if (!any) {
return std::nullopt;
}
return BroadcastLabel::tryFromChipBytes(
std::string_view(rtBuffer_.data(), rtBuffer_.size()));
}
} // namespace core
@@ -240,6 +240,21 @@ parseStationRemoveJson(std::string_view json)
return StationRemoveRequest{.index = static_cast<std::size_t>(index)};
}
std::expected<StationReorderRequest, ParseError>
parseStationReorderJson(std::string_view json)
{
unsigned long fromIndex = 0;
unsigned long toIndex = 0;
if (!extractJsonUint(json, "from", fromIndex)
|| !extractJsonUint(json, "to", toIndex)) {
return std::unexpected(ParseError::MissingField);
}
return StationReorderRequest{
.fromIndex = static_cast<std::size_t>(fromIndex),
.toIndex = static_cast<std::size_t>(toIndex),
};
}
std::string serializeStationListErrorJson(const char* reason)
{
std::ostringstream out;
@@ -258,6 +273,8 @@ const char* stationListErrorToken(StationListError error) noexcept
return "not_found";
case StationListError::SlotInUse:
return "slot_in_use";
case StationListError::PersistFailed:
return "persist_failed";
}
return "station_error";
}
+42 -11
View File
@@ -58,6 +58,29 @@ namespace {
return band == TunerBand::Fm ? "fm" : "dab";
}
void appendJsonString(std::ostringstream& out, std::string_view value)
{
out << '"';
for (char c : value) {
if (c == '"' || c == '\\') {
out << '\\';
}
out << c;
}
out << '"';
}
void appendOptionalLabel(std::ostringstream& out,
std::string_view key,
const std::optional<BroadcastLabel>& label)
{
if (!label) {
return;
}
out << ",\"" << key << "\":";
appendJsonString(out, label->value());
}
} // namespace
std::string serializeTunerStatusJson(const TunerStatus& status)
@@ -82,6 +105,15 @@ std::string serializeTunerStatusJson(const TunerStatus& status)
if (status.dabCnrDb) {
out << ",\"cnr_db\":" << static_cast<int>(*status.dabCnrDb);
}
if (status.dabPlayingServiceId) {
out << ",\"playing_service_id\":"
<< *status.dabPlayingServiceId;
}
if (status.dabPlayingComponentId) {
out << ",\"playing_component_id\":"
<< *status.dabPlayingComponentId;
}
appendOptionalLabel(out, "dynamic_label", status.dabDynamicLabel);
out << "},\"fm\":null";
} else {
out << ",\"fm\":{";
@@ -100,6 +132,8 @@ std::string serializeTunerStatusJson(const TunerStatus& status)
if (status.fmStereo) {
out << ",\"stereo\":" << (*status.fmStereo ? "true" : "false");
}
appendOptionalLabel(out, "station_name", status.fmStationName);
appendOptionalLabel(out, "radiotext", status.fmRadiotext);
out << "},\"dab\":null";
}
out << '}';
@@ -116,18 +150,15 @@ std::string serializeTunerServicesJson(
out << ',';
}
const auto& s = services[i];
out << "{\"service_id\":" << s.serviceId
<< ",\"component_id\":" << s.componentId << ",\"label\":\"";
for (char c : s.label) {
if (c == '\0') {
break;
}
if (c == '"' || c == '\\') {
out << '\\';
}
out << c;
std::string_view labelText(s.label.data(), s.label.size());
const std::size_t nul = labelText.find('\0');
if (nul != std::string_view::npos) {
labelText = labelText.substr(0U, nul);
}
out << "\"}";
out << "{\"service_id\":" << s.serviceId
<< ",\"component_id\":" << s.componentId << ",\"label\":";
appendJsonString(out, labelText);
out << "}";
}
out << "]}";
return out.str();
@@ -41,6 +41,9 @@ add_library(digiradio_core STATIC
"${CORE_SRC_DIR}/StationList.cpp"
"${CORE_SRC_DIR}/StationListJson.cpp"
"${CORE_SRC_DIR}/BluetoothJson.cpp"
"${CORE_SRC_DIR}/BroadcastLabel.cpp"
"${CORE_SRC_DIR}/RdsMetadataAccumulator.cpp"
"${CORE_SRC_DIR}/DabDynamicLabelAccumulator.cpp"
)
target_include_directories(digiradio_core PUBLIC
"${CMAKE_CURRENT_SOURCE_DIR}/../include"
@@ -78,6 +81,18 @@ add_executable(enhancements_design_test enhancements_design_test.cpp)
target_link_libraries(enhancements_design_test PRIVATE digiradio_core)
add_test(NAME enhancements_design_test COMMAND enhancements_design_test)
add_executable(station_service_test station_service_test.cpp)
target_include_directories(station_service_test PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/../../services/station/include"
"${CMAKE_CURRENT_SOURCE_DIR}/../../services/tuner/include"
)
target_sources(station_service_test PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/../../services/station/src/StationService.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/../../services/tuner/src/TunerService.cpp"
)
target_link_libraries(station_service_test PRIVATE digiradio_core)
add_test(NAME station_service_test COMMAND station_service_test)
add_executable(station_list_test station_list_test.cpp)
target_link_libraries(station_list_test PRIVATE digiradio_core)
add_test(NAME station_list_test COMMAND station_list_test)
@@ -85,3 +100,7 @@ add_test(NAME station_list_test COMMAND station_list_test)
add_executable(bt1035_at_test bt1035_at_test.cpp)
target_link_libraries(bt1035_at_test PRIVATE digiradio_core)
add_test(NAME bt1035_at_test COMMAND bt1035_at_test)
add_executable(broadcast_metadata_test broadcast_metadata_test.cpp)
target_link_libraries(broadcast_metadata_test PRIVATE digiradio_core)
add_test(NAME broadcast_metadata_test COMMAND broadcast_metadata_test)
@@ -0,0 +1,115 @@
/**
* @file broadcast_metadata_test.cpp
* @brief Host tests for broadcast metadata parsing (RDS / DLS).
*
* DigiRadio firmware — https://github.com/manvalan/DigiRadio
*
* Copyright 2026 Michele Bigi
* SPDX-License-Identifier: Apache-2.0
*
* @author Michele Bigi
* @date 2026-07-06
*/
#include "core/BroadcastLabel.hpp"
#include "core/DabDynamicLabelAccumulator.hpp"
#include "core/RdsMetadataAccumulator.hpp"
#include <cstdlib>
#include <iostream>
#include <string_view>
#include <vector>
namespace {
[[nodiscard]] int runChipLabelTrimTest()
{
const auto label = core::BroadcastLabel::tryFromChipBytes(" RAI 1 \0\0");
if (!label || label->value() != "RAI 1") {
std::cerr << "chip label trim failed\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
[[nodiscard]] int runRdsProgramNameTest()
{
core::RdsMetadataAccumulator acc;
acc.applyGroup(0U, 0x0000U, 0x5445U, 0U);
acc.applyGroup(0U, 0x0002U, 0x5354U, 0U);
acc.applyGroup(0U, 0x0004U, 0x2020U, 0U);
acc.applyGroup(0U, 0x0006U, 0x2020U, 0U);
const auto name = acc.programName();
if (!name || name->value() != "TEST") {
std::cerr << "RDS PS parse failed\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
[[nodiscard]] int runRdsRadiotextTest()
{
core::RdsMetadataAccumulator acc;
acc.applyGroup(0U, 0x2000U, 0x4E6FU, 0x7720U);
const auto text = acc.radiotext();
if (!text || text->value() != "Now") {
std::cerr << "RDS RT parse failed: "
<< (text ? std::string(text->value()) : "nullopt") << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
[[nodiscard]] int runDabDynamicLabelTest()
{
core::DabDynamicLabelAccumulator acc;
const std::vector<std::uint8_t> payload = {'L', 'i', 'v', 'e', ' ', 'D', 'J'};
acc.applySegment(0U, 1U, payload);
const auto label = acc.label();
if (!label || label->value() != "Live DJ") {
std::cerr << "DLS single-segment parse failed\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
[[nodiscard]] int runDabDynamicLabelSegmentsTest()
{
core::DabDynamicLabelAccumulator acc;
const std::vector<std::uint8_t> part1 = {'A', 'B', 'C'};
const std::vector<std::uint8_t> part2 = {'D', 'E', 'F'};
acc.applySegment(0U, 2U, part1);
acc.applySegment(1U, 2U, part2);
const auto label = acc.label();
if (!label || label->value() != "ABCDEF") {
std::cerr << "DLS multi-segment parse failed\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
} // namespace
int main()
{
if (runChipLabelTrimTest() != EXIT_SUCCESS) {
return EXIT_FAILURE;
}
if (runRdsProgramNameTest() != EXIT_SUCCESS) {
return EXIT_FAILURE;
}
if (runRdsRadiotextTest() != EXIT_SUCCESS) {
return EXIT_FAILURE;
}
if (runDabDynamicLabelTest() != EXIT_SUCCESS) {
return EXIT_FAILURE;
}
if (runDabDynamicLabelSegmentsTest() != EXIT_SUCCESS) {
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
@@ -81,6 +81,37 @@ namespace {
return EXIT_SUCCESS;
}
[[nodiscard]] int runParseStationReorderJsonTest()
{
const auto parsed =
core::parseStationReorderJson(R"({"from":1,"to":0})");
if (!parsed || parsed->fromIndex != 1U || parsed->toIndex != 0U) {
std::cerr << "reorder parse failed\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
[[nodiscard]] int runStationListReorderTest()
{
core::StationList list;
if (auto a = list.add(makeFmStation("A", 88000U, 1U)); !a) {
return EXIT_FAILURE;
}
if (auto b = list.add(makeFmStation("B", 90000U, 2U)); !b) {
return EXIT_FAILURE;
}
if (auto moved = list.move(1U, 0U); !moved) {
std::cerr << "move failed\n";
return EXIT_FAILURE;
}
if (list.stations()[0U].name().value() != "B") {
std::cerr << "expected B first after reorder\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
} // namespace
int main()
@@ -94,5 +125,11 @@ int main()
if (runParseStationJsonTest() != EXIT_SUCCESS) {
return EXIT_FAILURE;
}
if (runParseStationReorderJsonTest() != EXIT_SUCCESS) {
return EXIT_FAILURE;
}
if (runStationListReorderTest() != EXIT_SUCCESS) {
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
@@ -0,0 +1,226 @@
/**
* @file station_service_test.cpp
* @brief Host tests for StationService with in-memory fake store.
*
* DigiRadio firmware — https://github.com/manvalan/DigiRadio
*
* Copyright 2026 Michele Bigi
* SPDX-License-Identifier: Apache-2.0
*
* @author Michele Bigi
* @date 2026-07-06
*/
#include "core/FrequencyKHz.hpp"
#include "core/ISecureStore.hpp"
#include "core/StationListJson.hpp"
#include "core/StationName.hpp"
#include "core/TunerBand.hpp"
#include "station/StationService.hpp"
#include "tuner/TunerService.hpp"
#include <cstdlib>
#include <iostream>
#include <optional>
#include <string>
namespace {
class FakeTuner final : public core::ITuner {
public:
[[nodiscard]] std::expected<void, core::TunerError> boot(
core::TunerBand) override
{
return {};
}
[[nodiscard]] std::expected<core::TunerBand, core::TunerError> currentBand()
const override
{
return core::TunerBand::Dab;
}
[[nodiscard]] std::expected<core::TunerStatus, core::TunerError> readStatus()
override
{
core::TunerStatus status = {};
status.booted = true;
status.band = core::TunerBand::Dab;
status.locked = true;
status.volume = 40;
status.dabFreqIndex = 12U;
return status;
}
[[nodiscard]] std::expected<void, core::TunerError> tuneDab(
std::uint8_t) override
{
return {};
}
[[nodiscard]] std::expected<void, core::TunerError> tuneFm(
core::FrequencyKHz) override
{
return {};
}
[[nodiscard]] std::expected<core::FrequencyKHz, core::TunerError> seekFm(
core::SeekDirection) override
{
return std::unexpected(core::TunerError::WrongBand);
}
[[nodiscard]] std::expected<std::vector<core::TunerServiceEntry>,
core::TunerError>
listDabServices() override
{
return std::vector<core::TunerServiceEntry>{};
}
[[nodiscard]] std::expected<void, core::TunerError> playDabService(
std::uint32_t, std::uint32_t) override
{
return {};
}
[[nodiscard]] std::expected<void, core::TunerError> setVolume(
std::uint8_t) override
{
return {};
}
};
class FakeSecureStore final : public core::ISecureStore {
public:
[[nodiscard]] bool hasWifiCredentials() const override
{
return false;
}
[[nodiscard]] std::expected<void, core::StoreError> saveWifiCredentials(
const core::WifiCredentials&) override
{
return std::unexpected(core::StoreError::IoFailed);
}
[[nodiscard]] std::expected<core::WifiCredentials, core::StoreError>
loadWifiCredentials() const override
{
return std::unexpected(core::StoreError::NotFound);
}
[[nodiscard]] std::expected<void, core::StoreError> clearWifiCredentials()
override
{
return {};
}
[[nodiscard]] bool hasStationList() const override
{
return stationJson_.has_value();
}
[[nodiscard]] std::expected<void, core::StoreError> saveStationListJson(
std::string_view json) override
{
stationJson_ = std::string(json);
return {};
}
[[nodiscard]] std::expected<std::string, core::StoreError>
loadStationListJson() const override
{
if (!stationJson_) {
return std::unexpected(core::StoreError::NotFound);
}
return *stationJson_;
}
[[nodiscard]] std::expected<void, core::StoreError> clearStationList()
override
{
stationJson_.reset();
return {};
}
private:
std::optional<std::string> stationJson_;
};
[[nodiscard]] core::Station makeFmStation(const char* name, std::uint32_t khz)
{
return core::Station(
*core::StationName::tryFrom(name),
core::TunerBand::Fm,
0U,
std::nullopt,
std::nullopt,
*core::FrequencyKHz::tryFromKhz(khz),
std::nullopt);
}
[[nodiscard]] int runPersistRoundTripTest()
{
FakeSecureStore store;
FakeTuner tuner;
tuner::TunerService tunerService(tuner);
station::StationService service(store, tunerService);
if (auto added = service.add(makeFmStation("Jazz", 101500U)); !added) {
std::cerr << "add failed\n";
return EXIT_FAILURE;
}
station::StationService reloaded(store, tunerService);
if (auto loaded = reloaded.loadFromStore(); !loaded) {
std::cerr << "load failed\n";
return EXIT_FAILURE;
}
if (reloaded.list().stations().size() != 1U) {
std::cerr << "expected one preset after reload\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
[[nodiscard]] int runReorderPersistTest()
{
FakeSecureStore store;
FakeTuner tuner;
tuner::TunerService tunerService(tuner);
station::StationService service(store, tunerService);
if (auto a = service.add(makeFmStation("A", 88000U)); !a) {
return EXIT_FAILURE;
}
if (auto b = service.add(makeFmStation("B", 90000U)); !b) {
return EXIT_FAILURE;
}
if (auto moved = service.reorder(1U, 0U); !moved) {
std::cerr << "reorder failed\n";
return EXIT_FAILURE;
}
station::StationService reloaded(store, tunerService);
if (auto loaded = reloaded.loadFromStore(); !loaded) {
return EXIT_FAILURE;
}
if (reloaded.list().stations()[0U].name().value() != "B") {
std::cerr << "reorder not persisted\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
} // namespace
int main()
{
if (runPersistRoundTripTest() != EXIT_SUCCESS) {
return EXIT_FAILURE;
}
if (runReorderPersistTest() != EXIT_SUCCESS) {
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
@@ -16,6 +16,7 @@
#include "core/TunerBand.hpp"
#include "core/TunerJson.hpp"
#include "core/TunerStatus.hpp"
#include "core/BroadcastLabel.hpp"
#include <cstdlib>
#include <iostream>
@@ -102,6 +103,26 @@ namespace {
return EXIT_SUCCESS;
}
[[nodiscard]] int runTunerStatusPlayingSerialiseTest()
{
core::TunerStatus status = {};
status.booted = true;
status.band = core::TunerBand::Dab;
status.locked = true;
status.volume = 40;
status.dabFreqIndex = 12U;
status.dabPlayingServiceId = 42U;
status.dabPlayingComponentId = 7U;
const std::string json = core::serializeTunerStatusJson(status);
if (json.find("\"playing_service_id\":42") == std::string::npos
|| json.find("\"playing_component_id\":7") == std::string::npos) {
std::cerr << "playing ids missing: " << json << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
[[nodiscard]] int runTunerServicesSerialiseTest()
{
core::TunerServiceEntry entry = {};
@@ -118,6 +139,36 @@ namespace {
return EXIT_SUCCESS;
}
[[nodiscard]] int runTunerStatusMetadataSerialiseTest()
{
core::TunerStatus status = {};
status.booted = true;
status.band = core::TunerBand::Fm;
status.locked = true;
status.volume = 40;
status.fmFrequency = *core::FrequencyKHz::tryFromKhz(101500U);
status.fmStationName = core::BroadcastLabel::tryFromChipBytes("RADIO 1");
status.fmRadiotext = core::BroadcastLabel::tryFromChipBytes("Now playing");
const std::string json = core::serializeTunerStatusJson(status);
if (json.find("\"station_name\":\"RADIO 1\"") == std::string::npos
|| json.find("\"radiotext\":\"Now playing\"") == std::string::npos) {
std::cerr << "FM metadata missing: " << json << '\n';
return EXIT_FAILURE;
}
status.band = core::TunerBand::Dab;
status.dabFreqIndex = 5U;
status.dabDynamicLabel =
core::BroadcastLabel::tryFromChipBytes("Live show");
const std::string dabJson = core::serializeTunerStatusJson(status);
if (dabJson.find("\"dynamic_label\":\"Live show\"") == std::string::npos) {
std::cerr << "DAB metadata missing: " << dabJson << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
[[nodiscard]] int runTunerErrorSerialiseTest()
{
if (!expectEqual(core::serializeTunerErrorJson("not_booted"),
@@ -146,6 +197,12 @@ int main()
if (runTunerStatusSerialiseTest() != EXIT_SUCCESS) {
return EXIT_FAILURE;
}
if (runTunerStatusPlayingSerialiseTest() != EXIT_SUCCESS) {
return EXIT_FAILURE;
}
if (runTunerStatusMetadataSerialiseTest() != EXIT_SUCCESS) {
return EXIT_FAILURE;
}
if (runTunerServicesSerialiseTest() != EXIT_SUCCESS) {
return EXIT_FAILURE;
}