Skip to content

Commit

Permalink
feat!: refactor ble middleware (#346)
Browse files Browse the repository at this point in the history
* gap central updated to skip data length configuration in case is already configured

* remove dependencies with STM32WB

* remove dependencies with stm32wb from transport layer files

* ble middleware refactored in order to remove dependency torwards schi from gap/gatt layers. All dependecies with schi were moved to transport layer

* code format applied

* gap central flow simplified
  • Loading branch information
gabrielsantosphilips authored Jul 3, 2024
1 parent f77c16f commit 6703195
Show file tree
Hide file tree
Showing 17 changed files with 204 additions and 181 deletions.
57 changes: 42 additions & 15 deletions hal_st/middlewares/ble_middleware/GapCentralSt.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
#include "hal_st/middlewares/ble_middleware/GapCentralSt.hpp"
#include "ble_defs.h"
#include "infra/event/EventDispatcherWithWeakPtr.hpp"
#include "infra/stream/ByteInputStream.hpp"

namespace hal
{
Expand All @@ -12,6 +11,15 @@ namespace hal
50, // 500 ms
};

// Connection Interval parameters
const uint16_t minConnectionEventLength = 0;
const uint16_t maxConnectionEventLength = 0x280; // 400 ms

// Discovery parameters
const uint8_t filterDuplicatesEnabled = 1;
const uint8_t acceptParameters = 1;
const uint8_t rejectParameters = 0;

namespace
{
services::GapAdvertisingEventType ToAdvertisingEventType(uint8_t eventType)
Expand All @@ -23,10 +31,16 @@ namespace hal
{
return static_cast<services::GapAdvertisingEventAddressType>(addressType);
}

bool IsTxDataLengthConfigured(const hci_le_data_length_change_event_rp0& dataLengthChangeEvent)
{
return dataLengthChangeEvent.MaxTxOctets == services::GapConnectionParameters::connectionInitialMaxTxOctets &&
dataLengthChangeEvent.MaxTxTime == services::GapConnectionParameters::connectionInitialMaxTxTime;
}
}

GapCentralSt::GapCentralSt(hal::HciEventSource& hciEventSource, BleBondStorage bleBondStorage, const Configuration& configuration)
: GapSt(hciEventSource, bleBondStorage, configuration)
GapCentralSt::GapCentralSt(hal::HciEventSource& hciEventSource, services::BondStorageSynchronizer& bondStorageSynchronizer, const Configuration& configuration)
: GapSt(hciEventSource, bondStorageSynchronizer, configuration)
{
Initialize(configuration.gapService);

Expand All @@ -38,10 +52,10 @@ namespace hal

void GapCentralSt::Connect(hal::MacAddress macAddress, services::GapDeviceAddressType addressType)
{
auto peerAddress = addressType == services::GapDeviceAddressType::publicAddress ? PUBLIC_ADDR : RANDOM_ADDR;
auto peerAddress = addressType == services::GapDeviceAddressType::publicAddress ? GAP_PUBLIC_ADDR : GAP_STATIC_RANDOM_ADDR;

aci_gap_create_connection(
leScanInterval, leScanWindow, peerAddress, macAddress.data(), RESOLVABLE_PRIVATE_ADDR,
leScanInterval, leScanWindow, peerAddress, macAddress.data(), GAP_RESOLVABLE_PRIVATE_ADDR,
connectionUpdateParameters.minConnIntMultiplier, connectionUpdateParameters.maxConnIntMultiplier,
connectionUpdateParameters.slaveLatency, connectionUpdateParameters.supervisorTimeoutMs,
minConnectionEventLength, maxConnectionEventLength);
Expand Down Expand Up @@ -142,11 +156,16 @@ namespace hal
{
GapSt::HandleL2capConnectionUpdateRequestEvent(vendorEvent);

auto l2capEvent = *reinterpret_cast<aci_l2cap_connection_update_req_event_rp0*>(vendorEvent->data);
auto identifier = reinterpret_cast<aci_l2cap_connection_update_req_event_rp0*>(vendorEvent->data)->Identifier;

aci_l2cap_connection_parameter_update_resp(
l2capEvent.Connection_Handle, l2capEvent.Interval_Min, l2capEvent.Interval_Max, l2capEvent.Slave_Latency,
l2capEvent.Timeout_Multiplier, minConnectionEventLength, maxConnectionEventLength, l2capEvent.Identifier, rejectParameters);
infra::EventDispatcherWithWeakPtr::Instance().Schedule([this, identifier]()
{
auto status = aci_l2cap_connection_parameter_update_resp(
connectionContext.connectionHandle, connectionUpdateParameters.minConnIntMultiplier, connectionUpdateParameters.maxConnIntMultiplier,
connectionUpdateParameters.slaveLatency, connectionUpdateParameters.supervisorTimeoutMs,
minConnectionEventLength, maxConnectionEventLength, identifier, rejectParameters);
assert(status == BLE_STATUS_SUCCESS);
});

infra::EventDispatcherWithWeakPtr::Instance().Schedule([this]()
{
Expand All @@ -162,6 +181,17 @@ namespace hal

really_assert(dataLengthChangeEvent.Connection_Handle == connectionContext.connectionHandle);

if (!IsTxDataLengthConfigured(dataLengthChangeEvent))
onMtuExchangeDone = [this]()
{
SetDataLength();
};
else
onMtuExchangeDone = [this]()
{
SetPhy();
};

if (onDataLengthChanged)
onDataLengthChanged();
}
Expand All @@ -174,6 +204,8 @@ namespace hal

really_assert(phyUpdateCompleteEvent.Connection_Handle == connectionContext.connectionHandle);

onMtuExchangeDone = nullptr;

infra::Subject<services::GapCentralObserver>::NotifyObservers([](services::GapCentralObserver& observer)
{
observer.StateChanged(services::GapState::connected);
Expand All @@ -190,13 +222,8 @@ namespace hal
});
}

void GapCentralSt::MtuExchange()
void GapCentralSt::MtuExchange() const
{
onMtuExchangeDone = [this]()
{
SetDataLength();
};

auto status = aci_gatt_exchange_config(this->connectionContext.connectionHandle);
assert(status == BLE_STATUS_SUCCESS);
}
Expand Down
13 changes: 2 additions & 11 deletions hal_st/middlewares/ble_middleware/GapCentralSt.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ namespace hal
, public GapSt
{
public:
GapCentralSt(hal::HciEventSource& hciEventSource, BleBondStorage bleBondStorage, const Configuration& configuration);
GapCentralSt(hal::HciEventSource& hciEventSource, services::BondStorageSynchronizer& bondStorageSynchronizer, const Configuration& configuration);

// Implementation of services::GapCentral
void Connect(hal::MacAddress macAddress, services::GapDeviceAddressType addressType) override;
Expand Down Expand Up @@ -40,7 +40,7 @@ namespace hal
void HandleAdvertisingReport(const Advertising_Report_t& advertisingReport);
void SetPhy() const;
void SetDataLength();
void MtuExchange();
void MtuExchange() const;
void Initialize(const GapService& gapService);

private:
Expand All @@ -50,18 +50,9 @@ namespace hal
const uint16_t leScanInterval = 0x320;
const uint16_t leScanWindow = 0x320;

// Connection Interval parameters
const uint16_t minConnectionEventLength = 0;
const uint16_t maxConnectionEventLength = 0x280; // 400 ms

// Terminate connection
const uint8_t remoteUserTerminatedConnection = 0x13;

// Discovery parameters
const uint8_t filterDuplicatesEnabled = 1;
const uint8_t acceptParameters = 1;
const uint8_t rejectParameters = 0;

// HCI status
const uint8_t commandDisallowed = 0x0c;

Expand Down
4 changes: 2 additions & 2 deletions hal_st/middlewares/ble_middleware/GapPeripheralSt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ namespace

namespace hal
{
GapPeripheralSt::GapPeripheralSt(hal::HciEventSource& hciEventSource, BleBondStorage bleBondStorage, const Configuration& configuration)
: GapSt(hciEventSource, bleBondStorage, configuration)
GapPeripheralSt::GapPeripheralSt(hal::HciEventSource& hciEventSource, services::BondStorageSynchronizer& bondStorageSynchronizer, const Configuration& configuration)
: GapSt(hciEventSource, bondStorageSynchronizer, configuration)
{
Initialize(configuration.gapService);
}
Expand Down
2 changes: 1 addition & 1 deletion hal_st/middlewares/ble_middleware/GapPeripheralSt.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ namespace hal
, public GapSt
{
public:
GapPeripheralSt(hal::HciEventSource& hciEventSource, BleBondStorage bleBondStorage, const Configuration& configuration);
GapPeripheralSt(hal::HciEventSource& hciEventSource, services::BondStorageSynchronizer& bondStorageSynchronizer, const Configuration& configuration);

// Implementation of GapPeripheral
services::GapAddress GetAddress() const override;
Expand Down
82 changes: 6 additions & 76 deletions hal_st/middlewares/ble_middleware/GapSt.cpp
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
#include "hal_st/middlewares/ble_middleware/GapSt.hpp"
#include "ble_gap_aci.h"
#include "infra/event/EventDispatcherWithWeakPtr.hpp"
#include "services/ble/Gap.hpp"
#include "stm32wbxx_ll_system.h"

namespace hal
{
Expand Down Expand Up @@ -31,11 +29,6 @@ namespace hal
return services::GapPairingObserver::PairingErrorType::unknown;
}
}

constexpr auto RfWakeupClockSelection(const hal::GapSt::RfWakeupClock& rfWakeupClock)
{
return infra::enum_cast(rfWakeupClock);
}
}

const services::GapConnectionParameters GapSt::connectionParameters{
Expand All @@ -45,70 +38,12 @@ namespace hal
500,
};

GapSt::GapSt(hal::HciEventSource& hciEventSource, BleBondStorage bleBondStorage, const Configuration& configuration)
GapSt::GapSt(hal::HciEventSource& hciEventSource, services::BondStorageSynchronizer& bondStorageSynchronizer, const Configuration& configuration)
: HciEventSink(hciEventSource)
, txPowerLevel(configuration.txPowerLevel)
, bondStorageSynchronizer(bondStorageSynchronizer)
{
really_assert(configuration.maxAttMtuSize >= BLE_DEFAULT_ATT_MTU && configuration.maxAttMtuSize <= 251);
// BLE middleware supported maxAttMtuSize = 512. Current usage of library limits maxAttMtuSize to 251 (max HCI buffer size)

connectionContext.connectionHandle = GapSt::invalidConnection;

const uint8_t maxNumberOfBleLinks = 0x01;
const uint8_t prepareWriteListSize = BLE_PREP_WRITE_X_ATT(configuration.maxAttMtuSize);
const uint8_t numberOfBleMemoryBlocks = BLE_MBLOCKS_CALC(prepareWriteListSize, configuration.maxAttMtuSize, maxNumberOfBleLinks);
const uint8_t bleStackOptions = (SHCI_C2_BLE_INIT_OPTIONS_LL_HOST | SHCI_C2_BLE_INIT_OPTIONS_WITH_SVC_CHANGE_DESC | SHCI_C2_BLE_INIT_OPTIONS_DEVICE_NAME_RO | SHCI_C2_BLE_INIT_OPTIONS_NO_EXT_ADV | SHCI_C2_BLE_INIT_OPTIONS_NO_CS_ALGO2 |
SHCI_C2_BLE_INIT_OPTIONS_FULL_GATTDB_NVM | SHCI_C2_BLE_INIT_OPTIONS_GATT_CACHING_NOTUSED | SHCI_C2_BLE_INIT_OPTIONS_POWER_CLASS_2_3 | SHCI_C2_BLE_INIT_OPTIONS_APPEARANCE_READONLY | SHCI_C2_BLE_INIT_OPTIONS_ENHANCED_ATT_NOTSUPPORTED);

SHCI_C2_CONFIG_Cmd_Param_t configParam = {
SHCI_C2_CONFIG_PAYLOAD_CMD_SIZE,
SHCI_C2_CONFIG_CONFIG1_BIT0_BLE_NVM_DATA_TO_SRAM,
SHCI_C2_CONFIG_EVTMASK1_BIT1_BLE_NVM_RAM_UPDATE_ENABLE,
0, // Spare
reinterpret_cast<uint32_t>(&bleBondStorage.bleBondsStorage),
0, // ThreadNvmRamAddress
static_cast<uint16_t>(LL_DBGMCU_GetRevisionID()),
static_cast<uint16_t>(LL_DBGMCU_GetDeviceID()),
};

if (SHCI_C2_Config(&configParam) != SHCI_Success)
std::abort();

SHCI_C2_Ble_Init_Cmd_Packet_t bleInitCmdPacket = {
{ { 0, 0, 0 } }, // Header (unused)
{
0x00, // BLE buffer address (unused)
0x00, // BLE buffer size (unused)
0x44, // Maximum number of GATT Attributes
0x08, // Maximum number of Services that can be stored in the GATT database
0x540, // Size of the storage area for Attribute values
maxNumberOfBleLinks,
0x01, // Enable or disable the Extended Packet length feature
prepareWriteListSize,
numberOfBleMemoryBlocks,
configuration.maxAttMtuSize,
0x1FA, // Sleep clock accuracy in Slave mode
0x00, // Sleep clock accuracy in Master mode
RfWakeupClockSelection(configuration.rfWakeupClock), // Source for the low speed clock for RF wake-up
0xFFFFFFFF, // Maximum duration of the connection event when the device is in Slave mode in units of 625/256 us (~2.44 us)
0x148, // Start up time of the high speed (16 or 32 MHz) crystal oscillator in units of 625/256 us (~2.44 us)
0x01, // Viterbi Mode
bleStackOptions,
0, // HW version (unused)
32, // Maximum number of connection-oriented channels in initiator mode
-40, // Minimum transmit power in dBm supported by the Controller
6, // Maximum transmit power in dBm supported by the Controller
SHCI_C2_BLE_INIT_RX_MODEL_AGC_RSSI_LEGACY,
3, // Maximum number of advertising sets.
1650, // Maximum advertising data length (in bytes)
0, // RF TX Path Compensation Value (16-bit signed integer). Units: 0.1 dB.
0, // RF RX Path Compensation Value (16-bit signed integer). Units: 0.1 dB.
SHCI_C2_BLE_INIT_BLE_CORE_5_3 }
};

if (SHCI_C2_BLE_Init(&bleInitCmdPacket) != SHCI_Success)
std::abort();

// HCI Reset to synchronise BLE Stack
hci_reset();

Expand All @@ -118,9 +53,7 @@ namespace hal
// Write Encryption root key used to derive LTK and CSRK
aci_hal_write_config_data(CONFIG_DATA_ER_OFFSET, CONFIG_DATA_ER_LEN, configuration.rootKeys.encryption.data());

bondStorageSynchronizer.Emplace(bleBondStorage.bondStorageSynchronizerCreator);

aci_hal_set_tx_power_level(1, txPowerLevel);
aci_hal_set_tx_power_level(1, configuration.txPowerLevel);
aci_gatt_init();

aci_hal_write_config_data(CONFIG_DATA_PUBADDR_OFFSET, CONFIG_DATA_PUBADDR_LEN, configuration.address.data());
Expand All @@ -135,7 +68,7 @@ namespace hal

void GapSt::RemoveAllBonds()
{
(*bondStorageSynchronizer)->RemoveAllBonds();
bondStorageSynchronizer.RemoveAllBonds();
UpdateNrBonds();
}

Expand All @@ -146,10 +79,7 @@ namespace hal

std::size_t GapSt::GetMaxNumberOfBonds() const
{
if (bondStorageSynchronizer)
return (*bondStorageSynchronizer)->GetMaxNumberOfBonds();

return 0;
return bondStorageSynchronizer.GetMaxNumberOfBonds();
}

std::size_t GapSt::GetNumberOfBonds() const
Expand Down Expand Up @@ -281,7 +211,7 @@ namespace hal
{
hal::MacAddress address = connectionContext.peerAddress;
aci_gap_resolve_private_addr(connectionContext.peerAddress.data(), address.data());
(*bondStorageSynchronizer)->UpdateBondedDevice(address);
bondStorageSynchronizer.UpdateBondedDevice(address);
UpdateNrBonds();
}

Expand Down
21 changes: 2 additions & 19 deletions hal_st/middlewares/ble_middleware/GapSt.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,9 @@
#include "ble/ble.h"
#include "hal_st/middlewares/ble_middleware/HciEventObserver.hpp"
#include "infra/util/BoundedString.hpp"
#include "infra/util/ProxyCreator.hpp"
#include "services/ble/BondStorageSynchronizer.hpp"
#include "services/ble/Gap.hpp"
#include "services/ble/Gatt.hpp"
#include "shci.h"

namespace hal
{
Expand All @@ -31,26 +29,12 @@ namespace hal
std::array<uint8_t, 16> encryption;
};

enum class RfWakeupClock : uint8_t
{
highSpeedExternal = SHCI_C2_BLE_INIT_CFG_BLE_LS_CLK_HSE_1024,
lowSpeedExternal = SHCI_C2_BLE_INIT_CFG_BLE_LS_CLK_LSE,
};

struct Configuration
{
const hal::MacAddress& address;
const GapService& gapService;
const RootKeys& rootKeys;
uint16_t maxAttMtuSize;
uint8_t txPowerLevel;
RfWakeupClock rfWakeupClock;
};

struct BleBondStorage
{
infra::CreatorBase<services::BondStorageSynchronizer, void()>& bondStorageSynchronizerCreator;
uint32_t& bleBondsStorage;
};

// Implementation of AttMtuExchange
Expand All @@ -70,7 +54,7 @@ namespace hal
void NumericComparisonConfirm(bool accept) override;

protected:
GapSt(hal::HciEventSource& hciEventSource, BleBondStorage bleBondStorage, const Configuration& configuration);
GapSt(hal::HciEventSource& hciEventSource, services::BondStorageSynchronizer& bondStorageSynchronizer, const Configuration& configuration);

virtual void HandleHciDisconnectEvent(hci_event_pckt& eventPacket);

Expand Down Expand Up @@ -127,9 +111,8 @@ namespace hal
static constexpr uint8_t maxNumberOfBonds = 10;

private:
const uint8_t& txPowerLevel;
services::BondStorageSynchronizer& bondStorageSynchronizer;
uint16_t maxAttMtu = defaultMaxAttMtuSize;
infra::Optional<infra::ProxyCreator<services::BondStorageSynchronizer, void()>> bondStorageSynchronizer;
};
}

Expand Down
1 change: 0 additions & 1 deletion hal_st/middlewares/ble_middleware/GattClientSt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ extern "C"
{
#include "auto/ble_gatt_aci.h"
#include "ble/ble.h"
#include "ble/core/ble_core.h"
}

namespace hal
Expand Down
5 changes: 0 additions & 5 deletions hal_st/middlewares/ble_middleware/GattServerSt.cpp
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
#include "hal_st/middlewares/ble_middleware/GattServerSt.hpp"

extern "C"
{
#include "ble/core/ble_core.h"
}

namespace
{
uint8_t UuidToType(const services::AttAttribute::Uuid& uuid)
Expand Down
2 changes: 1 addition & 1 deletion hal_st/middlewares/ble_middleware/HciEventObserver.hpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#ifndef HAL_ST_HCI_EVENT_OBSERVER_HPP
#define HAL_ST_HCI_EVENT_OBSERVER_HPP

#include "ble/core/ble_legacy.h"
#include "ble/ble.h"
#include "infra/util/Observer.hpp"

namespace hal
Expand Down
Loading

0 comments on commit 6703195

Please sign in to comment.