From 544b0013b104a6584660724ccd502adcccd7ca6c Mon Sep 17 00:00:00 2001 From: jacqueline Date: Tue, 15 Aug 2023 17:32:57 +1000 Subject: persist preferred bluetooth device in nvs --- src/drivers/bluetooth.cpp | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) (limited to 'src/drivers/bluetooth.cpp') diff --git a/src/drivers/bluetooth.cpp b/src/drivers/bluetooth.cpp index 79999b2c..f6992f05 100644 --- a/src/drivers/bluetooth.cpp +++ b/src/drivers/bluetooth.cpp @@ -20,6 +20,7 @@ #include "esp_wifi.h" #include "esp_wifi_types.h" #include "freertos/portmacro.h" +#include "nvs.hpp" #include "tinyfsm/include/tinyfsm.hpp" namespace drivers { @@ -55,8 +56,8 @@ auto a2dp_data_cb(uint8_t* buf, int32_t buf_size) -> int32_t { return xStreamBufferReceive(stream, buf, buf_size, 0); } -Bluetooth::Bluetooth() { - tinyfsm::FsmList::start(); +Bluetooth::Bluetooth(NvsStorage* storage) { + bluetooth::BluetoothState::Init(storage); } auto Bluetooth::Enable() -> bool { @@ -101,12 +102,15 @@ auto DeviceName() -> std::string { uint8_t mac[8]{0}; esp_efuse_mac_get_default(mac); std::ostringstream name; - name << "TANGARA " << std::hex << mac[0] << mac[1]; + name << "TANGARA " << std::hex << static_cast(mac[0]) + << static_cast(mac[1]); return name.str(); } namespace bluetooth { +NvsStorage* BluetoothState::sStorage_; + std::mutex BluetoothState::sDevicesMutex_; std::map BluetoothState::sDevices_; std::optional BluetoothState::sPreferredDevice_; @@ -114,6 +118,12 @@ mac_addr_t BluetoothState::sCurrentDevice_; std::atomic BluetoothState::sSource_; +auto BluetoothState::Init(NvsStorage* storage) -> void { + sStorage_ = storage; + sPreferredDevice_ = storage->PreferredBluetoothDevice(); + tinyfsm::FsmList::start(); +} + auto BluetoothState::devices() -> std::vector { std::lock_guard lock{sDevicesMutex_}; std::vector out; @@ -417,6 +427,11 @@ void Connecting::react(const events::internal::A2dp& ev) { void Connected::entry() { ESP_LOGI(kTag, "entering connected state"); + + auto stored_pref = sStorage_->PreferredBluetoothDevice(); + if (stored_pref != sPreferredDevice_) { + sStorage_->PreferredBluetoothDevice(sPreferredDevice_); + } // TODO: if we already have a source, immediately start playing } -- cgit v1.2.3