Add BT1035 pairing and station presets (fw 0.7.0).

Expose discoverable mode and A2DP control over REST, add persisted
DAB/FM preset list with web UI, and document gaps in docs/TODO.md.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-07-06 17:42:11 +02:00
co-authored by Cursor
parent a08a9c19ee
commit 82c9f401da
46 changed files with 2819 additions and 33 deletions
+1 -1
View File
@@ -7,7 +7,7 @@ idf_component_register(
"src/NetBootstrap.cpp"
INCLUDE_DIRS "include"
EMBED_FILES "www/index.html.gz"
REQUIRES core esp_wifi esp_netif esp_event nvs_flash esp_http_server tuner audio
REQUIRES core esp_wifi esp_netif esp_event nvs_flash esp_http_server tuner audio bluetooth station bt1035
)
target_compile_features(${COMPONENT_LIB} PUBLIC cxx_std_23)
@@ -32,6 +32,14 @@ namespace audio {
class AudioService;
} // namespace audio
namespace bluetooth {
class BluetoothService;
} // namespace bluetooth
namespace station {
class StationService;
} // namespace station
namespace tuner {
class TunerService;
} // namespace tuner
@@ -66,7 +74,8 @@ public:
*/
[[nodiscard]] static std::expected<NetBootstrap, NetError>
start(core::ISecureStore& store, tuner::TunerService& tuner,
audio::AudioService& audio,
audio::AudioService& audio, bluetooth::BluetoothService& bluetooth,
station::StationService& stations,
core::CompanionChipStatus companionChips);
NetBootstrap(const NetBootstrap&) = delete;
@@ -30,6 +30,14 @@ namespace audio {
class AudioService;
} // namespace audio
namespace bluetooth {
class BluetoothService;
} // namespace bluetooth
namespace station {
class StationService;
} // namespace station
namespace tuner {
class TunerService;
} // namespace tuner
@@ -53,6 +61,8 @@ struct HttpRouteContext {
core::ISecureStore* store; ///< Secure store for Wi-Fi provisioning.
tuner::TunerService* tuner; ///< Tuner service for tuner REST routes.
audio::AudioService* audio; ///< Audio service for ADAU1701 REST routes.
bluetooth::BluetoothService* bluetooth; ///< Bluetooth pairing REST routes.
station::StationService* stations; ///< Preset list REST routes.
core::CompanionChipStatus companionChips; ///< Boot flags for /api/health.
};
@@ -127,8 +137,10 @@ public:
* @param netState Active network phase exposed to handlers.
* @param tuner Tuner service for the tuner REST routes.
* @param audio Audio service for the audio REST routes.
* @param bluetooth Bluetooth service for pairing REST routes.
* @param stations Station preset service for list REST routes.
* @return Ok on success, or NetError::HttpServerStartFailed.
* @pubstate writes server_, store_, netState_, tuner_, and audio_ on success.
* @pubstate writes server_, store_, netState_, and service pointers on success.
*
* @author Michele Bigi
* @date 2026-07-06
@@ -136,6 +148,8 @@ public:
[[nodiscard]] std::expected<void, NetError> start(
core::ISecureStore& store, NetState netState,
tuner::TunerService& tuner, audio::AudioService& audio,
bluetooth::BluetoothService& bluetooth,
station::StationService& stations,
core::CompanionChipStatus companionChips);
private:
@@ -144,6 +158,8 @@ private:
NetState netState_;
tuner::TunerService* tuner_;
audio::AudioService* audio_;
bluetooth::BluetoothService* bluetooth_;
station::StationService* stations_;
HttpRouteContext routeContext_;
};
+14 -4
View File
@@ -24,6 +24,8 @@
#include "esp_wifi.h"
#include "nvs_flash.h"
#include "audio/AudioService.hpp"
#include "bluetooth/BluetoothService.hpp"
#include "station/StationService.hpp"
#include "tuner/TunerService.hpp"
namespace net {
@@ -101,6 +103,8 @@ constexpr char kTag[] = "NetBootstrap";
[[nodiscard]] std::expected<NetBootstrap, NetError>
startSetupMode(core::ISecureStore& store, tuner::TunerService& tuner,
audio::AudioService& audio,
bluetooth::BluetoothService& bluetooth,
station::StationService& stations,
core::CompanionChipStatus companionChips)
{
esp_netif_create_default_wifi_ap();
@@ -113,7 +117,7 @@ startSetupMode(core::ISecureStore& store, tuner::TunerService& tuner,
SetupWebServer webServer;
if (auto webResult =
webServer.start(store, NetState::SoftApSetup, tuner, audio,
companionChips);
bluetooth, stations, companionChips);
!webResult) {
return std::unexpected(webResult.error());
}
@@ -137,6 +141,8 @@ startSetupMode(core::ISecureStore& store, tuner::TunerService& tuner,
[[nodiscard]] std::expected<NetBootstrap, NetError>
startStaMode(core::ISecureStore& store, tuner::TunerService& tuner,
audio::AudioService& audio,
bluetooth::BluetoothService& bluetooth,
station::StationService& stations,
core::CompanionChipStatus companionChips)
{
auto credsResult = store.loadWifiCredentials();
@@ -155,7 +161,7 @@ startStaMode(core::ISecureStore& store, tuner::TunerService& tuner,
SetupWebServer webServer;
if (auto webResult =
webServer.start(store, NetState::StaConnected, tuner, audio,
companionChips);
bluetooth, stations, companionChips);
!webResult) {
return std::unexpected(webResult.error());
}
@@ -170,6 +176,8 @@ startStaMode(core::ISecureStore& store, tuner::TunerService& tuner,
std::expected<NetBootstrap, NetError>
NetBootstrap::start(core::ISecureStore& store, tuner::TunerService& tuner,
audio::AudioService& audio,
bluetooth::BluetoothService& bluetooth,
station::StationService& stations,
core::CompanionChipStatus companionChips)
{
if (auto platform = initPlatform(); !platform) {
@@ -181,14 +189,16 @@ NetBootstrap::start(core::ISecureStore& store, tuner::TunerService& tuner,
}
if (store.hasWifiCredentials()) {
auto staResult = startStaMode(store, tuner, audio, companionChips);
auto staResult = startStaMode(store, tuner, audio, bluetooth, stations,
companionChips);
if (staResult) {
return staResult;
}
ESP_LOGW(kTag, "STA join failed — falling back to setup SoftAP");
}
return startSetupMode(store, tuner, audio, companionChips);
return startSetupMode(store, tuner, audio, bluetooth, stations,
companionChips);
}
NetBootstrap::NetBootstrap(std::optional<SoftApHost> softAp,
+296 -6
View File
@@ -20,17 +20,22 @@
#include "core/AudioProfile.hpp"
#include "core/AudioProfileJson.hpp"
#include "core/BluetoothJson.hpp"
#include "core/CompanionChipStatus.hpp"
#include "core/FirmwareVersion.hpp"
#include "core/HealthStatus.hpp"
#include "core/HealthStatusJson.hpp"
#include "core/ParseError.hpp"
#include "core/SeekDirection.hpp"
#include "core/StationListJson.hpp"
#include "core/StoreError.hpp"
#include "core/TunerJson.hpp"
#include "core/WifiProvisionJson.hpp"
#include "tuner/TunerService.hpp"
#include "audio/AudioService.hpp"
#include "bluetooth/BluetoothService.hpp"
#include "station/StationService.hpp"
#include "bt1035/Bt1035Error.hpp"
#include "esp_http_server.h"
#include "esp_log.h"
@@ -45,7 +50,7 @@ namespace net {
namespace {
constexpr char kTag[] = "SetupWebServer";
constexpr char kFirmwareVersion[] = "0.6.0";
constexpr char kFirmwareVersion[] = "0.7.0";
constexpr unsigned kRebootDelaySec = 3;
extern const uint8_t www_index_html_gz_start[] asm(
@@ -131,6 +136,24 @@ void rebootTask(void* arg)
return "tuner_error";
}
[[nodiscard]] const char* bt1035ErrorToken(bt1035::Bt1035Error error) noexcept
{
switch (error) {
case bt1035::Bt1035Error::NotBooted:
return "not_booted";
case bt1035::Bt1035Error::AtTimeout:
return "at_timeout";
case bt1035::Bt1035Error::AtError:
return "at_error";
case bt1035::Bt1035Error::UnexpectedResponse:
return "unexpected_response";
case bt1035::Bt1035Error::ResetFailed:
case bt1035::Bt1035Error::UartInitFailed:
return "driver_failed";
}
return "bluetooth_error";
}
template <std::size_t N>
[[nodiscard]] bool readRequestBodyImpl(httpd_req_t* req, std::array<char, N>& body)
{
@@ -624,6 +647,193 @@ esp_err_t wifiPostHandler(httpd_req_t* req)
return ESP_OK;
}
esp_err_t bluetoothStatusGetHandler(httpd_req_t* req)
{
auto* ctx = routeContextFrom(req);
if (ctx == nullptr || ctx->bluetooth == nullptr) {
httpd_resp_set_status(req, "503 Service Unavailable");
return httpd_resp_send(req, nullptr, 0);
}
auto status = ctx->bluetooth->refreshStatus();
if (!status) {
const std::string json =
core::serializeBluetoothErrorJson(bt1035ErrorToken(status.error()));
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());
}
const std::string json = core::serializeBluetoothStatusJson(*status);
httpd_resp_set_type(req, "application/json");
return httpd_resp_send(req, json.c_str(), json.size());
}
esp_err_t bluetoothPairPostHandler(httpd_req_t* req)
{
auto* ctx = routeContextFrom(req);
if (ctx == nullptr || ctx->bluetooth == nullptr) {
httpd_resp_set_status(req, "503 Service Unavailable");
return httpd_resp_send(req, nullptr, 0);
}
if (auto result = ctx->bluetooth->startPairing(); !result) {
const std::string json =
core::serializeBluetoothErrorJson(bt1035ErrorToken(result.error()));
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());
}
httpd_resp_set_type(req, "application/json");
return httpd_resp_send(req, "{\"status\":\"pairing\"}", 20);
}
esp_err_t bluetoothPairStopPostHandler(httpd_req_t* req)
{
auto* ctx = routeContextFrom(req);
if (ctx == nullptr || ctx->bluetooth == nullptr) {
httpd_resp_set_status(req, "503 Service Unavailable");
return httpd_resp_send(req, nullptr, 0);
}
if (auto result = ctx->bluetooth->stopPairing(); !result) {
const std::string json =
core::serializeBluetoothErrorJson(bt1035ErrorToken(result.error()));
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());
}
httpd_resp_set_type(req, "application/json");
return httpd_resp_send(req, "{\"status\":\"idle\"}", 17);
}
esp_err_t bluetoothDisconnectPostHandler(httpd_req_t* req)
{
auto* ctx = routeContextFrom(req);
if (ctx == nullptr || ctx->bluetooth == nullptr) {
httpd_resp_set_status(req, "503 Service Unavailable");
return httpd_resp_send(req, nullptr, 0);
}
if (auto result = ctx->bluetooth->disconnect(); !result) {
const std::string json =
core::serializeBluetoothErrorJson(bt1035ErrorToken(result.error()));
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());
}
httpd_resp_set_type(req, "application/json");
return httpd_resp_send(req, "{\"status\":\"disconnected\"}", 24);
}
esp_err_t stationsGetHandler(httpd_req_t* req)
{
auto* ctx = routeContextFrom(req);
if (ctx == nullptr || ctx->stations == nullptr) {
httpd_resp_set_status(req, "503 Service Unavailable");
return httpd_resp_send(req, nullptr, 0);
}
const std::string json =
core::serializeStationListJson(ctx->stations->list());
httpd_resp_set_type(req, "application/json");
return httpd_resp_send(req, json.c_str(), json.size());
}
esp_err_t stationsPostHandler(httpd_req_t* req)
{
auto* ctx = routeContextFrom(req);
if (ctx == nullptr || ctx->stations == nullptr) {
httpd_resp_set_status(req, "503 Service Unavailable");
return httpd_resp_send(req, nullptr, 0);
}
std::array<char, 512> body{};
if (!readRequestBody(req, body)) {
httpd_resp_set_status(req, "400 Bad Request");
return httpd_resp_send(req, nullptr, 0);
}
auto parsed = core::parseStationJson(body.data());
if (!parsed) {
const std::string json =
core::serializeStationListErrorJson(parseErrorToken(parsed.error()));
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());
}
if (auto added = ctx->stations->add(std::move(*parsed)); !added) {
const std::string json = core::serializeStationListErrorJson(
core::stationListErrorToken(added.error()));
httpd_resp_set_status(req, "409 Conflict");
httpd_resp_set_type(req, "application/json");
return httpd_resp_send(req, json.c_str(), json.size());
}
httpd_resp_set_type(req, "application/json");
return httpd_resp_send(req, "{\"status\":\"saved\"}", 18);
}
esp_err_t stationsRemovePostHandler(httpd_req_t* req)
{
auto* ctx = routeContextFrom(req);
if (ctx == nullptr || ctx->stations == 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);
}
auto parsed = core::parseStationRemoveJson(body.data());
if (!parsed) {
const std::string json =
core::serializeStationListErrorJson(parseErrorToken(parsed.error()));
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());
}
if (auto removed = ctx->stations->removeAt(parsed->index); !removed) {
const std::string json = core::serializeStationListErrorJson(
core::stationListErrorToken(removed.error()));
httpd_resp_set_status(req, "404 Not Found");
httpd_resp_set_type(req, "application/json");
return httpd_resp_send(req, json.c_str(), json.size());
}
httpd_resp_set_type(req, "application/json");
return httpd_resp_send(req, "{\"status\":\"removed\"}", 20);
}
esp_err_t stationsTunePostHandler(httpd_req_t* req)
{
auto* ctx = routeContextFrom(req);
if (ctx == nullptr || ctx->stations == nullptr || ctx->tuner == 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);
}
auto parsed = core::parseStationRemoveJson(body.data());
if (!parsed) {
const std::string json =
core::serializeStationListErrorJson(parseErrorToken(parsed.error()));
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());
}
if (parsed->index >= ctx->stations->list().stations().size()) {
const std::string json =
core::serializeStationListErrorJson("not_found");
httpd_resp_set_status(req, "404 Not Found");
httpd_resp_set_type(req, "application/json");
return httpd_resp_send(req, json.c_str(), json.size());
}
if (auto tuned = ctx->stations->tuneToIndex(parsed->index); !tuned) {
const std::string json =
core::serializeTunerErrorJson(tunerErrorToken(tuned.error()));
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());
}
httpd_resp_set_type(req, "application/json");
return httpd_resp_send(req, "{\"status\":\"tuned\"}", 18);
}
} // namespace
SetupWebServer::SetupWebServer()
@@ -632,7 +842,9 @@ SetupWebServer::SetupWebServer()
, netState_(NetState::Uninitialized)
, tuner_(nullptr)
, audio_(nullptr)
, routeContext_{nullptr, nullptr, nullptr, {}}
, bluetooth_(nullptr)
, stations_(nullptr)
, routeContext_{nullptr, nullptr, nullptr, nullptr, nullptr, {}}
{
}
@@ -642,6 +854,8 @@ SetupWebServer::SetupWebServer(SetupWebServer&& other) noexcept
, netState_(other.netState_)
, tuner_(other.tuner_)
, audio_(other.audio_)
, bluetooth_(other.bluetooth_)
, stations_(other.stations_)
, routeContext_(other.routeContext_)
{
other.server_ = nullptr;
@@ -649,7 +863,9 @@ SetupWebServer::SetupWebServer(SetupWebServer&& other) noexcept
other.netState_ = NetState::Uninitialized;
other.tuner_ = nullptr;
other.audio_ = nullptr;
other.routeContext_ = {nullptr, nullptr, nullptr, {}};
other.bluetooth_ = nullptr;
other.stations_ = nullptr;
other.routeContext_ = {nullptr, nullptr, nullptr, nullptr, nullptr, {}};
}
SetupWebServer& SetupWebServer::operator=(SetupWebServer&& other) noexcept
@@ -663,13 +879,17 @@ SetupWebServer& SetupWebServer::operator=(SetupWebServer&& other) noexcept
netState_ = other.netState_;
tuner_ = other.tuner_;
audio_ = other.audio_;
bluetooth_ = other.bluetooth_;
stations_ = other.stations_;
routeContext_ = other.routeContext_;
other.server_ = nullptr;
other.store_ = nullptr;
other.netState_ = NetState::Uninitialized;
other.tuner_ = nullptr;
other.audio_ = nullptr;
other.routeContext_ = {nullptr, nullptr, nullptr, {}};
other.bluetooth_ = nullptr;
other.stations_ = nullptr;
other.routeContext_ = {nullptr, nullptr, nullptr, nullptr, nullptr, {}};
}
return *this;
}
@@ -680,7 +900,7 @@ SetupWebServer::~SetupWebServer()
httpd_stop(server_);
server_ = nullptr;
}
routeContext_ = {nullptr, nullptr, nullptr, {}};
routeContext_ = {nullptr, nullptr, nullptr, nullptr, nullptr, {}};
}
std::expected<void, NetError> SetupWebServer::start(
@@ -688,6 +908,8 @@ std::expected<void, NetError> SetupWebServer::start(
NetState netState,
tuner::TunerService& tuner,
audio::AudioService& audio,
bluetooth::BluetoothService& bluetooth,
station::StationService& stations,
core::CompanionChipStatus companionChips)
{
if (server_ != nullptr) {
@@ -698,9 +920,13 @@ std::expected<void, NetError> SetupWebServer::start(
netState_ = netState;
tuner_ = &tuner;
audio_ = &audio;
bluetooth_ = &bluetooth;
stations_ = &stations;
routeContext_.store = &store;
routeContext_.tuner = &tuner;
routeContext_.audio = &audio;
routeContext_.bluetooth = &bluetooth;
routeContext_.stations = &stations;
routeContext_.companionChips = companionChips;
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
@@ -709,7 +935,7 @@ std::expected<void, NetError> SetupWebServer::start(
if (httpd_start(&server_, &config) != ESP_OK) {
ESP_LOGE(kTag, "httpd_start failed");
routeContext_ = {nullptr, nullptr, nullptr, {}};
routeContext_ = {nullptr, nullptr, nullptr, nullptr, nullptr, {}};
return std::unexpected(NetError::HttpServerStartFailed);
}
@@ -819,6 +1045,70 @@ std::expected<void, NetError> SetupWebServer::start(
};
httpd_register_uri_handler(server_, &audioBassEnhanceUri);
const httpd_uri_t bluetoothStatusUri = {
.uri = "/api/bluetooth/status",
.method = HTTP_GET,
.handler = bluetoothStatusGetHandler,
.user_ctx = routeCtx,
};
httpd_register_uri_handler(server_, &bluetoothStatusUri);
const httpd_uri_t bluetoothPairUri = {
.uri = "/api/bluetooth/pair",
.method = HTTP_POST,
.handler = bluetoothPairPostHandler,
.user_ctx = routeCtx,
};
httpd_register_uri_handler(server_, &bluetoothPairUri);
const httpd_uri_t bluetoothPairStopUri = {
.uri = "/api/bluetooth/pair/stop",
.method = HTTP_POST,
.handler = bluetoothPairStopPostHandler,
.user_ctx = routeCtx,
};
httpd_register_uri_handler(server_, &bluetoothPairStopUri);
const httpd_uri_t bluetoothDisconnectUri = {
.uri = "/api/bluetooth/disconnect",
.method = HTTP_POST,
.handler = bluetoothDisconnectPostHandler,
.user_ctx = routeCtx,
};
httpd_register_uri_handler(server_, &bluetoothDisconnectUri);
const httpd_uri_t stationsGetUri = {
.uri = "/api/stations",
.method = HTTP_GET,
.handler = stationsGetHandler,
.user_ctx = routeCtx,
};
httpd_register_uri_handler(server_, &stationsGetUri);
const httpd_uri_t stationsPostUri = {
.uri = "/api/stations",
.method = HTTP_POST,
.handler = stationsPostHandler,
.user_ctx = routeCtx,
};
httpd_register_uri_handler(server_, &stationsPostUri);
const httpd_uri_t stationsRemoveUri = {
.uri = "/api/stations/remove",
.method = HTTP_POST,
.handler = stationsRemovePostHandler,
.user_ctx = routeCtx,
};
httpd_register_uri_handler(server_, &stationsRemoveUri);
const httpd_uri_t stationsTuneUri = {
.uri = "/api/stations/tune",
.method = HTTP_POST,
.handler = stationsTunePostHandler,
.user_ctx = routeCtx,
};
httpd_register_uri_handler(server_, &stationsTuneUri);
ESP_LOGI(kTag, "HTTP server listening on port 80");
return {};
}
+170
View File
@@ -198,6 +198,33 @@
<p class="msg" id="tuner-msg" aria-live="polite"></p>
</section>
<section id="presets-section">
<h2>Presets</h2>
<p>Saved DAB/FM stations (persisted in NVS).</p>
<ul class="services" id="preset-list"></ul>
<label for="preset-name">Name</label>
<input id="preset-name" maxlength="32" placeholder="My station">
<label for="preset-slot">Preset slot (120, optional)</label>
<input id="preset-slot" type="number" min="1" max="20">
<button type="button" id="save-preset">Save current tune target</button>
<p class="msg" id="preset-msg" aria-live="polite"></p>
</section>
<section id="bluetooth-section">
<h2>Bluetooth</h2>
<p>FSC-BT1035 aptX transmitter — pair headphones or speakers.</p>
<div class="tuner-status" id="bt-status">No status yet.</div>
<div class="row">
<button type="button" id="bt-refresh">Refresh</button>
<button type="button" class="secondary" id="bt-pair">Start pairing</button>
</div>
<div class="row">
<button type="button" class="secondary" id="bt-stop-pair">Stop pairing</button>
<button type="button" class="secondary" id="bt-disconnect">Disconnect</button>
</div>
<p class="msg" id="bt-msg" aria-live="polite"></p>
</section>
<section id="audio-section">
<h2>Audio</h2>
<p>ADAU1701 mixer and master volume (safeload at runtime).</p>
@@ -521,6 +548,149 @@
.catch(function () { showMsg(msg, "Reset request failed.", false); });
});
function formatBtStatus(s) {
return [
"Booted: " + s.booted,
"Pairing: " + s.pairing,
"A2DP: " + s.a2dp
].join("\n");
}
function refreshBluetooth() {
var msg = document.getElementById("bt-msg");
return fetch("/api/bluetooth/status")
.then(function (r) { return r.json().then(function (d) { return { ok: r.ok, d: d }; }); })
.then(function (res) {
if (res.ok && res.d.booted != null) {
document.getElementById("bt-status").textContent = formatBtStatus(res.d);
showMsg(msg, "", true);
} else {
showMsg(msg, "BT error: " + (res.d.reason || "unknown"), false);
}
})
.catch(function () { showMsg(msg, "BT request failed.", false); });
}
document.getElementById("bt-refresh").addEventListener("click", refreshBluetooth);
document.getElementById("bt-pair").addEventListener("click", function () {
var msg = document.getElementById("bt-msg");
fetch("/api/bluetooth/pair", { method: "POST" })
.then(function (r) { return r.json().then(function (d) { return { ok: r.ok, d: d }; }); })
.then(function (res) {
if (res.ok) {
showMsg(msg, "Discoverable — pair from your phone.", true);
refreshBluetooth();
} else {
showMsg(msg, "Pair failed: " + (res.d.reason || "unknown"), false);
}
})
.catch(function () { showMsg(msg, "Pair request failed.", false); });
});
document.getElementById("bt-stop-pair").addEventListener("click", function () {
var msg = document.getElementById("bt-msg");
fetch("/api/bluetooth/pair/stop", { method: "POST" })
.then(function (r) { return r.json().then(function (d) { return { ok: r.ok, d: d }; }); })
.then(function (res) {
if (res.ok) {
showMsg(msg, "Pairing stopped.", true);
refreshBluetooth();
} else {
showMsg(msg, "Stop failed: " + (res.d.reason || "unknown"), false);
}
})
.catch(function () { showMsg(msg, "Stop request failed.", false); });
});
document.getElementById("bt-disconnect").addEventListener("click", function () {
var msg = document.getElementById("bt-msg");
fetch("/api/bluetooth/disconnect", { method: "POST" })
.then(function (r) { return r.json().then(function (d) { return { ok: r.ok, d: d }; }); })
.then(function (res) {
if (res.ok) {
showMsg(msg, "A2DP disconnected.", true);
refreshBluetooth();
} else {
showMsg(msg, "Disconnect failed: " + (res.d.reason || "unknown"), false);
}
})
.catch(function () { showMsg(msg, "Disconnect request failed.", false); });
});
function renderPresets(data) {
var list = document.getElementById("preset-list");
list.innerHTML = "";
(data.stations || []).forEach(function (s, idx) {
var li = document.createElement("li");
var label = s.name + " (" + s.band + ")";
if (s.fm_frequency_khz) label += " " + s.fm_frequency_khz + " kHz";
if (s.dab_freq_index != null) label += " idx " + s.dab_freq_index;
li.textContent = label;
var tuneBtn = document.createElement("button");
tuneBtn.textContent = "Tune";
tuneBtn.addEventListener("click", function () {
fetch("/api/stations/tune", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ index: idx })
}).then(function () { refreshTunerStatus(); });
});
var delBtn = document.createElement("button");
delBtn.textContent = "Del";
delBtn.className = "secondary";
delBtn.addEventListener("click", function () {
fetch("/api/stations/remove", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ index: idx })
}).then(function () { loadPresets(); });
});
li.appendChild(tuneBtn);
li.appendChild(delBtn);
list.appendChild(li);
});
}
function loadPresets() {
return fetch("/api/stations")
.then(function (r) { return r.json(); })
.then(function (d) { renderPresets(d); })
.catch(function () {});
}
document.getElementById("save-preset").addEventListener("click", function () {
var msg = document.getElementById("preset-msg");
var name = document.getElementById("preset-name").value.trim();
if (!name) {
showMsg(msg, "Enter a name.", false);
return;
}
var band = document.getElementById("band").value;
var body = { name: name, band: band };
if (band === "fm") {
body.fm_frequency_khz = parseInt(document.getElementById("fm-khz").value, 10);
} else {
body.dab_freq_index = parseInt(document.getElementById("dab-index").value, 10);
}
var slotVal = document.getElementById("preset-slot").value;
if (slotVal) body.preset_slot = parseInt(slotVal, 10);
fetch("/api/stations", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body)
})
.then(function (r) { return r.json().then(function (d) { return { ok: r.ok, d: d }; }); })
.then(function (res) {
if (res.ok && res.d.status === "saved") {
showMsg(msg, "Preset saved.", true);
loadPresets();
} else {
showMsg(msg, "Save failed: " + (res.d.reason || "unknown"), false);
}
})
.catch(function () { showMsg(msg, "Save request failed.", false); });
});
refreshBluetooth();
loadPresets();
loadAudioProfile();
</script>
</body>
Binary file not shown.